# Contact form Worker: design notes

Plain JavaScript module Worker (`src/index.js`), no runtime dependencies. `wrangler` is the only (dev) dependency.

## Running locally

```sh
npm install
cp .dev.vars.example .dev.vars        # Turnstile always-pass test secret + a test admin token
npx wrangler d1 migrations apply DB --local
npx wrangler dev
./test.sh http://127.0.0.1:8787       # smoke tests for the whole contract
```

Swap `TURNSTILE_SECRET` to `2x0000000000000000000000000000000AA` to check that a failed
challenge returns 403 and stores nothing.

## Storage

One table, `submissions` (`migrations/0001_create_submissions.sql`): `id INTEGER PRIMARY KEY
AUTOINCREMENT`, `name`, `email`, `message`, `ip`, `created_at`. `created_at` is set by the Worker
as an ISO 8601 UTC string (the column also has a SQL default). The insert uses `RETURNING id`, so
creation is a single round trip. The client IP is stored but deliberately not returned by the admin
GET, which returns exactly `id, name, email, message, created_at`.

## Request handling, in order (POST /api/contact)

1. Secrets check: a missing `TURNSTILE_SECRET` is a 500, so the Worker never silently accepts
   unverified mail.
2. Size: 413 if `Content-Length` is over 10 KB (10,240 bytes). The body is also counted while it
   streams, so chunked bodies or a false `Content-Length` cannot bypass the limit.
3. Parse: the body must be UTF-8 JSON and a JSON object. `Content-Type` is not required to be
   `application/json`, so `curl -d` and `text/plain` (CORS "simple") requests also work; the
   body itself still has to be valid JSON.
4. Validate (after trimming): name 1-100 characters, email plausible (one `@`, no whitespace,
   dotted domain with a 2+ letter TLD, at most 254 characters), message 1-5000 characters,
   turnstileToken non-empty (at most 2048, Turnstile's documented maximum). Lengths are counted in
   Unicode code points, so an emoji is one character. Non-string values are rejected. All problems
   are listed in one 400 response, e.g.
   `{"error":"Invalid submission: name is required; email must be a valid email address."}`.
5. Turnstile: validation runs before siteverify, so malformed requests never consume a
   siteverify call. The token is POSTed to siteverify with the secret and `CF-Connecting-IP` as
   `remoteip`. `success !== true` is a 403 and nothing is written. If siteverify is unreachable or
   returns a non-2xx status, the Worker returns 502 (also storing nothing) rather than presenting an
   outage as a failed challenge.
6. Insert, then 201 `{"id": n}`.

## Admin read (GET /api/contact/:id)

- The bearer check runs first, so unauthenticated callers cannot probe which ids exist.
- The token comparison is constant time (SHA-256 both sides, then `crypto.subtle.timingSafeEqual`).
- A 401 includes `WWW-Authenticate: Bearer`. A missing `ADMIN_TOKEN` secret is a 500, never open
  access.
- Ids that are not canonical positive integers (`abc`, `01`, `-1`) are 404, the same as unknown ids.

## HTTP behaviour

- Every response with a body is JSON (`application/json; charset=utf-8`), including 404, 405 and
  unexpected 500s (which are caught, logged, and returned as a generic error). 204 preflights have
  no body.
- 405 carries `Allow`: `POST, OPTIONS` on `/api/contact` and `GET, OPTIONS` on `/api/contact/:id`.
- CORS: `Access-Control-Allow-Origin: *` on every response. `OPTIONS` on either route returns 204
  with the allowed methods, `Content-Type, Authorization` as allowed headers, and a 24 h max-age.
  A wildcard origin is safe here because the API uses no cookies; the admin route is protected by
  the bearer token, not by origin.
- `Cache-Control: no-store` and `X-Content-Type-Options: nosniff` on all responses.
- A single trailing slash is accepted (`/api/contact/` is the same as `/api/contact`).

## Not included (possible next steps)

- Rate limiting per IP (Workers Rate Limiting binding or a WAF rule). Turnstile is the only abuse
  control today.
- Notifying staff of new submissions (email or queue), and a list/delete admin endpoint.
- A retention policy for stored IPs and messages (for example, a scheduled purge after N days).
- Restricting `Access-Control-Allow-Origin` to the association's domain once it is known.
