Editorial Benchmarks
~ / tests / cf-contact
BACKEND

>Cloudflare Contact Endpoint

id: cf-contact · deliverable: worker/wrangler.jsonc|worker/wrangler.toml · graders: cfcontact

Read exact fixed prompt
Build a Cloudflare Worker that handles the contact form for an association website. Put the whole project in a folder called `worker/` inside your working folder.

Requirements (this is the contract; it will be tested automatically):

- Config file `worker/wrangler.jsonc` (or `wrangler.toml`) with `main` pointing at your entry file, a `compatibility_date`, and one D1 binding named `DB` (database_name `contact`, any placeholder database_id).
- D1 migrations in `worker/migrations/` that create everything the Worker needs. They will be applied with `wrangler d1 migrations apply DB --local`.
- No npm dependencies beyond what Wrangler provides. Plain JavaScript or TypeScript is fine.
- Secrets arrive as environment variables: `TURNSTILE_SECRET` and `ADMIN_TOKEN`.

`POST /api/contact` with a JSON body `{ "name", "email", "message", "turnstileToken" }`:
- Validate: name 1-100 characters, a plausible email address, message 1-5000 characters, turnstileToken present. Trim whitespace first. Reject bodies over 10 KB with 413. Reject non-JSON or invalid input with 400 and a JSON body `{ "error": "..." }` that says what is wrong.
- Verify the Turnstile token server side with Cloudflare's siteverify API (https://challenges.cloudflare.com/turnstile/v0/siteverify) using `TURNSTILE_SECRET` and the client IP from `CF-Connecting-IP`. If verification fails, return 403 `{ "error": "..." }` and store nothing.
- On success, store the submission in D1 (name, email, message, created timestamp, client IP) and return 201 `{ "id": <id> }`.

`GET /api/contact/:id`:
- Requires `Authorization: Bearer <ADMIN_TOKEN>`. Missing or wrong token returns 401. Unknown id returns 404. Otherwise 200 with the stored submission as JSON (`id`, `name`, `email`, `message`, `created_at`).

Anything else:
- Wrong method on `/api/contact` returns 405 with an `Allow` header. Unknown paths return 404. All responses are JSON.
- Handle CORS for browser use: answer `OPTIONS` preflight with 204 and allow `POST` from any origin.

Test it yourself locally with `npx wrangler dev` before you finish (Cloudflare publishes Turnstile test secrets: `1x0000000000000000000000000000000AA` always passes, `2x0000000000000000000000000000000AA` always fails). Do not deploy anything and do not log in to Cloudflare. Write a short NOTES.md in `worker/` describing your design choices.
Model Outputs

>Model Outputs

Cloudflare Worker checks: 17/17
View all 17 checks
  • PASSmigrations apply
  • PASSvalid POST -> 201 with id
  • PASSPOST has CORS header
  • PASSGET with token -> 200, trimmed fields
  • PASSGET without token -> 401
  • PASSGET wrong token -> 401
  • PASSGET unknown id -> 404
  • PASSmissing name -> 400 with error
  • PASSbad email -> 400
  • PASSblank message -> 400
  • PASSmissing token -> 400
  • PASSnon-JSON -> 400
  • PASSover 10 KB -> 413
  • PASSPUT -> 405 with Allow
  • PASSunknown path -> 404
  • PASSOPTIONS preflight -> 204 + CORS
  • PASSfailed Turnstile -> 403, nothing stored
Read worker/NOTES.md
# 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.

Model note: Built a plain-JS Cloudflare Worker in worker/ (wrangler.jsonc with D1 binding DB, one migration, src/index.js, NOTES.md, test.sh) covering POST /api/contact with size/JSON/field validation, Turnstile siteverify and D1 insert, plus the bearer-protected GET /api/contact/:id, 405/404 handling and CORS. Verified locally with wrangler dev 4.166.0: all 19 smoke tests pass with the always-pass Turnstile secret, and the always-fail secret returns 403 and stores no row. Nothing was deployed.

Gemini 4 Neon thinking_level=high
Queued (Antigravity 502s (model unreachable) on high-effort Neon generation, 2026-11-23)

Provider: antigravityPersonal · Model ID: gemini-4-neon

GPT-6 Astra reasoningEffort=high
Cloudflare Worker checks: 17/17
View all 17 checks
  • PASSmigrations apply
  • PASSvalid POST -> 201 with id
  • PASSPOST has CORS header
  • PASSGET with token -> 200, trimmed fields
  • PASSGET without token -> 401
  • PASSGET wrong token -> 401
  • PASSGET unknown id -> 404
  • PASSmissing name -> 400 with error
  • PASSbad email -> 400
  • PASSblank message -> 400
  • PASSmissing token -> 400
  • PASSnon-JSON -> 400
  • PASSover 10 KB -> 413
  • PASSPUT -> 405 with Allow
  • PASSunknown path -> 404
  • PASSOPTIONS preflight -> 204 + CORS
  • PASSfailed Turnstile -> 403, nothing stored
