From 63e0b78d7cb60da598e31f410d64071a91352b27 Mon Sep 17 00:00:00 2001 From: Jonathan Senecal Date: Wed, 28 Oct 2026 13:39:13 +0000 Subject: [PATCH 01/14] Add contact form Worker design --- .../2026-10-28-contact-form-worker-design.md | 238 ++++++++++++++++++ 1 file changed, 238 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-28-contact-form-worker-design.md diff --git a/docs/superpowers/specs/2026-10-28-contact-form-worker-design.md b/docs/superpowers/specs/2026-10-28-contact-form-worker-design.md new file mode 100644 index 0000000..b1d6862 --- /dev/null +++ b/docs/superpowers/specs/2026-10-28-contact-form-worker-design.md @@ -0,0 +1,238 @@ +# Contact form on the site's own Worker + +Date: 2026-10-28 +Branch: `contact-forms` + +## Why + +The home page form posts to Formspree. Formspree emails hello@mtlnog.org, a Google group that holds Jonathan and Eric, and they reply from their own inboxes. + +Three problems drive this change: + +- **Nobody can reach the Formspree account.** That blocks the planned switch from hCaptcha to Turnstile (shelved on the `turnstile` branch), because Formspree holds the captcha secret. +- **The form only knows two topics**, Slack invite and sponsorship. People also want to speak at events, host events or ask general questions. Until today they did that by emailing addresses printed on the site. +- **Those addresses drew spam.** They were removed today (`Remove email addresses from the site`), so the form is now the only way in. + +The site already runs as a Cloudflare Worker serving static assets. Adding a small request handler to that Worker lets MTLNOG own the whole pipeline on the free tier: + +- Turnstile checked on our side. +- Submissions stored in D1. +- Notifications posted to Slack. + +## Goals + +- **One form, five topics,** still on the home page at `#invite`: + - Slack invite + - Sponsorship + - Speak at an event + - Host an event (venue) + - General question +- **Topic-specific fields** for speakers and venue hosts, so organizers rarely have to write back just to ask basic questions. +- **Turnstile verified server-side** by the Worker. hCaptcha and Formspree are removed entirely. +- **Every valid submission is stored before anything else,** then posted to one private Slack channel. If Slack fails, it is retried automatically, so nothing is lost silently. +- **Delivered submissions are deleted after 30 days.** +- **Everything stays on the Cloudflare free tier** (Workers, D1, cron triggers, Turnstile) plus a free Slack incoming webhook. + +## Non-goals + +- **No email sending.** No Cloudflare Email Service and no Email Routing: mtlnog.org mail stays on Google Workspace and its MX records are untouched. +- **No admin page for reading submissions.** Slack is the inbox, and replies go by email from the organizers' own mailboxes to the address the visitor typed. +- **No automatic Slack invites.** Organizers still invite people by hand. +- **No per-topic routing to different people or channels.** Everything goes to Jonathan and Eric in one channel, with the topic shown on the message. +- **No separate Contact page.** The form stays on the home page. + +## Anti-goals (would count as failure even if it "works") + +- **A submission the visitor was told succeeded never reaches Slack, and nobody is warned.** +- **Personal data kept indefinitely,** or stored anywhere outside D1 and Slack (logs included: do not log names, emails or message bodies). +- **Any secret in the repo or the built HTML:** the Turnstile secret or the Slack webhook URL. +- **Breaking existing links.** `/fr/?type=sponsorship#invite` and `/en/?type=sponsorship#invite` must keep pre-selecting Sponsorship, and `?type=slack` must keep working. +- **An email address reappearing anywhere in the built site.** + +## What the visitor sees + +The approved mockup is `.superpowers/brainstorm/1754413-1793192937/content/contact-form.html`. It is local and not committed; its contents are summarized here. + +**Copy.** The section keeps its `#invite` anchor and place on the home page. Its heading and intro change from "Join the Community" to a general contact framing; the mockup used "Get in touch" and "Join the Slack, sponsor, speak, host an event, or just ask us something." Final copy is in both `fr.json` and `en.json`, with straight apostrophes, matching the rest of the site. + +**Field order:** +1. **"What's this about?"** (required), a select with five options. The values are listed under "Data contract" below. +2. **Fields shared by every topic:** first name, last name and email (all required), and organization / ASN (optional). +3. **Topic fields,** shown only for the selected topic: + +| Topic | Fields (\* = required) | +|---|---| +| Slack invite | Role\* (the current six-option select), brief introduction | +| Sponsorship | Tier of interest (Not sure yet / Gold / Silver / Something custom), message | +| Speaking | Talk title\*, short abstract\*, talk length (Lightning 5–10 min / Standard 15–20 min, the default / Longer 30 min+), language (French / English / Either), anything else | +| Venue | Venue location\* (neighbourhood or address), approximate capacity\* (number), what's available (checkboxes: projector or screen, microphone / sound, guest Wi-Fi, food & drinks allowed, evening access), anything else | +| General question | Message\* | + +4. **Turnstile widget:** managed mode with a visible box, dark theme. Use the existing widget, sitekey `0x4AAAAAAFo_cWZB_zA8Phzj`. +5. **Send button,** with a note under it saying the information is only used to reply. The note makes no promise about deletion: the 30-day purge is internal housekeeping for D1, and the Slack notification and email replies follow the organizers' normal retention, like any email would. + +**Behavior:** +- Fields of hidden topics are not required and are not sent. +- With JavaScript off, the form can't work, because Turnstile needs JS. Showing a short message in that case is acceptable. +- Status messages stay localized: success, validation error, captcha error, network error. They reach the client script through `data-*` attributes, as today. + +**Links that pre-select a topic,** through `?type=#invite`: +- "Become a sponsor" (already exists) → `sponsorship` +- the Venue paragraph on the Sponsorship page → `venue` +- the Events page → `speaking`, for example a "Want to speak?" line + +`inviteTypeFromSearch` in `src/lib/inviteType.ts` grows to accept the new values. Unknown values still pre-select nothing. + +## Data contract + +**Topic values.** These are public, because they appear in `?type=` links, and they are stored in D1, so treat them as fixed: + +| Value | Topic | +|---|---| +| `slack` | Slack invite | +| `sponsorship` | Sponsorship | +| `speaking` | Speak at an event | +| `venue` | Host an event (venue) | +| `general` | General question | + +**Request.** The request body is JSON. Shared field names keep today's form names, so existing muscle memory and any saved data line up: +- `topic` (replaces `invite_type`), `locale` +- `fname`, `lname`, `email`, `org` +- the Turnstile token, `cf-turnstile-response` +- the honeypot field + +Topic fields are flat, snake_case and unique across topics: + +| Topic | Fields | +|---|---| +| `slack` | `role`, `intro` | +| `sponsorship` | `tier` (`unsure` / `gold` / `silver` / `custom`), `message` | +| `speaking` | `talk_title`, `abstract`, `talk_length` (`lightning` / `standard` / `long`), `talk_language` (`fr` / `en` / `either`), `notes` | +| `venue` | `venue_location`, `capacity` (integer), `amenities` (array of `projector` / `sound` / `wifi` / `food` / `evening`), `notes` | +| `general` | `message` | + +Select and checkbox fields send these stable values, not translated labels. `role` stays a free label from the six-option list; the Worker checks it against the English list, and the French form sends the English value. + +**Response.** +- **200** `{ "ok": true }` +- **400** `{ "ok": false, "error": "invalid" | "captcha" }` +- **500** `{ "ok": false, "error": "server" }` + +**Stored payload.** The `payload` column holds the validated request minus the token and the honeypot. That makes the rows readable with `wrangler d1 execute`. + +## How it works + +### Request path + +1. The browser POSTs JSON to `/api/contact` on the same origin. +2. The Worker handles `/api/*`; everything else falls through to the static assets as today. +3. **Validation**, done before anything is stored: + - **Method and content type:** only POST with `application/json`. + - **Honeypot:** a hidden field (named something a bot would fill in, kept off-screen and out of the tab order). If it isn't empty, the Worker answers with a fake success and stores nothing. + - **Topic** is one of the five values. **Email** is syntactically plausible. + - **Required fields** for that topic are present, and **every field has a length cap**: names and short fields about 200 characters, long text about 5,000. + - **Fields from other topics** are dropped. + - **Capacity** is a positive integer, and checkbox values come from the known set. + - **Turnstile:** the token is verified with Cloudflare's siteverify endpoint, using the secret plus the visitor's IP from `CF-Connecting-IP`. +4. **Response:** + - **On failure:** 400 with a machine-readable error code (`invalid`, `captcha`), which the client maps to localized text. A server error returns 500. + - **On success:** insert one row in D1, return 200 to the visitor, then try the Slack post in `ctx.waitUntil`, so the visitor never waits on Slack. + +### Storage (D1) + +One table, roughly: + +| Column | Notes | +|---|---| +| `id` | | +| `created_at` | | +| `topic` | | +| `locale` | `fr` or `en`, the page the visitor was on | +| `payload` | JSON: shared and topic fields | +| `delivered_at` | null until Slack accepts the message | +| `attempts` | | +| `last_error` | short, with no personal data | +| `failed_at` | set when retries stop | + +Exact schema and migration files are the builder's call. Migrations go through `wrangler d1 migrations`. + +### Slack message + +- One incoming webhook for one private channel. Each message shows: + - **topic** as a label; + - **visitor:** name, email and organization; + - **topic details:** the topic's fields as a short key/value list; + - **message:** the long text, if any; + - **language:** FR or EN, so organizers know which language to reply in. +- **Formatting:** + - Use Block Kit or mrkdwn, the builder's call. + - Labels are in English regardless of the visitor's language. + - The email is shown so it can be clicked and replied to. +- **Escaping:** Slack control characters (`<`, `>`, `&`) are escaped in user text, so a visitor can't inject mentions like `` or links. + +### Retries and cleanup (cron trigger) + +A cron trigger runs every 5 minutes. Each run does two things: + +**Retry.** Rows with `delivered_at` and `failed_at` both null are retried, oldest first and capped per run. Skip rows created in the last minute, so the first `waitUntil` attempt can finish. Rows that were never attempted, because `waitUntil` was cut short, are picked up too. Once a row has been failing for 24 hours, the run: +- sets `failed_at`; +- stops retrying it; +- posts a warning to Slack saying a submission could not be delivered, giving only its id and topic, with no personal data. + +If Slack itself is down, that warning is retried on later runs like any other message. Undelivered rows are kept until they are delivered or handled by hand. + +**Purge.** Delete rows whose `delivered_at` is older than 30 days. Rows marked failed are kept until someone handles them; the README explains how to read them with `wrangler d1 execute` and delete them. + +### Configuration + +| Name | Kind | Where | +|---|---|---| +| `PUBLIC_TURNSTILE_SITEKEY` | build var (public) | Workers Builds settings, `.env`, CI uses the test key `1x00000000000000000000AA` | +| `TURNSTILE_SECRET` | Worker secret | `wrangler secret put` | +| `SLACK_WEBHOOK_URL` | Worker secret | `wrangler secret put` | +| `DB` | D1 binding | `wrangler.jsonc` | + +- **Removed:** `PUBLIC_FORMSPREE_ID` and `PUBLIC_HCAPTCHA_SITEKEY` go from `.env.example`, CI, the README and the Workers Builds settings. +- **Build check:** the existing fail-the-build check becomes a check on `PUBLIC_TURNSTILE_SITEKEY` alone. +- **Local development:** use `.dev.vars` for secrets (git-ignored) with Turnstile's always-pass test secret, and a local D1. Running the full Worker locally should be one mise task. + +## Known blind spot (accepted) + +If the Slack webhook itself breaks (revoked, or the channel archived), every post fails, including the warning, because it goes through the same webhook. Submissions are still safe in D1, but nobody is told. This is accepted. The README documents a one-line `wrangler d1 execute` query to count undelivered rows, and a second alert channel can be added later if this ever bites. + +## Preview builds and migrations (my calls) + +**Preview builds.** If Workers Builds produces preview versions for other branches, those versions share the production D1 database and secrets. There is no separate environment. Two things keep previews from polluting the inbox: +- The Turnstile widget only allows mtlnog.org, so a preview hostname can't pass verification. If a preview hostname is ever added to the widget for testing, test submissions go to the real channel. That is acceptable, because they are labelled and purged like any other message. +- The README says so. + +**D1 migrations** stay manual: `wrangler d1 migrations apply --remote`, run before merging any change that needs one. The README documents this. The Workers Builds deploy command is unchanged. The schema is one small table that will rarely change. + +## Constraints + +- **Stack:** Astro 5 static output stays. The Worker is a separate TypeScript entry point in the repo, declared as `main` in `wrangler.jsonc` alongside the existing `assets` block, so `/api/*` reaches the script and other paths are served as assets. Workers Builds keeps deploying on push to `main`. +- **Tests:** vitest stays the test runner. Validation, payload shaping, Slack formatting and escaping, and the retry/purge selection logic are pure functions with unit tests. Adding the Cloudflare Workers vitest pool for integration tests is the builder's call. +- **Bilingual copy:** every new string goes in both `fr.json` and `en.json`. `shape.test.ts` enforces matching keys, and `translated.test.ts` checks that French strings differ from English. +- **Privacy (Quebec Law 25):** collect only what the form asks for, store it only in D1 and Slack, delete delivered rows after 30 days, and never write personal data to logs or error fields. The form note says how the data is used. + +## Rollout + +Nothing goes live until the Slack webhook exists, so the order matters: + +1. **Jonathan** creates the private channel and its incoming webhook. +2. **Create the D1 database, run the migration, and set both Worker secrets.** This is done by Claude with the Cloudflare token, if it has D1 and Workers edit permissions, or by Jonathan with `wrangler`. +3. **Check the Turnstile widget's allowed hostnames** cover mtlnog.org and any preview hostname used for testing. +4. **Merge and push.** Workers Builds deploys. +5. **Smoke test on production:** submit one message per topic and confirm each arrives in Slack and appears in D1. +6. **After the smoke test:** + - remove the Formspree build variables from the Workers Builds settings; + - delete the `turnstile` branch, since its work is folded in here; + - retire the Formspree form if anyone regains access. + +## Left to the builder + +- The final French and English copy for the heading, intro, field labels, placeholders and the deletion note, starting from the mockup wording. +- Worker file layout, D1 schema details, and Slack message formatting. +- How topic fields are shown and hidden. Prefer one form with grouped sections and `hidden` plus `disabled`, so hidden fields are neither validated by the browser nor sent. +- Exact length caps, the retry batch size, and the honeypot field name. +- Whether to add the Workers vitest pool. From 91af43dc8b9d85ae4e0b9d8e67fbf4012c9fa20d Mon Sep 17 00:00:00 2001 From: Jonathan Senecal Date: Wed, 28 Oct 2026 13:42:39 +0000 Subject: [PATCH 02/14] Add contact form Worker implementation plan --- .../plans/2026-10-28-contact-form-worker.md | 536 ++++++++++++++++++ 1 file changed, 536 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-28-contact-form-worker.md diff --git a/docs/superpowers/plans/2026-10-28-contact-form-worker.md b/docs/superpowers/plans/2026-10-28-contact-form-worker.md new file mode 100644 index 0000000..e6aa916 --- /dev/null +++ b/docs/superpowers/plans/2026-10-28-contact-form-worker.md @@ -0,0 +1,536 @@ +# Contact Form Worker Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace Formspree and hCaptcha with a `/api/contact` handler on the site's own Cloudflare Worker. The handler takes five topics, verifies Turnstile, stores each submission in D1, posts it to Slack, and has a cron job that retries failed posts and purges old rows. + +**Architecture:** +- **Static build:** the Astro site stays static. +- **Worker entry:** a TypeScript entry in `worker/` becomes the Worker's `main`. + - Only `/api/*` runs the script (`assets.run_worker_first`); everything else is served from `dist/` as today. + - A cron trigger runs retries and purges. +- **Shared contract:** `src/lib/contact.ts` holds the topic values, field rules and validation. Both the form (client script) and the Worker import it, so the two can't drift. +- **Thin I/O:** D1, Slack and Turnstile I/O sit behind small functions with injected `fetch` and a `Store` interface, so the handler and the cron logic are unit-tested with an in-memory store. + +**Tech Stack:** +- Astro 5 (static output), TypeScript. +- Cloudflare Workers with D1 and cron triggers, wrangler 4. +- vitest 2. +- Cloudflare Turnstile and Slack incoming webhooks. + +**Spec:** `docs/superpowers/specs/2026-10-28-contact-form-worker-design.md` + +## Global Constraints + +**Topics and fields** +- **Topic values are exactly** `slack`, `sponsorship`, `speaking`, `venue` and `general`. +- **Shared request fields:** `topic`, `locale` (`fr`|`en`), `fname`, `lname`, `email`, `org`, `cf-turnstile-response`, plus the honeypot field. +- **Topic fields:** + - `slack`: `role` (required), `intro` + - `sponsorship`: `tier` (`unsure`/`gold`/`silver`/`custom`), `message` + - `speaking`: `talk_title` (required), `abstract` (required), `talk_length` (`lightning`/`standard`/`long`), `talk_language` (`fr`/`en`/`either`), `notes` + - `venue`: `venue_location` (required), `capacity` (required, integer), `amenities` (array of `projector`/`sound`/`wifi`/`food`/`evening`), `notes` + - `general`: `message` (required) +- **`role` values** are the English labels: `Network Engineer`, `Network Operator`, `Systems & Infrastructure Engineer`, `Network Manager`, `Researcher & Academic`, `Other`. The French form shows French text but submits these values. + +**API and behavior** +- **Responses:** + - 200 `{ "ok": true }` + - 400 `{ "ok": false, "error": "invalid" | "captcha" }` + - 500 `{ "ok": false, "error": "server" }` + - Honeypot filled: 200 `{ "ok": true }`, and nothing is stored. +- **Slack and cron timing:** + - The Slack post happens in `ctx.waitUntil` after the row is stored. + - The cron runs every 5 minutes (`*/5 * * * *`). + - It retries undelivered, non-failed rows older than 1 minute, oldest first, 25 per run. + - After 24 hours of failures it sets `failed_at` and posts an alert containing only the id and topic. + - It purges rows with `delivered_at` older than 30 days. +- **Slack content:** + - Labels are in English. + - Every message includes the visitor's locale (FR/EN). + - `&`, `<` and `>` in user text are escaped. + +**Config and privacy** +- **Config names:** + - `PUBLIC_TURNSTILE_SITEKEY` (build var; CI uses `1x00000000000000000000AA`) + - `TURNSTILE_SECRET` and `SLACK_WEBHOOK_URL` (Worker secrets) + - `DB` (D1 binding) + - The production sitekey is `0x4AAAAAAFo_cWZB_zA8Phzj`. + - `PUBLIC_FORMSPREE_ID` and `PUBLIC_HCAPTCHA_SITEKEY` are removed everywhere. +- **Logging and storage:** + - Never log names, emails or message text. `last_error` holds a short code or status only. + - No secrets in the repo or in `dist/`. + - No email address anywhere in `dist/`. +- **Copy:** + - Every new string goes in both `src/i18n/fr.json` and `src/i18n/en.json`, using straight apostrophes (`'`). + - The form note promises no deletion period. +- **Commits:** no attribution trailers. + +## Review Focus + +1. **A visitor types `` or `` in their name or message.** Slack must show it as literal text, with no ping and no link. Pinned in Task 2. +2. **Fields from a different topic are sent anyway** (stale or crafted data, e.g. `talk_title` with `topic=general`). They must not be stored or posted. Pinned in Task 1. +3. **The Worker stops before the `waitUntil` Slack post runs** (row stored, `attempts = 0`). The next cron run must deliver it. Pinned in Task 4. +4. **A French visitor picks a role.** The submitted value is the English role and validation accepts it. A translated French label is rejected. Pinned in Tasks 1 and 5. +5. **Legacy links** `?type=slack` and `?type=sponsorship` still pre-select, and `?type=SPONSORSHIP` or an unknown value pre-selects nothing. Pinned in Task 1. + +--- + +## File map + +| File | Responsibility | +|---|---| +| `src/lib/contact.ts` (new) | Topics, field rules, `validateSubmission`, `formEntriesToPayload` | +| `src/lib/inviteType.ts` (modify) | `?type=` parsing over the new topic list | +| `worker/slack.ts` (new) | Escaping, message building, posting | +| `worker/turnstile.ts` (new) | Siteverify call | +| `worker/store.ts` (new) | `Store` interface, D1 implementation, time cutoffs | +| `worker/memoryStore.ts` (new) | In-memory `Store` used only by tests | +| `worker/index.ts` (new) | `fetch` (`/api/contact`) and `scheduled` handlers | +| `migrations/0001_submissions.sql` (new) | D1 schema | +| `wrangler.jsonc`, `worker/tsconfig.json`, `.dev.vars.example`, `mise.toml`, `.gitignore` | Worker config | +| `src/components/InviteForm.astro`, `src/i18n/{fr,en}.json` | The form | +| `src/i18n/routes.ts`, `SponsorshipPage.astro`, `MeetingsPage.astro` | Topic links | +| `.env.example`, `.github/workflows/ci.yml`, `README.md` | Config and docs | + +--- + +### Task 1: Shared contract and validation + +**Files:** +- Create: `src/lib/contact.ts` +- Create: `src/lib/contact.test.ts` +- Modify: `src/lib/inviteType.ts`, `src/lib/inviteType.test.ts` + +**Interfaces:** +- Produces, in `src/lib/contact.ts`: + - `TOPICS = ['slack','sponsorship','speaking','venue','general'] as const`, and `type Topic` + - `ROLES` (the six English labels, `as const`) + - `TIERS`, `TALK_LENGTHS`, `TALK_LANGUAGES`, `AMENITIES` (the value lists from Global Constraints, `as const`) + - `HONEYPOT_FIELD = 'website'` + - `LIMITS = { short: 200, long: 5000, maxCapacity: 100000, maxBodyBytes: 32768 }` + - `type Submission = { topic: Topic; locale: 'fr'|'en'; fname: string; lname: string; email: string; org: string; fields: Record }`. `fields` holds only the selected topic's fields, with empty optional fields left out. + - `validateSubmission(input: unknown): { ok: true; value: Submission } | { ok: false }`. It ignores the token and honeypot keys; the caller handles those. + - `formEntriesToPayload(entries: Iterable<[string, string]>): Record`. Repeated `amenities` keys become an array, `capacity` becomes a number when numeric, and other keys stay trimmed strings. +- Produces, in `src/lib/inviteType.ts`: `inviteTypeFromSearch(search: string): Topic | null`. + +- [ ] **Step 1: Write the failing tests** in `src/lib/contact.test.ts`. Use a `base = { topic, locale:'en', fname:'Alex', lname:'Tremblay', email:'alex@example.net', org:'' }` helper. + + `validateSubmission` cases: + - Accepts each topic with only its required fields: + - slack + `role:'Network Engineer'` + - sponsorship with no extra fields + - speaking + `talk_title`, `abstract` + - venue + `venue_location`, `capacity: 30` + - general + `message` + - Rejects: + - an unknown topic + - a missing `fname`, `lname` or `email` + - email `'not-an-email'` + - `locale:'de'` + - Rejects each topic missing one of its required fields. For venue that includes `capacity: 0`, `-1`, `2.5` and `100001`. + - Rejects `role:'Ingénieur réseau'` (Review Focus 4). + - Rejects unknown enum values: `tier:'platinum'`, `talk_length:'epic'`, `amenities:['jacuzzi']`. + - Rejects `fname` longer than 200 characters and `message` longer than 5000. + - Drops other topics' fields (Review Focus 2): `{...base, topic:'general', message:'hi', talk_title:'x'}` gives `value.fields` deep-equal to `{ message: 'hi' }`. + - Trims strings and omits empty optional fields. + + `formEntriesToPayload` cases: + - `[['amenities','wifi'],['amenities','food'],['capacity','30'],['fname',' Alex ']]` gives `{ amenities:['wifi','food'], capacity:30, fname:'Alex' }`. + - A single `amenities` value still gives an array. + + Update `src/lib/inviteType.test.ts`: add `'?type=venue'` → `'venue'`, `'?type=speaking'` → `'speaking'` and `'?type=general'` → `'general'`, and keep the existing cases (Review Focus 5). + +- [ ] **Step 2: Run the tests and confirm they fail** + + Run: `npx vitest run src/lib/contact.test.ts src/lib/inviteType.test.ts` + Expected: FAIL, because the module is not found or the venue/speaking cases return null. + +- [ ] **Step 3: Implement `src/lib/contact.ts`, and point `inviteType.ts` at `TOPICS`** (remove `INVITE_TYPES`, and re-export `Topic` as `InviteType` if anything still imports it). + - Check email with a simple `^[^\s@]+@[^\s@]+\.[^\s@]+$`. + - The module must have no DOM or Worker APIs, because both sides import it. + +- [ ] **Step 4: Run the tests and confirm they pass** + + Run: `npm test` + Expected: all pass. + +- [ ] **Step 5: Commit** + + ```bash + git add src/lib/contact.ts src/lib/contact.test.ts src/lib/inviteType.ts src/lib/inviteType.test.ts + git commit -m "Add shared contact form contract and validation" + ``` + +### Task 2: Slack message and Turnstile verification + +**Files:** +- Create: `worker/slack.ts`, `worker/slack.test.ts` +- Create: `worker/turnstile.ts`, `worker/turnstile.test.ts` +- Modify: `vitest.config.ts`, only if `worker/**/*.test.ts` isn't picked up by default. vitest's default include already matches it; verify in Step 2. + +**Interfaces:** +- Consumes: `Submission`, `Topic` from Task 1. +- Produces, in `worker/slack.ts`: + - `escapeSlack(text: string): string` + - `buildSubmissionMessage(id: number, sub: Submission): { text: string; blocks: unknown[] }` + - `buildFailureAlert(id: number, topic: Topic): { text: string }` + - `postToSlack(url: string, body: object, fetchFn: typeof fetch): Promise<{ ok: true } | { ok: false; error: string }>`. `error` is a short code: `http_` or `network`. +- Produces, in `worker/turnstile.ts`: + - `verifyTurnstile(token: string, secret: string, ip: string | null, fetchFn: typeof fetch): Promise`. It POSTs form data to `https://challenges.cloudflare.com/turnstile/v0/siteverify`, returns `success === true`, and returns false on any network or parse error. + +- [ ] **Step 1: Write the failing tests.** + + `slack.test.ts` cases: + - `escapeSlack(' & ')` returns `'<!channel> & <https://x|y>'`. + - **No raw user text** (Review Focus 1): build a speaking submission whose `fname` is `''` and whose `abstract` is `''`. The JSON-stringified result must not contain `` or `; // returns id + retryable(now: number, limit: number): Promise; // undelivered, not failed, created_at <= now - 60_000, oldest first + markDelivered(id: number, now: number): Promise; + markAttemptFailed(id: number, error: string): Promise; // attempts += 1, last_error = error + markFailed(id: number, now: number): Promise; + purgeDelivered(now: number): Promise; // deletes delivered_at < now - 30 days, returns count + } + export const RETRY_GRACE_MS = 60_000, GIVE_UP_MS = 24 * 3600_000, KEEP_DELIVERED_MS = 30 * 24 * 3600_000; + export function d1Store(db: D1Database): Store; + ``` + Times are epoch milliseconds, stored as `INTEGER`. `payload` is stored as JSON text and parsed on read. +- Produces, in `worker/memoryStore.ts`: `memoryStore(): Store & { rows: Row[] }`, for tests only. + +**Migration:** table `submissions`. Columns match `Row`; `payload` is TEXT and NOT NULL, and `attempts` is INTEGER NOT NULL DEFAULT 0. Add an index on `(delivered_at, failed_at, created_at)`. + +- [ ] **Step 1: Write the failing test** `worker/store.test.ts` against `memoryStore()`. It is the executable spec that `d1Store` must match. + - `retryable` excludes rows that are: + - created less than 60 s ago + - delivered + - failed + - `retryable` includes rows with `attempts: 0` (Review Focus 3), returns them oldest first, and honours `limit`. + - `purgeDelivered` deletes only rows delivered more than 30 days ago, keeps undelivered and failed rows of any age, and returns the count. + - `markAttemptFailed` increments `attempts` and sets `last_error`. + +- [ ] **Step 2: Run the test and confirm it fails** + + Run: `npx vitest run worker/store.test.ts` + Expected: FAIL, because the modules are not found. + +- [ ] **Step 3: Implement `memoryStore`, `d1Store` (prepared statements with `.bind`) and the migration.** + +- [ ] **Step 4: Run the tests and confirm they pass** + + Run: `npm test` + Expected: all pass. + +- [ ] **Step 5: Check the SQL against a local D1.** This needs the `wrangler.jsonc` binding. Add the `d1_databases` entry from Task 4 Step 3 now, with `database_id` set to a placeholder `"local"`. Then: + ```bash + npx wrangler d1 migrations apply DB --local + npx wrangler d1 execute DB --local --command "SELECT name FROM sqlite_master WHERE type='table' AND name='submissions'" + ``` + Expected: the migration applies, and the query returns `submissions`. + +- [ ] **Step 6: Commit** + + ```bash + git add migrations worker/store.ts worker/memoryStore.ts worker/store.test.ts wrangler.jsonc + git commit -m "Add submissions table and storage layer" + ``` + +### Task 4: Worker handlers and config + +**Files:** +- Create: `worker/index.ts`, `worker/index.test.ts`, `worker/tsconfig.json`, `.dev.vars.example` +- Modify: `wrangler.jsonc`, `mise.toml`, `.gitignore`, `package.json` + +**Interfaces:** +- Consumes: Tasks 1–3. +- Produces, in `worker/index.ts`: + ```ts + export interface Env { DB: D1Database; TURNSTILE_SECRET: string; SLACK_WEBHOOK_URL: string; ASSETS: Fetcher } + export interface Deps { store: Store; fetchFn: typeof fetch; now: () => number } + export async function handleContact(req: Request, env: Env, deps: Deps, waitUntil: (p: Promise) => void): Promise; + export async function deliver(id: number, sub: Submission, env: Env, deps: Deps): Promise; // posts, then markDelivered or markAttemptFailed + export async function runScheduled(env: Env, deps: Deps): Promise; + export default { fetch, scheduled } satisfies ExportedHandler; + ``` +- **The default `fetch`:** + - `POST /api/contact` → `handleContact`. + - Any other method on `/api/contact` → 405. + - Other `/api/*` paths → 404 JSON. + - Everything else → `env.ASSETS.fetch(req)`. + - It builds `deps` from `d1Store(env.DB)`, global `fetch` and `Date.now`. +- **`scheduled`** uses `ctx.waitUntil(runScheduled(...))`. + +**`handleContact` order:** +1. **Content type:** not JSON → 400 `invalid`. +2. **Body size:** over `LIMITS.maxBodyBytes` → 400 `invalid`. Unparseable JSON → 400 `invalid`. +3. **Honeypot:** if `HONEYPOT_FIELD` is non-empty, return 200 `{ok:true}`, with no store and no fetch. +4. **Validation:** `validateSubmission` fails → 400 `invalid`. +5. **Turnstile:** `verifyTurnstile(body['cf-turnstile-response'], env.TURNSTILE_SECRET, req.headers.get('CF-Connecting-IP'), fetchFn)` returns false → 400 `captcha`. +6. **Store and deliver:** call `store.insert`, then `waitUntil(deliver(...))`, then return 200 `{ok:true}`. +7. **Errors:** a thrown store error returns 500 `server`. Log only `console.error('contact: store failed')`, with no payload. + +**`runScheduled`:** for each `retryable(now, 25)` row: +- If `now - created_at >= GIVE_UP_MS`, call `markFailed` and post `buildFailureAlert`. Post the alert only once; the row is excluded afterwards because `failed_at` is set. +- Otherwise call `deliver`. + +Then call `purgeDelivered(now)`. + +- [ ] **Step 1: Write the failing tests** in `worker/index.test.ts`. Use `memoryStore()`, a fake `fetchFn` that routes by URL (siteverify vs the webhook) and records calls, a fixed `now`, and a `waitUntil` that collects promises the test awaits. + + `handleContact`: + - **Valid general submission:** returns 200 `{ok:true}`, stores 1 row, and after awaiting `waitUntil` the row is `delivered_at = now` and the webhook was called once. + - **Honeypot:** filled → 200, 0 rows, and no fetch at all. + - **Captcha:** siteverify answers `success:false` → 400 `{ok:false,error:'captcha'}`, 0 rows. + - **Invalid input:** a missing required field → 400 `invalid`, with no siteverify call (cheap checks first). + - **Bad requests:** a `text/plain` body → 400 `invalid`; a 40 KB body → 400 `invalid`. + - **Slack failure:** the webhook returns 500 → response still 200; the row is undelivered with `attempts: 1` and `last_error: 'http_500'`. + - **French role:** a French-locale slack submission with `role:'Network Engineer'` → 200 (Review Focus 4). + + `runScheduled`: + - **Never-attempted row** (Review Focus 3): created 2 minutes ago with `attempts: 0` → delivered. + - **Old failing row:** created 25 h ago, webhook failing → `failed_at` set. The alert was attempted, and its body has no name or email. A second run doesn't post again. + - **Purge:** a delivered row 31 days old is deleted; one 29 days old is kept. + + The default `fetch` handler (needs a fake `env.ASSETS`): + - `GET /api/contact` → 405. + - `GET /fr/` → passed to `ASSETS.fetch`. + +- [ ] **Step 2: Run the tests and confirm they fail** + + Run: `npx vitest run worker/index.test.ts` + Expected: FAIL, because the module is not found. + +- [ ] **Step 3: Implement `worker/index.ts`, and the config:** + - **`wrangler.jsonc`:** + - add `"main": "worker/index.ts"` + - add `"assets": { "directory": "./dist", "binding": "ASSETS", "run_worker_first": ["/api/*"] }` + - add `"d1_databases": [{ "binding": "DB", "database_name": "mtlnog-contact", "database_id": "", "migrations_dir": "migrations" }]` + - add `"triggers": { "crons": ["*/5 * * * *"] }` + - Keep `compatibility_date`. + - **Worker types:** add `@cloudflare/workers-types` as a devDependency. In `worker/tsconfig.json`, extend nothing, and set `"types": ["@cloudflare/workers-types"]`, `"strict": true`, `"noEmit": true`, `"module": "ESNext"`, `"moduleResolution": "Bundler"`, `"target": "ES2022"`, and `"include": ["./**/*.ts", "../src/lib/contact.ts"]`. Exclude `worker` from the root `tsconfig.json` if Astro's check complains. + - **`.dev.vars.example`:** + - `TURNSTILE_SECRET=1x0000000000000000000000000000000AA` (Turnstile's always-pass test secret) + - `SLACK_WEBHOOK_URL=` (fill in a test webhook) + - **`.gitignore`:** add `.dev.vars`. + - **`package.json` scripts:** + - `"typecheck:worker": "tsc -p worker"` + - `"dev:worker": "astro build && wrangler dev"` + - **`mise.toml`:** + - task `dev-worker`: description "Build, then run the Worker (API + assets) locally with a local D1", depends `install`, runs `npm run dev:worker`. + - task `typecheck`, which runs `npm run typecheck:worker`. + +- [ ] **Step 4: Run the tests and confirm they pass** + + Run: `npm test && npm run typecheck:worker` + Expected: all tests pass, and tsc reports no errors. + +- [ ] **Step 5: Local smoke test.** + 1. Copy `.dev.vars.example` to `.dev.vars`, with an empty webhook. + 2. Apply the local migration: `npx wrangler d1 migrations apply DB --local`. + 3. Start the Worker with `PUBLIC_TURNSTILE_SITEKEY=1x00000000000000000000AA npm run dev:worker` (in the background). + 4. Send a submission: + ```bash + curl -s -X POST localhost:8787/api/contact -H 'content-type: application/json' \ + -d '{"topic":"general","locale":"en","fname":"A","lname":"B","email":"a@b.co","org":"","message":"hi","cf-turnstile-response":"XXXX.DUMMY.TOKEN.XXXX"}' + ``` + 5. Check it was stored with `npx wrangler d1 execute DB --local --command "SELECT id, topic, attempts FROM submissions"`. + + Expected: + - The POST returns `{"ok":true}`. + - One row exists, with `attempts` 1, because the empty webhook fails. + - `curl -s -o /dev/null -w '%{http_code}' localhost:8787/en/` returns `200`. + + Stop the dev server afterwards. + +- [ ] **Step 6: Commit** + + ```bash + git add worker/index.ts worker/index.test.ts worker/tsconfig.json .dev.vars.example wrangler.jsonc mise.toml .gitignore package.json package-lock.json + git commit -m "Add contact API and cron handlers to the Worker" + ``` + +### Task 5: The form + +**Files:** +- Modify: `src/components/InviteForm.astro`, `src/i18n/fr.json`, `src/i18n/en.json`, `src/i18n/translated.test.ts`, `src/styles/_form.scss` (or whichever partial holds the form styles; find it with `grep -l "captcha-wrap" src/styles`), `src/styles/_responsive.scss` +- Create: `src/i18n/formTopics.test.ts` + +**Interfaces:** +- Consumes: `TOPICS`, `ROLES`, `TIERS`, `TALK_LENGTHS`, `TALK_LANGUAGES`, `AMENITIES`, `HONEYPOT_FIELD`, `formEntriesToPayload` (Task 1), and `inviteTypeFromSearch` (Task 1). +- Produces: + - the `form` i18n section, keyed by the value lists: + - `form.topics.` (option labels) + - `form.fields.topic` + - `form.roles` (an array aligned with `ROLES`) + - `form.tiers.`, `form.talkLengths.`, `form.talkLanguages.`, `form.amenities.` + - labels and placeholders for every topic field + - `form.noscript` + - the form posting JSON to `/api/contact`. + +**Markup and behavior:** +- **Structure:** one `
` with the topic select first (`id="invite-type"` kept for links, `name="topic"`), then the shared fields, then one `
` per topic. + - Non-selected fieldsets get `hidden` and `disabled`, so they are neither validated nor submitted. + - The default selection is `slack`. +- **Hidden fields:** `` with the page locale, and the honeypot `` inside an off-screen, `aria-hidden` wrapper. +- **Roles:** ``. +- **Turnstile:** `
`, plus the `https://challenges.cloudflare.com/turnstile/v0/api.js` script. The build fails if `PUBLIC_TURNSTILE_SITEKEY` is unset, with the message naming only that var. +- **Submit flow:** + - Require `turnstile.getResponse()`. + - Build the body with `formEntriesToPayload` over the `FormData` entries (string values only). + - POST `application/json` to `/api/contact`. + - Map responses: `ok` → success; `error:'captcha'` → captchaError; `invalid` → error; network failure → networkError. + - Call `turnstile.reset()` after every attempt, and on success also reset the form and re-apply the topic. +- **`