@consent-kit/server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 consent-kit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # @consent-kit/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The receiving end of consent-kit's [consent receipts](https://consent-kit.com/docs/project/#consent-receipts). The banner POSTs one receipt per decision. This package checks the receipt against the policy the site was built from, replaces the consent id with a keyed hash and appends the receipt to storage. It also ships an adapter and a migration for Cloudflare D1.
4
+
5
+ - `createReceiptHandler(options)` returns `(request: Request) => Promise<Response>`. It is built on the Fetch API alone, with no framework and no Cloudflare import, so it runs in a Worker, in Deno, in Bun or in Node 22+.
6
+ - `ReceiptStore` is the storage interface. Its one method is `append`: no method changes or removes a receipt.
7
+ - `createD1ReceiptStore(env.DB)` is a `ReceiptStore` over D1, created by `migrations/0001_consent_receipts.sql`.
8
+
9
+ It also receives [data subject requests](https://consent-kit.com/docs/manual/concepts/subject-requests/). See [Data subject requests](#data-subject-requests) below.
10
+
11
+ A complete Worker, with `wrangler.toml` and the deploy steps, is in [`examples/cloudflare-receipts`](https://github.com/pavelpascari/consent-kit/tree/main/examples/cloudflare-receipts).
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { createD1ReceiptStore, createReceiptHandler, type D1DatabaseLike } from '@consent-kit/server';
17
+ // Written by `consent-kit build` next to the site's other generated files.
18
+ import manifest from './consent.gen/receipts.manifest.gen.json';
19
+
20
+ interface Env {
21
+ DB: D1DatabaseLike;
22
+ RECEIPTS_HMAC_KEY?: string;
23
+ }
24
+
25
+ let handle: ((request: Request) => Promise<Response>) | undefined;
26
+
27
+ export default {
28
+ fetch(request: Request, env: Env) {
29
+ handle ??= createReceiptHandler({
30
+ store: createD1ReceiptStore(env.DB),
31
+ hmacKey: env.RECEIPTS_HMAC_KEY,
32
+ allowedOrigins: ['https://www.example.com'],
33
+ manifest,
34
+ });
35
+ return handle(request);
36
+ },
37
+ };
38
+ ```
39
+
40
+ | Option | |
41
+ | --- | --- |
42
+ | `store` | Where accepted receipts go. If `append` rejects, the answer is 503 and nothing is stored. |
43
+ | `hmacKey` | The key the consent id is hashed with. A string counts as its UTF-8 bytes, and it must be at least 32 bytes. Keep it in a secret (`wrangler secret put RECEIPTS_HMAC_KEY`), and keep a copy: receipts can only be found by consent id with the same key. |
44
+ | `allowedOrigins` | The site's origins, exactly as browsers send them in `Origin`, e.g. `https://www.example.com`. |
45
+ | `manifest` | The `receipts.manifest.gen.json` from `consent-kit build`. It is checked when the handler is created. An array of several manifests is also accepted, for example when one endpoint receives the receipts of several sites. |
46
+ | `path` | The path the handler answers. Default: the path of the manifest's `endpoint`. |
47
+ | `allowMissingOrigin` | Accept a POST without an `Origin` header. Default `false`. |
48
+ | `maxClockSkewMs` | How far the browser's timestamp may be from the server's clock. Default one day. |
49
+ | `maxSupersededAgeMs` | How long after a later release replaced it a policy is still accepted. Default unbounded. See [The manifest](#the-manifest). |
50
+ | `now`, `onStoreError` | The server's clock (default `new Date()`) and the store-failure report (default `console.error`, which never includes the receipt). |
51
+
52
+ `createReceiptHandler` throws straight away if the key is missing or shorter than 32 bytes, if a manifest is malformed, if two manifests disagree about a policy, or if an allowed origin is not an origin. A Worker built this way fails every request with a 500. It never accepts receipts it cannot store safely.
53
+
54
+ ## The manifest
55
+
56
+ `consent-kit build` writes `receipts.manifest.gen.json`, but only when the registry declares `receipts.endpoint`:
57
+
58
+ ```json
59
+ {
60
+ "manifestVersion": 1,
61
+ "endpoint": "/consent-receipts",
62
+ "policies": [
63
+ { "consentPurposes": { "analytics": 2, "media": 1 }, "otherPurposes": ["essential"], "policyHash": "…", "revision": 2, "supersededAt": null },
64
+ { "consentPurposes": { "analytics": 2, "media": 1 }, "otherPurposes": ["essential"], "policyHash": "…", "revision": 2, "supersededAt": null },
65
+ { "consentPurposes": { "analytics": 1, "media": 1 }, "otherPurposes": ["essential"], "policyHash": "…", "revision": 1, "supersededAt": "2026-06-01T00:00:00.000Z" }
66
+ ]
67
+ }
68
+ ```
69
+
70
+ The first policy belongs to the build: the hash, revision and purpose versions that its generated CookieConsent module sends. After it come all the released policies in the `history` of `privacy.lock.json`, newest first. That covers every policy a page could still be open or cached on. Releases that sent no receipts (an opt-out, or no `receipts` section) are left out. A receipt is checked against the versions of its own policy, so an old policy's receipt must carry the old versions, and a mix of one policy's hash and another's versions is refused.
71
+
72
+ A policy is its hash at a revision. The same registry released at two revisions is listed twice. A policy released twice at the same revision (a change that was later reverted) is listed once. If several manifests passed together list the same policy, its purposes must agree, or the handler refuses to start.
73
+
74
+ `supersededAt` is when the next release replaced the policy. It is `null` for the build's own policy, and for the latest release until this build is deployed, because nobody can tell when that will be. By default the handler ignores it: every listed policy is accepted for as long as it is listed. A receipt for a policy that was replaced long ago is unusual, since some page must have been open, or served from a cache, all that time. It is still harmless: the receipt names a real policy with that policy's own purposes, and the row keeps the policy hash, so the age is visible to anyone who reads it. Refusing it would lose a real decision. To refuse it anyway, set `maxSupersededAgeMs`, for example 30 days. A receipt for a policy replaced longer ago is then answered 422 `receipt/policy-superseded`.
75
+
76
+ The bound is an option of the receiving end and not a field of the registry. It says nothing to visitors and changes nothing in the documents, so it has no place in the policy hash or the diff.
77
+
78
+ Rebuild and redeploy the receiving end with every release of the registry, just as you do the site.
79
+
80
+ ## What is checked
81
+
82
+ A receipt is stored only if every check passes. Anything else gets a 4xx answer and nothing is written.
83
+
84
+ | Check | Status, `error` |
85
+ | --- | --- |
86
+ | The path is the receipt path | 404 `request/not-found` |
87
+ | The method is `POST`. Other methods, `OPTIONS` included, get `Allow: POST`. | 405 `request/method-not-allowed` |
88
+ | `Origin` is present (see below) and in `allowedOrigins`. The literal `null` is never allowed. | 403 `request/origin-missing`, `request/origin-forbidden` |
89
+ | `Content-Type` is `text/plain` (what `sendBeacon` sends) or `application/json`. A charset, if given, is UTF-8. | 415 `request/unsupported-media-type` |
90
+ | The body is at most 4 KB. The stream is read up to that limit, whatever `Content-Length` says. | 413 `request/body-too-large` |
91
+ | The body is JSON in valid UTF-8 | 400 `request/invalid-json` |
92
+ | It has exactly the seven fields of a receipt, and each `accepted` / `rejected` entry has exactly `purpose` and `version` | 400 `receipt/unexpected-fields`, `receipt/invalid-purposes` |
93
+ | `consentId` has 1 to 128 URL-safe characters, `event` is `first` or `change`, `policyHash` is 64 lowercase hex digits, `revision` is a non-negative integer, each version is a positive integer | 400 `receipt/invalid-…` |
94
+ | `timestamp` is exactly what `toISOString()` writes and names a real date | 400 `receipt/invalid-timestamp` |
95
+ | `timestamp` is within `maxClockSkewMs` of the server's clock | 422 `receipt/timestamp-out-of-range` |
96
+ | `policyHash` and `revision` name a policy in the manifest | 422 `receipt/unknown-policy`, `receipt/revision-mismatch` |
97
+ | That policy was not replaced longer ago than `maxSupersededAgeMs` (unbounded by default) | 422 `receipt/policy-superseded` |
98
+ | Every purpose is a consent purpose of that policy, at that policy's version | 422 `receipt/unknown-purpose`, `receipt/not-consent-purpose`, `receipt/version-mismatch` |
99
+ | No purpose appears twice, or in both lists | 400 `receipt/duplicate-purpose`, `receipt/conflicting-purpose` |
100
+ | Together, `accepted` and `rejected` hold every consent purpose of that policy | 422 `receipt/missing-purpose` |
101
+ | The store accepted the row | 503 `server/store-failed` |
102
+
103
+ Success is 204 with no body. An error is `{"error": "<code>"}` and never echoes the input. Every answer carries `Cache-Control: no-store` and `Vary: Origin`.
104
+
105
+ The choices behind these checks:
106
+
107
+ - **Versions.** A version is valid only if it is the version that the receipt's own policy (`policyHash` + `revision`) gives the purpose. "Older" is not a property of a version on its own: an older version is accepted with the older release it came from, and the manifest lists every release. The current version paired with an old hash is a contradiction and is refused.
108
+ - **Missing purposes.** The browser always sends every consent purpose, each in one of the two lists. A receipt that leaves a purpose out proves nothing about it, so it is refused.
109
+ - **Policy hash.** The server knows only the hashes in its manifest, which the build derives from the registry. An unknown hash is refused, because storing a hash the server cannot vouch for would make the record claim a policy nobody can produce.
110
+ - **Timestamps.** The browser's clock is stored as the client's claim (`client_timestamp`). The server's clock (`received_at`) is the time of record. A receipt more than a day off is refused: the server cannot tell a broken clock from a replayed or fabricated body, and a row whose own two times contradict each other is weak proof. The banner fires the beacon as the decision is made, so honest receipts arrive within seconds. Set `maxClockSkewMs: Infinity` to store any well-formed timestamp.
111
+ - **Missing `Origin`.** Browsers send `Origin` with every `sendBeacon` and `fetch` POST, same-origin included. A request without one did not come from the banner, so it is refused by default. The check is no authentication, since a non-browser client can send any `Origin`. What it stops is other sites' pages posting into your record from visitors' browsers.
112
+ - **CORS.** A beacon is a no-CORS request with a CORS-safelisted type (`text/plain`), so it needs no preflight and its answer is never read. The `fetch` fallback (`keepalive`, same type) needs no preflight either. To let a cross-origin page read the answer, the handler sets `Access-Control-Allow-Origin` to the request's origin when that origin is allowed. It never sends `*` or `Allow-Credentials`, and it answers no preflight, because none is ever needed.
113
+
114
+ ## What is stored
115
+
116
+ `migrations/0001_consent_receipts.sql` (apply it with `wrangler d1 migrations apply <DATABASE>`) creates one `STRICT` table:
117
+
118
+ | Column | |
119
+ | --- | --- |
120
+ | `id` | `INTEGER PRIMARY KEY AUTOINCREMENT`. Ids are never reused, even after rows are deleted. |
121
+ | `subject_hash` | HMAC-SHA-256(key, consentId) in lowercase hex. The consent id itself is never stored. |
122
+ | `event` | `first` or `change` |
123
+ | `accepted`, `rejected` | JSON arrays of `{"purpose", "version"}`, sorted by purpose. They can be queried with `json_each`. |
124
+ | `policy_hash`, `revision` | The policy the visitor decided on |
125
+ | `client_timestamp` | The browser's claim, ISO 8601 UTC |
126
+ | `received_at` | The server's clock, ISO 8601 UTC |
127
+
128
+ Indexes on `subject_hash` (for subject requests) and `received_at` (for retention). A trigger refuses every `UPDATE`. Nothing from the request beyond the receipt is stored: no IP address, user agent, headers, URL or raw body. CHECK constraints enforce the shape of the hashes, the event and the JSON columns.
129
+
130
+ The table is append-only. `DELETE` is left to the database on purpose, because the only two legitimate deletions are planned: a retention sweep (old rows, by `received_at`) and erasure on a subject request (one visitor's rows, found by hashing the consent id they present). Neither is built yet. Both need the same HMAC key, so keep it as long as the receipts. Rotating it makes older rows unreachable by consent id.
131
+
132
+ ## Limits
133
+
134
+ - No rate limiting or bot filtering. Use Cloudflare's rate limiting rules or WAF on the route. The endpoint is unauthenticated by nature: anyone can send a well-formed receipt with a made-up consent id. The record proves what was received, not who sent it.
135
+ - JSON with duplicate keys is read the way `JSON.parse` reads it (the last key wins).
136
+ - No retries on either side. A receipt lost to a network error is not re-sent; the consent cookie in the browser still holds the decision.
137
+
138
+ ## Data subject requests
139
+
140
+ `createSubjectRequestHandler(options)` answers the request form that `consent-kit build` generates, on the site's own domain. It takes a same-origin POST of `application/x-www-form-urlencoded`, up to 4 KB, and checks the email, the type, the details (at most 2000 characters) and a honeypot. It hashes the consent id in `cc_cookie` with the receipts' key, so the request joins that browser's receipts. It stores the request first and only then emails the controller's mailbox. Every answer is the same 303 to `<path>?request=<id>`. The complete reference is [the subject requests reference](https://consent-kit.com/docs/manual/reference/subject-requests/).
141
+
142
+ ```ts
143
+ import { cloudflareEmailSender, createD1ReceiptStore, createD1SubjectRequestStore, createSubjectRequestHandler } from '@consent-kit/server';
144
+ import requestsManifest from './consent.gen/subject-requests.manifest.gen.json';
145
+
146
+ const handle = createSubjectRequestHandler({
147
+ store: createD1SubjectRequestStore(env.DB),
148
+ receipts: createD1ReceiptStore(env.DB),
149
+ hmacKey: env.RECEIPTS_HMAC_KEY,
150
+ allowedOrigins: ['https://www.example.com'],
151
+ manifest: requestsManifest,
152
+ notifySender: cloudflareEmailSender(env.PRIVACY_EMAIL),
153
+ from: 'Privacy requests <requests@example.com>',
154
+ });
155
+ // fetch(request, env, ctx) { return handle(request, ctx); } // emails after the answer
156
+ ```
157
+
158
+ - **Failures.** A store failure is a 503 (`server/store-failed`): the visitor learns that the request was not received, and nothing is emailed. An email failure goes to `onEmailError` with the request id only. The request stays stored with `notifiedAt` empty, and `remindDueRequests` lists it every day until it is closed.
159
+ - **Confirmation** (only when the registry has `requesterEmail`). The link is signed with HMAC, valid for 7 days and used once. Opening it shows a page whose button POSTs the token back; only that POST, same-origin, confirms. Each address gets at most one email an hour, reserved atomically before sending, keyed by an HMAC of the address lowercased and without a `+tag`. All addresses together get at most `maxConfirmationsPerHour` (default 100). `onConfirmationCapReached` reports the cap without personal data. Rate rows are deleted once their hour is over. Put a Cloudflare rate-limiting rule in front of the route: this package stores no IP addresses.
160
+ - **Storage.** `SubjectRequestStore`, with `createMemorySubjectRequestStore` and `createD1SubjectRequestStore` over `migrations/0002_subject_requests.sql`. The table is STRICT, and its triggers keep a request's content fixed and a closed request untouched.
161
+ - **Tasks.** `remindDueRequests({ store, sender, manifest, from, withinDays: 7 })` and `sweepClosedRequests({ store, retention })` run from a Cron Trigger. `findReceipts` and `eraseReceipts` are for the person answering; no handler calls them.
162
+
163
+ ### Email adapters
164
+
165
+ All of them use `fetch` or a Worker binding, and none of them logs a message, an address or a response body.
166
+
167
+ | Adapter | Verified against |
168
+ | --- | --- |
169
+ | `cloudflareEmailSender(env.SEND_EMAIL)`: the `send_email` binding's structured `send({ from, to, subject, text, replyTo })`, without MIME and without importing `cloudflare:email`. | <https://developers.cloudflare.com/email-service/api/send-emails/workers-api/>, <https://developers.cloudflare.com/email-service/configuration/send-bindings/>, <https://developers.cloudflare.com/email-routing/email-workers/send-email-workers/> (Email Sending public beta: <https://developers.cloudflare.com/changelog/post/2026-04-16-email-sending-public-beta/>) |
170
+ | `resendEmailSender({ apiKey })`: `POST https://api.resend.com/emails`, bearer key, `User-Agent` set, `{ from, to: [to], subject, text, reply_to }`. | <https://resend.com/docs/api-reference/emails/send-email> |
171
+ | `postmarkEmailSender({ serverToken })`: `POST https://api.postmarkapp.com/email`, `X-Postmark-Server-Token`, `{ From, To, Subject, TextBody, ReplyTo, MessageStream }`, success only with `ErrorCode: 0`. | <https://postmarkapp.com/developer/api/email-api> |
172
+
173
+ These were checked against the official pages in November 2026, and the tests assert the exact request each adapter sends. Not verified: the JSON shape of Resend's error body (the adapter reads only the status), and delivery through the structured binding call under local `wrangler dev`.