Read worker/NOTES.md
# Association contact Worker

Plain JavaScript module Worker with no runtime dependencies. Wrangler is the only development dependency; its lockfile is included. The `DB` binding is a local D1 database named `contact`, with a placeholder production ID. Nothing is deployed by these instructions.

## Design

- `POST /api/contact` accepts an `application/json` object. All four fields must be strings and are trimmed. Name and message lengths count Unicode code points. Email uses a practical address-shape check rather than attempting full RFC mailbox parsing.
- The body limit is 10 KB = 10,240 UTF-8 bytes, inclusive. Both declared length and streamed actual bytes are checked, so chunked requests cannot evade it. Unknown JSON fields are ignored but still count toward the byte limit.
- The Worker sends the token, secret and `CF-Connecting-IP` to Cloudflare Siteverify. Only a successful HTTP response with `success: true` permits insertion. Verification errors and a 10-second timeout return 403 without writing. A missing configured secret returns 500.
- D1 uses bound SQL parameters and an autoincrement integer ID. `created_at` is an ISO 8601 UTC timestamp. Client IP is stored as `client_ip` (null when unavailable), but is omitted from the admin response. Tokens are never stored.
- Administrator credentials are compared using timing-safe SHA-256 digest comparison. Missing configuration fails closed. Internal exceptions return generic JSON errors without exposing personal data or secrets.
- CORS permits POST from any origin and the Content-Type request header. OPTIONS on `/api/contact` returns an empty 204 as HTTP requires. JSON responses, including errors, carry CORS headers. Admin access is intended for same-origin or server-side tools; cross-origin Authorization preflights are not enabled. Unknown paths return JSON 404. Known routes with unsupported methods return JSON 405 plus Allow.

## Local use

Requires a current Node.js version supported by Wrangler. The integration test additionally uses the built-in `node:sqlite` module (Node 22.13+).

```sh
npm ci
npx wrangler d1 migrations apply DB --local
```

Create a local `.dev.vars` file (ignored by Git) with `TURNSTILE_SECRET` and `ADMIN_TOKEN`. For manual local development, Cloudflare's public always-pass test secret is `1x0000000000000000000000000000000AA`; the always-fail secret is `2x0000000000000000000000000000000AA`. Use a disposable local admin token. Then:

```sh
npx wrangler dev --local
```

The Worker reads secrets from the environment bindings supplied by Cloudflare/Wrangler. No secret values are in the source or Wrangler config.

## Repeatable verification

After applying the migration, run `npm test`. It starts `npx wrangler dev --local` on loopback port 18987 (override with `TEST_PORT`), exercises HTTP routes against real Siteverify using both public test secrets, and inspects the local D1 database read-only. It checks trimming, validation, exact and oversized bodies, multibyte/chunked sizes, auth, missing IDs, CORS, parameterized storage, timestamps, client IP and unchanged row counts after rejected requests.

The test temporarily supplies public test credentials in `.dev.vars`, restores any previous file in `finally`, and stops its own development server. Run it with no other dev server using this project. Successful test submissions remain in the local test database. Logs are in `.wrangler/integration-wrangler.log`. Internet access to Cloudflare Siteverify is necessary for integration tests. No login, remote database, or browser is used.

References: [Siteverify](https://developers.cloudflare.com/turnstile/get-started/server-side-validation/), [D1 prepared statements](https://developers.cloudflare.com/d1/worker-api/prepared-statements/), [Workers best practices](https://developers.cloudflare.com/workers/best-practices/workers-best-practices/).

## Verified result

On 2026-11-23 with Node 26.8.2 and Wrangler 4.166.0, the local migration applied successfully and `npm test` passed all 57 HTTP checks plus database assertions. Both real Cloudflare Turnstile test-secret outcomes were verified. Local generated runtime types confirmed the D1 and timing-safe comparison APIs. The host's memory pressure made initial Wrangler startup slow, but verification completed. Development servers were stopped and temporary test credentials removed. No deployment or Cloudflare login occurred.

Model note: Built the complete contact-form Worker in worker/ with D1 migration, bounded JSON validation, Turnstile verification, admin retrieval and CORS. Verified locally with npx wrangler dev: all 57 HTTP checks and database assertions passed using real passing and failing Turnstile test secrets; nothing was deployed.