# Form submission API

import openapi from "@recit/form/form-submission.openapi.json";
import openapiUrl from "@recit/form/form-submission.openapi.json?url";

A `:::form` of a Récit site posts its answers to an API that **you** write and host. Récit hosts no
endpoint and stores nothing. This page is the contract between the form and that API: what the form
sends, what it expects back, and what the API must check. The client only helps. Security is the
API's job.

The contract is published as OpenAPI 3.1 at
`https://recit.dev/schema/v1/form-submission.openapi.json` (the file
`@recit/form/form-submission.openapi.json` of the package). The same zod schemas generate it and
check the code, so the contract and the code cannot drift. The reference server `@recit/form/server`
implements every rule below.

## The request

`POST <endpoint>`, where `endpoint=` is set on the form.

| Content-Type                        | When                                  | Preflight |
| ----------------------------------- | ------------------------------------- | --------- |
| `application/x-www-form-urlencoded` | **default**, the same with JavaScript | no        |
| `multipart/form-data`               | as soon as a field is a `file`        | no        |
| `application/json`                  | only with `encoding=json`             | yes       |

The default body is a "simple" request: the browser sends it without a CORS preflight, and the same
`<form>` works without JavaScript (`submit=native`). The form sends
`Accept: application/json, application/problem+json` and no custom header, except `Idempotency-Key`
with `encoding=json`.

### Default body (`encoding=form`)

The fields of the form, flat, plus reserved fields prefixed with `_recit.`. A field written by an
author never starts with `_recit.` (the build refuses it, with its line).

| Field               | Content                                                               |
| ------------------- | --------------------------------------------------------------------- |
| `_recit.form`       | the id of the form (`signup`)                                         |
| `_recit.version`    | `1`, the version of this contract                                     |
| `_recit.locale`     | the language of the page, so that the API answers in it               |
| `_recit.submission` | the idempotency key, one UUID per attempt (absent without JavaScript) |
| `_recit.story`      | the id of the story                                                   |
| `_recit.about`      | the scene the answer is about (below), when a link names one          |
| `_recit.elapsed`    | milliseconds between display and submission (the time trap)           |
| `_recit.consent`    | the version of the consent text, when the box is checked              |
| `_recit.key`        | `auth=publishable-key` only: a public key, never a secret             |
| `_recit.website`    | the honeypot: always empty when a person fills the form               |

A field hidden by `visible-if` is **not sent** (minimisation). A checkbox group sends its name once
per checked value.

### JSON body (`encoding=json`)

An envelope that keeps data and meta apart:

```json
{
  "form": "signup",
  "version": 1,
  "locale": "en",
  "data": { "name": "Lorem Ipsum", "email": "lorem@example.com", "mode": "remote" },
  "meta": {
    "submissionId": "3f2c0d8e-0000-4000-8000-000000000000",
    "story": "meetup",
    "page": "https://example.com/meetup",
    "elapsedMs": 8421,
    "consent": { "name": "consent", "version": "2026-10", "granted": true },
    "antispam": { "honeypot": "", "turnstile": null }
  }
}
```

`meta.about` (`_recit.about` in a flat body) names the scene the answer is about: the event of a
calendar a person registers for (`register=`), the item of a roadmap a feedback is on (`feedback=`).
The link that opens the form adds `?recit-about=<scene id>` to its address, and the form sends it;
`meta.story` stays the id of the story that holds the form. Without JavaScript, the field is not
sent. The visitor writes the address: treat `about` as untrusted input. It holds at most 200
characters; a longer value is left out.

`data` holds typed values: numbers for `number` and `range`, booleans for `checkbox`, lists for
`checkbox-group`. It follows `/forms/<id>.schema.json`, the JSON Schema of the form's data.

### Flat body (`contract=openapi`)

A form generated from an OpenAPI operation sends **exactly** that operation's `requestBody`: the
fields flat, in its media type (JSON, urlencoded, or multipart with a file), no envelope and no
`_recit.*` entry. The meta travels in headers, so the request always has a CORS preflight:

| Header                | Value                                                  |
| --------------------- | ------------------------------------------------------ |
| `Recit-Form`          | the form id                                            |
| `Recit-Locale`        | the language of the page                               |
| `Recit-Submission-Id` | the idempotency key, the same on every retry           |
| `Recit-Consent`       | the version of the accepted consent text, when granted |
| `Recit-Honeypot`      | the honeypot, only when a robot filled it              |

