# Subject requests reference

> The server side of data subject requests: the build manifest, createSubjectRequestHandler, its responses, the request record and store, the D1 tables, the reminder and the sweep, the receipt…

The server side of [data subject requests](/docs/manual/concepts/subject-requests/): the build manifest, `createSubjectRequestHandler`, its responses, the request record and store, the D1 tables, the reminder and the sweep, the receipt helpers and the email adapters. Everything is exported by `@consent-kit/server`, and runs on the Fetch API with no Cloudflare import.

## subject-requests.manifest.gen.json

`consent-kit build` writes it only when the registry has `subjectRequests`. `parseSubjectRequestManifest` checks it; the handler, `remindDueRequests` and the Worker read it.

| Field | |
| --- | --- |
| `manifestVersion` | `1`. |
| `endpoint`, `notify`, `types`, `retention` | From the registry section. |
| `requesterEmail` | `{ processor }`, or `null`: no email to the requester. |
| `controller` | `{ name }`, signed under the confirmation email. |
| `policyHash` | The policy of the build, stored with each request. |
| `defaultLocale` | The language of the emails to `notify`, and of a request from a form whose locale the manifest lacks. |
| `locales.<locale>.pages` | `form`, `received`, `confirm` (with a `{token}` placeholder), `confirmed`, `linkInvalid`: complete HTML pages with no script and no inline style. |
| `locales.<locale>.texts` | The email texts, with `{placeholders}` the server fills in. |
| `locales.<locale>.checklists` | The [fulfilment checklist](/docs/manual/reference/documents/#fulfilment-checklist) per offered type, plain text. |
| `unreviewedPhrases` | Ids of the phrases in it that no lawyer has reviewed. |

## createSubjectRequestHandler

```ts
const handle = createSubjectRequestHandler({
  store: createD1SubjectRequestStore(env.DB),
  receipts: createD1ReceiptStore(env.DB),
  hmacKey: env.RECEIPTS_HMAC_KEY,
  allowedOrigins: ['https://www.example.com'],
  manifest: requestsManifest,
  notifySender: cloudflareEmailSender(env.PRIVACY_EMAIL),
  from: 'Privacy requests <requests@example.com>',
});
// In a Worker: handle(request, ctx), so that the emails go out after the answer.
```

| Option | Default | |
| --- | --- | --- |
| `store` | | A `SubjectRequestStore`. |
| `hmacKey` | | The receipts' key, at least 32 bytes. It hashes the cookie's consent id (so requests join receipts), the email address (`email_hash`) and the rate-limit key, and it signs confirmation links. |
| `allowedOrigins` | | The site's origins, exactly as browsers send them in `Origin`. |
| `manifest` | | The manifest above. Checked at once. |
| `notifySender` | | An `EmailSender` that reaches `notify`. |
| `from` | | The From address of every email. |
| `requesterSender`, `requesterFrom` | none, `from` | Required when the manifest has `requesterEmail`: sends the confirmation link. |
| `receipts` | none | A receipt store with `listBySubject`. Used only to count matches for the notification. |
| `path` | the manifest's endpoint | |
| `pages` | the manifest's pages | Per locale. `false`: GET is answered 404, except for a confirmation link, whose page comes from the manifest. |
| `allowMissingOrigin` | `false` | |
| `maxConfirmationsPerHour` | `100` | A cap on confirmation emails in all. |
| `onConfirmationCapReached` | `console.warn` | Called with `{ cap, windowMs }` when the cap refuses an email. Carries no personal data. |
| `confirmationTtlMs` | 7 days | |
| `consentCookieName` | `cc_cookie` | |
| `now`, `onStoreError`, `onEmailError` | clock, `console.error` | `onEmailError(error, { requestId, email: 'notification' \| 'confirmation' })` never gets the address. |

It throws at once on a missing or short key, a malformed manifest or origin, a `from` without `@`, or `requesterEmail` without a `requesterSender`.

### The form POST

`POST <path>`, `Content-Type: application/x-www-form-urlencoded`, body at most 4096 bytes. The fields are `email`, `type`, `details`, `locale` and the honeypot `website`, each at most once, and nothing else.

| Check | Answer | Code |
| --- | --- | --- |
| No `Origin` / a foreign one | 403 | `request/origin-missing` / `request/origin-forbidden` |
| Another media type | 415 | `request/unsupported-media-type` |
| Body over 4096 bytes | 413 | `request/body-too-large` |
| Not UTF-8 form encoding | 400 | `request/invalid-form` |
| An unknown or repeated field | 400 | `request/unexpected-fields` |
| `email` empty, malformed (the registry's `EMAIL_PATTERN`) or over 254 characters | 400 | `request/invalid-email` |
| `type` not in the manifest | 400 | `request/invalid-type` |
| `details` over 2000 characters (line breaks count as one) | 400 | `request/details-too-long` |
| `website` (honeypot) not empty | 303 | nothing stored, nothing sent |
| The store rejects | 503, `Retry-After: 60` | `server/store-failed`; nothing sent |
| Stored | 303 to `<path>?request=<id>` | |
| Another path / method | 404 / 405 (`Allow: GET, HEAD, POST`) | `request/not-found` / `request/method-not-allowed` |

Refusals are `text/plain` with the code only, never the input. Every answer has `Cache-Control: no-store`, `Referrer-Policy: no-referrer` and `X-Content-Type-Options: nosniff`. The `locale` falls back to the default locale. `details` has CRLF normalised and whitespace trimmed; an empty one is stored as `NULL`.

After storing, in this order and never throwing:

1. With `receipts` and a consent id in the cookie, count the matching receipts.
2. Send the notification to `notify`, Reply-To the requester; on success set `notifiedAt`.
3. With `requesterEmail`, and unless the address is on a reserved `.invalid` domain: reserve a confirmation slot, first for the address (lowercased, without a `+tag`, as an HMAC) and then in all. Send the link only if both slots are reserved. If the cap refuses, release the address's slot and call `onConfirmationCapReached`. On success set `confirmationSentAt`.

With a second argument `{ waitUntil }`, these steps run after the answer.

### GET

| Request | Answer |
| --- | --- |
| `<path>` | The form page, by `Accept-Language`. |
| `<path>?request=<anything>` | The received page, the same for every id. |
| `<path>?confirm=<token>` | A valid, unexpired token: the confirm page, with a button that POSTs `confirm=<token>`. Anything else: 303 to `?status=link-invalid`. Changes nothing. |
| `<path>?status=confirmed` / `?status=link-invalid` | Those pages. |

Pages are served with `Content-Security-Policy: default-src 'none'; style-src 'self'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`.

### The confirming POST

`POST <path>` with the single field `confirm`, Origin checked like the form. A valid token of a request that is still `received` confirms it and answers 303 to `?status=confirmed`. Anything else, including a second use of the same token, answers 303 to `?status=link-invalid`. Tokens are `<id>.<expiry>.<HMAC-SHA-256, base64url>` and are compared by WebCrypto's `verify`.

## SubjectRequestRecord

`id` (32 hex digits, random), `type`, `email` (as typed, trimmed), `emailHash`, `subjectHash` (or `null`), `details`, `locale`, `policyHash`, `receivedAt`, `dueAt` (one calendar month later: 31 January is due 28 or 29 February), `extendedDueAt` and `extensionReason`, `status` (`received`, `confirmed`, `closed`), `confirmedAt`, `closedAt`, `outcome`, `notifiedAt`, `confirmationSentAt`. No IP address, user agent or header.

## SubjectRequestStore

| Method | |
| --- | --- |
| `create(record)` | The one write the handler waits for. |
| `getById(id)` | |
| `confirm(id, at)` | `received` to `confirmed`; `false` otherwise. |
| `markNotified(id, at)`, `markConfirmationSent(id, at)` | |
| `extend(id, { dueAt, reason })`, `close(id, { outcome, at })` | For the person answering. |
| `listOpen()`, `listDueBefore(at)` | Open requests, oldest first; by the extended deadline if any. |
| `deleteClosedBefore(at)` | Retention. |
| `reserveConfirmationSlot(key, { at, windowStart, cap })` | Atomic: of concurrent calls, only as many as `cap` win per window. Also deletes ended per-address windows. |
| `releaseConfirmationSlot(key, at)` | Undoes a reservation that sent nothing. |
| `deleteExpiredConfirmationSlots(windowStart)` | Never the global `*` row. |

Updates never touch a closed request. `createMemorySubjectRequestStore()` is for tests and local development. `createD1SubjectRequestStore(env.DB)` is the D1 store.

## The D1 tables

`migrations/0002_subject_requests.sql`, a `STRICT` table `subject_requests` with the record's columns in snake case, `CHECK`s on every format (hex ids and hashes, `type`, `status`, the length of `email` and `details`, an extension with its reason, a closed request with its outcome), indexes on `(status, due_at)`, `email_hash` and `closed_at`, and three triggers:

- `subject_requests_content_fixed` refuses any change to `id`, `type`, `email`, `email_hash`, `subject_hash`, `details`, `locale`, `policy_hash`, `received_at` and `due_at`;
- `subject_requests_closed_fixed` refuses any change to a closed request;
- `subject_requests_confirmation_once` refuses changing a confirmation time once set.

`subject_request_confirmation_slots` (`rate_key`, `window_start`, `count`) holds the rate limits. `rate_key` is `*` or 64 hex digits (an HMAC, never an address). A reservation is one `INSERT … ON CONFLICT DO UPDATE … WHERE`; only a call whose statement changes the row may send.

## remindDueRequests and sweepClosedRequests

```ts
await sweepClosedRequests({ store, retention: requestsManifest.retention });
await remindDueRequests({ store, sender, manifest: requestsManifest, from, withinDays: 7 });
```

`remindDueRequests` sends one email to `notify` (or `notify` given as an option). It lists the open requests that are overdue, due within `withinDays`, or never notified. It sends nothing when there are none, and rejects when sending fails. `sweepClosedRequests` deletes requests closed longer ago than `retention` (`<n>d`, or `<n>y` in calendar years), and the rate-limit windows that have ended.

## findReceipts and eraseReceipts

```ts
await findReceipts(receiptStore, request.subjectHash);
await findReceipts(receiptStore, consentId, { hmacKey });
await eraseReceipts(receiptStore, consentId, { hmacKey });   // resolves to how many
```

A 64-hex-digit argument is taken as a subject hash; anything else is hashed as a consent id. Both functions need a store with `listBySubject` / `deleteBySubject`, which the memory and D1 receipt stores have. The handlers never call them.

## Email adapters

`EmailSender` is `{ send({ to, from, replyTo?, subject, text }): Promise<void> }`. The adapters refuse a line break in `to`, `from`, `replyTo` or `subject` before sending. A refusal becomes an `EmailSendError` that names the provider and its status or code, never the message or the response body.

| Adapter | Request | Checked against |
| --- | --- | --- |
| `cloudflareEmailSender(env.BINDING)` | The `send_email` binding's structured `send({ from, to, subject, text, replyTo })`. No MIME, no `cloudflare:email` import. Errors keep the binding's `code` (e.g. `E_SENDER_NOT_VERIFIED`). | [Workers API](https://developers.cloudflare.com/email-service/api/send-emails/workers-api/), [send bindings](https://developers.cloudflare.com/email-service/configuration/send-bindings/), [send emails from Workers](https://developers.cloudflare.com/email-routing/email-workers/send-email-workers/) |
| `resendEmailSender({ apiKey })` | `POST https://api.resend.com/emails`, `Authorization: Bearer`, `User-Agent: consent-kit` (Resend refuses requests without one), JSON `{ from, to: [to], subject, text, reply_to }`. Success is any 2xx. | [Send email](https://resend.com/docs/api-reference/emails/send-email) |
| `postmarkEmailSender({ serverToken, messageStream? })` | `POST https://api.postmarkapp.com/email`, `Accept` and `Content-Type: application/json`, `X-Postmark-Server-Token`, JSON `{ From, To, Subject, TextBody, ReplyTo, MessageStream }` (default stream `outbound`). Success is 200 with `ErrorCode: 0`. | [Email API](https://postmarkapp.com/developer/api/email-api) |

The request shapes were checked against those pages in November 2026. Not verified: how Resend's error body is shaped (the adapter reads only the status), and whether local `wrangler dev` delivers through the structured binding call (the Workers test does not depend on it: a failed notification leaves the request stored and un-notified).
