@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 +21 -0
- package/README.md +172 -2
- package/dist/index.d.ts +691 -0
- package/dist/index.js +1152 -0
- package/migrations/0001_consent_receipts.sql +38 -0
- package/migrations/0002_subject_requests.sql +91 -0
- package/package.json +59 -3
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The receipt manifest: what `consent-kit build` writes to `receipts.manifest.gen.json`
|
|
3
|
+
* when the registry declares `receipts.endpoint`. The handler accepts a receipt only for a
|
|
4
|
+
* policy listed in it, with exactly that policy's consent purposes and versions.
|
|
5
|
+
*
|
|
6
|
+
* The shape is declared again here (the compiler has its own copy) so that this package
|
|
7
|
+
* depends on nothing that runs at build time.
|
|
8
|
+
*/
|
|
9
|
+
/** One policy receipts are accepted for: what a build's CookieConsent module sends. */
|
|
10
|
+
interface ReceiptPolicy {
|
|
11
|
+
/** `policySnapshot(registry).hash`: lowercase hex SHA-256. */
|
|
12
|
+
readonly policyHash: string;
|
|
13
|
+
/** CookieConsent's revision of the build. */
|
|
14
|
+
readonly revision: number;
|
|
15
|
+
/** Consent purpose id to its version: every receipt names each one exactly once. */
|
|
16
|
+
readonly consentPurposes: Readonly<Record<string, number>>;
|
|
17
|
+
/** Ids of the purposes with another lawful basis: never part of a receipt. */
|
|
18
|
+
readonly otherPurposes: readonly string[];
|
|
19
|
+
/**
|
|
20
|
+
* When a later release replaced this policy (ISO 8601), or `null` while it may still be
|
|
21
|
+
* live. Only `maxSupersededAgeMs` reads it.
|
|
22
|
+
*/
|
|
23
|
+
readonly supersededAt: string | null;
|
|
24
|
+
}
|
|
25
|
+
interface ReceiptManifest {
|
|
26
|
+
readonly manifestVersion: 1;
|
|
27
|
+
/** `receipts.endpoint`, exactly as the registry declares it. */
|
|
28
|
+
readonly endpoint: string;
|
|
29
|
+
/** The policy of the build first, then every released policy that sent receipts, newest first. */
|
|
30
|
+
readonly policies: readonly ReceiptPolicy[];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Checks a manifest (typically an imported `receipts.manifest.gen.json`, whose type is
|
|
34
|
+
* wider than this) and returns it typed. Throws on anything malformed: a handler must not
|
|
35
|
+
* start on a manifest it cannot trust.
|
|
36
|
+
*/
|
|
37
|
+
declare function parseReceiptManifest(value: unknown): ReceiptManifest;
|
|
38
|
+
|
|
39
|
+
interface ReceiptPurpose {
|
|
40
|
+
purpose: string;
|
|
41
|
+
version: number;
|
|
42
|
+
}
|
|
43
|
+
/** A receipt that passed every check, as `@consent-kit/storage` sends it. Purposes sorted by id. */
|
|
44
|
+
interface Receipt {
|
|
45
|
+
consentId: string;
|
|
46
|
+
event: 'first' | 'change';
|
|
47
|
+
accepted: ReceiptPurpose[];
|
|
48
|
+
rejected: ReceiptPurpose[];
|
|
49
|
+
policyHash: string;
|
|
50
|
+
revision: number;
|
|
51
|
+
timestamp: string;
|
|
52
|
+
}
|
|
53
|
+
/** Why a receipt is refused. Each is answered with `{"error": code}` and nothing is stored. */
|
|
54
|
+
type ReceiptProblem =
|
|
55
|
+
/** Not exactly the seven fields of a receipt. */
|
|
56
|
+
'receipt/unexpected-fields' | 'receipt/invalid-consent-id' | 'receipt/invalid-event' | 'receipt/invalid-purposes' | 'receipt/invalid-policy-hash' | 'receipt/invalid-revision' | 'receipt/invalid-timestamp'
|
|
57
|
+
/** The timestamp is further from the server's clock than the handler allows. */
|
|
58
|
+
| 'receipt/timestamp-out-of-range'
|
|
59
|
+
/** No policy in the manifest has this hash. */
|
|
60
|
+
| 'receipt/unknown-policy'
|
|
61
|
+
/** The hash is known, with another revision. */
|
|
62
|
+
| 'receipt/revision-mismatch'
|
|
63
|
+
/** The policy was replaced longer ago than the handler allows (`maxSupersededAgeMs`). */
|
|
64
|
+
| 'receipt/policy-superseded' | 'receipt/unknown-purpose'
|
|
65
|
+
/** A purpose of the policy whose lawful basis is not consent. */
|
|
66
|
+
| 'receipt/not-consent-purpose'
|
|
67
|
+
/** Not the version this policy has for the purpose. */
|
|
68
|
+
| 'receipt/version-mismatch'
|
|
69
|
+
/** A purpose listed twice in `accepted` or twice in `rejected`. */
|
|
70
|
+
| 'receipt/duplicate-purpose'
|
|
71
|
+
/** A purpose both accepted and rejected. */
|
|
72
|
+
| 'receipt/conflicting-purpose'
|
|
73
|
+
/** A consent purpose of the policy in neither list. */
|
|
74
|
+
| 'receipt/missing-purpose';
|
|
75
|
+
type ReceiptCheck = {
|
|
76
|
+
ok: true;
|
|
77
|
+
receipt: Receipt;
|
|
78
|
+
} | {
|
|
79
|
+
ok: false;
|
|
80
|
+
problem: ReceiptProblem;
|
|
81
|
+
};
|
|
82
|
+
interface CheckContext {
|
|
83
|
+
/** By `policyKey(hash, revision)`. */
|
|
84
|
+
policies: ReadonlyMap<string, ReceiptPolicy>;
|
|
85
|
+
/** Every policy hash of the manifest, whatever its revision. */
|
|
86
|
+
hashes: ReadonlySet<string>;
|
|
87
|
+
now: Date;
|
|
88
|
+
maxClockSkewMs: number;
|
|
89
|
+
/** How long after a later release replaced it a policy is still accepted, in ms. */
|
|
90
|
+
maxSupersededAgeMs: number;
|
|
91
|
+
}
|
|
92
|
+
/** Checks a parsed JSON body against the manifest. Pure. */
|
|
93
|
+
declare function checkReceipt(body: unknown, context: CheckContext): ReceiptCheck;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* One stored receipt: the proof of one decision. It holds no personal data beyond
|
|
97
|
+
* `subjectHash`; the `consentId`, IP address, user agent, headers, URL and raw body are
|
|
98
|
+
* never part of it.
|
|
99
|
+
*/
|
|
100
|
+
interface StoredReceipt {
|
|
101
|
+
/** HMAC-SHA-256(key, consentId), lowercase hex. */
|
|
102
|
+
subjectHash: string;
|
|
103
|
+
event: 'first' | 'change';
|
|
104
|
+
/** Sorted by purpose. */
|
|
105
|
+
accepted: readonly ReceiptPurpose[];
|
|
106
|
+
/** Sorted by purpose. */
|
|
107
|
+
rejected: readonly ReceiptPurpose[];
|
|
108
|
+
policyHash: string;
|
|
109
|
+
revision: number;
|
|
110
|
+
/** The browser's claim, ISO 8601 UTC. */
|
|
111
|
+
clientTimestamp: string;
|
|
112
|
+
/** The server's clock, ISO 8601 UTC: the time of record. */
|
|
113
|
+
receivedAt: string;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Where receipts go. Append-only by design: there is no method that changes a receipt.
|
|
117
|
+
* Rejecting the promise makes the handler answer 503 and store nothing.
|
|
118
|
+
*/
|
|
119
|
+
interface ReceiptStore {
|
|
120
|
+
append(receipt: StoredReceipt): Promise<void>;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* A receipt store that can also be read and erased by subject, for answering data subject
|
|
124
|
+
* requests (`findReceipts`, `eraseReceipts`). The receipt handler never reads or deletes; the
|
|
125
|
+
* subject request handler only counts, for the notification.
|
|
126
|
+
*/
|
|
127
|
+
interface SubjectReceiptStore extends ReceiptStore {
|
|
128
|
+
/** Every receipt of one subject hash, in the order received. */
|
|
129
|
+
listBySubject(subjectHash: string): Promise<StoredReceipt[]>;
|
|
130
|
+
/** Deletes every receipt of one subject hash; resolves to how many. */
|
|
131
|
+
deleteBySubject(subjectHash: string): Promise<number>;
|
|
132
|
+
}
|
|
133
|
+
/** A store that keeps receipts in an array, for tests and local development. */
|
|
134
|
+
declare function createMemoryReceiptStore(): SubjectReceiptStore & {
|
|
135
|
+
readonly receipts: readonly StoredReceipt[];
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/** The largest body read, in bytes. A receipt of a registry with twenty purposes is about 1.5 KB. */
|
|
139
|
+
declare const MAX_RECEIPT_BYTES = 4096;
|
|
140
|
+
/** How far the browser's timestamp may be from the server's clock by default: one day. */
|
|
141
|
+
declare const DEFAULT_MAX_CLOCK_SKEW_MS: number;
|
|
142
|
+
interface ReceiptHandlerOptions {
|
|
143
|
+
/** Where accepted receipts are appended, e.g. `createD1ReceiptStore(env.DB)`. */
|
|
144
|
+
store: ReceiptStore;
|
|
145
|
+
/**
|
|
146
|
+
* The HMAC key `consentId` is hashed with (a string is used as its UTF-8 bytes), at least
|
|
147
|
+
* 32 bytes. Keep it secret (a Worker secret) and keep it as long as the receipts: subject
|
|
148
|
+
* requests find a visitor's receipts by hashing their consent id with it.
|
|
149
|
+
*/
|
|
150
|
+
hmacKey: string | Uint8Array | undefined;
|
|
151
|
+
/**
|
|
152
|
+
* The origins of the site's pages, exactly as browsers send them in `Origin`
|
|
153
|
+
* (`https://www.example.com`, no path, no trailing slash).
|
|
154
|
+
*/
|
|
155
|
+
allowedOrigins: readonly string[];
|
|
156
|
+
/**
|
|
157
|
+
* The `receipts.manifest.gen.json` that `consent-kit build` writes, or several of them (to
|
|
158
|
+
* keep accepting receipts from pages built before an earlier release). Checked at once.
|
|
159
|
+
*/
|
|
160
|
+
manifest: unknown;
|
|
161
|
+
/**
|
|
162
|
+
* The path the handler answers; every other path is a 404. Default: the path of the
|
|
163
|
+
* manifest's `endpoint`.
|
|
164
|
+
*/
|
|
165
|
+
path?: string;
|
|
166
|
+
/**
|
|
167
|
+
* Accept a POST that carries no `Origin` header. Default `false`: every browser sends
|
|
168
|
+
* `Origin` with a beacon or a `fetch` POST, so a request without one is not from the banner.
|
|
169
|
+
*/
|
|
170
|
+
allowMissingOrigin?: boolean;
|
|
171
|
+
/** How far the browser's timestamp may be from `now()`, in ms. Default one day. */
|
|
172
|
+
maxClockSkewMs?: number;
|
|
173
|
+
/**
|
|
174
|
+
* How long after a later release replaced it a policy is still accepted, in ms. Default
|
|
175
|
+
* unbounded: every released policy in the manifest is accepted, since a page built from it
|
|
176
|
+
* can stay open or cached for as long as it likes, and such a receipt is still a real
|
|
177
|
+
* decision on a real policy. Set it to refuse receipts from long-replaced policies.
|
|
178
|
+
*/
|
|
179
|
+
maxSupersededAgeMs?: number;
|
|
180
|
+
/** The server's clock. Default `() => new Date()`. */
|
|
181
|
+
now?: () => Date;
|
|
182
|
+
/** Called when the store fails (the request is answered 503). Default: `console.error`, without the receipt. */
|
|
183
|
+
onStoreError?: (error: unknown) => void;
|
|
184
|
+
}
|
|
185
|
+
/** Every error code a response can carry, as `{"error": code}`. */
|
|
186
|
+
type ReceiptErrorCode = 'request/not-found' | 'request/method-not-allowed' | 'request/origin-missing' | 'request/origin-forbidden' | 'request/unsupported-media-type' | 'request/body-too-large' | 'request/invalid-json' | ReceiptProblem | 'server/store-failed' | 'server/error';
|
|
187
|
+
/**
|
|
188
|
+
* Builds the receiving end of consent receipts: a Fetch API handler that answers `POST` to
|
|
189
|
+
* the receipt path with 204 once the receipt is valid and appended to the store, and with a
|
|
190
|
+
* 4xx and `{"error": code}` (never echoing the input) otherwise, storing nothing.
|
|
191
|
+
*
|
|
192
|
+
* Throws at once on a missing or short HMAC key, a malformed manifest or allowed origin, so
|
|
193
|
+
* that a misconfigured Worker fails every request instead of accepting receipts it cannot
|
|
194
|
+
* store safely.
|
|
195
|
+
*/
|
|
196
|
+
declare function createReceiptHandler(options: ReceiptHandlerOptions): (request: Request) => Promise<Response>;
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* The part of Cloudflare's `D1Database` these adapters use. Declared structurally so that
|
|
200
|
+
* nothing here imports Cloudflare's types; a real `env.DB` binding satisfies it.
|
|
201
|
+
*/
|
|
202
|
+
interface D1DatabaseLike {
|
|
203
|
+
prepare(query: string): {
|
|
204
|
+
bind(...values: unknown[]): {
|
|
205
|
+
/** D1 resolves to `{ meta: { changes } }` among others. */
|
|
206
|
+
run(): Promise<unknown>;
|
|
207
|
+
all<T = Record<string, unknown>>(): Promise<{
|
|
208
|
+
results: T[];
|
|
209
|
+
}>;
|
|
210
|
+
};
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
/** The table `migrations/0001_consent_receipts.sql` creates. */
|
|
214
|
+
declare const RECEIPTS_TABLE = "consent_receipts";
|
|
215
|
+
/**
|
|
216
|
+
* A receipt store over a D1 database (Cloudflare's SQLite) migrated with
|
|
217
|
+
* `migrations/0001_consent_receipts.sql`. The handler only ever INSERTs, one row per receipt;
|
|
218
|
+
* `accepted` and `rejected` are stored as JSON arrays. `listBySubject` and `deleteBySubject`
|
|
219
|
+
* serve the person who answers a subject request (`findReceipts`, `eraseReceipts`); nothing
|
|
220
|
+
* calls them on its own.
|
|
221
|
+
*/
|
|
222
|
+
declare function createD1ReceiptStore(db: D1DatabaseLike): SubjectReceiptStore;
|
|
223
|
+
|
|
224
|
+
/** The shortest HMAC key accepted, in bytes: the output size of SHA-256. */
|
|
225
|
+
declare const MIN_KEY_BYTES = 32;
|
|
226
|
+
/**
|
|
227
|
+
* Returns the function that turns a `consentId` into the subject hash that is stored in its
|
|
228
|
+
* place: HMAC-SHA-256(key, consentId) as lowercase hex, via WebCrypto. The same key always
|
|
229
|
+
* gives the same hash, which is what lets a later subject request (access or erasure by
|
|
230
|
+
* consent id) find a visitor's receipts; so the key must be kept as long as the receipts.
|
|
231
|
+
*
|
|
232
|
+
* A string key is used as its UTF-8 bytes. Throws at once when the key is missing or shorter
|
|
233
|
+
* than `MIN_KEY_BYTES`, so that a handler never starts without one.
|
|
234
|
+
*/
|
|
235
|
+
declare function subjectHasher(key: string | Uint8Array | undefined | null): (consentId: string) => Promise<string>;
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Sending email: one interface, and adapters for three providers. Each adapter speaks to its
|
|
239
|
+
* provider over `fetch` or a Worker binding, so it runs in a Cloudflare Worker (and in Deno,
|
|
240
|
+
* Bun or Node 20+) without an SDK. None of them logs a message, an address or a response body:
|
|
241
|
+
* an error says which provider failed and with which status or code, nothing else.
|
|
242
|
+
*
|
|
243
|
+
* Checked against the providers' documentation of 2026-11 (links in the package README).
|
|
244
|
+
*/
|
|
245
|
+
/** One plain-text email. Addresses are bare (`privacy@example.com`) or named (`Privacy <privacy@example.com>`). */
|
|
246
|
+
interface EmailMessage {
|
|
247
|
+
to: string;
|
|
248
|
+
from: string;
|
|
249
|
+
replyTo?: string;
|
|
250
|
+
subject: string;
|
|
251
|
+
text: string;
|
|
252
|
+
}
|
|
253
|
+
interface EmailSender {
|
|
254
|
+
/** Resolves once the provider accepted the message; rejects otherwise. */
|
|
255
|
+
send(message: EmailMessage): Promise<void>;
|
|
256
|
+
}
|
|
257
|
+
/** An email that was not accepted, with the provider and its status or error code. Never the message. */
|
|
258
|
+
declare class EmailSendError extends Error {
|
|
259
|
+
readonly provider: string;
|
|
260
|
+
readonly detail: string;
|
|
261
|
+
constructor(provider: string, detail: string);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The part of a Workers `send_email` binding this adapter uses: `send()` with a structured
|
|
265
|
+
* message. Declared structurally so nothing here imports Cloudflare's types.
|
|
266
|
+
*/
|
|
267
|
+
interface SendEmailBindingLike {
|
|
268
|
+
send(message: {
|
|
269
|
+
from: string;
|
|
270
|
+
to: string;
|
|
271
|
+
subject: string;
|
|
272
|
+
text: string;
|
|
273
|
+
replyTo?: string;
|
|
274
|
+
}): Promise<unknown>;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Sends through a Worker's `send_email` binding (`[[send_email]]` in wrangler.toml), with the
|
|
278
|
+
* structured form of `send()` that Cloudflare Email Service accepts: `{ from, to, subject,
|
|
279
|
+
* text, replyTo }`. No MIME is built and nothing is imported from `cloudflare:email`. The
|
|
280
|
+
* binding's restrictions apply: the sender must be on a domain set up for Email Service, and a
|
|
281
|
+
* `destination_address` or `allowed_destination_addresses` binding only reaches those
|
|
282
|
+
* addresses (bind the controller's mailbox for the notifications). A refusal is thrown by the
|
|
283
|
+
* binding as an error with a `code` such as `E_SENDER_NOT_VERIFIED`.
|
|
284
|
+
*/
|
|
285
|
+
declare function cloudflareEmailSender(binding: SendEmailBindingLike): EmailSender;
|
|
286
|
+
interface ResendOptions {
|
|
287
|
+
/** A Resend API key (`re_…`), from a secret. */
|
|
288
|
+
apiKey: string;
|
|
289
|
+
/** Default: the global `fetch`. */
|
|
290
|
+
fetch?: typeof fetch;
|
|
291
|
+
}
|
|
292
|
+
declare const RESEND_ENDPOINT = "https://api.resend.com/emails";
|
|
293
|
+
/**
|
|
294
|
+
* Sends through Resend's REST API: `POST https://api.resend.com/emails` with a bearer key and a
|
|
295
|
+
* JSON body of `from`, `to`, `subject`, `text` and `reply_to` (snake case). Resend refuses
|
|
296
|
+
* requests without a `User-Agent`, which a Worker's `fetch` does not set, so one is sent.
|
|
297
|
+
* Success is a 2xx with `{ id }`.
|
|
298
|
+
*/
|
|
299
|
+
declare function resendEmailSender(options: ResendOptions): EmailSender;
|
|
300
|
+
interface PostmarkOptions {
|
|
301
|
+
/** A Postmark server token, from a secret. */
|
|
302
|
+
serverToken: string;
|
|
303
|
+
/** Default "outbound", Postmark's transactional stream. */
|
|
304
|
+
messageStream?: string;
|
|
305
|
+
/** Default: the global `fetch`. */
|
|
306
|
+
fetch?: typeof fetch;
|
|
307
|
+
}
|
|
308
|
+
declare const POSTMARK_ENDPOINT = "https://api.postmarkapp.com/email";
|
|
309
|
+
/**
|
|
310
|
+
* Sends through Postmark's Email API: `POST https://api.postmarkapp.com/email` with the
|
|
311
|
+
* `X-Postmark-Server-Token` header and a JSON body of `From`, `To`, `Subject`, `TextBody`,
|
|
312
|
+
* `ReplyTo` and `MessageStream`. Success is a 200 whose `ErrorCode` is 0; anything else is
|
|
313
|
+
* reported with Postmark's `ErrorCode`.
|
|
314
|
+
*/
|
|
315
|
+
declare function postmarkEmailSender(options: PostmarkOptions): EmailSender;
|
|
316
|
+
|
|
317
|
+
type SubjectRequestType = 'access' | 'erasure';
|
|
318
|
+
declare const SUBJECT_REQUEST_TYPES: readonly SubjectRequestType[];
|
|
319
|
+
interface SubjectRequestPages {
|
|
320
|
+
form: string;
|
|
321
|
+
received: string;
|
|
322
|
+
/** With `{token}`, which the handler fills in. */
|
|
323
|
+
confirm: string;
|
|
324
|
+
confirmed: string;
|
|
325
|
+
linkInvalid: string;
|
|
326
|
+
}
|
|
327
|
+
/** Email texts with `{placeholders}` the handler fills in. */
|
|
328
|
+
interface SubjectRequestTexts {
|
|
329
|
+
typeLabels: Record<SubjectRequestType, string>;
|
|
330
|
+
notification: {
|
|
331
|
+
subject: string;
|
|
332
|
+
body: string;
|
|
333
|
+
};
|
|
334
|
+
cookiePresent: string;
|
|
335
|
+
cookieAbsent: string;
|
|
336
|
+
confirmedPending: string;
|
|
337
|
+
confirmedNotAsked: string;
|
|
338
|
+
noDetails: string;
|
|
339
|
+
confirmation: {
|
|
340
|
+
subject: string;
|
|
341
|
+
body: string;
|
|
342
|
+
};
|
|
343
|
+
reminder: {
|
|
344
|
+
subject: string;
|
|
345
|
+
body: string;
|
|
346
|
+
item: string;
|
|
347
|
+
overdue: string;
|
|
348
|
+
notNotified: string;
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
interface SubjectRequestLocale {
|
|
352
|
+
texts: SubjectRequestTexts;
|
|
353
|
+
checklists: Partial<Record<SubjectRequestType, string>>;
|
|
354
|
+
pages: SubjectRequestPages;
|
|
355
|
+
}
|
|
356
|
+
interface SubjectRequestManifest {
|
|
357
|
+
readonly manifestVersion: 1;
|
|
358
|
+
readonly endpoint: string;
|
|
359
|
+
readonly notify: string;
|
|
360
|
+
readonly types: readonly SubjectRequestType[];
|
|
361
|
+
/** "<n>d" or "<n>y". */
|
|
362
|
+
readonly retention: string;
|
|
363
|
+
readonly requesterEmail: {
|
|
364
|
+
readonly processor: string;
|
|
365
|
+
} | null;
|
|
366
|
+
readonly controller: {
|
|
367
|
+
readonly name: string;
|
|
368
|
+
};
|
|
369
|
+
readonly policyHash: string;
|
|
370
|
+
readonly defaultLocale: string;
|
|
371
|
+
readonly locales: Readonly<Record<string, SubjectRequestLocale>>;
|
|
372
|
+
readonly unreviewedPhrases: readonly string[];
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Checks a manifest (typically an imported `subject-requests.manifest.gen.json`) and returns
|
|
376
|
+
* it typed. Throws on anything malformed: a handler must not start on texts or pages it
|
|
377
|
+
* cannot trust to be complete.
|
|
378
|
+
*/
|
|
379
|
+
declare function parseSubjectRequestManifest(value: unknown): SubjectRequestManifest;
|
|
380
|
+
|
|
381
|
+
type SubjectRequestStatus = 'received' | 'confirmed' | 'closed';
|
|
382
|
+
/**
|
|
383
|
+
* One data subject request, as stored. Its content (who asked for what, when, under which
|
|
384
|
+
* policy) is fixed once created; only its progress changes: confirmation, the notification
|
|
385
|
+
* having gone out, an extension of the deadline, and closing with an outcome. No IP address,
|
|
386
|
+
* user agent or request header is part of it.
|
|
387
|
+
*/
|
|
388
|
+
interface SubjectRequestRecord {
|
|
389
|
+
/** 128 random bits, 32 lowercase hex digits. */
|
|
390
|
+
id: string;
|
|
391
|
+
type: SubjectRequestType;
|
|
392
|
+
/** As given, trimmed: needed to answer. */
|
|
393
|
+
email: string;
|
|
394
|
+
/** HMAC-SHA-256(key, lowercased email), lowercase hex: finds the requests of one address. */
|
|
395
|
+
emailHash: string;
|
|
396
|
+
/** HMAC-SHA-256(key, consentId) of the browser's consent cookie, the same hash consent receipts carry; `null` without the cookie. */
|
|
397
|
+
subjectHash: string | null;
|
|
398
|
+
details: string | null;
|
|
399
|
+
/** The locale of the form the request came from. */
|
|
400
|
+
locale: string;
|
|
401
|
+
/** The policy of the build that received it. */
|
|
402
|
+
policyHash: string;
|
|
403
|
+
/** ISO 8601 UTC, the server's clock. */
|
|
404
|
+
receivedAt: string;
|
|
405
|
+
/** One calendar month after `receivedAt` (Art. 12(3) GDPR). */
|
|
406
|
+
dueAt: string;
|
|
407
|
+
/** A deadline extended by up to two further months, with the reason given to the requester. */
|
|
408
|
+
extendedDueAt: string | null;
|
|
409
|
+
extensionReason: string | null;
|
|
410
|
+
status: SubjectRequestStatus;
|
|
411
|
+
confirmedAt: string | null;
|
|
412
|
+
closedAt: string | null;
|
|
413
|
+
/** What was done, in a few words: "data sent", "erased", "refused: identity not shown". */
|
|
414
|
+
outcome: string | null;
|
|
415
|
+
/** When the email to `notify` went out; `null` while it has not (the reminder lists such requests). */
|
|
416
|
+
notifiedAt: string | null;
|
|
417
|
+
/** When the confirmation email of this request went out, if it did. */
|
|
418
|
+
confirmationSentAt: string | null;
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Where requests are kept. `create` is the one write the handler waits for before answering:
|
|
422
|
+
* when it rejects, the visitor is told that the request was not received.
|
|
423
|
+
*
|
|
424
|
+
* The update methods only ever touch the progress columns, and never a closed request (the D1
|
|
425
|
+
* migration enforces the same with triggers). Methods that update by id resolve to whether a
|
|
426
|
+
* request was changed.
|
|
427
|
+
*/
|
|
428
|
+
interface SubjectRequestStore {
|
|
429
|
+
create(record: SubjectRequestRecord): Promise<void>;
|
|
430
|
+
getById(id: string): Promise<SubjectRequestRecord | null>;
|
|
431
|
+
/** `received` → `confirmed`. False when the request is unknown, already confirmed or closed. */
|
|
432
|
+
confirm(id: string, at: string): Promise<boolean>;
|
|
433
|
+
markNotified(id: string, at: string): Promise<boolean>;
|
|
434
|
+
markConfirmationSent(id: string, at: string): Promise<boolean>;
|
|
435
|
+
/**
|
|
436
|
+
* Reserves one confirmation email under the rate key `key`, atomically: allowed when the key
|
|
437
|
+
* has no window starting after `slot.windowStart` (a new window then starts at `slot.at`), or
|
|
438
|
+
* its current window has sent fewer than `slot.cap`. Of several concurrent calls, only as many
|
|
439
|
+
* as the cap allows resolve `true`; the caller sends only then.
|
|
440
|
+
*/
|
|
441
|
+
reserveConfirmationSlot(key: string, slot: ConfirmationSlot): Promise<boolean>;
|
|
442
|
+
/**
|
|
443
|
+
* Undoes a reservation of `key` made at `at` that sent nothing (the global cap refused), so
|
|
444
|
+
* the address is not locked out for an hour. Does nothing if the window is not that one.
|
|
445
|
+
*/
|
|
446
|
+
releaseConfirmationSlot(key: string, at: string): Promise<void>;
|
|
447
|
+
/**
|
|
448
|
+
* Deletes the per-address windows that started at or before `windowStart` (they have ended),
|
|
449
|
+
* never the global "*" row; resolves to how many. Called by every reservation and by
|
|
450
|
+
* `sweepClosedRequests`, so no rate-limit row outlives its window for long.
|
|
451
|
+
*/
|
|
452
|
+
deleteExpiredConfirmationSlots(windowStart: string): Promise<number>;
|
|
453
|
+
extend(id: string, extension: {
|
|
454
|
+
dueAt: string;
|
|
455
|
+
reason: string;
|
|
456
|
+
}): Promise<boolean>;
|
|
457
|
+
close(id: string, closing: {
|
|
458
|
+
outcome: string;
|
|
459
|
+
at: string;
|
|
460
|
+
}): Promise<boolean>;
|
|
461
|
+
/** Every request that is not closed, oldest first. */
|
|
462
|
+
listOpen(): Promise<SubjectRequestRecord[]>;
|
|
463
|
+
/** Open requests whose deadline (the extended one, if any) is at or before `at`, oldest first. */
|
|
464
|
+
listDueBefore(at: string): Promise<SubjectRequestRecord[]>;
|
|
465
|
+
/** Deletes closed requests closed before `at`; resolves to how many. For retention only. */
|
|
466
|
+
deleteClosedBefore(at: string): Promise<number>;
|
|
467
|
+
}
|
|
468
|
+
interface ConfirmationSlot {
|
|
469
|
+
/** Now, ISO 8601 UTC. */
|
|
470
|
+
at: string;
|
|
471
|
+
/** A window that started at or before this has ended: `at` less the window length. */
|
|
472
|
+
windowStart: string;
|
|
473
|
+
/** Sends allowed per window. */
|
|
474
|
+
cap: number;
|
|
475
|
+
}
|
|
476
|
+
/** The deadline that applies: the extended one, if any. */
|
|
477
|
+
declare function effectiveDueAt(record: Pick<SubjectRequestRecord, 'dueAt' | 'extendedDueAt'>): string;
|
|
478
|
+
/** A store that keeps requests in memory, for tests and local development. */
|
|
479
|
+
declare function createMemorySubjectRequestStore(): SubjectRequestStore & {
|
|
480
|
+
readonly requests: readonly SubjectRequestRecord[];
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
/** The largest form body read, in bytes. A request with 2000 characters of details fits (form encoding triples non-ASCII at most for most scripts). */
|
|
484
|
+
declare const MAX_SUBJECT_REQUEST_BYTES = 4096;
|
|
485
|
+
/** The longest email address accepted. */
|
|
486
|
+
declare const MAX_EMAIL_LENGTH = 254;
|
|
487
|
+
/** The longest `details` accepted, in characters, after line breaks are counted as one. */
|
|
488
|
+
declare const MAX_DETAILS_LENGTH = 2000;
|
|
489
|
+
/** The form field that catches automated submissions: filled in, nothing is stored and nothing is sent. */
|
|
490
|
+
declare const HONEYPOT_FIELD = "website";
|
|
491
|
+
/** At most one confirmation email per (normalised) email address in this window. */
|
|
492
|
+
declare const CONFIRMATION_RATE_LIMIT_MS: number;
|
|
493
|
+
/** At most this many confirmation emails per hour in all, by default. */
|
|
494
|
+
declare const DEFAULT_MAX_CONFIRMATIONS_PER_HOUR = 100;
|
|
495
|
+
/**
|
|
496
|
+
* The address as the rate limit sees it: lowercased, without a "+tag" in the local part, so
|
|
497
|
+
* "Ada+1@Example.org" and "ada@example.org" share one limit. Only for rate limiting; the
|
|
498
|
+
* request keeps the address as typed.
|
|
499
|
+
*/
|
|
500
|
+
declare function rateLimitAddress(email: string): string;
|
|
501
|
+
/** How long a confirmation link is valid by default: 7 days. */
|
|
502
|
+
declare const DEFAULT_CONFIRMATION_TTL_MS: number;
|
|
503
|
+
/** CookieConsent's cookie. */
|
|
504
|
+
declare const DEFAULT_CONSENT_COOKIE = "cc_cookie";
|
|
505
|
+
type SubjectRequestErrorCode = 'request/not-found' | 'request/method-not-allowed' | 'request/origin-missing' | 'request/origin-forbidden' | 'request/unsupported-media-type' | 'request/body-too-large' | 'request/invalid-form' | 'request/unexpected-fields' | 'request/invalid-email' | 'request/invalid-type' | 'request/details-too-long' | 'server/store-failed' | 'server/error';
|
|
506
|
+
/** The Workers `ExecutionContext` part the handler uses: work that may finish after the response. */
|
|
507
|
+
interface WaitUntil {
|
|
508
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
509
|
+
}
|
|
510
|
+
interface SubjectRequestHandlerOptions {
|
|
511
|
+
/** Where requests are kept, e.g. `createD1SubjectRequestStore(env.DB)`. */
|
|
512
|
+
store: SubjectRequestStore;
|
|
513
|
+
/**
|
|
514
|
+
* The HMAC key of the consent receipts (`RECEIPTS_HMAC_KEY`): the consent id of the browser's
|
|
515
|
+
* cookie is hashed with it, so the request joins that browser's receipts. It also hashes the
|
|
516
|
+
* email address and signs the confirmation links.
|
|
517
|
+
*/
|
|
518
|
+
hmacKey: string | Uint8Array | undefined;
|
|
519
|
+
/** The site's origins, exactly as browsers send them in `Origin`. */
|
|
520
|
+
allowedOrigins: readonly string[];
|
|
521
|
+
/** The `subject-requests.manifest.gen.json` that `consent-kit build` writes. Checked at once. */
|
|
522
|
+
manifest: unknown;
|
|
523
|
+
/** Sends the notification of every request to the manifest's `notify` mailbox. */
|
|
524
|
+
notifySender: EmailSender;
|
|
525
|
+
/** The From address of the emails, e.g. "Privacy requests <requests@example.com>". */
|
|
526
|
+
from: string;
|
|
527
|
+
/** Sends the confirmation link to the requester. Required when the manifest has `requesterEmail`. */
|
|
528
|
+
requesterSender?: EmailSender;
|
|
529
|
+
/** The From of the confirmation email. Default: `from`. */
|
|
530
|
+
requesterFrom?: string;
|
|
531
|
+
/** Counted (never read out) for the notification: how many receipts the browser's consent id matches. */
|
|
532
|
+
receipts?: Pick<SubjectReceiptStore, 'listBySubject'>;
|
|
533
|
+
/** The path the handler answers. Default: the manifest's endpoint. */
|
|
534
|
+
path?: string;
|
|
535
|
+
/**
|
|
536
|
+
* The pages a GET of the path is answered with, per locale: the form, and the pages the
|
|
537
|
+
* handler redirects to. Default: the manifest's generated pages. `false`: GET is answered 404
|
|
538
|
+
* (the site serves the pages itself), except for a confirmation link, whose page (`confirm`,
|
|
539
|
+
* a button that POSTs the token back) always comes from here or the manifest.
|
|
540
|
+
*/
|
|
541
|
+
pages?: false | Readonly<Record<string, Partial<SubjectRequestPages>>>;
|
|
542
|
+
/** Accept a POST without `Origin`. Default `false`: browsers send it with every form POST. */
|
|
543
|
+
allowMissingOrigin?: boolean;
|
|
544
|
+
/**
|
|
545
|
+
* At most this many confirmation emails per hour in all, whatever the addresses: bounds what
|
|
546
|
+
* anyone can make the site send to third parties. Default 100. Each address gets at most one an hour anyway.
|
|
547
|
+
*/
|
|
548
|
+
maxConfirmationsPerHour?: number;
|
|
549
|
+
/**
|
|
550
|
+
* Called when the global cap refuses a confirmation email (the request is stored and notified;
|
|
551
|
+
* only its confirmation email is not sent). Its argument holds no personal data. Default:
|
|
552
|
+
* `console.warn`. Bound abuse per client with a Cloudflare rate-limiting rule in front of the
|
|
553
|
+
* route: this package stores no IP address.
|
|
554
|
+
*/
|
|
555
|
+
onConfirmationCapReached?: (info: {
|
|
556
|
+
cap: number;
|
|
557
|
+
windowMs: number;
|
|
558
|
+
}) => void;
|
|
559
|
+
/** How long a confirmation link is valid, in ms. Default 7 days. */
|
|
560
|
+
confirmationTtlMs?: number;
|
|
561
|
+
/** Default "cc_cookie". */
|
|
562
|
+
consentCookieName?: string;
|
|
563
|
+
/** Default `() => new Date()`. */
|
|
564
|
+
now?: () => Date;
|
|
565
|
+
/** Called when the store fails (the request is answered 503). Default: `console.error`, without the request. */
|
|
566
|
+
onStoreError?: (error: unknown) => void;
|
|
567
|
+
/**
|
|
568
|
+
* Called when an email is not accepted. The request is stored either way: a failed
|
|
569
|
+
* notification leaves `notifiedAt` empty, and `remindDueRequests` lists it until it is closed.
|
|
570
|
+
* Default: `console.error` with the request id, never the address.
|
|
571
|
+
*/
|
|
572
|
+
onEmailError?: (error: unknown, context: {
|
|
573
|
+
requestId: string;
|
|
574
|
+
email: 'notification' | 'confirmation';
|
|
575
|
+
}) => void;
|
|
576
|
+
}
|
|
577
|
+
/** Where the handler sends the browser: always relative to the path, never carrying input. */
|
|
578
|
+
declare const LOCATIONS: {
|
|
579
|
+
readonly received: (path: string, id: string) => string;
|
|
580
|
+
readonly confirmed: (path: string) => string;
|
|
581
|
+
readonly linkInvalid: (path: string) => string;
|
|
582
|
+
readonly confirm: (origin: string, path: string, token: string) => string;
|
|
583
|
+
};
|
|
584
|
+
/** The consent id in CookieConsent's cookie (`encodeURIComponent(JSON.stringify({…, consentId}))`), or `null`. */
|
|
585
|
+
declare function consentIdFromCookie(header: string | null, name?: string): string | null;
|
|
586
|
+
/**
|
|
587
|
+
* Builds the receiving end of the request form: a Fetch API handler for one path.
|
|
588
|
+
*
|
|
589
|
+
* - `POST` (`application/x-www-form-urlencoded`, from the generated form, no script) with a
|
|
590
|
+
* same-origin `Origin`: the fields are checked, the consent id of the browser's `cc_cookie` is
|
|
591
|
+
* hashed with the receipts' key, the request is stored, and only then are the emails sent
|
|
592
|
+
* (the notification to `notify`, and the confirmation link if the manifest asks for one).
|
|
593
|
+
* The answer is `303 See Other` to `<path>?request=<id>`, the same whatever the request held;
|
|
594
|
+
* a filled-in honeypot gets the same answer and nothing is stored or sent.
|
|
595
|
+
* - `GET <path>?confirm=<token>` (the link in the confirmation email) changes nothing: a valid
|
|
596
|
+
* link shows a page whose button POSTs the token back; an invalid one is sent on to
|
|
597
|
+
* `?status=link-invalid`. Only that POST, same-origin like the form, confirms an unconfirmed
|
|
598
|
+
* request, once, and answers `303` to `?status=confirmed` or `?status=link-invalid`.
|
|
599
|
+
* - `GET <path>` (and the redirect targets): the pages, unless `pages: false`.
|
|
600
|
+
*
|
|
601
|
+
* With a Workers `ExecutionContext` as the second argument, the emails are sent after the
|
|
602
|
+
* response (`waitUntil`), so that the answer takes the same time whatever happens next.
|
|
603
|
+
* Nothing the request held is ever echoed: refusals carry an error code only.
|
|
604
|
+
*
|
|
605
|
+
* Throws at once on a missing or short key, a malformed manifest or origin, or a manifest
|
|
606
|
+
* that asks for confirmation emails without a `requesterSender`.
|
|
607
|
+
*/
|
|
608
|
+
declare function createSubjectRequestHandler(options: SubjectRequestHandlerOptions): (request: Request, context?: WaitUntil) => Promise<Response>;
|
|
609
|
+
|
|
610
|
+
/** The table `migrations/0002_subject_requests.sql` creates. */
|
|
611
|
+
declare const SUBJECT_REQUESTS_TABLE = "subject_requests";
|
|
612
|
+
declare const CONFIRMATION_SLOTS_TABLE = "subject_request_confirmation_slots";
|
|
613
|
+
/**
|
|
614
|
+
* A `SubjectRequestStore` over a D1 database migrated with `migrations/0002_subject_requests.sql`.
|
|
615
|
+
* Every update names the progress columns only and skips closed requests; the migration's
|
|
616
|
+
* triggers refuse anything else.
|
|
617
|
+
*/
|
|
618
|
+
declare function createD1SubjectRequestStore(db: D1DatabaseLike): SubjectRequestStore;
|
|
619
|
+
|
|
620
|
+
/** Calendar arithmetic for due dates and retention, in UTC. */
|
|
621
|
+
/**
|
|
622
|
+
* `date` plus `months` calendar months: the same day of the month, or the last day of the
|
|
623
|
+
* target month when it is shorter (31 January + 1 month = 28 or 29 February). This is how
|
|
624
|
+
* Art. 12(3) GDPR's "within one month of receipt" is counted under Regulation 1182/71 on time
|
|
625
|
+
* limits. Negative `months` go back.
|
|
626
|
+
*/
|
|
627
|
+
declare function addMonths(date: Date, months: number): Date;
|
|
628
|
+
/** When a request received at `receivedAt` must be answered: one calendar month later. */
|
|
629
|
+
declare function dueDate(receivedAt: Date): Date;
|
|
630
|
+
/**
|
|
631
|
+
* The moment before which a request closed at that moment is past `retention` ("<n>d" or
|
|
632
|
+
* "<n>y", calendar years) when it is `now`. Throws on any other retention.
|
|
633
|
+
*/
|
|
634
|
+
declare function retentionCutoff(retention: string, now: Date): Date;
|
|
635
|
+
|
|
636
|
+
interface RemindOptions {
|
|
637
|
+
store: SubjectRequestStore;
|
|
638
|
+
sender: EmailSender;
|
|
639
|
+
/** The `subject-requests.manifest.gen.json`: the texts of the reminder, and `notify`. */
|
|
640
|
+
manifest: unknown;
|
|
641
|
+
/** The From address. */
|
|
642
|
+
from: string;
|
|
643
|
+
/** Where the reminder goes. Default: the manifest's `notify`. */
|
|
644
|
+
notify?: string;
|
|
645
|
+
now?: Date;
|
|
646
|
+
/** Requests due within this many days are listed, with the overdue ones. Default 7. */
|
|
647
|
+
withinDays?: number;
|
|
648
|
+
}
|
|
649
|
+
interface RemindResult {
|
|
650
|
+
/** The requests the reminder listed; empty when none was sent. */
|
|
651
|
+
listed: SubjectRequestRecord[];
|
|
652
|
+
sent: boolean;
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* For a Cron Trigger: one email to the controller's mailbox listing every open request that is
|
|
656
|
+
* overdue or due within `withinDays`, and every open request whose notification never went
|
|
657
|
+
* out (so a failed notification is not lost). Nothing is sent when there is none. A failure of
|
|
658
|
+
* the store or the sender rejects, so the scheduled run is reported as failed.
|
|
659
|
+
*/
|
|
660
|
+
declare function remindDueRequests(options: RemindOptions): Promise<RemindResult>;
|
|
661
|
+
interface SweepOptions {
|
|
662
|
+
store: SubjectRequestStore;
|
|
663
|
+
/** "<n>d" or "<n>y": the manifest's `retention` (`subjectRequests.retention`). */
|
|
664
|
+
retention: string;
|
|
665
|
+
now?: Date;
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Deletes the requests that were closed longer ago than `retention`, and the confirmation
|
|
669
|
+
* rate-limit windows that have ended; resolves to how many requests. Open requests are never
|
|
670
|
+
* deleted.
|
|
671
|
+
*/
|
|
672
|
+
declare function sweepClosedRequests(options: SweepOptions): Promise<number>;
|
|
673
|
+
/**
|
|
674
|
+
* The stored consent receipts of one browser, for answering an access request: by its consent
|
|
675
|
+
* id (from the requester, or from the cookie of the request), hashed with the receipts' key, or
|
|
676
|
+
* by the subject hash itself (a request record's `subjectHash`).
|
|
677
|
+
*/
|
|
678
|
+
declare function findReceipts(store: Pick<SubjectReceiptStore, 'listBySubject'>, consentIdOrSubjectHash: string, options?: {
|
|
679
|
+
hmacKey?: string | Uint8Array;
|
|
680
|
+
}): Promise<StoredReceipt[]>;
|
|
681
|
+
/**
|
|
682
|
+
* Deletes the consent receipts of one browser, for an erasure request; resolves to how many.
|
|
683
|
+
* Receipts are the proof of consent (Art. 7(1) GDPR): decide first whether they are still
|
|
684
|
+
* needed. The request handler never calls this.
|
|
685
|
+
*/
|
|
686
|
+
declare function eraseReceipts(store: Pick<SubjectReceiptStore, 'deleteBySubject'>, consentIdOrSubjectHash: string, options?: {
|
|
687
|
+
hmacKey?: string | Uint8Array;
|
|
688
|
+
}): Promise<number>;
|
|
689
|
+
|
|
690
|
+
export { CONFIRMATION_RATE_LIMIT_MS, CONFIRMATION_SLOTS_TABLE, DEFAULT_CONFIRMATION_TTL_MS, DEFAULT_CONSENT_COOKIE, DEFAULT_MAX_CLOCK_SKEW_MS, DEFAULT_MAX_CONFIRMATIONS_PER_HOUR, EmailSendError, HONEYPOT_FIELD, MAX_DETAILS_LENGTH, MAX_EMAIL_LENGTH, MAX_RECEIPT_BYTES, MAX_SUBJECT_REQUEST_BYTES, MIN_KEY_BYTES, POSTMARK_ENDPOINT, RECEIPTS_TABLE, RESEND_ENDPOINT, SUBJECT_REQUESTS_TABLE, LOCATIONS as SUBJECT_REQUEST_LOCATIONS, SUBJECT_REQUEST_TYPES, addMonths, checkReceipt, cloudflareEmailSender, consentIdFromCookie, createD1ReceiptStore, createD1SubjectRequestStore, createMemoryReceiptStore, createMemorySubjectRequestStore, createReceiptHandler, createSubjectRequestHandler, dueDate, effectiveDueAt, eraseReceipts, findReceipts, parseReceiptManifest, parseSubjectRequestManifest, postmarkEmailSender, rateLimitAddress, remindDueRequests, resendEmailSender, retentionCutoff, subjectHasher, sweepClosedRequests };
|
|
691
|
+
export type { CheckContext, ConfirmationSlot, D1DatabaseLike, EmailMessage, EmailSender, PostmarkOptions, Receipt, ReceiptCheck, ReceiptErrorCode, ReceiptHandlerOptions, ReceiptManifest, ReceiptPolicy, ReceiptProblem, ReceiptPurpose, ReceiptStore, RemindOptions, RemindResult, ResendOptions, SendEmailBindingLike, StoredReceipt, SubjectReceiptStore, SubjectRequestErrorCode, SubjectRequestHandlerOptions, SubjectRequestLocale, SubjectRequestManifest, SubjectRequestPages, SubjectRequestRecord, SubjectRequestStatus, SubjectRequestStore, SubjectRequestTexts, SubjectRequestType, SweepOptions, WaitUntil };
|