Errors point at the flat body: `#/title`. `submit=native` cannot send headers, so it is refused.

## The answers

| Status        | Meaning                              | Body                                                    |
| ------------- | ------------------------------------ | ------------------------------------------------------- |
| 200, 201, 202 | accepted                             | `{ "id"?, "message"?, "redirect"? }`, already localised |
| 303           | accepted, `submit=native`            | `Location` to the success page                          |
| 400           | malformed body                       | `application/problem+json`                              |
| 401, 403      | authentication, origin or key        | `application/problem+json`                              |
| 409           | same idempotency key, different body | `application/problem+json`                              |
| 413, 415      | too large, type refused              | `application/problem+json`                              |
| 422           | validation                           | RFC 9457 with `errors[]` (below)                        |
| 429           | too many requests                    | `Retry-After` is required                               |
| 5xx           | server error                         | generic `application/problem+json`                      |

A validation error follows RFC 9457 (Problem Details), with an `errors` member that is a Récit
extension. Each entry points at a field with a JSON Pointer and a code named after the JSON Schema
keyword (`required`, `type`, `format`, `minLength`, `maxLength`, `minimum`, `maximum`, `pattern`,
`enum`, `maxSize`, `accept`):

```json
{
  "type": "https://recit.dev/problems/validation",
  "title": "Your answers need a correction",
  "status": 422,
  "errors": [{ "pointer": "#/data/email", "code": "format", "detail": "Lorem ipsum." }]
}
```

The form shows the `detail` of an entry as it is, or the message of its `code` from the language
pack (en, fr). It shows `message` and `detail` as text, never as HTML. Unknown members are ignored:
the API may add its own.

## The rules an API must follow

1. **Validate on the server** with the published schema. The validation of the form is a help, not a
   guard.
2. **Replay the same answer for the same key** (`_recit.submission`, `meta.submissionId` or
   `Idempotency-Key`). The same key with a different body is a 409.
3. **Accept urlencoded and multipart**, and set `Access-Control-Allow-Origin` to the site's origin
   on **every** answer. Without it the browser delivers the submission but the form cannot read the
   answer, and falls back to a native submission. Serve `OPTIONS` (`Allow-Methods: POST`,
   `Allow-Headers: Content-Type, Idempotency-Key, Authorization`,
   `Expose-Headers: Location, Retry-After`) for `encoding=json` or an auth header. Never `*` with
   credentials.
4. **Drop a filled honeypot in silence**: answer 2xx and do nothing, so that the bot learns nothing.
5. **Never send back personal data** of another submission, not even in an error.
6. **Tolerate unknown members**, and add your own if you need them.

Authentication: `auth=none` (origin check and anti-spam) or `auth=publishable-key`, a public key
restricted to the origin and sent in the body so that the request stays simple. A static site never
holds a secret: the build refuses any value that looks like one (a private key, an `sk_…` key, a
`Bearer` token, a token in a URL).

### Turnstile, opt-in (`antispam=turnstile`)

The honeypot stays the default and needs no third party. A form that faces stronger robots can ask
for Cloudflare Turnstile: `:::form{#signup antispam=turnstile sitekey=0x4AAA…}`, or
`forms.turnstileSiteKey` in the front matter. The site key is public; the secret key lives on the
server only, never in a page. `contract=openapi` and `contract=formspree` have no place for the
token: the build refuses them with Turnstile.

- The page loads Cloudflare's script for that form only, once per page however many forms ask for
  it, and shows no honeypot. When the script cannot load (a blocker, offline), the form says so
  instead of showing an empty frame. The widget writes its token in the reserved `_recit.turnstile`
  field (`encoding=form`, `submit=native` included), or the form sends it as
  `meta.antispam.turnstile` (`encoding=json`, `null` before the widget passes).
- **The widget alone protects nothing.** The API sends the token to
  `https://challenges.cloudflare.com/turnstile/v0/siteverify` with its secret, and refuses the
  submission (403) unless the answer is `success: true` from one of the site's hostnames. A token is
  single-use and valid for 300 seconds: after any refused submission (a correction, `429`, `5xx`,
  `403`), the form asks the widget for a new one. `verifyTurnstile` of `@recit/form/server` does
  that call and never throws: a missing token, a network failure, an answer slower than `timeoutMs`
  (5 seconds by default) or an unreadable answer is a refusal. The reference handler calls it before
  the answers are read:
  `createFormHandler({ forms, onSubmit, origins, turnstile: { secret, hostnames, remoteIp } })`, and
  refuses to start when a form asks for Turnstile without the secret. `remoteIp` reads the visitor's
  address from the request (`(request) => request.headers.get("CF-Connecting-IP")` behind
  Cloudflare): only the host knows which header it can trust, so the handler reads none by itself.
