@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/dist/index.js ADDED
@@ -0,0 +1,1152 @@
1
+ // src/manifest.ts
2
+ var HEX_64 = /^[0-9a-f]{64}$/;
3
+ var MANIFEST_KEYS = ["endpoint", "manifestVersion", "policies"];
4
+ var POLICY_KEYS = ["consentPurposes", "otherPurposes", "policyHash", "revision", "supersededAt"];
5
+ var ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
6
+ function parseReceiptManifest(value) {
7
+ const fail = (problem) => {
8
+ throw new Error(`consent-kit: invalid receipt manifest: ${problem}`);
9
+ };
10
+ if (!isRecord(value)) return fail("not an object");
11
+ if (!sameKeys(value, MANIFEST_KEYS)) return fail(`expected exactly the keys ${MANIFEST_KEYS.join(", ")}`);
12
+ if (value.manifestVersion !== 1) return fail("manifestVersion must be 1");
13
+ if (typeof value.endpoint !== "string" || value.endpoint === "") return fail("endpoint must be a non-empty string");
14
+ if (!Array.isArray(value.policies) || value.policies.length === 0) return fail("policies must be a non-empty array");
15
+ const policies = value.policies.map((policy, index) => {
16
+ const at = `policies[${index}]`;
17
+ if (!isRecord(policy) || !sameKeys(policy, POLICY_KEYS)) return fail(`${at} must have exactly the keys ${POLICY_KEYS.join(", ")}`);
18
+ if (typeof policy.policyHash !== "string" || !HEX_64.test(policy.policyHash)) return fail(`${at}.policyHash must be 64 lowercase hex digits`);
19
+ if (!isCount(policy.revision, 0)) return fail(`${at}.revision must be a non-negative integer`);
20
+ if (!isRecord(policy.consentPurposes)) return fail(`${at}.consentPurposes must be an object`);
21
+ const consentPurposes = {};
22
+ for (const [id, version] of Object.entries(policy.consentPurposes)) {
23
+ if (!isCount(version, 1)) return fail(`${at}.consentPurposes.${id} must be a positive integer`);
24
+ consentPurposes[id] = version;
25
+ }
26
+ if (Object.keys(consentPurposes).length === 0) return fail(`${at}.consentPurposes is empty: there is nothing to record`);
27
+ const other = policy.otherPurposes;
28
+ if (!Array.isArray(other) || !other.every((id) => typeof id === "string")) return fail(`${at}.otherPurposes must be an array of ids`);
29
+ if (other.some((id) => Object.hasOwn(consentPurposes, id))) return fail(`${at} lists a purpose both as a consent purpose and as another one`);
30
+ const supersededAt = policy.supersededAt;
31
+ if (supersededAt !== null && (typeof supersededAt !== "string" || !ISO_TIMESTAMP.test(supersededAt) || Number.isNaN(Date.parse(supersededAt)))) {
32
+ return fail(`${at}.supersededAt must be null or an ISO 8601 UTC timestamp`);
33
+ }
34
+ return { policyHash: policy.policyHash, revision: policy.revision, consentPurposes, otherPurposes: [...other], supersededAt };
35
+ });
36
+ return { manifestVersion: 1, endpoint: value.endpoint, policies };
37
+ }
38
+ function policyKey(policyHash, revision) {
39
+ return `${policyHash}:${revision}`;
40
+ }
41
+ function isRecord(value) {
42
+ return typeof value === "object" && value !== null && !Array.isArray(value);
43
+ }
44
+ function sameKeys(value, expected) {
45
+ const keys = Object.keys(value).sort();
46
+ return keys.length === expected.length && keys.every((key, index) => key === expected[index]);
47
+ }
48
+ function isCount(value, min) {
49
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= min;
50
+ }
51
+
52
+ // src/receipt.ts
53
+ var RECEIPT_KEYS = ["accepted", "consentId", "event", "policyHash", "rejected", "revision", "timestamp"];
54
+ var PURPOSE_KEYS = ["purpose", "version"];
55
+ var CONSENT_ID = /^[A-Za-z0-9._~-]{1,128}$/;
56
+ var HEX_642 = /^[0-9a-f]{64}$/;
57
+ var ISO_TIMESTAMP2 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
58
+ function checkReceipt(body, context) {
59
+ const refuse = (problem) => ({ ok: false, problem });
60
+ if (!isRecord(body) || !sameKeys(body, RECEIPT_KEYS)) return refuse("receipt/unexpected-fields");
61
+ const { consentId, event, accepted, rejected, policyHash, revision, timestamp } = body;
62
+ if (typeof consentId !== "string" || !CONSENT_ID.test(consentId)) return refuse("receipt/invalid-consent-id");
63
+ if (event !== "first" && event !== "change") return refuse("receipt/invalid-event");
64
+ const acceptedList = purposeList(accepted);
65
+ const rejectedList = purposeList(rejected);
66
+ if (acceptedList === null || rejectedList === null) return refuse("receipt/invalid-purposes");
67
+ if (typeof policyHash !== "string" || !HEX_642.test(policyHash)) return refuse("receipt/invalid-policy-hash");
68
+ if (!isCount(revision, 0)) return refuse("receipt/invalid-revision");
69
+ if (typeof timestamp !== "string" || !ISO_TIMESTAMP2.test(timestamp)) return refuse("receipt/invalid-timestamp");
70
+ const time = Date.parse(timestamp);
71
+ if (Number.isNaN(time) || new Date(time).toISOString() !== timestamp) return refuse("receipt/invalid-timestamp");
72
+ if (Math.abs(time - context.now.getTime()) > context.maxClockSkewMs) return refuse("receipt/timestamp-out-of-range");
73
+ const policy = context.policies.get(policyKey(policyHash, revision));
74
+ if (policy === void 0) return refuse(context.hashes.has(policyHash) ? "receipt/revision-mismatch" : "receipt/unknown-policy");
75
+ if (policy.supersededAt !== null && context.now.getTime() - Date.parse(policy.supersededAt) > context.maxSupersededAgeMs) {
76
+ return refuse("receipt/policy-superseded");
77
+ }
78
+ const seen = /* @__PURE__ */ new Map();
79
+ for (const [list, items] of [["accepted", acceptedList], ["rejected", rejectedList]]) {
80
+ for (const { purpose, version } of items) {
81
+ if (!Object.hasOwn(policy.consentPurposes, purpose)) {
82
+ return refuse(policy.otherPurposes.includes(purpose) ? "receipt/not-consent-purpose" : "receipt/unknown-purpose");
83
+ }
84
+ if (policy.consentPurposes[purpose] !== version) return refuse("receipt/version-mismatch");
85
+ const earlier = seen.get(purpose);
86
+ if (earlier !== void 0) return refuse(earlier === list ? "receipt/duplicate-purpose" : "receipt/conflicting-purpose");
87
+ seen.set(purpose, list);
88
+ }
89
+ }
90
+ if (seen.size !== Object.keys(policy.consentPurposes).length) return refuse("receipt/missing-purpose");
91
+ return {
92
+ ok: true,
93
+ receipt: { consentId, event, accepted: sorted(acceptedList), rejected: sorted(rejectedList), policyHash, revision, timestamp }
94
+ };
95
+ }
96
+ function purposeList(value) {
97
+ if (!Array.isArray(value)) return null;
98
+ const out = [];
99
+ for (const item of value) {
100
+ if (!isRecord(item) || !sameKeys(item, PURPOSE_KEYS)) return null;
101
+ if (typeof item.purpose !== "string" || !isCount(item.version, 1)) return null;
102
+ out.push({ purpose: item.purpose, version: item.version });
103
+ }
104
+ return out;
105
+ }
106
+ function sorted(purposes) {
107
+ return [...purposes].sort((a, b) => a.purpose < b.purpose ? -1 : a.purpose > b.purpose ? 1 : 0);
108
+ }
109
+
110
+ // src/subject.ts
111
+ var MIN_KEY_BYTES = 32;
112
+ function hmacKeyBytes(key) {
113
+ if (key === void 0 || key === null || key === "") {
114
+ throw new Error("consent-kit: the HMAC key for consent receipts is missing (set it as a secret, e.g. `wrangler secret put RECEIPTS_HMAC_KEY`)");
115
+ }
116
+ const bytes = typeof key === "string" ? new TextEncoder().encode(key) : new Uint8Array(key);
117
+ if (bytes.byteLength < MIN_KEY_BYTES) {
118
+ throw new Error(`consent-kit: the HMAC key for consent receipts is ${bytes.byteLength} bytes; it needs at least ${MIN_KEY_BYTES} (e.g. \`openssl rand -base64 48\`)`);
119
+ }
120
+ return bytes;
121
+ }
122
+ function subjectHasher(key) {
123
+ const bytes = hmacKeyBytes(key);
124
+ let imported;
125
+ return async (consentId) => {
126
+ imported ??= crypto.subtle.importKey("raw", bytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
127
+ const signature = await crypto.subtle.sign("HMAC", await imported, new TextEncoder().encode(consentId));
128
+ return [...new Uint8Array(signature)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
129
+ };
130
+ }
131
+
132
+ // src/handler.ts
133
+ var MAX_RECEIPT_BYTES = 4096;
134
+ var DEFAULT_MAX_CLOCK_SKEW_MS = 24 * 60 * 60 * 1e3;
135
+ var MALFORMED = /* @__PURE__ */ new Set([
136
+ "receipt/unexpected-fields",
137
+ "receipt/invalid-consent-id",
138
+ "receipt/invalid-event",
139
+ "receipt/invalid-purposes",
140
+ "receipt/invalid-policy-hash",
141
+ "receipt/invalid-revision",
142
+ "receipt/invalid-timestamp",
143
+ "receipt/duplicate-purpose",
144
+ "receipt/conflicting-purpose"
145
+ ]);
146
+ var MEDIA_TYPES = /* @__PURE__ */ new Set(["text/plain", "application/json"]);
147
+ function createReceiptHandler(options) {
148
+ const hash = subjectHasher(options.hmacKey);
149
+ const allowed = allowedOriginSet(options.allowedOrigins);
150
+ const manifests = (Array.isArray(options.manifest) ? options.manifest : [options.manifest]).map(parseReceiptManifest);
151
+ if (manifests.length === 0) throw new Error("consent-kit: no receipt manifest given");
152
+ const path = options.path ?? endpointPath(manifests.map((manifest) => manifest.endpoint));
153
+ const policies = /* @__PURE__ */ new Map();
154
+ for (const policy of manifests.flatMap((manifest) => manifest.policies)) {
155
+ const key = policyKey(policy.policyHash, policy.revision);
156
+ const known = policies.get(key);
157
+ if (known === void 0) {
158
+ policies.set(key, policy);
159
+ continue;
160
+ }
161
+ if (canonical(known.consentPurposes) !== canonical(policy.consentPurposes) || canonical([...known.otherPurposes].sort()) !== canonical([...policy.otherPurposes].sort())) {
162
+ throw new Error(`consent-kit: two receipt manifests disagree about policy ${policy.policyHash} at revision ${policy.revision}`);
163
+ }
164
+ const supersededAt = known.supersededAt === null || policy.supersededAt === null ? null : known.supersededAt > policy.supersededAt ? known.supersededAt : policy.supersededAt;
165
+ policies.set(key, { ...known, supersededAt });
166
+ }
167
+ const hashes = new Set([...policies.values()].map((policy) => policy.policyHash));
168
+ const maxClockSkewMs = options.maxClockSkewMs ?? DEFAULT_MAX_CLOCK_SKEW_MS;
169
+ const maxSupersededAgeMs = options.maxSupersededAgeMs ?? Number.POSITIVE_INFINITY;
170
+ if (!(maxSupersededAgeMs >= 0)) throw new Error("consent-kit: maxSupersededAgeMs must be a non-negative number of milliseconds");
171
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
172
+ const onStoreError = options.onStoreError ?? ((error) => console.error("consent-kit: storing a consent receipt failed", error));
173
+ const store = options.store;
174
+ return async (request) => {
175
+ const origin = request.headers.get("Origin");
176
+ const corsOrigin = origin !== null && allowed.has(origin) ? origin : null;
177
+ const respond = (status, error, extra = {}) => {
178
+ const headers = new Headers({ "Cache-Control": "no-store", Vary: "Origin", ...extra });
179
+ if (corsOrigin !== null) headers.set("Access-Control-Allow-Origin", corsOrigin);
180
+ if (error === void 0) return new Response(null, { status, headers });
181
+ headers.set("Content-Type", "application/json");
182
+ headers.set("X-Content-Type-Options", "nosniff");
183
+ return new Response(JSON.stringify({ error }), { status, headers });
184
+ };
185
+ try {
186
+ if (new URL(request.url).pathname !== path) return respond(404, "request/not-found");
187
+ if (request.method !== "POST") return respond(405, "request/method-not-allowed", { Allow: "POST" });
188
+ if (origin === null) {
189
+ if (options.allowMissingOrigin !== true) return respond(403, "request/origin-missing");
190
+ } else if (corsOrigin === null) {
191
+ return respond(403, "request/origin-forbidden");
192
+ }
193
+ if (!acceptableMediaType(request.headers.get("Content-Type"))) return respond(415, "request/unsupported-media-type");
194
+ const bytes = await readAtMost(request, MAX_RECEIPT_BYTES);
195
+ if (bytes === null) return respond(413, "request/body-too-large");
196
+ let body;
197
+ try {
198
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes));
199
+ } catch {
200
+ return respond(400, "request/invalid-json");
201
+ }
202
+ const receivedAt = now();
203
+ const checked = checkReceipt(body, { policies, hashes, now: receivedAt, maxClockSkewMs, maxSupersededAgeMs });
204
+ if (!checked.ok) return respond(MALFORMED.has(checked.problem) ? 400 : 422, checked.problem);
205
+ const { receipt } = checked;
206
+ const subjectHash = await hash(receipt.consentId);
207
+ try {
208
+ await store.append({
209
+ subjectHash,
210
+ event: receipt.event,
211
+ accepted: receipt.accepted,
212
+ rejected: receipt.rejected,
213
+ policyHash: receipt.policyHash,
214
+ revision: receipt.revision,
215
+ clientTimestamp: receipt.timestamp,
216
+ receivedAt: receivedAt.toISOString()
217
+ });
218
+ } catch (error) {
219
+ onStoreError(error);
220
+ return respond(503, "server/store-failed");
221
+ }
222
+ return respond(204);
223
+ } catch {
224
+ return respond(500, "server/error");
225
+ }
226
+ };
227
+ }
228
+ function canonical(value) {
229
+ return Array.isArray(value) ? JSON.stringify(value) : JSON.stringify(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
230
+ }
231
+ function allowedOriginSet(origins) {
232
+ if (!Array.isArray(origins)) throw new Error("consent-kit: allowedOrigins must be an array of origins");
233
+ for (const origin of origins) {
234
+ let parsed;
235
+ try {
236
+ parsed = new URL(origin);
237
+ } catch {
238
+ parsed = void 0;
239
+ }
240
+ if (parsed === void 0 || parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.origin !== origin) {
241
+ throw new Error(`consent-kit: "${origin}" is not an origin; give it as a browser sends it, e.g. "https://www.example.com"`);
242
+ }
243
+ }
244
+ return new Set(origins);
245
+ }
246
+ function endpointPath(endpoints) {
247
+ const paths = new Set(endpoints.map((endpoint) => new URL(endpoint, "https://site.invalid").pathname));
248
+ if (paths.size !== 1) throw new Error(`consent-kit: the receipt manifests name different endpoints (${[...paths].join(", ")}); pass \`path\``);
249
+ return [...paths][0];
250
+ }
251
+ function acceptableMediaType(header) {
252
+ if (header === null) return false;
253
+ const [type, ...parameters] = header.split(";").map((part) => part.trim().toLowerCase());
254
+ if (type === void 0 || !MEDIA_TYPES.has(type)) return false;
255
+ return parameters.every((parameter) => parameter === "" || /^charset="?utf-8"?$/.test(parameter));
256
+ }
257
+ async function readAtMost(request, limit) {
258
+ const declared = Number(request.headers.get("Content-Length"));
259
+ if (Number.isFinite(declared) && declared > limit) return null;
260
+ if (request.body === null) return new Uint8Array(0);
261
+ const reader = request.body.getReader();
262
+ const chunks = [];
263
+ let total = 0;
264
+ for (; ; ) {
265
+ const { done, value } = await reader.read();
266
+ if (done) break;
267
+ total += value.byteLength;
268
+ if (total > limit) {
269
+ await reader.cancel().catch(() => void 0);
270
+ return null;
271
+ }
272
+ chunks.push(value);
273
+ }
274
+ const bytes = new Uint8Array(total);
275
+ let offset = 0;
276
+ for (const chunk of chunks) {
277
+ bytes.set(chunk, offset);
278
+ offset += chunk.byteLength;
279
+ }
280
+ return bytes;
281
+ }
282
+
283
+ // src/store.ts
284
+ function createMemoryReceiptStore() {
285
+ const receipts = [];
286
+ return {
287
+ receipts,
288
+ async append(receipt) {
289
+ receipts.push(structuredClone(receipt));
290
+ },
291
+ async listBySubject(subjectHash) {
292
+ return receipts.filter((receipt) => receipt.subjectHash === subjectHash).map((receipt) => structuredClone(receipt));
293
+ },
294
+ async deleteBySubject(subjectHash) {
295
+ let deleted = 0;
296
+ for (let index = receipts.length - 1; index >= 0; index -= 1) {
297
+ if (receipts[index]?.subjectHash !== subjectHash) continue;
298
+ receipts.splice(index, 1);
299
+ deleted += 1;
300
+ }
301
+ return deleted;
302
+ }
303
+ };
304
+ }
305
+
306
+ // src/d1.ts
307
+ var RECEIPTS_TABLE = "consent_receipts";
308
+ var INSERT = `INSERT INTO ${RECEIPTS_TABLE} (subject_hash, event, accepted, rejected, policy_hash, revision, client_timestamp, received_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
309
+ var SELECT_BY_SUBJECT = `SELECT subject_hash, event, accepted, rejected, policy_hash, revision, client_timestamp, received_at FROM ${RECEIPTS_TABLE} WHERE subject_hash = ? ORDER BY id`;
310
+ var DELETE_BY_SUBJECT = `DELETE FROM ${RECEIPTS_TABLE} WHERE subject_hash = ?`;
311
+ function changesOf(result) {
312
+ if (typeof result !== "object" || result === null) return 0;
313
+ const meta = result.meta;
314
+ const changes = meta?.changes ?? result.changes;
315
+ return typeof changes === "number" ? changes : typeof changes === "bigint" ? Number(changes) : 0;
316
+ }
317
+ function createD1ReceiptStore(db) {
318
+ return {
319
+ async append(receipt) {
320
+ await db.prepare(INSERT).bind(
321
+ receipt.subjectHash,
322
+ receipt.event,
323
+ JSON.stringify(receipt.accepted.map(({ purpose, version }) => ({ purpose, version }))),
324
+ JSON.stringify(receipt.rejected.map(({ purpose, version }) => ({ purpose, version }))),
325
+ receipt.policyHash,
326
+ receipt.revision,
327
+ receipt.clientTimestamp,
328
+ receipt.receivedAt
329
+ ).run();
330
+ },
331
+ async listBySubject(subjectHash) {
332
+ const { results } = await db.prepare(SELECT_BY_SUBJECT).bind(subjectHash).all();
333
+ return results.map((row) => ({
334
+ subjectHash: row.subject_hash,
335
+ event: row.event,
336
+ accepted: JSON.parse(row.accepted),
337
+ rejected: JSON.parse(row.rejected),
338
+ policyHash: row.policy_hash,
339
+ revision: row.revision,
340
+ clientTimestamp: row.client_timestamp,
341
+ receivedAt: row.received_at
342
+ }));
343
+ },
344
+ async deleteBySubject(subjectHash) {
345
+ return changesOf(await db.prepare(DELETE_BY_SUBJECT).bind(subjectHash).run());
346
+ }
347
+ };
348
+ }
349
+
350
+ // src/requests/dates.ts
351
+ function addMonths(date, months) {
352
+ const result = new Date(date.getTime());
353
+ const day = result.getUTCDate();
354
+ result.setUTCDate(1);
355
+ result.setUTCMonth(result.getUTCMonth() + months);
356
+ const lastDay = new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate();
357
+ result.setUTCDate(Math.min(day, lastDay));
358
+ return result;
359
+ }
360
+ function dueDate(receivedAt) {
361
+ return addMonths(receivedAt, 1);
362
+ }
363
+ var RETENTION = /^([1-9][0-9]*)([dy])$/;
364
+ function retentionCutoff(retention, now) {
365
+ const match = RETENTION.exec(retention);
366
+ if (!match) throw new Error(`consent-kit: retention ${JSON.stringify(retention)} is not "<n>d" or "<n>y"`);
367
+ const count = Number(match[1]);
368
+ if (match[2] === "d") return new Date(now.getTime() - count * 24 * 60 * 60 * 1e3);
369
+ return addMonths(now, -12 * count);
370
+ }
371
+ function isoDay(date) {
372
+ return date.toISOString().slice(0, 10);
373
+ }
374
+
375
+ // src/requests/store.ts
376
+ function effectiveDueAt(record) {
377
+ return record.extendedDueAt ?? record.dueAt;
378
+ }
379
+ function createMemorySubjectRequestStore() {
380
+ const requests = [];
381
+ const slots = /* @__PURE__ */ new Map();
382
+ const expire = (windowStart) => {
383
+ let deleted = 0;
384
+ for (const [key, slot] of slots) {
385
+ if (key === "*" || slot.windowStart > windowStart) continue;
386
+ slots.delete(key);
387
+ deleted += 1;
388
+ }
389
+ return deleted;
390
+ };
391
+ const open = (id) => requests.find((request) => request.id === id && request.status !== "closed");
392
+ const update = (id, change) => {
393
+ const request = open(id);
394
+ return Promise.resolve(request === void 0 ? false : change(request));
395
+ };
396
+ const byReceived = (a, b) => a.receivedAt < b.receivedAt ? -1 : a.receivedAt > b.receivedAt ? 1 : 0;
397
+ return {
398
+ requests,
399
+ async create(record) {
400
+ if (requests.some((request) => request.id === record.id)) throw new Error(`consent-kit: request ${record.id} exists already`);
401
+ requests.push(structuredClone(record));
402
+ },
403
+ async getById(id) {
404
+ const request = requests.find((candidate) => candidate.id === id);
405
+ return request === void 0 ? null : structuredClone(request);
406
+ },
407
+ confirm: (id, at) => update(id, (request) => {
408
+ if (request.status !== "received") return false;
409
+ request.status = "confirmed";
410
+ request.confirmedAt = at;
411
+ return true;
412
+ }),
413
+ markNotified: (id, at) => update(id, (request) => (request.notifiedAt = at, true)),
414
+ markConfirmationSent: (id, at) => update(id, (request) => (request.confirmationSentAt = at, true)),
415
+ // No await between the check and the write: atomic within the one JavaScript thread.
416
+ async reserveConfirmationSlot(key, slot) {
417
+ expire(slot.windowStart);
418
+ const current = slots.get(key);
419
+ if (current === void 0 || current.windowStart <= slot.windowStart) {
420
+ slots.set(key, { windowStart: slot.at, count: 1 });
421
+ return true;
422
+ }
423
+ if (current.count >= slot.cap) return false;
424
+ current.count += 1;
425
+ return true;
426
+ },
427
+ async releaseConfirmationSlot(key, at) {
428
+ const current = slots.get(key);
429
+ if (current !== void 0 && current.windowStart === at && current.count === 1) slots.delete(key);
430
+ },
431
+ async deleteExpiredConfirmationSlots(windowStart) {
432
+ return expire(windowStart);
433
+ },
434
+ extend: (id, extension) => update(id, (request) => {
435
+ request.extendedDueAt = extension.dueAt;
436
+ request.extensionReason = extension.reason;
437
+ return true;
438
+ }),
439
+ close: (id, closing) => update(id, (request) => {
440
+ request.status = "closed";
441
+ request.closedAt = closing.at;
442
+ request.outcome = closing.outcome;
443
+ return true;
444
+ }),
445
+ async listOpen() {
446
+ return requests.filter((request) => request.status !== "closed").sort(byReceived).map((request) => structuredClone(request));
447
+ },
448
+ async listDueBefore(at) {
449
+ return requests.filter((request) => request.status !== "closed" && effectiveDueAt(request) <= at).sort(byReceived).map((request) => structuredClone(request));
450
+ },
451
+ async deleteClosedBefore(at) {
452
+ let deleted = 0;
453
+ for (let index = requests.length - 1; index >= 0; index -= 1) {
454
+ const request = requests[index];
455
+ if (request.status === "closed" && request.closedAt !== null && request.closedAt < at) {
456
+ requests.splice(index, 1);
457
+ deleted += 1;
458
+ }
459
+ }
460
+ return deleted;
461
+ }
462
+ };
463
+ }
464
+
465
+ // src/requests/emails.ts
466
+ function fill(template, values) {
467
+ return template.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name) => Object.hasOwn(values, name) ? String(values[name]) : match);
468
+ }
469
+ function localeOf(manifest, locale) {
470
+ return manifest.locales[locale ?? ""] ?? manifest.locales[manifest.defaultLocale];
471
+ }
472
+ function notificationEmail(manifest, request, facts) {
473
+ const { texts, checklists } = localeOf(manifest, manifest.defaultLocale);
474
+ const type = texts.typeLabels[request.type];
475
+ const cookie = facts.cookie ? fill(texts.cookiePresent, { count: facts.receipts ?? "?" }) : texts.cookieAbsent;
476
+ const confirmed = manifest.requesterEmail === null ? texts.confirmedNotAsked : request.status === "confirmed" ? request.confirmedAt ?? "" : texts.confirmedPending;
477
+ return {
478
+ subject: fill(texts.notification.subject, { id: request.id, type }),
479
+ text: fill(texts.notification.body, {
480
+ type,
481
+ email: request.email,
482
+ id: request.id,
483
+ received: request.receivedAt,
484
+ due: isoDay(new Date(effectiveDueAt(request))),
485
+ cookie,
486
+ confirmed,
487
+ details: request.details ?? texts.noDetails,
488
+ checklist: checklists[request.type] ?? ""
489
+ }),
490
+ replyTo: request.email
491
+ };
492
+ }
493
+ function confirmationEmail(manifest, request, link, days) {
494
+ const { texts } = localeOf(manifest, request.locale);
495
+ return {
496
+ subject: texts.confirmation.subject,
497
+ text: fill(texts.confirmation.body, { type: texts.typeLabels[request.type], link, days })
498
+ };
499
+ }
500
+ function reminderEmail(manifest, requests, options) {
501
+ if (requests.length === 0) return null;
502
+ const { texts } = localeOf(manifest, manifest.defaultLocale);
503
+ const now = options.now.toISOString();
504
+ const items = requests.map((request) => {
505
+ const due = effectiveDueAt(request);
506
+ const line = fill(texts.reminder.item, { id: request.id, type: texts.typeLabels[request.type], email: request.email, received: isoDay(new Date(request.receivedAt)), due: isoDay(new Date(due)) });
507
+ return line + (due < now ? texts.reminder.overdue : "") + (request.notifiedAt === null ? texts.reminder.notNotified : "");
508
+ });
509
+ return {
510
+ subject: fill(texts.reminder.subject, { count: requests.length }),
511
+ text: fill(texts.reminder.body, { days: options.withinDays, items: items.join("\n") })
512
+ };
513
+ }
514
+
515
+ // src/requests/manifest.ts
516
+ var SUBJECT_REQUEST_TYPES = ["access", "erasure"];
517
+ var HEX_643 = /^[0-9a-f]{64}$/;
518
+ var RETENTION2 = /^[1-9][0-9]*[dy]$/;
519
+ var KEYS = ["controller", "defaultLocale", "endpoint", "locales", "manifestVersion", "notify", "policyHash", "requesterEmail", "retention", "types", "unreviewedPhrases"];
520
+ function parseSubjectRequestManifest(value) {
521
+ const fail = (problem) => {
522
+ throw new Error(`consent-kit: invalid subject request manifest: ${problem}`);
523
+ };
524
+ if (!isRecord(value)) return fail("not an object");
525
+ const keys = Object.keys(value).sort();
526
+ if (keys.length !== KEYS.length || keys.some((key, index) => key !== KEYS[index])) return fail(`expected exactly the keys ${KEYS.join(", ")}`);
527
+ if (value.manifestVersion !== 1) return fail("manifestVersion must be 1");
528
+ if (typeof value.endpoint !== "string" || !value.endpoint.startsWith("/") || value.endpoint.startsWith("//")) return fail("endpoint must be a site-relative path");
529
+ if (typeof value.notify !== "string" || !value.notify.includes("@")) return fail("notify must be an email address");
530
+ const types = value.types;
531
+ if (!Array.isArray(types) || types.length === 0 || !types.every((type) => SUBJECT_REQUEST_TYPES.includes(type))) {
532
+ return fail(`types must be a non-empty list of ${SUBJECT_REQUEST_TYPES.join(", ")}`);
533
+ }
534
+ if (typeof value.retention !== "string" || !RETENTION2.test(value.retention)) return fail('retention must be "<n>d" or "<n>y"');
535
+ const requesterEmail = value.requesterEmail;
536
+ if (requesterEmail !== null && !(isRecord(requesterEmail) && typeof requesterEmail.processor === "string")) return fail("requesterEmail must be null or { processor }");
537
+ if (!isRecord(value.controller) || typeof value.controller.name !== "string") return fail("controller must be { name }");
538
+ if (typeof value.policyHash !== "string" || !HEX_643.test(value.policyHash)) return fail("policyHash must be 64 lowercase hex digits");
539
+ if (!isRecord(value.locales) || Object.keys(value.locales).length === 0) return fail("locales must be a non-empty object");
540
+ if (typeof value.defaultLocale !== "string" || !Object.hasOwn(value.locales, value.defaultLocale)) return fail("defaultLocale must be one of the locales");
541
+ const locales = {};
542
+ for (const [locale, entry] of Object.entries(value.locales)) {
543
+ const at = `locales.${locale}`;
544
+ if (!isRecord(entry) || !isRecord(entry.texts) || !isRecord(entry.checklists) || !isRecord(entry.pages)) return fail(`${at} must have texts, checklists and pages`);
545
+ const strings = (holder, names, where) => {
546
+ if (!isRecord(holder)) return fail(`${where} must be an object`);
547
+ for (const name of names) if (typeof holder[name] !== "string") fail(`${where}.${name} must be a string`);
548
+ };
549
+ const texts = entry.texts;
550
+ strings(texts, ["cookiePresent", "cookieAbsent", "confirmedPending", "confirmedNotAsked", "noDetails"], `${at}.texts`);
551
+ strings(texts.typeLabels, SUBJECT_REQUEST_TYPES, `${at}.texts.typeLabels`);
552
+ strings(texts.notification, ["subject", "body"], `${at}.texts.notification`);
553
+ strings(texts.confirmation, ["subject", "body"], `${at}.texts.confirmation`);
554
+ strings(texts.reminder, ["subject", "body", "item", "overdue", "notNotified"], `${at}.texts.reminder`);
555
+ strings(entry.pages, ["form", "received", "confirm", "confirmed", "linkInvalid"], `${at}.pages`);
556
+ if (!entry.pages.confirm.includes("{token}")) fail(`${at}.pages.confirm must hold the {token} placeholder`);
557
+ strings(entry.checklists, types, `${at}.checklists`);
558
+ locales[locale] = entry;
559
+ }
560
+ const unreviewed = value.unreviewedPhrases;
561
+ if (!Array.isArray(unreviewed) || !unreviewed.every((id) => typeof id === "string")) return fail("unreviewedPhrases must be a list of phrase ids");
562
+ return {
563
+ manifestVersion: 1,
564
+ endpoint: value.endpoint,
565
+ notify: value.notify,
566
+ types: [...types],
567
+ retention: value.retention,
568
+ requesterEmail: requesterEmail === null ? null : { processor: requesterEmail.processor },
569
+ controller: { name: value.controller.name },
570
+ policyHash: value.policyHash,
571
+ defaultLocale: value.defaultLocale,
572
+ locales,
573
+ unreviewedPhrases: [...unreviewed]
574
+ };
575
+ }
576
+
577
+ // src/requests/token.ts
578
+ var LABEL = "consent-kit/subject-request-confirmation/v1";
579
+ var ID = /^[0-9a-f]{32}$/;
580
+ function base64url(bytes) {
581
+ let binary = "";
582
+ for (const byte of bytes) binary += String.fromCharCode(byte);
583
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
584
+ }
585
+ function fromBase64url(text) {
586
+ if (!/^[A-Za-z0-9_-]+$/.test(text)) return null;
587
+ try {
588
+ const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/"));
589
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
590
+ } catch {
591
+ return null;
592
+ }
593
+ }
594
+ function tokenSigner(keyBytes) {
595
+ let imported;
596
+ const key = () => imported ??= crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
597
+ const message = (id, expires) => new TextEncoder().encode(`${LABEL}
598
+ ${id}
599
+ ${expires}`);
600
+ return {
601
+ async sign(requestId, expiresAt) {
602
+ const expires = Math.floor(expiresAt.getTime() / 1e3);
603
+ const signature = new Uint8Array(await crypto.subtle.sign("HMAC", await key(), message(requestId, expires)));
604
+ return `${requestId}.${expires}.${base64url(signature)}`;
605
+ },
606
+ async verify(token, now) {
607
+ if (token.length > 200) return null;
608
+ const [id, expiresText, signatureText, ...rest] = token.split(".");
609
+ if (rest.length > 0 || id === void 0 || expiresText === void 0 || signatureText === void 0) return null;
610
+ if (!ID.test(id) || !/^[0-9]{1,12}$/.test(expiresText)) return null;
611
+ const signature = fromBase64url(signatureText);
612
+ if (signature === null || signature.byteLength !== 32) return null;
613
+ const expires = Number(expiresText);
614
+ const valid = await crypto.subtle.verify("HMAC", await key(), signature, message(id, expires));
615
+ if (!valid || expires * 1e3 <= now.getTime()) return null;
616
+ return id;
617
+ }
618
+ };
619
+ }
620
+
621
+ // src/requests/handler.ts
622
+ var MAX_SUBJECT_REQUEST_BYTES = 4096;
623
+ var MAX_EMAIL_LENGTH = 254;
624
+ var MAX_DETAILS_LENGTH = 2e3;
625
+ var HONEYPOT_FIELD = "website";
626
+ var CONFIRMATION_RATE_LIMIT_MS = 60 * 60 * 1e3;
627
+ var DEFAULT_MAX_CONFIRMATIONS_PER_HOUR = 100;
628
+ function rateLimitAddress(email) {
629
+ const lower = email.toLowerCase();
630
+ const at = lower.lastIndexOf("@");
631
+ const local = lower.slice(0, at);
632
+ const plus = local.indexOf("+");
633
+ return `${plus === -1 ? local : local.slice(0, plus)}${lower.slice(at)}`;
634
+ }
635
+ var DEFAULT_CONFIRMATION_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
636
+ var DEFAULT_CONSENT_COOKIE = "cc_cookie";
637
+ var FIELDS = /* @__PURE__ */ new Set(["email", "type", "details", "locale", HONEYPOT_FIELD]);
638
+ var CONFIRM_FIELD = "confirm";
639
+ var TOKEN_SHAPE = /^[0-9a-f]{32}\.[0-9]{1,12}\.[A-Za-z0-9_-]{43}$/;
640
+ var EMAIL = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
641
+ var CONSENT_ID2 = /^[A-Za-z0-9-]{1,128}$/;
642
+ var LOCATIONS = {
643
+ received: (path, id) => `${path}?request=${id}`,
644
+ confirmed: (path) => `${path}?status=confirmed`,
645
+ linkInvalid: (path) => `${path}?status=link-invalid`,
646
+ confirm: (origin, path, token) => `${origin}${path}?confirm=${encodeURIComponent(token)}`
647
+ };
648
+ function randomId() {
649
+ return [...crypto.getRandomValues(new Uint8Array(16))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
650
+ }
651
+ function consentIdFromCookie(header, name = DEFAULT_CONSENT_COOKIE) {
652
+ if (header === null) return null;
653
+ for (const part of header.split(";")) {
654
+ const separator = part.indexOf("=");
655
+ if (separator === -1 || part.slice(0, separator).trim() !== name) continue;
656
+ try {
657
+ const value = JSON.parse(decodeURIComponent(part.slice(separator + 1).trim()));
658
+ const id = typeof value === "object" && value !== null ? value.consentId : void 0;
659
+ return typeof id === "string" && CONSENT_ID2.test(id) ? id : null;
660
+ } catch {
661
+ return null;
662
+ }
663
+ }
664
+ return null;
665
+ }
666
+ function negotiate(header, available, fallback) {
667
+ if (header === null) return fallback;
668
+ const ranked = header.split(",").map((part, index) => {
669
+ const [tag = "", ...params] = part.trim().split(";");
670
+ const q = Number(params.find((param) => param.trim().startsWith("q="))?.trim().slice(2) ?? "1");
671
+ return { tag: tag.toLowerCase(), q: Number.isFinite(q) ? q : 0, index };
672
+ }).filter((entry) => entry.tag !== "" && entry.q > 0).sort((a, b) => b.q - a.q || a.index - b.index);
673
+ for (const { tag } of ranked) {
674
+ const exact = available.find((locale) => locale.toLowerCase() === tag);
675
+ if (exact !== void 0) return exact;
676
+ const base = available.find((locale) => locale.toLowerCase().split("-")[0] === tag.split("-")[0]);
677
+ if (base !== void 0) return base;
678
+ }
679
+ return fallback;
680
+ }
681
+ function createSubjectRequestHandler(options) {
682
+ const keyBytes = hmacKeyBytes(options.hmacKey);
683
+ const hash = subjectHasher(keyBytes);
684
+ const tokens = tokenSigner(keyBytes);
685
+ const manifest = parseSubjectRequestManifest(options.manifest);
686
+ const allowed = originSet(options.allowedOrigins);
687
+ const path = options.path ?? manifest.endpoint;
688
+ if (typeof options.from !== "string" || !options.from.includes("@")) throw new Error("consent-kit: `from` must be the address the emails are sent from");
689
+ const confirming = manifest.requesterEmail !== null;
690
+ if (confirming && options.requesterSender === void 0) {
691
+ throw new Error(`consent-kit: the manifest asks for a confirmation email to the requester (through "${manifest.requesterEmail?.processor}") but no requesterSender was given`);
692
+ }
693
+ const ttl = options.confirmationTtlMs ?? DEFAULT_CONFIRMATION_TTL_MS;
694
+ const maxConfirmations = options.maxConfirmationsPerHour ?? DEFAULT_MAX_CONFIRMATIONS_PER_HOUR;
695
+ if (!Number.isSafeInteger(maxConfirmations) || maxConfirmations < 1) throw new Error("consent-kit: maxConfirmationsPerHour must be a positive integer");
696
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
697
+ const onStoreError = options.onStoreError ?? ((error) => console.error("consent-kit: storing a subject request failed", error));
698
+ const onEmailError = options.onEmailError ?? ((error, context) => console.error(`consent-kit: the ${context.email} email of subject request ${context.requestId} was not sent`, error));
699
+ const onCapReached = options.onConfirmationCapReached ?? ((info) => console.warn(`consent-kit: the cap of ${info.cap} confirmation emails per hour was reached; a confirmation email was not sent`));
700
+ const pages = options.pages === false ? void 0 : options.pages ?? Object.fromEntries(Object.entries(manifest.locales).map(([locale, entry]) => [locale, entry.pages]));
701
+ const { store } = options;
702
+ const headers = (extra = {}) => new Headers({ "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff", ...extra });
703
+ const refuse = (status, error, extra = {}) => new Response(`consent-kit: the request was not accepted (${error}).
704
+ `, { status, headers: headers({ "Content-Type": "text/plain; charset=utf-8", ...extra }) });
705
+ const redirect = (location) => new Response(null, { status: 303, headers: headers({ Location: location }) });
706
+ const manifestPages = Object.fromEntries(Object.entries(manifest.locales).map(([locale, entry]) => [locale, entry.pages]));
707
+ const page = (request, which, fillToken) => {
708
+ const source = which === "confirm" ? { ...manifestPages, ...Object.fromEntries(Object.entries(pages ?? {}).filter(([, entry]) => entry.confirm !== void 0)) } : pages;
709
+ const locales = Object.keys(source ?? {}).filter((locale2) => source?.[locale2]?.[which] !== void 0);
710
+ const fallback = locales.includes(manifest.defaultLocale) ? manifest.defaultLocale : locales[0];
711
+ if (fallback === void 0) return refuse(404, "request/not-found");
712
+ const locale = negotiate(request.headers.get("Accept-Language"), locales, fallback);
713
+ const template = source?.[locale]?.[which];
714
+ const html = fillToken === void 0 ? template : template.replaceAll("{token}", fillToken);
715
+ return new Response(request.method === "HEAD" ? null : html, {
716
+ status: 200,
717
+ headers: headers({
718
+ "Content-Type": "text/html; charset=utf-8",
719
+ "Content-Language": locale,
720
+ Vary: "Accept-Language",
721
+ // The generated pages have no script and no inline style; a site's own stylesheet is allowed.
722
+ "Content-Security-Policy": "default-src 'none'; style-src 'self'; img-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'"
723
+ })
724
+ });
725
+ };
726
+ const sendEmails = async (record, origin, cookie) => {
727
+ let receipts = null;
728
+ if (record.subjectHash !== null && options.receipts !== void 0) {
729
+ try {
730
+ receipts = (await options.receipts.listBySubject(record.subjectHash)).length;
731
+ } catch {
732
+ receipts = null;
733
+ }
734
+ }
735
+ try {
736
+ const email = notificationEmail(manifest, record, { cookie, receipts });
737
+ await options.notifySender.send({ to: manifest.notify, from: options.from, replyTo: email.replyTo, subject: email.subject, text: email.text });
738
+ await store.markNotified(record.id, now().toISOString());
739
+ } catch (error) {
740
+ onEmailError(error, { requestId: record.id, email: "notification" });
741
+ }
742
+ if (!confirming || options.requesterSender === void 0 || /\.invalid$/i.test(record.email)) return;
743
+ try {
744
+ const at = now();
745
+ const slot = { at: at.toISOString(), windowStart: new Date(at.getTime() - CONFIRMATION_RATE_LIMIT_MS).toISOString() };
746
+ const rateKey = await hash(`consent-kit/confirmation-rate
747
+ ${rateLimitAddress(record.email)}`);
748
+ if (!await store.reserveConfirmationSlot(rateKey, { ...slot, cap: 1 })) return;
749
+ if (!await store.reserveConfirmationSlot("*", { ...slot, cap: maxConfirmations })) {
750
+ await store.releaseConfirmationSlot(rateKey, slot.at);
751
+ onCapReached({ cap: maxConfirmations, windowMs: CONFIRMATION_RATE_LIMIT_MS });
752
+ return;
753
+ }
754
+ const token = await tokens.sign(record.id, new Date(at.getTime() + ttl));
755
+ const email = confirmationEmail(manifest, record, LOCATIONS.confirm(origin, path, token), Math.round(ttl / (24 * 60 * 60 * 1e3)));
756
+ await options.requesterSender.send({ to: record.email, from: options.requesterFrom ?? options.from, subject: email.subject, text: email.text });
757
+ await store.markConfirmationSent(record.id, at.toISOString());
758
+ } catch (error) {
759
+ onEmailError(error, { requestId: record.id, email: "confirmation" });
760
+ }
761
+ };
762
+ const submit = async (request, context) => {
763
+ const origin = request.headers.get("Origin");
764
+ if (origin === null) {
765
+ if (options.allowMissingOrigin !== true) return refuse(403, "request/origin-missing");
766
+ } else if (!allowed.has(origin)) {
767
+ return refuse(403, "request/origin-forbidden");
768
+ }
769
+ if (!isFormEncoded(request.headers.get("Content-Type"))) return refuse(415, "request/unsupported-media-type");
770
+ const bytes = await readAtMost2(request, MAX_SUBJECT_REQUEST_BYTES);
771
+ if (bytes === null) return refuse(413, "request/body-too-large");
772
+ let form;
773
+ try {
774
+ form = new URLSearchParams(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
775
+ } catch {
776
+ return refuse(400, "request/invalid-form");
777
+ }
778
+ const names = [...form.keys()];
779
+ if (names.includes(CONFIRM_FIELD)) return names.length === 1 ? confirm(form.get(CONFIRM_FIELD)) : refuse(400, "request/unexpected-fields");
780
+ if (names.some((name) => !FIELDS.has(name)) || new Set(names).size !== names.length) return refuse(400, "request/unexpected-fields");
781
+ const email = (form.get("email") ?? "").trim();
782
+ if (email.length > MAX_EMAIL_LENGTH || !EMAIL.test(email)) return refuse(400, "request/invalid-email");
783
+ const type = form.get("type") ?? "";
784
+ if (!manifest.types.includes(type)) return refuse(400, "request/invalid-type");
785
+ const details = (form.get("details") ?? "").replace(/\r\n?/g, "\n").trim();
786
+ if ([...details].length > MAX_DETAILS_LENGTH) return refuse(400, "request/details-too-long");
787
+ const locale = Object.hasOwn(manifest.locales, form.get("locale") ?? "") ? form.get("locale") : manifest.defaultLocale;
788
+ const consentId = consentIdFromCookie(request.headers.get("Cookie"), options.consentCookieName);
789
+ const [emailHash, subjectHash] = await Promise.all([hash(email.toLowerCase()), consentId === null ? hash("") : hash(consentId)]);
790
+ const id = randomId();
791
+ if ((form.get(HONEYPOT_FIELD) ?? "") !== "") return redirect(LOCATIONS.received(path, id));
792
+ const receivedAt = now();
793
+ const record = {
794
+ id,
795
+ type,
796
+ email,
797
+ emailHash,
798
+ subjectHash: consentId === null ? null : subjectHash,
799
+ details: details === "" ? null : details,
800
+ locale,
801
+ policyHash: manifest.policyHash,
802
+ receivedAt: receivedAt.toISOString(),
803
+ dueAt: dueDate(receivedAt).toISOString(),
804
+ extendedDueAt: null,
805
+ extensionReason: null,
806
+ status: "received",
807
+ confirmedAt: null,
808
+ closedAt: null,
809
+ outcome: null,
810
+ notifiedAt: null,
811
+ confirmationSentAt: null
812
+ };
813
+ try {
814
+ await store.create(record);
815
+ } catch (error) {
816
+ onStoreError(error);
817
+ return refuse(503, "server/store-failed", { "Retry-After": "60" });
818
+ }
819
+ const send = () => sendEmails(record, origin ?? new URL(request.url).origin, consentId !== null);
820
+ if (context !== void 0) context.waitUntil(new Promise((resolve) => setTimeout(resolve, 0)).then(send));
821
+ else await send();
822
+ return redirect(LOCATIONS.received(path, id));
823
+ };
824
+ async function confirm(token) {
825
+ const id = await tokens.verify(token, now());
826
+ if (id === null) return redirect(LOCATIONS.linkInvalid(path));
827
+ try {
828
+ return redirect(await store.confirm(id, now().toISOString()) ? LOCATIONS.confirmed(path) : LOCATIONS.linkInvalid(path));
829
+ } catch (error) {
830
+ onStoreError(error);
831
+ return refuse(503, "server/store-failed", { "Retry-After": "60" });
832
+ }
833
+ }
834
+ return async (request, context) => {
835
+ try {
836
+ const url = new URL(request.url);
837
+ if (url.pathname !== path) return refuse(404, "request/not-found");
838
+ if (request.method === "POST") return await submit(request, context);
839
+ if (request.method !== "GET" && request.method !== "HEAD") return refuse(405, "request/method-not-allowed", { Allow: "GET, HEAD, POST" });
840
+ const token = url.searchParams.get(CONFIRM_FIELD);
841
+ if (token !== null) {
842
+ const valid = TOKEN_SHAPE.test(token) && await tokens.verify(token, now()) !== null;
843
+ return valid ? page(request, "confirm", token) : redirect(LOCATIONS.linkInvalid(path));
844
+ }
845
+ if (pages === void 0) return refuse(404, "request/not-found");
846
+ if (url.searchParams.has("request")) return page(request, "received");
847
+ const status = url.searchParams.get("status");
848
+ if (status === "confirmed") return page(request, "confirmed");
849
+ if (status === "link-invalid") return page(request, "linkInvalid");
850
+ return page(request, "form");
851
+ } catch {
852
+ return refuse(500, "server/error");
853
+ }
854
+ };
855
+ }
856
+ function originSet(origins) {
857
+ if (!Array.isArray(origins)) throw new Error("consent-kit: allowedOrigins must be an array of origins");
858
+ for (const origin of origins) {
859
+ let parsed;
860
+ try {
861
+ parsed = new URL(origin);
862
+ } catch {
863
+ parsed = void 0;
864
+ }
865
+ if (parsed === void 0 || parsed.protocol !== "https:" && parsed.protocol !== "http:" || parsed.origin !== origin) {
866
+ throw new Error(`consent-kit: "${origin}" is not an origin; give it as a browser sends it, e.g. "https://www.example.com"`);
867
+ }
868
+ }
869
+ return new Set(origins);
870
+ }
871
+ function isFormEncoded(header) {
872
+ if (header === null) return false;
873
+ const [type, ...parameters] = header.split(";").map((part) => part.trim().toLowerCase());
874
+ if (type !== "application/x-www-form-urlencoded") return false;
875
+ return parameters.every((parameter) => parameter === "" || /^charset="?utf-8"?$/.test(parameter));
876
+ }
877
+ async function readAtMost2(request, limit) {
878
+ const declared = Number(request.headers.get("Content-Length"));
879
+ if (Number.isFinite(declared) && declared > limit) return null;
880
+ if (request.body === null) return new Uint8Array(0);
881
+ const reader = request.body.getReader();
882
+ const chunks = [];
883
+ let total = 0;
884
+ for (; ; ) {
885
+ const { done, value } = await reader.read();
886
+ if (done) break;
887
+ total += value.byteLength;
888
+ if (total > limit) {
889
+ await reader.cancel().catch(() => void 0);
890
+ return null;
891
+ }
892
+ chunks.push(value);
893
+ }
894
+ const bytes = new Uint8Array(total);
895
+ let offset = 0;
896
+ for (const chunk of chunks) {
897
+ bytes.set(chunk, offset);
898
+ offset += chunk.byteLength;
899
+ }
900
+ return bytes;
901
+ }
902
+
903
+ // src/requests/d1.ts
904
+ var SUBJECT_REQUESTS_TABLE = "subject_requests";
905
+ var COLUMNS = [
906
+ "id",
907
+ "type",
908
+ "email",
909
+ "email_hash",
910
+ "subject_hash",
911
+ "details",
912
+ "locale",
913
+ "policy_hash",
914
+ "received_at",
915
+ "due_at",
916
+ "extended_due_at",
917
+ "extension_reason",
918
+ "status",
919
+ "confirmed_at",
920
+ "closed_at",
921
+ "outcome",
922
+ "notified_at",
923
+ "confirmation_sent_at"
924
+ ];
925
+ var T = SUBJECT_REQUESTS_TABLE;
926
+ var SELECT = `SELECT ${COLUMNS.join(", ")} FROM ${T}`;
927
+ var OPEN = `status <> 'closed'`;
928
+ var CONFIRMATION_SLOTS_TABLE = "subject_request_confirmation_slots";
929
+ var RESERVE = `INSERT INTO ${CONFIRMATION_SLOTS_TABLE} (rate_key, window_start, count) VALUES (?, ?, 1)
930
+ ON CONFLICT (rate_key) DO UPDATE SET
931
+ count = CASE WHEN window_start <= ? THEN 1 ELSE count + 1 END,
932
+ window_start = CASE WHEN window_start <= ? THEN ? ELSE window_start END
933
+ WHERE window_start <= ? OR count < ?`;
934
+ var EXPIRE = `DELETE FROM ${CONFIRMATION_SLOTS_TABLE} WHERE rate_key <> '*' AND window_start <= ?`;
935
+ function toRow(record) {
936
+ return [
937
+ record.id,
938
+ record.type,
939
+ record.email,
940
+ record.emailHash,
941
+ record.subjectHash,
942
+ record.details,
943
+ record.locale,
944
+ record.policyHash,
945
+ record.receivedAt,
946
+ record.dueAt,
947
+ record.extendedDueAt,
948
+ record.extensionReason,
949
+ record.status,
950
+ record.confirmedAt,
951
+ record.closedAt,
952
+ record.outcome,
953
+ record.notifiedAt,
954
+ record.confirmationSentAt
955
+ ];
956
+ }
957
+ function fromRow(row) {
958
+ return {
959
+ id: row.id,
960
+ type: row.type,
961
+ email: row.email,
962
+ emailHash: row.email_hash,
963
+ subjectHash: row.subject_hash,
964
+ details: row.details,
965
+ locale: row.locale,
966
+ policyHash: row.policy_hash,
967
+ receivedAt: row.received_at,
968
+ dueAt: row.due_at,
969
+ extendedDueAt: row.extended_due_at,
970
+ extensionReason: row.extension_reason,
971
+ status: row.status,
972
+ confirmedAt: row.confirmed_at,
973
+ closedAt: row.closed_at,
974
+ outcome: row.outcome,
975
+ notifiedAt: row.notified_at,
976
+ confirmationSentAt: row.confirmation_sent_at
977
+ };
978
+ }
979
+ function createD1SubjectRequestStore(db) {
980
+ const all = async (query, ...values) => (await db.prepare(query).bind(...values).all()).results.map(fromRow);
981
+ const change = async (query, ...values) => changesOf(await db.prepare(query).bind(...values).run());
982
+ return {
983
+ async create(record) {
984
+ await db.prepare(`INSERT INTO ${T} (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`).bind(...toRow(record)).run();
985
+ },
986
+ async getById(id) {
987
+ return (await all(`${SELECT} WHERE id = ?`, id))[0] ?? null;
988
+ },
989
+ async confirm(id, at) {
990
+ return await change(`UPDATE ${T} SET status = 'confirmed', confirmed_at = ? WHERE id = ? AND status = 'received'`, at, id) > 0;
991
+ },
992
+ async markNotified(id, at) {
993
+ return await change(`UPDATE ${T} SET notified_at = ? WHERE id = ? AND ${OPEN}`, at, id) > 0;
994
+ },
995
+ async markConfirmationSent(id, at) {
996
+ return await change(`UPDATE ${T} SET confirmation_sent_at = ? WHERE id = ? AND ${OPEN}`, at, id) > 0;
997
+ },
998
+ // One statement: of concurrent calls, only those whose upsert changes the row win.
999
+ async reserveConfirmationSlot(key, slot) {
1000
+ await change(EXPIRE, slot.windowStart);
1001
+ return await change(RESERVE, key, slot.at, slot.windowStart, slot.windowStart, slot.at, slot.windowStart, slot.cap) > 0;
1002
+ },
1003
+ async releaseConfirmationSlot(key, at) {
1004
+ await change(`DELETE FROM ${CONFIRMATION_SLOTS_TABLE} WHERE rate_key = ? AND window_start = ? AND count = 1`, key, at);
1005
+ },
1006
+ deleteExpiredConfirmationSlots: (windowStart) => change(EXPIRE, windowStart),
1007
+ async extend(id, extension) {
1008
+ return await change(`UPDATE ${T} SET extended_due_at = ?, extension_reason = ? WHERE id = ? AND ${OPEN}`, extension.dueAt, extension.reason, id) > 0;
1009
+ },
1010
+ async close(id, closing) {
1011
+ return await change(`UPDATE ${T} SET status = 'closed', closed_at = ?, outcome = ? WHERE id = ? AND ${OPEN}`, closing.at, closing.outcome, id) > 0;
1012
+ },
1013
+ listOpen: () => all(`${SELECT} WHERE ${OPEN} ORDER BY received_at, id`),
1014
+ listDueBefore: (at) => all(`${SELECT} WHERE ${OPEN} AND coalesce(extended_due_at, due_at) <= ? ORDER BY received_at, id`, at),
1015
+ deleteClosedBefore: (at) => change(`DELETE FROM ${T} WHERE status = 'closed' AND closed_at < ?`, at)
1016
+ };
1017
+ }
1018
+
1019
+ // src/requests/tasks.ts
1020
+ async function remindDueRequests(options) {
1021
+ const manifest = parseSubjectRequestManifest(options.manifest);
1022
+ const now = options.now ?? /* @__PURE__ */ new Date();
1023
+ const withinDays = options.withinDays ?? 7;
1024
+ const cutoff = new Date(now.getTime() + withinDays * 24 * 60 * 60 * 1e3).toISOString();
1025
+ const listed = (await options.store.listOpen()).filter((request) => effectiveDueAt(request) <= cutoff || request.notifiedAt === null);
1026
+ const email = reminderEmail(manifest, listed, { now, withinDays });
1027
+ if (email === null) return { listed: [], sent: false };
1028
+ await options.sender.send({ to: options.notify ?? manifest.notify, from: options.from, subject: email.subject, text: email.text });
1029
+ return { listed, sent: true };
1030
+ }
1031
+ async function sweepClosedRequests(options) {
1032
+ const now = options.now ?? /* @__PURE__ */ new Date();
1033
+ await options.store.deleteExpiredConfirmationSlots(new Date(now.getTime() - CONFIRMATION_RATE_LIMIT_MS).toISOString());
1034
+ return options.store.deleteClosedBefore(retentionCutoff(options.retention, now).toISOString());
1035
+ }
1036
+ var SUBJECT_HASH = /^[0-9a-f]{64}$/;
1037
+ async function subjectHashOf(consentIdOrSubjectHash, hmacKey) {
1038
+ if (SUBJECT_HASH.test(consentIdOrSubjectHash)) return consentIdOrSubjectHash;
1039
+ if (hmacKey === void 0) throw new Error("consent-kit: a consent id is hashed with the receipts' HMAC key; pass { hmacKey }, or give the subject hash itself");
1040
+ return subjectHasher(hmacKey)(consentIdOrSubjectHash);
1041
+ }
1042
+ async function findReceipts(store, consentIdOrSubjectHash, options = {}) {
1043
+ return store.listBySubject(await subjectHashOf(consentIdOrSubjectHash, options.hmacKey));
1044
+ }
1045
+ async function eraseReceipts(store, consentIdOrSubjectHash, options = {}) {
1046
+ return store.deleteBySubject(await subjectHashOf(consentIdOrSubjectHash, options.hmacKey));
1047
+ }
1048
+
1049
+ // src/email.ts
1050
+ var EmailSendError = class extends Error {
1051
+ provider;
1052
+ detail;
1053
+ // No parameter properties: this package also runs under Node's type stripping.
1054
+ constructor(provider, detail) {
1055
+ super(`consent-kit: ${provider} did not accept the email (${detail})`);
1056
+ this.name = "EmailSendError";
1057
+ this.provider = provider;
1058
+ this.detail = detail;
1059
+ }
1060
+ };
1061
+ function assertSingleLine(message) {
1062
+ for (const field of ["to", "from", "replyTo", "subject"]) {
1063
+ const value = message[field];
1064
+ if (value !== void 0 && /[\r\n]/.test(value)) throw new Error(`consent-kit: the ${field} of an email must not contain a line break`);
1065
+ }
1066
+ }
1067
+ function cloudflareEmailSender(binding) {
1068
+ return {
1069
+ async send(message) {
1070
+ assertSingleLine(message);
1071
+ try {
1072
+ await binding.send({
1073
+ from: message.from,
1074
+ to: message.to,
1075
+ subject: message.subject,
1076
+ text: message.text,
1077
+ ...message.replyTo === void 0 ? {} : { replyTo: message.replyTo }
1078
+ });
1079
+ } catch (error) {
1080
+ const code = typeof error === "object" && error !== null && typeof error.code === "string" ? error.code : "error";
1081
+ throw new EmailSendError("Cloudflare Email Service", code);
1082
+ }
1083
+ }
1084
+ };
1085
+ }
1086
+ var RESEND_ENDPOINT = "https://api.resend.com/emails";
1087
+ function resendEmailSender(options) {
1088
+ if (typeof options.apiKey !== "string" || options.apiKey === "") throw new Error("consent-kit: the Resend API key is missing");
1089
+ const send = options.fetch ?? ((input, init) => fetch(input, init));
1090
+ return {
1091
+ async send(message) {
1092
+ assertSingleLine(message);
1093
+ const response = await send(RESEND_ENDPOINT, {
1094
+ method: "POST",
1095
+ headers: {
1096
+ Authorization: `Bearer ${options.apiKey}`,
1097
+ "Content-Type": "application/json",
1098
+ "User-Agent": "consent-kit"
1099
+ },
1100
+ body: JSON.stringify({
1101
+ from: message.from,
1102
+ to: [message.to],
1103
+ subject: message.subject,
1104
+ text: message.text,
1105
+ ...message.replyTo === void 0 ? {} : { reply_to: message.replyTo }
1106
+ })
1107
+ });
1108
+ if (!response.ok) {
1109
+ await response.body?.cancel().catch(() => void 0);
1110
+ throw new EmailSendError("Resend", `HTTP ${response.status}`);
1111
+ }
1112
+ await response.body?.cancel().catch(() => void 0);
1113
+ }
1114
+ };
1115
+ }
1116
+ var POSTMARK_ENDPOINT = "https://api.postmarkapp.com/email";
1117
+ function postmarkEmailSender(options) {
1118
+ if (typeof options.serverToken !== "string" || options.serverToken === "") throw new Error("consent-kit: the Postmark server token is missing");
1119
+ const send = options.fetch ?? ((input, init) => fetch(input, init));
1120
+ return {
1121
+ async send(message) {
1122
+ assertSingleLine(message);
1123
+ const response = await send(POSTMARK_ENDPOINT, {
1124
+ method: "POST",
1125
+ headers: {
1126
+ Accept: "application/json",
1127
+ "Content-Type": "application/json",
1128
+ "X-Postmark-Server-Token": options.serverToken
1129
+ },
1130
+ body: JSON.stringify({
1131
+ From: message.from,
1132
+ To: message.to,
1133
+ Subject: message.subject,
1134
+ TextBody: message.text,
1135
+ ...message.replyTo === void 0 ? {} : { ReplyTo: message.replyTo },
1136
+ MessageStream: options.messageStream ?? "outbound"
1137
+ })
1138
+ });
1139
+ let code;
1140
+ try {
1141
+ code = (await response.json()).ErrorCode;
1142
+ } catch {
1143
+ code = void 0;
1144
+ }
1145
+ if (response.status !== 200 || code !== 0) {
1146
+ throw new EmailSendError("Postmark", `HTTP ${response.status}${typeof code === "number" ? `, ErrorCode ${code}` : ""}`);
1147
+ }
1148
+ }
1149
+ };
1150
+ }
1151
+
1152
+ 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 };