- A retry of the same submission replays the stored answer: the token is left out of the idempotency
  fingerprint, and a single-use token is never checked twice.
- The script receives the visitor's address: name Cloudflare in the privacy notice linked by
  `privacy=`.

### The signed-in person (`auth=bearer`)

`auth=bearer` sends the token of the person signed in to the site in an
`Authorization: Bearer <token>` header. The story never holds it: the host gives the `Form`
component a `token` provider (`token={() => session.token}`), asked at each submission, and
`@recit/form` never reads a session or a storage itself. A header needs JavaScript, so
`submit=native` is refused, and so are `contract=formspree` and `key=`. On the server,
`createFormHandler` takes `verifyBearer(token, form, request)`: it answers `401` with
`WWW-Authenticate: Bearer` when the header is missing or `verifyBearer` does not return `true`, and
refuses every token when you give no `verifyBearer`. A `401` is never kept for the idempotency key,
so the same attempt passes once the person is signed in. With `upload=presigned`, each ticket
request to `<endpoint>/uploads` carries the same header and gets the same `401` without an accepted
token, before `uploads.sign` is called; the bytes sent to the ticket's address never carry it.

```ts
export const handler = createFormHandler({
  forms,
  origins: ["https://lorem.example.com"],
  verifyBearer: async (token) => (await sessions.find(token)) !== undefined,
  onSubmit: async ({ data, request }) => save(data, request),
});
```

Webhooks without CORS headers (Slack, Discord) cannot be called from the browser, whatever the
encoding: put a relay in front of them (a Worker or a function that receives the form and calls the
webhook).

## TODO API: what to build

Récit gives you the contract and a reference handler. The rest is yours. Tick each item before you
open the form to the public:

- [ ] **Validation.** Validate every submission on the server with `/forms/<id>.schema.json`, or
      with `createFormHandler` of `@recit/form/server`, which builds the schema from the form.
      Answer 422 with one `errors[]` entry per field.
- [ ] **CORS.** Set `Access-Control-Allow-Origin` to the exact origins of the site on every answer,
      `Vary: Origin`, and serve `OPTIONS` if you use `encoding=json`. Refuse (403) a `POST` whose
      `Origin`, or without it `Referer`, is another origin, and redirect only to a page of the site.
- [ ] **Idempotency.** Store the answer of each key for at least a day and replay it; refuse the
      same key with another body (409). A shared store (a database, a KV) if the API runs on several
      instances.
- [ ] **Anti-spam.** Drop a filled honeypot with a 2xx. Read `_recit.elapsed` (or `meta.elapsedMs`)
      and set your own threshold for answers that come too fast. Limit the rate per IP and answer
      429 with `Retry-After`.
- [ ] **Files.** Check `accept` and `max-size` again on the server (415, 413). With
      `upload=presigned`, answer the tickets of `<endpoint>/uploads` (below), bind each address to
      the asked size and type, and refuse a reference you did not give (422, `format`).
- [ ] **Errors.** Answer in `application/problem+json`; never put the data of a submission in an
      error message or in your logs.
- [ ] **Language.** Answer `message` and `detail` in `_recit.locale` when you can.
- [ ] **Retention (GDPR).** Decide how long you keep the answers, and delete them after that. A
      backend that deletes the answers after `N` days tells the visitor with `retention=N`.
- [ ] **Rights (GDPR).** Give a way to access, correct and erase an answer, and say it in the
      privacy notice linked by `privacy=`.
- [ ] **Consent.** Store the version of the consent text (`_recit.consent`) with the answer.
- [ ] **Check.** Run `recit form check-endpoint <url> --form <id>` against your endpoint before
      going live.

## The reference handler

`createFormHandler` takes the forms, the origins of the site and your `onSubmit`, and returns a
web-standard handler, `(request: Request) => Promise<Response>`. It runs as is on Node 22, a
Cloudflare Worker, a Vercel function or an API gateway.

```ts
import { createFormHandler } from "@recit/form/server";
import signup from "./forms/signup.json" with { type: "json" };

export const handler = createFormHandler({
  forms: [signup],
  origins: ["https://lorem.example.com"],
  onSubmit: async ({ data, locale }) => {
    // Store or forward the answer: it is yours
    return { message: locale === "fr" ? "Merci !" : "Thank you!" };
  },
});
```

If `onSubmit` finds that the idempotency key already holds another body (two concurrent sends), it
throws `FormSubmissionConflictError` from `@recit/form/server` and the handler answers `409` without
storing that answer; a replay of the same body is not an error.

It refuses with 403 a `POST` whose `Origin` (or, without it, `Referer`) is not one of `origins`, so
a third-party page cannot make its visitors submit; a request with neither header, from a server or
a script, passes. A native submission goes back to its `Referer` only when that page is on one of
`origins`. `onSubmit` receives only the answers it validated (`submittedData`): the non-empty values
of the fields `visible-if` shows, never a key the form does not know, a hidden field, a file field
(in `files`) or the consent (in `consent`); a `locale` that is not a language tag (`fr_FR` is read
as `fr-FR`) of at most 35 characters gets a 422 on `#/locale`. It validates with the form's schema,
answers in problem+json, sets CORS, drops a filled honeypot and, with `minElapsedMs`, an answer sent
faster than that after the form was shown, checks a publishable key and replays an idempotency key
from a store you can replace (memory by default). `examples/form-api-node` runs it behind
`node:http`, with its README.

### Files sent first

A form with `upload=presigned` sends each file before the answers. It first posts a ticket request
to `<endpoint>/uploads`, in JSON (`FormUploadRequestSchema` of `@recit/core/schema`):

```json
{ "form": "apply", "field": "cv", "name": "lorem.pdf", "type": "application/pdf", "size": 182044,
  "submissionId": "3f2c0d8e-0000-4000-8000-000000000000" }
```

The API answers `201` with a ticket (`FormUploadTicketSchema`): `file`, the reference the submission
will carry as the field's value, and `url`, where the bytes go, with `method` (`PUT` by default, the
body is the file, sent with `headers`; or `POST` with `fields` then the file, as a presigned policy
expects). A refused file is a `422` on its field: `accept`, `maxSize`, or `enum` when the field is
not a file; a form without `upload=presigned` is a `422` on `#/form`. The request is JSON, so it has
a preflight: serve `OPTIONS` on this path too.

The reference handler answers this path when you give it `uploads`. It reads a small JSON body,
checks the form, the field, `accept=` and `max-size=`, then calls your `sign`, which bundles no
storage SDK: it returns the presigned address of your object store. The size and type of the request
come from the visitor: `sign` **must bind them into the presigned URL** (a `Content-Length` and a
`Content-Type` the store enforces), or the store takes any file. The handler refuses to start when a
form asks `upload=presigned` without `uploads: { sign, check }`, or when that form's endpoint
already ends with `/uploads` (its answers and its tickets would share one path). A handler without a
presigned form never treats `/uploads` as a ticket path. An API that serves no presigned upload
answers this path `501`.

```ts
export const handler = createFormHandler({
  forms: [apply],
  origins: ["https://lorem.example.com"],
  uploads: {
    sign: async ({ field, type, size }) => presign(field, type, size), // your store
    check: async (file) => exists(file), // the bytes arrived, and you gave this reference
  },
  onSubmit: async ({ data, uploads }) => {
    // uploads: { cv: "up_01" }, the references by field, apart from data
  },
});
```

`check` is required: it refuses with a `422` (`format`) a reference it does not know, so a visitor
can submit neither a reference `sign` never gave nor another visitor's file. Never trust a reference
only because it came with an answer.

### Recipes

- **Cloudflare Worker**: `export default { fetch: handler }`.
- **Vercel function**: `export const POST = handler; export const OPTIONS = handler;` in
  `api/forms.ts`.
- **API gateway**: map the gateway's event to a `Request` and the `Response` back; keep CORS in the
  handler, not in the gateway, so that every answer carries it.
- **Relay to a webhook without CORS**: in `onSubmit`, `fetch` the webhook from the server with its
  secret, which never reaches the site.

## The OpenAPI document

The contract as the OpenAPI 3.1 file of `@recit/form`, rendered from its JSON: every operation,
every response and its examples, which the tests check against the reference server.

<OpenApiReference document={openapi} href={openapiUrl} />
