@cookiemunch/sdk 0.38.0 → 0.39.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/rights.cjs CHANGED
@@ -37,6 +37,7 @@ __export(rights_exports, {
37
37
  createRightsHandlers: () => createRightsHandlers,
38
38
  fileStore: () => fileStore,
39
39
  ioredisStore: () => ioredisStore,
40
+ lookupByRule: () => lookupByRule,
40
41
  prismaStore: () => prismaStore,
41
42
  redisStore: () => redisStore,
42
43
  sqlStore: () => sqlStore
@@ -47,6 +48,23 @@ module.exports = __toCommonJS(rights_exports);
47
48
  var CANARY_ISSUER = "https://canary.cookiemunch.net";
48
49
 
49
50
  // src/rights.ts
51
+ async function lookupByRule(f, input) {
52
+ const sub = input.identity?.sub;
53
+ if (sub && f.bySubject) {
54
+ const id = await f.bySubject(sub, input.identity, input.scope);
55
+ if (typeof id === "string" && id) return id;
56
+ }
57
+ for (const email of input.emails) {
58
+ const found = await f.byEmail(email, input.scope);
59
+ const list = found == null ? [] : Array.isArray(found) ? found : [found];
60
+ for (const m of list) {
61
+ const id = typeof m === "string" ? m : m?.id;
62
+ const other = typeof m === "object" && m?.subject && sub && m.subject !== sub;
63
+ if (typeof id === "string" && id && !other) return id;
64
+ }
65
+ }
66
+ return null;
67
+ }
50
68
  var IDEMPOTENCY_TTL_SECONDS = 24 * 60 * 60;
51
69
  var CANONICAL = {
52
70
  access: "access",
@@ -112,7 +130,9 @@ function createRightsHandlers(o) {
112
130
  if (typeof o.key !== "string" || !o.key) throw new Error("createRightsHandlers: key is required");
113
131
  if (o.key.length < 24) console.warn("createRightsHandlers: key is shorter than 24 characters; rotate it to a longer one (PATCH /v1/dsar/executors/{id} {secretKey}) so it cannot be guessed");
114
132
  if (typeof o.idSecret !== "string" || o.idSecret.length < 32) throw new Error("createRightsHandlers: idSecret must be at least 32 characters");
115
- if (typeof o.lookup !== "function") throw new Error("createRightsHandlers: lookup is required");
133
+ const finders = typeof o.lookup === "object" && o.lookup !== null ? o.lookup : null;
134
+ if (finders ? typeof finders.byEmail !== "function" : typeof o.lookup !== "function") throw new Error("createRightsHandlers: lookup is required (a function, or { bySubject?, byEmail })");
135
+ const find = finders ? (i) => lookupByRule(finders, i) : o.lookup;
116
136
  const subtle = globalThis.crypto?.subtle;
117
137
  if (!subtle) throw new Error("createRightsHandlers: needs Web Crypto (globalThis.crypto.subtle)");
118
138
  const store = o.store ?? /* @__PURE__ */ new Map();
@@ -142,10 +162,40 @@ function createRightsHandlers(o) {
142
162
  return null;
143
163
  }
144
164
  }
145
- const getStored = async (id) => {
165
+ const getStored = async (id, signed) => {
146
166
  const v = await store.get(`req:${id}`);
147
- return v ? JSON.parse(v) : null;
167
+ return v ? JSON.parse(v) : signed ?? null;
168
+ };
169
+ const sl = o.stateless === true ? {} : o.stateless || null;
170
+ const jwksUrl = sl?.jwksUrl ?? "https://api.cookiemunch.net/v1/partner/jwks.json";
171
+ let keys = null;
172
+ let keysAt = 0;
173
+ const loadKeys = async (jwks) => {
174
+ const list = jwks?.keys ?? (await (await globalThis.fetch(jwksUrl)).json()).keys;
175
+ keys = new Map(list.filter((k) => k.kty === "OKP" && k.crv === "Ed25519").map((k) => [k.kid ?? "", subtle.importKey("jwk", k, { name: "Ed25519" }, false, ["verify"])]));
176
+ keysAt = now();
148
177
  };
178
+ const STATE_STATUSES = /* @__PURE__ */ new Set([...OUTCOMES, "scheduled", "cancelled"]);
179
+ async function signedState(req, id) {
180
+ const jws = sl && req.headers.get("cookiemunch-request-state");
181
+ if (!jws) return null;
182
+ try {
183
+ const [h, p, sig, extra] = jws.split(".");
184
+ if (!h || !p || !sig || extra !== void 0) return null;
185
+ const header = JSON.parse(dec.decode(fromB64url(h) ?? new Uint8Array()));
186
+ if (header.alg !== "EdDSA" || !header.kid) return null;
187
+ if (!keys || !keys.has(header.kid) && !sl.jwks && now() - keysAt > 3e5) await loadKeys(sl.jwks);
188
+ const key = keys.get(header.kid);
189
+ const sigBytes = fromB64url(sig);
190
+ if (!key || !sigBytes || !await subtle.verify({ name: "Ed25519" }, await key, sigBytes, enc.encode(`${h}.${p}`))) return null;
191
+ const cl = JSON.parse(dec.decode(fromB64url(p)));
192
+ const t = now() / 1e3;
193
+ if (cl.id !== id || typeof cl.exp !== "number" || cl.exp < t || cl.exp > t + 900 || !cl.status || !STATE_STATUSES.has(cl.status)) return null;
194
+ return { status: cl.status, ...cl.status === "scheduled" && cl.executeAfter ? { eta: cl.executeAfter } : {} };
195
+ } catch {
196
+ return null;
197
+ }
198
+ }
149
199
  const putStored = async (id, s) => {
150
200
  await store.set(`req:${id}`, JSON.stringify(s));
151
201
  };
@@ -229,14 +279,17 @@ function createRightsHandlers(o) {
229
279
  return bad("identity must be { iss, sub, ext?, principal? }", "identity");
230
280
  }
231
281
  const identity = isObject(raw) ? raw : void 0;
282
+ if (body.scope !== void 0 && !isObject(body.scope)) return bad("scope must be an object", "scope");
283
+ const scope = isObject(body.scope) ? body.scope : void 0;
284
+ const echo = scope ? { scope } : {};
232
285
  const canaryByEmail = emails.map((e) => CANARY_EMAIL.exec(e.toLowerCase())?.[1]).find(Boolean);
233
286
  const canaryExt = typeof identity?.ext === "string" ? CANARY_EXT.exec(identity.ext)?.[1] : void 0;
234
287
  if (canaryByEmail || canaryExt || identity?.iss === CANARY_ISSUER) {
235
288
  const tag = identity ? (identity.iss === CANARY_ISSUER ? CANARY_SUBJECT.exec(identity.sub)?.[1] : void 0) ?? canaryExt : canaryByEmail;
236
- return json(200, tag ? { subjectId: `canary_${tag}`, status: "found" } : { subjectId: null, status: "no_match" });
289
+ return json(200, tag ? { subjectId: `canary_${tag}`, status: "found", ...echo } : { subjectId: null, status: "no_match", ...echo });
237
290
  }
238
- const subjectId = await o.lookup({ emails, ...identity ? { identity } : {} });
239
- return json(200, typeof subjectId === "string" && subjectId ? { subjectId, status: "found" } : { subjectId: null, status: "no_match" });
291
+ const subjectId = await find({ emails, ...identity ? { identity } : {}, ...scope ? { scope } : {} });
292
+ return json(200, typeof subjectId === "string" && subjectId ? { subjectId, status: "found", ...echo } : { subjectId: null, status: "no_match", ...echo });
240
293
  }
241
294
  async function open(body) {
242
295
  const word = typeof body.right === "string" && CANONICAL[body.right] ? body.right : body.type;
@@ -261,21 +314,21 @@ function createRightsHandlers(o) {
261
314
  }
262
315
  return json(201, view(id, c, await act(id, c, s, cb)));
263
316
  }
264
- async function read(id, c) {
265
- let s = await getStored(id);
317
+ async function read(id, c, signed) {
318
+ let s = await getStored(id, signed);
266
319
  if (!s) {
267
320
  return json(200, view(id, c, { status: "rejected", detail: "this system no longer holds the request's state; nothing was done. Open it again." }));
268
321
  }
269
322
  if ((s.status === "pending" || s.status === "processing" || s.status === "blocked") && o.status && !CANARY_SUBJECT.test(c.s)) s = await act(id, c, s, o.status);
270
323
  return json(200, view(id, c, s));
271
324
  }
272
- async function run(id, c) {
273
- const s = await getStored(id);
325
+ async function run(id, c, signed) {
326
+ const s = await getStored(id, signed);
274
327
  if (s?.status === "scheduled" && c.a !== void 0 && now() >= c.a) return json(200, view(id, c, await act(id, c, s, callbackFor(c.t))));
275
- return read(id, c);
328
+ return read(id, c, signed);
276
329
  }
277
- async function cancel(id, c) {
278
- const s = await getStored(id);
330
+ async function cancel(id, c, signed) {
331
+ const s = await getStored(id, signed);
279
332
  if (!s) return json(409, { error: "this system no longer holds the request's state", field: "id" });
280
333
  if (s.status === "cancelled") return json(200, view(id, c, s));
281
334
  if (s.status !== "scheduled" && s.status !== "pending") return json(409, { error: `too late to cancel a ${s.status} request`, field: "id" });
@@ -326,9 +379,10 @@ function createRightsHandlers(o) {
326
379
  }
327
380
  const c = await readId(id);
328
381
  if (!c) return json(404, { error: "unknown request" });
329
- if (action === "cancel" && method === "POST") res = await cancel(id, c);
330
- else if (action === "run" && method === "POST") res = await run(id, c);
331
- else if (!action && method === "GET") res = await read(id, c);
382
+ const signed = await signedState(req, id);
383
+ if (action === "cancel" && method === "POST") res = await cancel(id, c, signed);
384
+ else if (action === "run" && method === "POST") res = await run(id, c, signed);
385
+ else if (!action && method === "GET") res = await read(id, c, signed);
332
386
  else return json(404, { error: "not_found" });
333
387
  } else return json(404, { error: "not_found" });
334
388
  if (idemKey !== null && res.ok) {
@@ -344,7 +398,7 @@ function createRightsHandlers(o) {
344
398
  async function complete(requestId, outcome) {
345
399
  const c = await readId(requestId);
346
400
  if (!c) throw new Error("createRightsHandlers.complete: not a request id these handlers issued");
347
- const s = await getStored(requestId);
401
+ const s = await getStored(requestId) ?? (sl ? { status: "processing" } : null);
348
402
  if (!s) throw new Error("createRightsHandlers.complete: this system no longer holds the request's state");
349
403
  if (FINAL.has(s.status)) return { status: s.status, delivered: await notify(requestId, c, s) };
350
404
  const next = await record(requestId, s, outcome ?? { status: "completed" });
@@ -483,6 +537,7 @@ function ioredisStore(client) {
483
537
  createRightsHandlers,
484
538
  fileStore,
485
539
  ioredisStore,
540
+ lookupByRule,
486
541
  prismaStore,
487
542
  redisStore,
488
543
  sqlStore
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/rights.ts","../src/executor-conformance.ts"],"sourcesContent":["/**\n * `@cookiemunch/sdk/rights` — the cm-standard-v2 executor contract, server side.\n *\n * A product that holds personal data implements four calls and Cookie Munch drives it (docs:\n * cookiemunch.net/docs/executor-contract-v2). This builds those four calls from callbacks, so the\n * product writes only \"find this person\", \"export them\", \"erase them\":\n *\n * import { createRightsHandlers } from '@cookiemunch/sdk/rights';\n * const rights = createRightsHandlers({\n * key: process.env.CM_EXECUTOR_KEY!, // the secretKey you registered with Cookie Munch\n * idSecret: process.env.CM_REQUEST_ID_SECRET!,\n * lookup: async ({ emails, identity }) => (await findUser(emails, identity))?.id ?? null,\n * access: async (r) => ({ status: 'completed', result: await exportUser(r.subjectId) }),\n * erase: async (r) => { await deleteUser(r.subjectId); },\n * });\n * // Next.js app/privacy/[...path]/route.ts: export const { GET, POST } = rights;\n * // Deno: Deno.serve(rights.fetch) Workers / Bun: export default rights\n *\n * Built in: a constant-time key check (no key or a wrong key is a bare 404, so the endpoint is not\n * advertised), `X-Version` and `Cache-Control: no-store` on every authorised answer, Idempotency-Key\n * replay, HMAC-signed request ids (a forged id is a 404), `executeAfter` scheduling and cancel, and\n * the canary subject, answered here so your callbacks never see it. With `completion`, each request\n * that reaches a final status is also pushed to Cookie Munch as a signed completion, so it closes in\n * seconds instead of on the next poll.\n *\n * A separate entry point so the API client never loads it. Web platform only (Request, Response,\n * crypto.subtle): Node 20+, Deno, Bun and edge runtimes.\n */\nimport { CANARY_ISSUER } from './executor-conformance.js';\n\n/**\n * The six rights, one word each. Every word Cookie Munch has sent is read as one of them: `deletion`,\n * `erase` → `erasure`; `export` → `access`. A portability request is `portability` (its callback falls\n * back to `access` when there is no `portability`).\n */\nexport type RightsType = 'access' | 'erasure' | 'rectification' | 'portability' | 'restriction' | 'closure';\nexport type RightsStatus = 'pending' | 'scheduled' | 'processing' | 'blocked' | 'completed' | 'completed_with_retention' | 'no_match' | 'rejected' | 'cancelled';\n\nexport interface RightsIdentity {\n iss: string;\n sub: string;\n ext?: string;\n principal?: string;\n}\n\nexport interface RightsLookupInput {\n emails: string[];\n /** A signed-in identity (sent as `identity`, or `atlas`). Match on it before the emails, and never through an email that belongs to a different identity. */\n identity?: RightsIdentity;\n}\n\nexport interface RightsRetention {\n category: string;\n basis: 'legal_obligation' | 'legal_claims' | 'contract' | 'public_interest' | 'legitimate_interest';\n until?: string;\n}\n\n/** What a callback answers. Returning nothing means `completed`. */\nexport interface RightsOutcome {\n status: 'pending' | 'processing' | 'blocked' | 'completed' | 'completed_with_retention' | 'no_match' | 'rejected';\n eta?: string;\n /**\n * With `blocked`: the person must act before you can (e.g. hand over an organisation they own alone).\n * `message` is shown to them on their status page as your words; `reason` is a short code for the controller.\n */\n blocked?: { reason?: string; message?: string };\n /** Plain words; required in spirit for `rejected`. */\n detail?: string;\n retention?: RightsRetention[];\n /** For `access`: `{ downloadUrl, expiresAt, sha256 }`, or the bundle inline (at most 5 MB). */\n result?: unknown;\n}\n\n/** The request a callback acts on. */\nexport interface RightsRequest {\n id: string;\n subjectId: string;\n type: RightsType;\n /** The word Cookie Munch sent: its `right` (one of the RightsType words) when present, else its `type`. */\n requestedType: string;\n caseId: string;\n reason?: string;\n executeAfter?: string;\n}\n\ntype Callback = (r: RightsRequest) => Promise<RightsOutcome | void> | RightsOutcome | void;\n\n/**\n * Where request state and idempotency answers live. A `Map` is one; `fileStore`, `sqlStore` and\n * `redisStore` below are durable ones. Idempotency answers are set with `ttlSeconds` (24 hours) and\n * a store may drop them after that; request state (a scheduled erasure included) is set with none and\n * must be kept. `delete`, when present, removes an answer the handlers found expired.\n */\nexport interface RightsStore {\n get(key: string): Promise<string | null | undefined> | string | null | undefined;\n set(key: string, value: string, opts?: { ttlSeconds?: number }): unknown;\n delete?(key: string): unknown;\n}\n\n/** How long an Idempotency-Key answer is replayed. */\nexport const IDEMPOTENCY_TTL_SECONDS = 24 * 60 * 60;\n\nexport interface RightsHandlersOptions {\n /** The key Cookie Munch sends as `Authorization: Bearer <key>`; at least 24 characters. */\n key: string;\n /** Signs request ids; at least 32 characters, the same on every instance and across restarts. */\n idSecret: string;\n /** The subject id for these emails / this identity, or null. */\n lookup: (input: RightsLookupInput) => Promise<string | null | undefined> | string | null | undefined;\n access?: Callback;\n /** `portability`: the person's data in a machine-readable form. Without it, `access` answers it. */\n portability?: Callback;\n /**\n * `erasure` (and `closure`, when there is no `close`). With a future `executeAfter` the request is\n * stored as `scheduled` and there is NO timer in your process: `erase` runs when Cookie Munch sends\n * `POST /requests/{id}/run` at or after `executeAfter` (its sweep runs every 10 minutes). A `GET` never\n * runs it. The state must survive a restart: give production a durable `store`.\n */\n erase?: Callback;\n close?: Callback;\n restrict?: Callback;\n rectify?: Callback;\n /** Read back a request a callback answered `pending` or `processing` for. */\n status?: Callback;\n /**\n * Default: in memory, which a restart empties. A scheduled erasure whose state is gone is never\n * run (it answers `rejected`), so give production a durable store: `fileStore(dir)`,\n * `sqlStore({ query })`, `redisStore(client)` or `ioredisStore(client)`.\n */\n store?: RightsStore;\n now?: () => number;\n /**\n * Signed completions (cm-standard-v2): the connection's `completionUrl` and its `completionSecret`\n * (`whsec_…`; read it again with `fulfillment.getExecutorCompletionSecret(id)`). Profile-based\n * systems use `webhookUrl` + `webhookSecret` instead; a `webhookSecret` also verifies here. Each request that reaches a final status is POSTed there, signed,\n * with up to 3 attempts. A failed push never fails a request: Cookie Munch's poll still closes it.\n */\n completion?: { url: string; secret: string; fetch?: typeof fetch };\n}\n\nexport interface RightsHandlers {\n /** The whole contract, routed on the path's tail: mount it under any prefix. */\n fetch(req: Request): Promise<Response>;\n GET(req: Request): Promise<Response>;\n POST(req: Request): Promise<Response>;\n /**\n * Finish a request a callback answered `pending` or `processing` for, out of band (a job queue, a\n * manual review): stores the final outcome and, with `completion`, pushes it and waits for the push.\n * `delivered` is false when there is no `completion` or every attempt failed (polling still closes it).\n * A request already final is left as it is; its completion is re-sent only if it was never delivered.\n */\n complete(requestId: string, outcome?: RightsOutcome): Promise<{ status: RightsStatus; delivered: boolean }>;\n}\n\nconst CANONICAL: Record<string, RightsType> = {\n access: 'access', export: 'access', portability: 'portability', erasure: 'erasure', deletion: 'erasure', erase: 'erasure',\n closure: 'closure', restriction: 'restriction', rectification: 'rectification',\n};\n/** The contract's `canonicalType` on the wire (executor-contract-v2), which predates the six words. */\nconst WIRE: Record<RightsType, string> = {\n access: 'access', portability: 'access', erasure: 'deletion', closure: 'closure', restriction: 'restriction', rectification: 'rectification',\n};\nconst TYPE_WORDS = 'access, export, portability, erasure, deletion, erase, closure, restriction, rectification';\nconst OUTCOMES = new Set(['pending', 'processing', 'blocked', 'completed', 'completed_with_retention', 'no_match', 'rejected']);\n/** The contract's final statuses: each one is pushed as a signed completion. */\nconst FINAL = new Set<RightsStatus>(['completed', 'completed_with_retention', 'no_match', 'rejected', 'cancelled']);\n/** Wait before each completion attempt after the first. */\nconst COMPLETION_BACKOFF_MS = [1_000, 4_000];\nconst CANARY_EMAIL = /^canary-([0-9a-f]{16})@canary\\.cookiemunch\\.net$/;\nconst CANARY_SUBJECT = /^canary_([0-9a-f]{16})$/;\nconst CANARY_EXT = /^canary:([0-9a-f]{16})$/;\n\n/** What the signed id carries: enough to answer without trusting the store for it. */\ntype IdClaims = { s: string; t: RightsType; y: string; c: string; a?: number; n: string };\n/** The request's mutable state, in the store under `req:<id>`. */\ntype Stored = { status: RightsStatus; eta?: string; detail?: string; blocked?: { reason?: string; message?: string }; retention?: RightsRetention[]; result?: unknown; reason?: string; notified?: true };\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\nfunction b64url(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\nfunction fromB64url(s: string) {\n if (!/^[A-Za-z0-9_-]*$/.test(s)) return null;\n try {\n const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'));\n return Uint8Array.from(bin, (c) => c.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\n/** Constant-time in the presented value: every byte of the expected key is compared. */\nfunction sameKey(presented: string, expected: string): boolean {\n const a = enc.encode(presented);\n const b = enc.encode(expected);\n let diff = a.length ^ b.length;\n for (let i = 0; i < b.length; i++) diff |= (a[i] ?? 0) ^ b[i]!;\n return diff === 0;\n}\n\nfunction json(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json', 'x-version': '2', 'cache-control': 'no-store' },\n });\n}\nconst bad = (error: string, field: string) => json(400, { error, field });\n// No X-Version and nothing contract-shaped: to a caller without the key this is any other 404.\nconst hidden = () => new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain' } });\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return !!v && typeof v === 'object' && !Array.isArray(v);\n}\n\nexport function createRightsHandlers(o: RightsHandlersOptions): RightsHandlers {\n if (typeof o.key !== 'string' || !o.key) throw new Error('createRightsHandlers: key is required');\n // A warning, not a throw: Cookie Munch has accepted 8-character keys, and an SDK upgrade must not take a working rights endpoint down.\n if (o.key.length < 24) console.warn('createRightsHandlers: key is shorter than 24 characters; rotate it to a longer one (PATCH /v1/dsar/executors/{id} {secretKey}) so it cannot be guessed');\n if (typeof o.idSecret !== 'string' || o.idSecret.length < 32) throw new Error('createRightsHandlers: idSecret must be at least 32 characters');\n if (typeof o.lookup !== 'function') throw new Error('createRightsHandlers: lookup is required');\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new Error('createRightsHandlers: needs Web Crypto (globalThis.crypto.subtle)');\n // shortcut: the default Map keeps an expired idempotency answer until it is read again; fine for the volume of rights requests, pass `store` for more.\n const store: RightsStore = o.store ?? new Map<string, string>();\n const now = o.now ?? (() => Date.now());\n const hmacKey = subtle.importKey('raw', enc.encode(o.idSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);\n const completion = o.completion;\n if (completion && (typeof completion.url !== 'string' || !/^https?:\\/\\//.test(completion.url) || typeof completion.secret !== 'string' || !completion.secret)) {\n throw new Error('createRightsHandlers: completion needs { url, secret }: the connection\\'s completionUrl and completionSecret');\n }\n // Standard Webhooks: a `whsec_` secret's HMAC key is its base64-decoded remainder; anything else signs as typed.\n const completionKey = completion\n ? subtle.importKey('raw', (completion.secret.startsWith('whsec_') && fromB64url(completion.secret.slice(6).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''))) || enc.encode(completion.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])\n : undefined;\n\n async function mintId(claims: IdClaims): Promise<string> {\n const payload = b64url(enc.encode(JSON.stringify(claims)));\n const sig = new Uint8Array(await subtle.sign('HMAC', await hmacKey, enc.encode(payload)));\n return `r1.${payload}.${b64url(sig)}`;\n }\n async function readId(id: string): Promise<IdClaims | null> {\n const [v, payload, sig, extra] = id.split('.');\n if (v !== 'r1' || !payload || !sig || extra !== undefined) return null;\n const sigBytes = fromB64url(sig);\n if (!sigBytes || !(await subtle.verify('HMAC', await hmacKey, sigBytes, enc.encode(payload)))) return null;\n const raw = fromB64url(payload);\n try {\n if (!raw) return null;\n const c = JSON.parse(dec.decode(raw)) as IdClaims;\n // An id minted before the six words carries `deletion`.\n return { ...c, t: CANONICAL[c.t] ?? c.t };\n } catch {\n return null;\n }\n }\n\n const getStored = async (id: string): Promise<Stored | null> => {\n const v = await store.get(`req:${id}`);\n return v ? (JSON.parse(v) as Stored) : null;\n };\n const putStored = async (id: string, s: Stored) => {\n await store.set(`req:${id}`, JSON.stringify(s));\n };\n\n const view = (id: string, c: IdClaims, s: Stored) => ({\n id,\n type: c.y,\n canonicalType: WIRE[c.t] ?? c.t,\n status: s.status,\n ...(s.eta ? { eta: s.eta } : {}),\n ...(s.detail ? { detail: s.detail } : {}),\n ...(s.blocked && s.status === 'blocked' ? { blocked: s.blocked } : {}),\n ...(s.retention ? { retention: s.retention } : {}),\n ...(s.result !== undefined ? { result: s.result } : {}),\n });\n\n /**\n * Push a final status to `completionsUrl`, signed. Never throws: a failure is logged and left to the poll.\n * Retried on a network error, a 5xx or a 429, with the same Webhook-Id, so a retry that did land is a no-op.\n */\n async function notify(id: string, c: IdClaims, s: Stored): Promise<boolean> {\n if (!completion || !completionKey || !FINAL.has(s.status) || s.notified) return false;\n try {\n const body = JSON.stringify({ caseId: c.c, request: view(id, c, s) });\n const webhookId = `cmc_${b64url(globalThis.crypto.getRandomValues(new Uint8Array(12)))}`;\n const send = completion.fetch ?? globalThis.fetch;\n for (let attempt = 0; attempt <= COMPLETION_BACKOFF_MS.length; attempt++) {\n if (attempt > 0) await new Promise((r) => setTimeout(r, COMPLETION_BACKOFF_MS[attempt - 1]));\n const stamp = String(Math.floor(now() / 1000));\n const sig = new Uint8Array(await subtle.sign('HMAC', await completionKey, enc.encode(`${webhookId}.${stamp}.${body}`)));\n let status = 0;\n try {\n status = (await send(completion.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', 'webhook-id': webhookId, 'webhook-timestamp': stamp, 'webhook-signature': `v1,${btoa(String.fromCharCode(...sig))}` },\n body,\n })).status;\n } catch (err) {\n console.warn('createRightsHandlers: completion push failed:', err);\n }\n if (status >= 200 && status < 300) {\n const latest = await getStored(id);\n if (latest && latest.status === s.status) await putStored(id, { ...latest, notified: true });\n return true;\n }\n if (status !== 0 && status < 500 && status !== 429) {\n console.warn(`createRightsHandlers: completion refused with ${status}; check completion.url and completion.secret`);\n return false;\n }\n }\n } catch (err) {\n console.warn('createRightsHandlers: completion push failed:', err);\n }\n return false;\n }\n\n const callbackFor = (t: RightsType): Callback | undefined =>\n ({ access: o.access, portability: o.portability ?? o.access, erasure: o.erase, closure: o.close ?? o.erase, restriction: o.restrict, rectification: o.rectify })[t];\n\n /** Run a callback (or, for the canary, nothing) and fold its answer into the stored state. */\n async function act(id: string, c: IdClaims, s: Stored, cb: Callback | undefined): Promise<Stored> {\n // The canary is a synthetic person: requests on it complete without touching anything real.\n const out = CANARY_SUBJECT.test(c.s) || !cb\n ? undefined\n : ((await cb({\n id,\n subjectId: c.s,\n type: c.t,\n requestedType: c.y,\n caseId: c.c,\n ...(s.reason ? { reason: s.reason } : {}),\n ...(c.a !== undefined ? { executeAfter: new Date(c.a).toISOString() } : {}),\n })) as RightsOutcome | undefined);\n const next = await record(id, s, out ?? { status: 'completed' });\n void notify(id, c, next);\n return next;\n }\n\n /** Fold an outcome into the stored state. */\n async function record(id: string, s: Stored, o2: RightsOutcome): Promise<Stored> {\n if (!OUTCOMES.has(o2.status)) throw new Error(`a rights callback answered an unknown status \"${String(o2.status)}\"`);\n const next: Stored = { status: o2.status, ...(s.reason ? { reason: s.reason } : {}) };\n if (o2.eta) next.eta = o2.eta;\n if (o2.detail) next.detail = o2.detail;\n if (o2.status === 'blocked' && o2.blocked) next.blocked = o2.blocked;\n if (o2.retention) next.retention = o2.retention;\n if (o2.result !== undefined) next.result = o2.result;\n await putStored(id, next);\n return next;\n }\n\n async function lookup(body: Record<string, unknown>): Promise<Response> {\n if (!Array.isArray(body.emails) || body.emails.some((e) => typeof e !== 'string')) return bad('emails must be an array of strings', 'emails');\n const emails = (body.emails as string[]).map((e) => e.trim());\n const raw = body.identity ?? body.atlas;\n if (raw !== undefined && raw !== null && !(isObject(raw) && typeof raw.iss === 'string' && typeof raw.sub === 'string')) {\n return bad('identity must be { iss, sub, ext?, principal? }', 'identity');\n }\n const identity = isObject(raw) ? (raw as unknown as RightsIdentity) : undefined;\n\n const canaryByEmail = emails.map((e) => CANARY_EMAIL.exec(e.toLowerCase())?.[1]).find(Boolean);\n const canaryExt = typeof identity?.ext === 'string' ? CANARY_EXT.exec(identity.ext)?.[1] : undefined;\n if (canaryByEmail || canaryExt || identity?.iss === CANARY_ISSUER) {\n // When an identity is given only it decides: the canary's email next to anyone else's identity is no one.\n const tag = identity ? (identity.iss === CANARY_ISSUER ? CANARY_SUBJECT.exec(identity.sub)?.[1] : undefined) ?? canaryExt : canaryByEmail;\n return json(200, tag ? { subjectId: `canary_${tag}`, status: 'found' } : { subjectId: null, status: 'no_match' });\n }\n const subjectId = await o.lookup({ emails, ...(identity ? { identity } : {}) });\n return json(200, typeof subjectId === 'string' && subjectId ? { subjectId, status: 'found' } : { subjectId: null, status: 'no_match' });\n }\n\n async function open(body: Record<string, unknown>): Promise<Response> {\n // `right` names the right itself (portability, which `type` sends as access); a receiver that predates it reads `type`.\n const word = typeof body.right === 'string' && CANONICAL[body.right] ? body.right : body.type;\n const t = typeof word === 'string' ? CANONICAL[word] : undefined;\n if (!t) return bad(`type must be one of ${TYPE_WORDS}`, 'type');\n if (typeof body.subjectId !== 'string' || !body.subjectId) return bad('subjectId is required', 'subjectId');\n if (typeof body.caseId !== 'string' || !body.caseId) return bad('caseId is required', 'caseId');\n if (body.reason !== undefined && typeof body.reason !== 'string') return bad('reason must be a string', 'reason');\n const after = typeof body.executeAfter === 'string' ? Date.parse(body.executeAfter) : NaN;\n if (body.executeAfter !== undefined && body.executeAfter !== null && Number.isNaN(after)) return bad('executeAfter must be an ISO date-time', 'executeAfter');\n const cb = callbackFor(t);\n if (!cb && !CANARY_SUBJECT.test(body.subjectId)) return bad(`this system does not handle ${t}`, 'type');\n\n const c: IdClaims = { s: body.subjectId, t, y: word as string, c: body.caseId, n: b64url(globalThis.crypto.getRandomValues(new Uint8Array(9))) };\n if (!Number.isNaN(after)) c.a = after;\n const id = await mintId(c);\n const s: Stored = { status: 'pending', ...(typeof body.reason === 'string' && body.reason ? { reason: body.reason } : {}) };\n const erasing = t === 'erasure' || t === 'closure';\n if (erasing && c.a !== undefined && c.a > now()) {\n const scheduled: Stored = { ...s, status: 'scheduled', eta: new Date(c.a).toISOString() };\n await putStored(id, scheduled);\n return json(201, view(id, c, scheduled));\n }\n return json(201, view(id, c, await act(id, c, s, cb)));\n }\n\n async function read(id: string, c: IdClaims): Promise<Response> {\n let s = await getStored(id);\n if (!s) {\n // A genuine id whose state is gone (an emptied store): never act on it, say so.\n return json(200, view(id, c, { status: 'rejected', detail: \"this system no longer holds the request's state; nothing was done. Open it again.\" }));\n }\n // A scheduled erasure waits for POST /run: a GET is safe, it never acts.\n if ((s.status === 'pending' || s.status === 'processing' || s.status === 'blocked') && o.status && !CANARY_SUBJECT.test(c.s)) s = await act(id, c, s, o.status);\n return json(200, view(id, c, s));\n }\n\n /** Run a scheduled erasure whose executeAfter has passed; anything else answers as a read. Safe to repeat. */\n async function run(id: string, c: IdClaims): Promise<Response> {\n const s = await getStored(id);\n if (s?.status === 'scheduled' && c.a !== undefined && now() >= c.a) return json(200, view(id, c, await act(id, c, s, callbackFor(c.t))));\n return read(id, c);\n }\n\n async function cancel(id: string, c: IdClaims): Promise<Response> {\n const s = await getStored(id);\n if (!s) return json(409, { error: \"this system no longer holds the request's state\", field: 'id' });\n if (s.status === 'cancelled') return json(200, view(id, c, s));\n if (s.status !== 'scheduled' && s.status !== 'pending') return json(409, { error: `too late to cancel a ${s.status} request`, field: 'id' });\n const next: Stored = { status: 'cancelled', ...(s.reason ? { reason: s.reason } : {}) };\n await putStored(id, next);\n void notify(id, c, next);\n return json(200, view(id, c, next));\n }\n\n async function handle(req: Request): Promise<Response> {\n const m = /^Bearer\\s+(.+)$/i.exec(req.headers.get('authorization') ?? '');\n if (!m || !sameKey(m[1]!.trim(), o.key)) return hidden();\n\n const path = new URL(req.url).pathname.replace(/\\/+$/, '');\n const route = /\\/(lookup|requests)(?:\\/([^/]+)(?:\\/(cancel|run))?)?$/.exec(path);\n const method = req.method.toUpperCase();\n if (!route) return json(404, { error: 'not_found' });\n const [, what, rawId, action] = route;\n\n let body: Record<string, unknown> = {};\n let text = '';\n if (method === 'POST') {\n text = await req.text();\n try {\n const parsed: unknown = text ? JSON.parse(text) : {};\n if (!isObject(parsed)) return bad('body must be a JSON object', 'body');\n body = parsed;\n } catch {\n return bad('body must be JSON', 'body');\n }\n }\n\n // Replay: the same key and body answer what they answered first; another body is a 409.\n const idemKey = method === 'POST' && what === 'requests' ? req.headers.get('idempotency-key') : null;\n if (idemKey !== null) {\n if (idemKey.length < 16 || idemKey.length > 128) return bad('Idempotency-Key must be 16-128 characters', 'Idempotency-Key');\n const seen = await store.get(`idem:${idemKey}`);\n const first = seen ? (JSON.parse(seen) as { body: string; status: number; answer: unknown; at?: number }) : null;\n // Checked here too, so a store that ignores ttlSeconds (a Map) still forgets after 24 hours.\n if (first && first.at !== undefined && now() - first.at >= IDEMPOTENCY_TTL_SECONDS * 1000) await store.delete?.(`idem:${idemKey}`);\n else if (first) {\n return first.body === text ? json(first.status, first.answer) : json(409, { error: 'Idempotency-Key reused with a different body', field: 'Idempotency-Key' });\n }\n }\n\n let res: Response;\n if (what === 'lookup' && !rawId && method === 'POST') res = await lookup(body);\n else if (what === 'requests' && !rawId && method === 'POST') res = await open(body);\n else if (what === 'requests' && rawId) {\n let id: string;\n try {\n id = decodeURIComponent(rawId);\n } catch {\n return json(404, { error: 'unknown request' });\n }\n const c = await readId(id);\n if (!c) return json(404, { error: 'unknown request' });\n if (action === 'cancel' && method === 'POST') res = await cancel(id, c);\n else if (action === 'run' && method === 'POST') res = await run(id, c);\n else if (!action && method === 'GET') res = await read(id, c);\n else return json(404, { error: 'not_found' });\n } else return json(404, { error: 'not_found' });\n\n if (idemKey !== null && res.ok) {\n const answer = { body: text, status: res.status, answer: await res.clone().json(), at: now() };\n await store.set(`idem:${idemKey}`, JSON.stringify(answer), { ttlSeconds: IDEMPOTENCY_TTL_SECONDS });\n }\n return res;\n }\n\n // A throwing callback is a 500 Cookie Munch retries; nothing is recorded for it.\n const fetch = (req: Request) =>\n handle(req).catch((err: unknown) => {\n console.error('createRightsHandlers:', err);\n return json(500, { error: 'internal_error' });\n });\n async function complete(requestId: string, outcome?: RightsOutcome): Promise<{ status: RightsStatus; delivered: boolean }> {\n const c = await readId(requestId);\n if (!c) throw new Error('createRightsHandlers.complete: not a request id these handlers issued');\n const s = await getStored(requestId);\n if (!s) throw new Error(\"createRightsHandlers.complete: this system no longer holds the request's state\");\n if (FINAL.has(s.status)) return { status: s.status, delivered: await notify(requestId, c, s) };\n const next = await record(requestId, s, outcome ?? { status: 'completed' });\n return { status: next.status, delivered: await notify(requestId, c, next) };\n }\n\n return { fetch, GET: fetch, POST: fetch, complete };\n}\n\n// ---------------------------------------------------------------------------------------------------\n// Durable stores. No dependencies: each adapts something your app already has.\n\ntype DurableStore = RightsStore & { delete(key: string): Promise<void> };\n\n/**\n * One JSON file per key in `dir` (created if missing), named by the key's SHA-256 so any key is a safe\n * filename. Writes go to a temporary file renamed into place, so a crash never leaves half a file. An\n * entry past its TTL reads as missing and is removed. Node, Deno and Bun: `node:fs` is loaded on first\n * use, so importing this entry point on an edge runtime still works.\n */\nexport function fileStore(dir: string): DurableStore {\n // shortcut: an expired idempotency file is removed when read, not swept; prune `dir` by mtime if it ever grows large.\n let fsp: Promise<typeof import('node:fs/promises')> | undefined;\n const fs = () => (fsp ??= import('node:fs/promises').then(async (m) => (await m.mkdir(dir, { recursive: true }), m)));\n const pathOf = async (key: string) => {\n const hash = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', enc.encode(key)));\n return `${dir.replace(/[\\\\/]+$/, '')}/${[...hash].map((b) => b.toString(16).padStart(2, '0')).join('')}.json`;\n };\n const del = async (key: string) => {\n await (await fs()).rm(await pathOf(key), { force: true });\n };\n return {\n async get(key) {\n let raw: string;\n try {\n raw = await (await fs()).readFile(await pathOf(key), 'utf8');\n } catch (e) {\n if ((e as { code?: string }).code === 'ENOENT') return null;\n throw e;\n }\n const rec = JSON.parse(raw) as { v: string; exp?: number };\n if (rec.exp !== undefined && Date.now() >= rec.exp) {\n await del(key);\n return null;\n }\n return rec.v;\n },\n async set(key, value, opts) {\n const m = await fs();\n const file = await pathOf(key);\n const tmp = `${file}.${b64url(globalThis.crypto.getRandomValues(new Uint8Array(6)))}.tmp`;\n await m.writeFile(tmp, JSON.stringify({ v: value, ...(opts?.ttlSeconds ? { exp: Date.now() + opts.ttlSeconds * 1000 } : {}) }));\n await m.rename(tmp, file);\n },\n delete: del,\n };\n}\n\n/** The table `sqlStore` uses (Postgres). Run it once, in a migration. For SQLite: `RIGHTS_STORE_TABLE_SQLITE`. */\nexport const RIGHTS_STORE_TABLE_SQL = `CREATE TABLE IF NOT EXISTS cookiemunch_rights_store (\n key text PRIMARY KEY,\n value text NOT NULL,\n expires_at timestamptz\n)`;\n\n/** The same table for SQLite (`sqlStore({ dialect: 'sqlite' })`): `expires_at` is epoch milliseconds. */\nexport const RIGHTS_STORE_TABLE_SQLITE = `CREATE TABLE IF NOT EXISTS cookiemunch_rights_store (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n expires_at INTEGER\n)`;\n\n/**\n * A store over one SQL table (`RIGHTS_STORE_TABLE_SQL`, or `RIGHTS_STORE_TABLE_SQLITE` with\n * `dialect: 'sqlite'`). `query(sql, params)` runs a parameterised statement and answers `{ rows }` or the\n * rows: `pool.query` from `pg` as it is; for better-sqlite3 (and Drizzle's `db.$client`),\n * `(sql, p) => { const s = db.prepare(sql); return Promise.resolve(s.reader ? s.all(...p) : (s.run(...p), [])); }`.\n * `query` answers the rows for a SELECT; for a write (INSERT … ON CONFLICT, DELETE) its answer is ignored.\n * Prisma: use `prismaStore(prisma)`. An expired row reads as missing; expired rows are purged by the next write that carries a TTL.\n */\nexport function sqlStore(o: { query: (sql: string, params: unknown[]) => Promise<{ rows: unknown[] } | unknown[]>; dialect?: 'postgres' | 'sqlite' }): DurableStore {\n const rows = async (sql: string, params: unknown[]) => {\n const r = await o.query(sql, params);\n return (Array.isArray(r) ? r : r.rows) as Array<{ value?: string }>;\n };\n if (o.dialect === 'sqlite') {\n return {\n async get(key) {\n return (await rows('SELECT value FROM cookiemunch_rights_store WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)', [key, Date.now()]))[0]?.value ?? null;\n },\n async set(key, value, opts) {\n const exp = opts?.ttlSeconds ? Date.now() + opts.ttlSeconds * 1000 : null;\n await rows(\n 'INSERT INTO cookiemunch_rights_store (key, value, expires_at) VALUES (?, ?, ?) '\n + 'ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at',\n [key, value, exp],\n );\n if (exp !== null) await rows('DELETE FROM cookiemunch_rights_store WHERE expires_at <= ?', [Date.now()]);\n },\n async delete(key) {\n await rows('DELETE FROM cookiemunch_rights_store WHERE key = ?', [key]);\n },\n };\n }\n return {\n async get(key) {\n return (await rows('SELECT value FROM cookiemunch_rights_store WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())', [key]))[0]?.value ?? null;\n },\n async set(key, value, opts) {\n const ttl = opts?.ttlSeconds ?? null;\n await rows(\n 'INSERT INTO cookiemunch_rights_store (key, value, expires_at) VALUES ($1, $2, now() + make_interval(secs => $3::integer)) '\n + 'ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at',\n [key, value, ttl],\n );\n if (ttl !== null) await rows('DELETE FROM cookiemunch_rights_store WHERE expires_at <= now()', []);\n },\n async delete(key) {\n await rows('DELETE FROM cookiemunch_rights_store WHERE key = $1', [key]);\n },\n };\n}\n\n/**\n * The `sqlStore` table as a Prisma model (Postgres). Paste it into `schema.prisma`, so `prisma db push` and\n * `migrate` create and keep it; a table made with `RIGHTS_STORE_TABLE_SQL` outside the schema is dropped by\n * the next `db push` (LinkHub CM-L2).\n */\nexport const RIGHTS_STORE_PRISMA_MODEL = `model CookiemunchRightsStore {\n key String @id\n value String\n expiresAt DateTime? @map(\"expires_at\") @db.Timestamptz(6)\n\n @@map(\"cookiemunch_rights_store\")\n}`;\n\n/** The part of a Prisma client `prismaStore` uses. */\nexport interface RightsPrismaClient {\n $queryRawUnsafe(sql: string, ...params: unknown[]): Promise<unknown>;\n $executeRawUnsafe(sql: string, ...params: unknown[]): Promise<unknown>;\n}\n\n/**\n * `sqlStore` over a Prisma client on Postgres (model: `RIGHTS_STORE_PRISMA_MODEL`). Reads go through\n * `$queryRawUnsafe`; writes through `$executeRawUnsafe`, which is what Prisma means for them. This is the\n * whole contract of `sqlStore`'s `query`: answer the rows for a SELECT, and anything (here `[]`) for a write.\n */\nexport function prismaStore(prisma: RightsPrismaClient): DurableStore {\n return sqlStore({\n query: async (sql, params) => (/^\\s*select\\b/i.test(sql)\n ? ((await prisma.$queryRawUnsafe(sql, ...params)) as unknown[])\n : (await prisma.$executeRawUnsafe(sql, ...params), [])),\n });\n}\n\n/** The part of a Redis client `redisStore` uses: node-redis v4's shape, `set(key, value, { EX })`. */\nexport interface RightsRedisClient {\n get(key: string): Promise<string | null | undefined>;\n set(key: string, value: string, opts?: { EX: number }): Promise<unknown>;\n del(key: string): Promise<unknown>;\n}\n\n/** Keys under `cookiemunch:rights:`; idempotency answers expire through Redis's own `EX`. */\nexport function redisStore(client: RightsRedisClient): DurableStore {\n const k = (key: string) => `cookiemunch:rights:${key}`;\n return {\n get: (key) => client.get(k(key)),\n async set(key, value, opts) {\n await (opts?.ttlSeconds ? client.set(k(key), value, { EX: opts.ttlSeconds }) : client.set(k(key), value));\n },\n async delete(key) {\n await client.del(k(key));\n },\n };\n}\n\n/** The part of an ioredis client `ioredisStore` uses: `set(key, value, 'EX', seconds)`. */\nexport interface RightsIoredisClient {\n get(key: string): Promise<string | null | undefined>;\n // Two overloads, as ioredis declares them, so a real `Redis` instance type-checks (one signature with optionals does not).\n set(key: string, value: string): Promise<unknown>;\n set(key: string, value: string, ex: 'EX', seconds: number): Promise<unknown>;\n del(key: string): Promise<unknown>;\n}\n\n/** `redisStore` for ioredis: the same keys, the TTL passed as `'EX', seconds`. */\nexport function ioredisStore(client: RightsIoredisClient): DurableStore {\n const k = (key: string) => `cookiemunch:rights:${key}`;\n return {\n get: (key) => client.get(k(key)),\n async set(key, value, opts) {\n await (opts?.ttlSeconds ? client.set(k(key), value, 'EX', opts.ttlSeconds) : client.set(k(key), value));\n },\n async delete(key) {\n await client.del(k(key));\n },\n };\n}\n","/**\n * The cm-standard-v2 executor conformance kit.\n *\n * cm-standard-v2 is an open contract: any system that holds personal data can implement it and\n * be driven by Cookie Munch with no code on our side (docs: cookiemunch.net/docs/executor-contract-v2).\n * This kit checks an implementation rule by rule, and names the rule that fails. It is the same\n * suite Cookie Munch runs on `POST /v1/dsar/executors/{id}/test {conformance: true}`, and the\n * `cookiemunch executors conformance <baseUrl>` command runs it from a terminal or CI.\n *\n * It only ever touches the CANARY subject — an address no real person has. The contract asks every\n * implementation to treat the canary as an existing synthetic person: it is found by its email and\n * by its identity, requests on it move through the full state machine, and nothing real is ever\n * erased (the one exception is `eraseSubjectEmail`, a throwaway subject the caller names). So the kit can check that an erasure waits for `executeAfter`, that a cancel leaves the\n * person in place, and that an identity is never matched to someone else through a shared email —\n * without a real person's data being anywhere near it.\n *\n * No dependencies: `fetch` only, so it runs in Node 18+, a browser, or an edge runtime.\n */\n\n/** `blocked`: not run, because the rule named in `blockedBy` failed first and decides it. */\nexport type ConformanceStatus = 'pass' | 'fail' | 'skip' | 'blocked';\n\nexport interface ConformanceRuleResult {\n /** A stable id, e.g. `requests.execute_after.scheduled`. */\n id: string;\n /** What the rule says, in one sentence. */\n title: string;\n status: ConformanceStatus;\n /** What was seen, when it failed or was skipped. */\n detail?: string;\n /** With status `blocked`: the rule whose failure stopped this one. */\n blockedBy?: string;\n}\n\nexport interface ConformanceReport {\n /** True when no rule failed. */\n ok: boolean;\n passed: number;\n failed: number;\n skipped: number;\n /** Rules not run because an earlier failure decides them. */\n blocked: number;\n /** Set when the credential itself was refused: `missing_scope` (403) or `credential_refused` (401). */\n code?: 'missing_scope' | 'credential_refused';\n /** With `missing_scope`: the scopes the key needs, when known. */\n required?: string[];\n /** With `code`: the one thing to do next. */\n fix?: string;\n rules: ConformanceRuleResult[];\n /** The `X-Version` the executor answered with, when it sent one. */\n version?: string;\n}\n\nexport interface ConformanceOptions {\n /** The executor's base: the contract paths are `{baseUrl}/privacy/lookup` and so on. https (http only for localhost). */\n baseUrl: string;\n /** The credential Cookie Munch would send. */\n secret: string;\n /**\n * The canary address: `canary-<16 hex>@canary.cookiemunch.net`, per organisation\n * (`GET /v1/dsar/executors/presets` → `canaryEmail`).\n */\n canaryEmail: string;\n /** A subject you seeded in your own store. It is looked up and exported (an access request), never erased. Without it, `lookup.test_subject.found` and `requests.access.no_secrets` are skipped. */\n testSubjectEmail?: string;\n /**\n * A THROWAWAY subject you seeded in your own store. It IS erased, for real, through your own erase code, so reseed it\n * before each run. Without it, `requests.erase.removes_subject` does not run and nothing real is touched.\n */\n eraseSubjectEmail?: string;\n /** How long to wait for that erasure to finish, in ms. Default 30000. */\n eraseTimeoutMs?: number;\n /** How the secret is sent. Default `Authorization: Bearer {secret}`. */\n auth?: { header: string; format: string };\n /** Path prefix under baseUrl. Default `/privacy`. */\n prefix?: string;\n fetch?: typeof fetch;\n now?: () => number;\n /** A per-run tag for idempotency keys and case ids. Default random. */\n runId?: string;\n /** The scopes this system's key needs, when the caller knows them. Otherwise read off the system's own 403. */\n requiredScopes?: string[];\n /** Where to get a key with those scopes, added to `fix`. */\n keyHint?: string;\n}\n\n/** The issuer the canary identity carries. */\nexport const CANARY_ISSUER = 'https://canary.cookiemunch.net';\nconst CANARY_EMAIL_RE = /^canary-([0-9a-f]{16})@canary\\.cookiemunch\\.net$/;\n\n/** The canary subject's identity, derived from its address. */\nexport function canaryIdentityFor(canaryEmail: string): { iss: string; sub: string; ext: string } {\n const m = CANARY_EMAIL_RE.exec(canaryEmail.trim().toLowerCase());\n if (!m) throw new Error('canaryEmail must be the canary address canary-<16 hex>@canary.cookiemunch.net');\n return { iss: CANARY_ISSUER, sub: `canary_${m[1]}`, ext: `canary:${m[1]}` };\n}\n\n/** Every rule, in the order they run. */\nexport const CONFORMANCE_RULES: ReadonlyArray<{ id: string; title: string }> = [\n { id: 'auth.required', title: 'A request without the credential is refused (401, 403, or a 404 without X-Version).' },\n { id: 'lookup.email.found', title: 'The canary subject is found by its email.' },\n { id: 'lookup.identity.found', title: 'The canary subject is found by its identity alone (iss + sub), and it is the same subject.' },\n { id: 'lookup.unknown.no_match', title: 'An address nobody has answers { subjectId: null, status: \"no_match\" }.' },\n { id: 'lookup.identity_beats_email', title: 'An identity that matches no one is never matched through the email of someone else.' },\n { id: 'requests.bad_body.400', title: 'A request with an unknown type answers 400 { error, field }.' },\n { id: 'requests.alias.canonical_type', title: 'An alias (erasure) is accepted and answered with canonicalType \"deletion\".' },\n { id: 'requests.execute_after.scheduled', title: 'A deletion with a future executeAfter is \"scheduled\" with eta equal to executeAfter — nothing is deleted before it.' },\n { id: 'requests.idempotency.replay', title: 'The same Idempotency-Key with the same body returns the same request, not a second one.' },\n { id: 'requests.idempotency.mismatch_409', title: 'The same Idempotency-Key with a different body answers 409.' },\n { id: 'requests.get', title: 'GET /privacy/requests/{id} returns the request, still scheduled.' },\n { id: 'requests.unknown.404', title: 'An unknown request id answers 404.' },\n { id: 'requests.cancel.before_execute_after', title: 'A cancel before executeAfter answers status \"cancelled\".' },\n { id: 'requests.cancel.keeps_data', title: 'After a cancel the subject is still there: a lookup finds it.' },\n { id: 'version.header', title: 'Answers carry X-Version (the highest contract version the executor supports).' },\n];\n\n/** Asked for, not assumed: only with `testSubjectEmail`, so a run without one still reads as the 15 rules every receiver is held to. */\nconst TEST_SUBJECT_RULE = { id: 'lookup.test_subject.found', title: 'A real test subject of yours (testSubjectEmail) is found: this rule alone reaches your own store through createRightsHandlers, which answers the canary itself.' };\n\n/** With `testSubjectEmail` too: an access request reads that subject's export, which must carry no credential (Lucida CM6). */\nconst EXPORT_RULE = { id: 'requests.access.no_secrets', title: 'An access request for your test subject (testSubjectEmail) finishes, and its export carries no credential: no password, password hash, secret, API key, token or private key, by field name or by shape.' };\n\n/** Field names that hold a credential, compared lowercased with `_` and `-` removed. */\nconst SECRET_FIELD = /^(password|passwd|passwordhash|passhash|hashedpassword|secret|clientsecret|apikey|apisecret|accesstoken|refreshtoken|sessiontoken|idtoken|authtoken|privatekey|totpsecret|otpsecret|mfasecret|recoverycodes|salt)$/;\n/** Values shaped like a live credential, whatever the field is called. */\nconst SECRET_VALUE = /^(sk_(live|test)_|rk_(live|test)_|cmk_|ghp_|gho_|github_pat_|xox[abpr]-|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----|\\$2[aby]\\$\\d\\d\\$|\\$argon2)/;\n\n/** The paths in an export that look like credentials (never their values). */\nexport function secretPaths(v: unknown, path = '$', out: string[] = []): string[] {\n if (out.length >= 20) return out;\n if (typeof v === 'string') { if (SECRET_VALUE.test(v.trim())) out.push(path); return out; }\n if (Array.isArray(v)) { v.forEach((x, i) => secretPaths(x, `${path}[${i}]`, out)); return out; }\n if (v && typeof v === 'object') {\n for (const [k, x] of Object.entries(v as Record<string, unknown>)) {\n const p = `${path}.${k}`;\n if (SECRET_FIELD.test(k.toLowerCase().replace(/[_-]/g, '')) && x !== null && x !== '' && x !== undefined) out.push(p);\n else secretPaths(x, p, out);\n }\n }\n return out;\n}\n\n/** Asked for by name: only with `eraseSubjectEmail`, because it really erases that subject. */\nconst ERASE_RULE = { id: 'requests.erase.removes_subject', title: 'A real erasure of your throwaway subject (eraseSubjectEmail) finishes, and a lookup no longer finds them: this rule alone runs your own erase code.' };\n\ntype Answer = { status: number; json: unknown; version: string | null; error?: string };\n\nfunction randomTag(): string {\n const bytes = new Uint8Array(8);\n const c = (globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;\n if (c?.getRandomValues) c.getRandomValues(bytes);\n else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction field(json: unknown, key: string): unknown {\n return json && typeof json === 'object' ? (json as Record<string, unknown>)[key] : undefined;\n}\n\n/** Run every rule against one executor. Never throws for an executor's answer; only for bad options. */\nexport async function runExecutorConformance(o: ConformanceOptions): Promise<ConformanceReport> {\n const doFetch = o.fetch ?? fetch;\n const now = o.now ?? (() => Date.now());\n const base = o.baseUrl.replace(/\\/+$/, '') + (o.prefix ?? '/privacy');\n let url: URL;\n try {\n url = new URL(base);\n } catch {\n throw new Error('baseUrl must be an absolute URL');\n }\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && /^(localhost|127\\.0\\.0\\.1|\\[::1\\])$/.test(url.hostname))) {\n throw new Error('baseUrl must be https (http only for localhost)');\n }\n for (const [name, v] of [['testSubjectEmail', o.testSubjectEmail], ['eraseSubjectEmail', o.eraseSubjectEmail]] as const) {\n if (v !== undefined && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(v)) throw new Error(`${name} must be an email address, not \"${v}\"`);\n }\n const lower = (x: string | undefined) => x?.trim().toLowerCase();\n if (o.eraseSubjectEmail && [lower(o.canaryEmail), lower(o.testSubjectEmail)].includes(lower(o.eraseSubjectEmail))) throw new Error('eraseSubjectEmail must be its own throwaway subject, not the canary or testSubjectEmail');\n const identity = canaryIdentityFor(o.canaryEmail);\n const canaryEmail = o.canaryEmail.trim().toLowerCase();\n const auth = o.auth ?? { header: 'Authorization', format: 'Bearer {secret}' };\n const run = o.runId ?? randomTag();\n const results = new Map<string, ConformanceRuleResult>();\n let version: string | undefined;\n\n const set = (id: string, status: ConformanceStatus, detail?: string): void => {\n const rule = [...CONFORMANCE_RULES, TEST_SUBJECT_RULE, EXPORT_RULE, ERASE_RULE].find((r) => r.id === id)!;\n results.set(id, { id, title: rule.title, status, ...(detail ? { detail } : {}) });\n };\n const pass = (id: string) => set(id, 'pass');\n const fail = (id: string, detail: string) => set(id, 'fail', detail);\n const skip = (id: string, detail: string) => set(id, 'skip', detail);\n\n async function call(method: string, path: string, body?: unknown, extra: Record<string, string> = {}, withAuth = true): Promise<Answer> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n 'X-Version': '2',\n ...(withAuth ? { [auth.header]: auth.format.replace('{secret}', o.secret) } : {}),\n ...(body !== undefined ? { 'content-type': 'application/json' } : {}),\n ...extra,\n };\n try {\n const res = await doFetch(base + path, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });\n const text = await res.text().catch(() => '');\n let json: unknown;\n try {\n json = text ? JSON.parse(text) : undefined;\n } catch {\n json = undefined;\n }\n const v = res.headers.get('x-version');\n if (v && !version) version = v;\n return { status: res.status, json, version: v };\n } catch (err) {\n return { status: 0, json: undefined, version: null, error: err instanceof Error ? err.message : String(err) };\n }\n }\n const said = (a: Answer): string => (a.status === 0 ? `unreachable: ${a.error}` : `HTTP ${a.status} ${JSON.stringify(a.json ?? null).slice(0, 200)}`);\n const key = (rule: string) => `conformance:${run}:${rule}`;\n\n // auth.required\n const anon = await call('POST', '/lookup', { emails: [canaryEmail] }, {}, false);\n if (anon.status === 0) {\n // Nothing else can be judged against a system we cannot reach.\n for (const r of CONFORMANCE_RULES) skip(r.id, said(anon));\n fail('auth.required', said(anon));\n return report();\n }\n // A bare 404 (no X-Version) is a refusal that does not even admit the endpoint exists.\n if (anon.status === 401 || anon.status === 403 || (anon.status === 404 && !anon.version)) pass('auth.required');\n else fail('auth.required', `without a credential: ${said(anon)}`);\n\n // lookups\n const byEmail = await call('POST', '/lookup', { emails: [canaryEmail] }, { 'Idempotency-Key': key('lookup-email') });\n // The key itself is refused: every later rule would fail for this one reason, so it is the only failure.\n // A 404 with no X-Version is how createRightsHandlers answers a wrong secret: it does not admit the API exists.\n const hidden = byEmail.status === 404 && !byEmail.version;\n if (byEmail.status === 401 || byEmail.status === 403 || hidden) {\n fail('lookup.email.found', `the canary address: ${said(byEmail)}`);\n for (const r of CONFORMANCE_RULES) if (!results.has(r.id)) results.set(r.id, { id: r.id, title: r.title, status: 'blocked', blockedBy: 'lookup.email.found' });\n const code = byEmail.status === 403 ? 'missing_scope' as const : 'credential_refused' as const;\n const named = [...new Set(JSON.stringify(byEmail.json ?? '').match(/\\b[a-z_]+:[a-z_]+(?::[a-z_]+)*\\b/g) ?? [])];\n const required = o.requiredScopes?.length ? o.requiredScopes : named;\n const hint = o.keyHint ? ` ${o.keyHint}` : '';\n const fix = code === 'missing_scope'\n ? `This key may not call the rights API (HTTP 403).${required.length ? ` It needs ${required.join(' or ')}.` : ' Give it the rights scope that system documents.'}${hint}`\n : hidden\n ? `No rights API answered this key (HTTP 404, no X-Version). createRightsHandlers answers a wrong secret this way, so check the secret first, then the base URL.${hint}`\n : `This key was refused (HTTP 401): it is wrong, expired or revoked. Send a current one.${hint}`;\n return { ...report(), code, ...(code === 'missing_scope' && required.length ? { required } : {}), fix };\n }\n const subjectId = field(byEmail.json, 'subjectId');\n if (byEmail.status === 200 && field(byEmail.json, 'status') === 'found' && typeof subjectId === 'string' && subjectId) pass('lookup.email.found');\n else fail('lookup.email.found', `the canary address: ${said(byEmail)}`);\n\n if (o.testSubjectEmail) {\n const seeded = await call('POST', '/lookup', { emails: [o.testSubjectEmail] }, { 'Idempotency-Key': key('lookup-seeded') });\n if (seeded.status === 200 && field(seeded.json, 'status') === 'found') pass('lookup.test_subject.found');\n else fail('lookup.test_subject.found', `${o.testSubjectEmail}: ${said(seeded)}`);\n const seededId = field(seeded.json, 'subjectId');\n if (typeof seededId === 'string' && seededId) await exportRule(seededId);\n else skip(EXPORT_RULE.id, 'needs the test subject, which the lookup did not find');\n }\n\n // A receiver that takes the two names as alternatives refuses the body every real request is sent in.\n const bothNames = (a: Answer) => (a.status === 400 ? ' A body carries `identity` and `atlas` together, identical, and `emails` can be empty: accept all of that (see the v2 contract).' : '');\n const byIdentity = await call('POST', '/lookup', { emails: [], identity: identity, atlas: identity }, { 'Idempotency-Key': key('lookup-identity') });\n if (byIdentity.status === 200 && field(byIdentity.json, 'status') === 'found' && field(byIdentity.json, 'subjectId') === subjectId && typeof subjectId === 'string') {\n pass('lookup.identity.found');\n } else {\n fail('lookup.identity.found', `the canary identity ${identity.sub}: ${said(byIdentity)}${typeof subjectId === 'string' ? ` (by email it was ${subjectId})` : ''}${bothNames(byIdentity)}`);\n }\n\n const nobody = await call('POST', '/lookup', { emails: [`nobody-${run}@canary.cookiemunch.net`] }, { 'Idempotency-Key': key('lookup-nobody') });\n if (nobody.status === 200 && field(nobody.json, 'status') === 'no_match' && field(nobody.json, 'subjectId') === null) pass('lookup.unknown.no_match');\n else fail('lookup.unknown.no_match', said(nobody));\n\n const stranger = { iss: identity.iss, sub: `canary_other_${run}` };\n const crossed = await call('POST', '/lookup', { emails: [canaryEmail], identity: stranger, atlas: stranger }, { 'Idempotency-Key': key('lookup-crossed') });\n if (crossed.status === 200 && field(crossed.json, 'status') === 'no_match') pass('lookup.identity_beats_email');\n else {\n fail(\n 'lookup.identity_beats_email',\n `an identity nobody has (${stranger.sub}) with the canary's email: ${said(crossed)} — the email belongs to a different identity, so this must be no_match${bothNames(crossed)}`,\n );\n }\n\n // requests\n const bad = await call('POST', '/requests', { subjectId: subjectId ?? 'x', type: 'teleport', caseId: `conformance-${run}` }, { 'Idempotency-Key': key('bad-body') });\n if (bad.status === 400 && typeof field(bad.json, 'error') === 'string' && typeof field(bad.json, 'field') === 'string') pass('requests.bad_body.400');\n else fail('requests.bad_body.400', said(bad));\n\n if (typeof subjectId !== 'string') {\n for (const id of ['requests.alias.canonical_type', 'requests.execute_after.scheduled', 'requests.idempotency.replay', 'requests.idempotency.mismatch_409', 'requests.get', 'requests.cancel.before_execute_after', 'requests.cancel.keeps_data']) {\n skip(id, 'needs the canary subject, which the lookup did not find');\n }\n } else {\n const executeAfter = new Date(Math.ceil((now() + 3_600_000) / 1000) * 1000).toISOString();\n const body = { subjectId, type: 'erasure', executeAfter, caseId: `conformance-${run}`, reason: 'Cookie Munch conformance check (canary subject)' };\n const opened = await call('POST', '/requests', body, { 'Idempotency-Key': key('open') });\n const id = field(opened.json, 'id');\n const st = field(opened.json, 'status');\n if ((opened.status === 200 || opened.status === 201) && field(opened.json, 'canonicalType') === 'deletion') pass('requests.alias.canonical_type');\n else fail('requests.alias.canonical_type', `type \"erasure\": ${said(opened)}`);\n\n const eta = field(opened.json, 'eta');\n if ((opened.status === 200 || opened.status === 201) && st === 'scheduled' && typeof eta === 'string' && Date.parse(eta) === Date.parse(executeAfter)) {\n pass('requests.execute_after.scheduled');\n } else if (st === 'completed' || st === 'completed_with_retention' || st === 'processing') {\n fail('requests.execute_after.scheduled', `executeAfter is ${executeAfter}, an hour away, and the executor answered \"${String(st)}\": it acted before executeAfter`);\n } else {\n fail('requests.execute_after.scheduled', `expected status \"scheduled\" with eta ${executeAfter}: ${said(opened)}`);\n }\n\n const replay = await call('POST', '/requests', body, { 'Idempotency-Key': key('open') });\n if (typeof id === 'string' && (replay.status === 200 || replay.status === 201) && field(replay.json, 'id') === id) pass('requests.idempotency.replay');\n else fail('requests.idempotency.replay', `a retry with the same key: ${said(replay)}${typeof id === 'string' ? ` (first answer id ${id})` : ''}`);\n\n const mismatch = await call('POST', '/requests', { ...body, reason: 'a different body' }, { 'Idempotency-Key': key('open') });\n if (mismatch.status === 409) pass('requests.idempotency.mismatch_409');\n else fail('requests.idempotency.mismatch_409', `the same key with a different body: ${said(mismatch)}`);\n\n if (typeof id !== 'string') {\n skip('requests.get', 'no request id came back');\n skip('requests.cancel.before_execute_after', 'no request id came back');\n skip('requests.cancel.keeps_data', 'no request id came back');\n } else {\n const got = await call('GET', `/requests/${encodeURIComponent(id)}`, undefined, { 'Idempotency-Key': key('get') });\n if (got.status === 200 && field(got.json, 'id') === id && field(got.json, 'status') === 'scheduled') pass('requests.get');\n else fail('requests.get', said(got));\n\n const cancelled = await call('POST', `/requests/${encodeURIComponent(id)}/cancel`, {}, { 'Idempotency-Key': key('cancel') });\n if (cancelled.status === 200 && field(cancelled.json, 'status') === 'cancelled') pass('requests.cancel.before_execute_after');\n else fail('requests.cancel.before_execute_after', said(cancelled));\n\n const after = await call('POST', '/lookup', { emails: [canaryEmail] }, { 'Idempotency-Key': key('lookup-after-cancel') });\n if (after.status === 200 && field(after.json, 'status') === 'found') pass('requests.cancel.keeps_data');\n else fail('requests.cancel.keeps_data', `a lookup after the cancel: ${said(after)} — a cancel before executeAfter must leave the data intact`);\n }\n }\n\n const unknown = await call('GET', `/requests/conformance-missing-${run}`, undefined, { 'Idempotency-Key': key('unknown') });\n if (unknown.status === 404) pass('requests.unknown.404');\n else fail('requests.unknown.404', said(unknown));\n\n if (o.eraseSubjectEmail) await eraseRule(o.eraseSubjectEmail);\n\n if (version) pass('version.header');\n else fail('version.header', 'no answer carried an X-Version header');\n\n return report();\n\n async function eraseRule(email: string): Promise<void> {\n const rule = ERASE_RULE.id;\n const before = await call('POST', '/lookup', { emails: [email] }, { 'Idempotency-Key': key('erase-lookup') });\n const subject = field(before.json, 'subjectId');\n if (before.status !== 200 || field(before.json, 'status') !== 'found' || typeof subject !== 'string') {\n return fail(rule, `${email} must exist before the run, so seed it each time: ${said(before)}`);\n }\n const opened = await call('POST', '/requests', { subjectId: subject, type: 'deletion', caseId: `conformance-erase-${run}`, reason: 'Cookie Munch conformance check (throwaway subject)' }, { 'Idempotency-Key': key('erase') });\n const id = field(opened.json, 'id');\n if ((opened.status !== 200 && opened.status !== 201) || typeof id !== 'string') return fail(rule, `the erasure was not accepted: ${said(opened)}`);\n let st = field(opened.json, 'status');\n const deadline = Date.now() + (o.eraseTimeoutMs ?? 30_000);\n while ((st === 'pending' || st === 'processing') && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 500));\n st = field((await call('GET', `/requests/${encodeURIComponent(id)}`, undefined, { 'Idempotency-Key': key('erase-get') })).json, 'status');\n }\n if (st !== 'completed' && st !== 'completed_with_retention') return fail(rule, `the erasure ended as \"${String(st)}\", not completed`);\n const gone = await call('POST', '/lookup', { emails: [email] }, { 'Idempotency-Key': key('erase-after') });\n // A retention is a declared exception: the contract lets that subject remain.\n if (gone.status === 200 && (field(gone.json, 'status') === 'no_match' || st === 'completed_with_retention')) pass(rule);\n else fail(rule, `the erasure said \"${String(st)}\", but a lookup afterwards: ${said(gone)}`);\n }\n\n async function exportRule(subject: string): Promise<void> {\n const rule = EXPORT_RULE.id;\n const opened = await call('POST', '/requests', { subjectId: subject, type: 'access', caseId: `conformance-access-${run}`, reason: 'Cookie Munch conformance check (test subject export)' }, { 'Idempotency-Key': key('access') });\n const id = field(opened.json, 'id');\n if ((opened.status !== 200 && opened.status !== 201) || typeof id !== 'string') return fail(rule, `the access request was not accepted: ${said(opened)}`);\n let answer = opened;\n const deadline = Date.now() + (o.eraseTimeoutMs ?? 30_000);\n while (['pending', 'processing'].includes(String(field(answer.json, 'status'))) && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 500));\n answer = await call('GET', `/requests/${encodeURIComponent(id)}`, undefined, { 'Idempotency-Key': key('access-get') });\n }\n const st = field(answer.json, 'status');\n if (st !== 'completed' && st !== 'completed_with_retention') return fail(rule, `the access request ended as \"${String(st)}\", not completed`);\n let bundle = field(answer.json, 'result');\n const url = field(bundle, 'downloadUrl');\n if (typeof url === 'string') {\n try {\n const res = await doFetch(url, { headers: { accept: 'application/json' } });\n const text = await res.text();\n if (text.length > 5_000_000) return fail(rule, 'the export is over 5 MB');\n try { bundle = JSON.parse(text); } catch { bundle = text; }\n } catch (err) {\n return fail(rule, `the export's downloadUrl could not be read: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n if (bundle === undefined) return fail(rule, 'the completed access request carried no result (inline, or { downloadUrl })');\n const found = typeof bundle === 'string' ? bundle.split(/\\s+/).filter((w) => SECRET_VALUE.test(w)).map(() => '$ (text)') : secretPaths(bundle);\n if (found.length) fail(rule, `the export carries what looks like a credential at ${[...new Set(found)].join(', ')}; leave credentials out of an access export`);\n else pass(rule);\n }\n\n function report(): ConformanceReport {\n const rules = [...CONFORMANCE_RULES, ...(o.testSubjectEmail ? [TEST_SUBJECT_RULE, EXPORT_RULE] : []), ...(o.eraseSubjectEmail ? [ERASE_RULE] : [])].map((r) => results.get(r.id) ?? { id: r.id, title: r.title, status: 'skip' as const, detail: 'not reached' });\n const count = (s: ConformanceStatus) => rules.filter((r) => r.status === s).length;\n return { ok: count('fail') === 0, passed: count('pass'), failed: count('fail'), skipped: count('skip'), blocked: count('blocked'), rules, ...(version ? { version } : {}) };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuFO,IAAM,gBAAgB;;;ADatB,IAAM,0BAA0B,KAAK,KAAK;AAsDjD,IAAM,YAAwC;AAAA,EAC5C,QAAQ;AAAA,EAAU,QAAQ;AAAA,EAAU,aAAa;AAAA,EAAe,SAAS;AAAA,EAAW,UAAU;AAAA,EAAW,OAAO;AAAA,EAChH,SAAS;AAAA,EAAW,aAAa;AAAA,EAAe,eAAe;AACjE;AAEA,IAAM,OAAmC;AAAA,EACvC,QAAQ;AAAA,EAAU,aAAa;AAAA,EAAU,SAAS;AAAA,EAAY,SAAS;AAAA,EAAW,aAAa;AAAA,EAAe,eAAe;AAC/H;AACA,IAAM,aAAa;AACnB,IAAM,WAAW,oBAAI,IAAI,CAAC,WAAW,cAAc,WAAW,aAAa,4BAA4B,YAAY,UAAU,CAAC;AAE9H,IAAM,QAAQ,oBAAI,IAAkB,CAAC,aAAa,4BAA4B,YAAY,YAAY,WAAW,CAA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AAO,KAAK;AAChB,YAAM,OAAO,IAAI,EAAE,GAAG,CAAC;AAAA,IACzB;AAAA,EACF;AACF;AAYO,SAAS,aAAa,QAA2C;AACtE,QAAM,IAAI,CAAC,QAAgB,sBAAsB,GAAG;AACpD,SAAO;AAAA,IACL,KAAK,CAAC,QAAQ,OAAO,IAAI,EAAE,GAAG,CAAC;AAAA,IAC/B,MAAM,IAAI,KAAK,OAAO,MAAM;AAC1B,aAAO,MAAM,aAAa,OAAO,IAAI,EAAE,GAAG,GAAG,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,IAAI,EAAE,GAAG,GAAG,KAAK;AAAA,IACvG;AAAA,IACA,MAAM,OAAO,KAAK;AAChB,YAAM,OAAO,IAAI,EAAE,GAAG,CAAC;AAAA,IACzB;AAAA,EACF;AACF;","names":["fetch"]}
1
+ {"version":3,"sources":["../src/rights.ts","../src/executor-conformance.ts"],"sourcesContent":["/**\n * `@cookiemunch/sdk/rights` — the cm-standard-v2 executor contract, server side.\n *\n * A product that holds personal data implements four calls and Cookie Munch drives it (docs:\n * cookiemunch.net/docs/executor-contract-v2). This builds those four calls from callbacks, so the\n * product writes only \"find this person\", \"export them\", \"erase them\":\n *\n * import { createRightsHandlers } from '@cookiemunch/sdk/rights';\n * const rights = createRightsHandlers({\n * key: process.env.CM_EXECUTOR_KEY!, // the secretKey you registered with Cookie Munch\n * idSecret: process.env.CM_REQUEST_ID_SECRET!,\n * lookup: async ({ emails, identity }) => (await findUser(emails, identity))?.id ?? null,\n * access: async (r) => ({ status: 'completed', result: await exportUser(r.subjectId) }),\n * erase: async (r) => { await deleteUser(r.subjectId); },\n * });\n * // Next.js app/privacy/[...path]/route.ts: export const { GET, POST } = rights;\n * // Deno: Deno.serve(rights.fetch) Workers / Bun: export default rights\n *\n * Built in: a constant-time key check (no key or a wrong key is a bare 404, so the endpoint is not\n * advertised), `X-Version` and `Cache-Control: no-store` on every authorised answer, Idempotency-Key\n * replay, HMAC-signed request ids (a forged id is a 404), `executeAfter` scheduling and cancel, and\n * the canary subject, answered here so your callbacks never see it. With `completion`, each request\n * that reaches a final status is also pushed to Cookie Munch as a signed completion, so it closes in\n * seconds instead of on the next poll.\n *\n * A separate entry point so the API client never loads it. Web platform only (Request, Response,\n * crypto.subtle): Node 20+, Deno, Bun and edge runtimes.\n */\nimport { CANARY_ISSUER } from './executor-conformance.js';\n\n/**\n * The six rights, one word each. Every word Cookie Munch has sent is read as one of them: `deletion`,\n * `erase` → `erasure`; `export` → `access`. A portability request is `portability` (its callback falls\n * back to `access` when there is no `portability`).\n */\nexport type RightsType = 'access' | 'erasure' | 'rectification' | 'portability' | 'restriction' | 'closure';\nexport type RightsStatus = 'pending' | 'scheduled' | 'processing' | 'blocked' | 'completed' | 'completed_with_retention' | 'no_match' | 'rejected' | 'cancelled';\n\nexport interface RightsIdentity {\n iss: string;\n sub: string;\n ext?: string;\n principal?: string;\n}\n\nexport interface RightsLookupInput {\n emails: string[];\n /** A signed-in identity (sent as `identity`, or `atlas`). Match on it before the emails, and never through an email that belongs to a different identity. */\n identity?: RightsIdentity;\n /**\n * The part of your account the request is for, when Cookie Munch sends one: `{ tenant }` for a tenant site's case\n * (your id for the customer, /docs/tenants), or a connection's own scope such as `{ programId }`. Look only inside\n * it. The handler echoes it on the answer, which Cookie Munch requires before it sends anything further.\n */\n scope?: Record<string, unknown>;\n}\n\n/** What `byEmail` answers: account ids, or `{ id, subject }` when the account is linked to an identity. */\nexport type RightsEmailMatch = string | { id: string; subject?: string | null };\n\n/**\n * `lookup` as two finders: the SDK applies the identity-first rule (LinkHub CM-X5, snapnedit CM-I2). With an\n * identity it asks `bySubject` first; it then tries each email in order and drops an account linked to a\n * different subject, so a request signed in as one person never reaches another's account through a shared email.\n * Include deleted (tombstoned) accounts in both, so a closure filed after the deletion still matches.\n */\nexport interface RightsLookupFinders {\n /** `scope`: as RightsLookupInput.scope; look only inside it. */\n bySubject?: (sub: string, identity: RightsIdentity, scope?: Record<string, unknown>) => Promise<string | null | undefined> | string | null | undefined;\n byEmail: (email: string, scope?: Record<string, unknown>) => Promise<RightsEmailMatch[] | RightsEmailMatch | null | undefined> | RightsEmailMatch[] | RightsEmailMatch | null | undefined;\n}\n\n/** The identity-first rule over two finders. Exported for products that call it themselves. */\nexport async function lookupByRule(f: RightsLookupFinders, input: RightsLookupInput): Promise<string | null> {\n const sub = input.identity?.sub;\n if (sub && f.bySubject) {\n const id = await f.bySubject(sub, input.identity!, input.scope);\n if (typeof id === 'string' && id) return id;\n }\n for (const email of input.emails) {\n const found = await f.byEmail(email, input.scope);\n const list = found == null ? [] : Array.isArray(found) ? found : [found];\n for (const m of list) {\n const id = typeof m === 'string' ? m : m?.id;\n const other = typeof m === 'object' && m?.subject && sub && m.subject !== sub;\n if (typeof id === 'string' && id && !other) return id;\n }\n }\n return null;\n}\n\nexport interface RightsRetention {\n category: string;\n basis: 'legal_obligation' | 'legal_claims' | 'contract' | 'public_interest' | 'legitimate_interest';\n until?: string;\n}\n\n/** What a callback answers. Returning nothing means `completed`. */\nexport interface RightsOutcome {\n status: 'pending' | 'processing' | 'blocked' | 'completed' | 'completed_with_retention' | 'no_match' | 'rejected';\n eta?: string;\n /**\n * With `blocked`: the person must act before you can (e.g. hand over an organisation they own alone).\n * `message` is shown to them on their status page as your words; `reason` is a short code for the controller.\n */\n blocked?: { reason?: string; message?: string };\n /** Plain words; required in spirit for `rejected`. */\n detail?: string;\n retention?: RightsRetention[];\n /** For `access`: `{ downloadUrl, expiresAt, sha256 }`, or the bundle inline (at most 5 MB). */\n result?: unknown;\n}\n\n/** The request a callback acts on. */\nexport interface RightsRequest {\n id: string;\n subjectId: string;\n type: RightsType;\n /** The word Cookie Munch sent: its `right` (one of the RightsType words) when present, else its `type`. */\n requestedType: string;\n caseId: string;\n reason?: string;\n executeAfter?: string;\n}\n\ntype Callback = (r: RightsRequest) => Promise<RightsOutcome | void> | RightsOutcome | void;\n\n/**\n * Where request state and idempotency answers live. A `Map` is one; `fileStore`, `sqlStore` and\n * `redisStore` below are durable ones. Idempotency answers are set with `ttlSeconds` (24 hours) and\n * a store may drop them after that; request state (a scheduled erasure included) is set with none and\n * must be kept. `delete`, when present, removes an answer the handlers found expired.\n */\nexport interface RightsStore {\n get(key: string): Promise<string | null | undefined> | string | null | undefined;\n set(key: string, value: string, opts?: { ttlSeconds?: number }): unknown;\n delete?(key: string): unknown;\n}\n\n/** How long an Idempotency-Key answer is replayed. */\nexport const IDEMPOTENCY_TTL_SECONDS = 24 * 60 * 60;\n\nexport interface RightsHandlersOptions {\n /** The key Cookie Munch sends as `Authorization: Bearer <key>`; at least 24 characters. */\n key: string;\n /** Signs request ids; at least 32 characters, the same on every instance and across restarts. */\n idSecret: string;\n /** The subject id for these emails / this identity, or null. Or two finders, and the SDK applies the identity-first rule. */\n lookup: ((input: RightsLookupInput) => Promise<string | null | undefined> | string | null | undefined) | RightsLookupFinders;\n access?: Callback;\n /** `portability`: the person's data in a machine-readable form. Without it, `access` answers it. */\n portability?: Callback;\n /**\n * `erasure` (and `closure`, when there is no `close`). With a future `executeAfter` the request is\n * stored as `scheduled` and there is NO timer in your process: `erase` runs when Cookie Munch sends\n * `POST /requests/{id}/run` at or after `executeAfter` (its sweep runs every 10 minutes). A `GET` never\n * runs it. The state must survive a restart: give production a durable `store`.\n */\n erase?: Callback;\n close?: Callback;\n restrict?: Callback;\n rectify?: Callback;\n /** Read back a request a callback answered `pending` or `processing` for. */\n status?: Callback;\n /**\n * Default: in memory, which a restart empties. A scheduled erasure whose state is gone is never\n * run (it answers `rejected`), so give production a durable store: `fileStore(dir)`,\n * `sqlStore({ query })`, `redisStore(client)` or `ioredisStore(client)`.\n */\n store?: RightsStore;\n /**\n * Stateless (LinkHub CM-L2): keep no table. Cookie Munch signs each request's state (`Cookiemunch-Request-State`,\n * an EdDSA JWS from its platform key) on every read, run and cancel; when the store holds nothing for a request,\n * the handlers use that state instead, so a scheduled erasure still runs after a restart or on another instance.\n * `true` verifies against https://api.cookiemunch.net/v1/partner/jwks.json; or pass `{ jwksUrl }` or `{ jwks }`.\n * Your callbacks must then be safe to repeat for one caseId: a retried open whose first answer was lost runs again.\n */\n stateless?: boolean | { jwksUrl?: string; jwks?: { keys: JsonWebKey[] } };\n now?: () => number;\n /**\n * Signed completions (cm-standard-v2): the connection's `completionUrl` and its `completionSecret`\n * (`whsec_…`; read it again with `fulfillment.getExecutorCompletionSecret(id)`). Profile-based\n * systems use `webhookUrl` + `webhookSecret` instead; a `webhookSecret` also verifies here. Each request that reaches a final status is POSTed there, signed,\n * with up to 3 attempts. A failed push never fails a request: Cookie Munch's poll still closes it.\n */\n completion?: { url: string; secret: string; fetch?: typeof fetch };\n}\n\nexport interface RightsHandlers {\n /** The whole contract, routed on the path's tail: mount it under any prefix. */\n fetch(req: Request): Promise<Response>;\n GET(req: Request): Promise<Response>;\n POST(req: Request): Promise<Response>;\n /**\n * Finish a request a callback answered `pending` or `processing` for, out of band (a job queue, a\n * manual review): stores the final outcome and, with `completion`, pushes it and waits for the push.\n * `delivered` is false when there is no `completion` or every attempt failed (polling still closes it).\n * A request already final is left as it is; its completion is re-sent only if it was never delivered.\n */\n complete(requestId: string, outcome?: RightsOutcome): Promise<{ status: RightsStatus; delivered: boolean }>;\n}\n\nconst CANONICAL: Record<string, RightsType> = {\n access: 'access', export: 'access', portability: 'portability', erasure: 'erasure', deletion: 'erasure', erase: 'erasure',\n closure: 'closure', restriction: 'restriction', rectification: 'rectification',\n};\n/** The contract's `canonicalType` on the wire (executor-contract-v2), which predates the six words. */\nconst WIRE: Record<RightsType, string> = {\n access: 'access', portability: 'access', erasure: 'deletion', closure: 'closure', restriction: 'restriction', rectification: 'rectification',\n};\nconst TYPE_WORDS = 'access, export, portability, erasure, deletion, erase, closure, restriction, rectification';\nconst OUTCOMES = new Set(['pending', 'processing', 'blocked', 'completed', 'completed_with_retention', 'no_match', 'rejected']);\n/** The contract's final statuses: each one is pushed as a signed completion. */\nconst FINAL = new Set<RightsStatus>(['completed', 'completed_with_retention', 'no_match', 'rejected', 'cancelled']);\n/** Wait before each completion attempt after the first. */\nconst COMPLETION_BACKOFF_MS = [1_000, 4_000];\nconst CANARY_EMAIL = /^canary-([0-9a-f]{16})@canary\\.cookiemunch\\.net$/;\nconst CANARY_SUBJECT = /^canary_([0-9a-f]{16})$/;\nconst CANARY_EXT = /^canary:([0-9a-f]{16})$/;\n\n/** What the signed id carries: enough to answer without trusting the store for it. */\ntype IdClaims = { s: string; t: RightsType; y: string; c: string; a?: number; n: string };\n/** The request's mutable state, in the store under `req:<id>`. */\ntype Stored = { status: RightsStatus; eta?: string; detail?: string; blocked?: { reason?: string; message?: string }; retention?: RightsRetention[]; result?: unknown; reason?: string; notified?: true };\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\nfunction b64url(bytes: Uint8Array): string {\n let s = '';\n for (const b of bytes) s += String.fromCharCode(b);\n return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\nfunction fromB64url(s: string) {\n if (!/^[A-Za-z0-9_-]*$/.test(s)) return null;\n try {\n const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'));\n return Uint8Array.from(bin, (c) => c.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\n/** Constant-time in the presented value: every byte of the expected key is compared. */\nfunction sameKey(presented: string, expected: string): boolean {\n const a = enc.encode(presented);\n const b = enc.encode(expected);\n let diff = a.length ^ b.length;\n for (let i = 0; i < b.length; i++) diff |= (a[i] ?? 0) ^ b[i]!;\n return diff === 0;\n}\n\nfunction json(status: number, body: unknown): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json', 'x-version': '2', 'cache-control': 'no-store' },\n });\n}\nconst bad = (error: string, field: string) => json(400, { error, field });\n// No X-Version and nothing contract-shaped: to a caller without the key this is any other 404.\nconst hidden = () => new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain' } });\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return !!v && typeof v === 'object' && !Array.isArray(v);\n}\n\nexport function createRightsHandlers(o: RightsHandlersOptions): RightsHandlers {\n if (typeof o.key !== 'string' || !o.key) throw new Error('createRightsHandlers: key is required');\n // A warning, not a throw: Cookie Munch has accepted 8-character keys, and an SDK upgrade must not take a working rights endpoint down.\n if (o.key.length < 24) console.warn('createRightsHandlers: key is shorter than 24 characters; rotate it to a longer one (PATCH /v1/dsar/executors/{id} {secretKey}) so it cannot be guessed');\n if (typeof o.idSecret !== 'string' || o.idSecret.length < 32) throw new Error('createRightsHandlers: idSecret must be at least 32 characters');\n const finders = typeof o.lookup === 'object' && o.lookup !== null ? o.lookup : null;\n if (finders ? typeof finders.byEmail !== 'function' : typeof o.lookup !== 'function') throw new Error('createRightsHandlers: lookup is required (a function, or { bySubject?, byEmail })');\n const find = finders ? (i: RightsLookupInput) => lookupByRule(finders, i) : (o.lookup as (i: RightsLookupInput) => Promise<string | null | undefined> | string | null | undefined);\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new Error('createRightsHandlers: needs Web Crypto (globalThis.crypto.subtle)');\n // shortcut: the default Map keeps an expired idempotency answer until it is read again; fine for the volume of rights requests, pass `store` for more.\n const store: RightsStore = o.store ?? new Map<string, string>();\n const now = o.now ?? (() => Date.now());\n const hmacKey = subtle.importKey('raw', enc.encode(o.idSecret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);\n const completion = o.completion;\n if (completion && (typeof completion.url !== 'string' || !/^https?:\\/\\//.test(completion.url) || typeof completion.secret !== 'string' || !completion.secret)) {\n throw new Error('createRightsHandlers: completion needs { url, secret }: the connection\\'s completionUrl and completionSecret');\n }\n // Standard Webhooks: a `whsec_` secret's HMAC key is its base64-decoded remainder; anything else signs as typed.\n const completionKey = completion\n ? subtle.importKey('raw', (completion.secret.startsWith('whsec_') && fromB64url(completion.secret.slice(6).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''))) || enc.encode(completion.secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])\n : undefined;\n\n async function mintId(claims: IdClaims): Promise<string> {\n const payload = b64url(enc.encode(JSON.stringify(claims)));\n const sig = new Uint8Array(await subtle.sign('HMAC', await hmacKey, enc.encode(payload)));\n return `r1.${payload}.${b64url(sig)}`;\n }\n async function readId(id: string): Promise<IdClaims | null> {\n const [v, payload, sig, extra] = id.split('.');\n if (v !== 'r1' || !payload || !sig || extra !== undefined) return null;\n const sigBytes = fromB64url(sig);\n if (!sigBytes || !(await subtle.verify('HMAC', await hmacKey, sigBytes, enc.encode(payload)))) return null;\n const raw = fromB64url(payload);\n try {\n if (!raw) return null;\n const c = JSON.parse(dec.decode(raw)) as IdClaims;\n // An id minted before the six words carries `deletion`.\n return { ...c, t: CANONICAL[c.t] ?? c.t };\n } catch {\n return null;\n }\n }\n\n const getStored = async (id: string, signed?: Stored | null): Promise<Stored | null> => {\n const v = await store.get(`req:${id}`);\n return v ? (JSON.parse(v) as Stored) : (signed ?? null);\n };\n\n // ---- stateless: the request state Cookie Munch signs (CM-L2) ----\n const sl = o.stateless === true ? {} : o.stateless || null;\n const jwksUrl = sl?.jwksUrl ?? 'https://api.cookiemunch.net/v1/partner/jwks.json';\n let keys: Map<string, Promise<CryptoKey>> | null = null;\n let keysAt = 0;\n const loadKeys = async (jwks?: { keys: JsonWebKey[] }) => {\n const list = jwks?.keys ?? ((await (await globalThis.fetch(jwksUrl)).json()) as { keys: JsonWebKey[] }).keys;\n keys = new Map(list.filter((k) => k.kty === 'OKP' && k.crv === 'Ed25519').map((k) => [(k as { kid?: string }).kid ?? '', subtle.importKey('jwk', k, { name: 'Ed25519' }, false, ['verify'])]));\n keysAt = now();\n };\n const STATE_STATUSES = new Set<string>([...OUTCOMES, 'scheduled', 'cancelled']);\n /** The verified state for `id` from the request's header, or null: a bad, expired or foreign one is ignored. */\n async function signedState(req: Request, id: string): Promise<Stored | null> {\n const jws = sl && req.headers.get('cookiemunch-request-state');\n if (!jws) return null;\n try {\n const [h, p, sig, extra] = jws.split('.');\n if (!h || !p || !sig || extra !== undefined) return null;\n const header = JSON.parse(dec.decode(fromB64url(h) ?? new Uint8Array())) as { alg?: string; kid?: string };\n if (header.alg !== 'EdDSA' || !header.kid) return null;\n // An unknown kid refetches the key set, at most every five minutes (a rotated key).\n if (!keys || (!keys.has(header.kid) && !sl.jwks && now() - keysAt > 300_000)) await loadKeys(sl.jwks);\n const key = keys!.get(header.kid);\n const sigBytes = fromB64url(sig);\n if (!key || !sigBytes || !(await subtle.verify({ name: 'Ed25519' }, await key, sigBytes, enc.encode(`${h}.${p}`)))) return null;\n const cl = JSON.parse(dec.decode(fromB64url(p)!)) as { id?: string; status?: string; executeAfter?: string; exp?: number };\n const t = now() / 1000;\n if (cl.id !== id || typeof cl.exp !== 'number' || cl.exp < t || cl.exp > t + 900 || !cl.status || !STATE_STATUSES.has(cl.status)) return null;\n return { status: cl.status as RightsStatus, ...(cl.status === 'scheduled' && cl.executeAfter ? { eta: cl.executeAfter } : {}) };\n } catch {\n return null;\n }\n }\n const putStored = async (id: string, s: Stored) => {\n await store.set(`req:${id}`, JSON.stringify(s));\n };\n\n const view = (id: string, c: IdClaims, s: Stored) => ({\n id,\n type: c.y,\n canonicalType: WIRE[c.t] ?? c.t,\n status: s.status,\n ...(s.eta ? { eta: s.eta } : {}),\n ...(s.detail ? { detail: s.detail } : {}),\n ...(s.blocked && s.status === 'blocked' ? { blocked: s.blocked } : {}),\n ...(s.retention ? { retention: s.retention } : {}),\n ...(s.result !== undefined ? { result: s.result } : {}),\n });\n\n /**\n * Push a final status to `completionsUrl`, signed. Never throws: a failure is logged and left to the poll.\n * Retried on a network error, a 5xx or a 429, with the same Webhook-Id, so a retry that did land is a no-op.\n */\n async function notify(id: string, c: IdClaims, s: Stored): Promise<boolean> {\n if (!completion || !completionKey || !FINAL.has(s.status) || s.notified) return false;\n try {\n const body = JSON.stringify({ caseId: c.c, request: view(id, c, s) });\n const webhookId = `cmc_${b64url(globalThis.crypto.getRandomValues(new Uint8Array(12)))}`;\n const send = completion.fetch ?? globalThis.fetch;\n for (let attempt = 0; attempt <= COMPLETION_BACKOFF_MS.length; attempt++) {\n if (attempt > 0) await new Promise((r) => setTimeout(r, COMPLETION_BACKOFF_MS[attempt - 1]));\n const stamp = String(Math.floor(now() / 1000));\n const sig = new Uint8Array(await subtle.sign('HMAC', await completionKey, enc.encode(`${webhookId}.${stamp}.${body}`)));\n let status = 0;\n try {\n status = (await send(completion.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', 'webhook-id': webhookId, 'webhook-timestamp': stamp, 'webhook-signature': `v1,${btoa(String.fromCharCode(...sig))}` },\n body,\n })).status;\n } catch (err) {\n console.warn('createRightsHandlers: completion push failed:', err);\n }\n if (status >= 200 && status < 300) {\n const latest = await getStored(id);\n if (latest && latest.status === s.status) await putStored(id, { ...latest, notified: true });\n return true;\n }\n if (status !== 0 && status < 500 && status !== 429) {\n console.warn(`createRightsHandlers: completion refused with ${status}; check completion.url and completion.secret`);\n return false;\n }\n }\n } catch (err) {\n console.warn('createRightsHandlers: completion push failed:', err);\n }\n return false;\n }\n\n const callbackFor = (t: RightsType): Callback | undefined =>\n ({ access: o.access, portability: o.portability ?? o.access, erasure: o.erase, closure: o.close ?? o.erase, restriction: o.restrict, rectification: o.rectify })[t];\n\n /** Run a callback (or, for the canary, nothing) and fold its answer into the stored state. */\n async function act(id: string, c: IdClaims, s: Stored, cb: Callback | undefined): Promise<Stored> {\n // The canary is a synthetic person: requests on it complete without touching anything real.\n const out = CANARY_SUBJECT.test(c.s) || !cb\n ? undefined\n : ((await cb({\n id,\n subjectId: c.s,\n type: c.t,\n requestedType: c.y,\n caseId: c.c,\n ...(s.reason ? { reason: s.reason } : {}),\n ...(c.a !== undefined ? { executeAfter: new Date(c.a).toISOString() } : {}),\n })) as RightsOutcome | undefined);\n const next = await record(id, s, out ?? { status: 'completed' });\n void notify(id, c, next);\n return next;\n }\n\n /** Fold an outcome into the stored state. */\n async function record(id: string, s: Stored, o2: RightsOutcome): Promise<Stored> {\n if (!OUTCOMES.has(o2.status)) throw new Error(`a rights callback answered an unknown status \"${String(o2.status)}\"`);\n const next: Stored = { status: o2.status, ...(s.reason ? { reason: s.reason } : {}) };\n if (o2.eta) next.eta = o2.eta;\n if (o2.detail) next.detail = o2.detail;\n if (o2.status === 'blocked' && o2.blocked) next.blocked = o2.blocked;\n if (o2.retention) next.retention = o2.retention;\n if (o2.result !== undefined) next.result = o2.result;\n await putStored(id, next);\n return next;\n }\n\n async function lookup(body: Record<string, unknown>): Promise<Response> {\n if (!Array.isArray(body.emails) || body.emails.some((e) => typeof e !== 'string')) return bad('emails must be an array of strings', 'emails');\n const emails = (body.emails as string[]).map((e) => e.trim());\n const raw = body.identity ?? body.atlas;\n if (raw !== undefined && raw !== null && !(isObject(raw) && typeof raw.iss === 'string' && typeof raw.sub === 'string')) {\n return bad('identity must be { iss, sub, ext?, principal? }', 'identity');\n }\n const identity = isObject(raw) ? (raw as unknown as RightsIdentity) : undefined;\n if (body.scope !== undefined && !isObject(body.scope)) return bad('scope must be an object', 'scope');\n const scope = isObject(body.scope) ? (body.scope as Record<string, unknown>) : undefined;\n // The scope goes back on every answer: Cookie Munch sends nothing further to a lookup that does not echo it.\n const echo = scope ? { scope } : {};\n\n const canaryByEmail = emails.map((e) => CANARY_EMAIL.exec(e.toLowerCase())?.[1]).find(Boolean);\n const canaryExt = typeof identity?.ext === 'string' ? CANARY_EXT.exec(identity.ext)?.[1] : undefined;\n if (canaryByEmail || canaryExt || identity?.iss === CANARY_ISSUER) {\n // When an identity is given only it decides: the canary's email next to anyone else's identity is no one.\n const tag = identity ? (identity.iss === CANARY_ISSUER ? CANARY_SUBJECT.exec(identity.sub)?.[1] : undefined) ?? canaryExt : canaryByEmail;\n return json(200, tag ? { subjectId: `canary_${tag}`, status: 'found', ...echo } : { subjectId: null, status: 'no_match', ...echo });\n }\n const subjectId = await find({ emails, ...(identity ? { identity } : {}), ...(scope ? { scope } : {}) });\n return json(200, typeof subjectId === 'string' && subjectId ? { subjectId, status: 'found', ...echo } : { subjectId: null, status: 'no_match', ...echo });\n }\n\n async function open(body: Record<string, unknown>): Promise<Response> {\n // `right` names the right itself (portability, which `type` sends as access); a receiver that predates it reads `type`.\n const word = typeof body.right === 'string' && CANONICAL[body.right] ? body.right : body.type;\n const t = typeof word === 'string' ? CANONICAL[word] : undefined;\n if (!t) return bad(`type must be one of ${TYPE_WORDS}`, 'type');\n if (typeof body.subjectId !== 'string' || !body.subjectId) return bad('subjectId is required', 'subjectId');\n if (typeof body.caseId !== 'string' || !body.caseId) return bad('caseId is required', 'caseId');\n if (body.reason !== undefined && typeof body.reason !== 'string') return bad('reason must be a string', 'reason');\n const after = typeof body.executeAfter === 'string' ? Date.parse(body.executeAfter) : NaN;\n if (body.executeAfter !== undefined && body.executeAfter !== null && Number.isNaN(after)) return bad('executeAfter must be an ISO date-time', 'executeAfter');\n const cb = callbackFor(t);\n if (!cb && !CANARY_SUBJECT.test(body.subjectId)) return bad(`this system does not handle ${t}`, 'type');\n\n const c: IdClaims = { s: body.subjectId, t, y: word as string, c: body.caseId, n: b64url(globalThis.crypto.getRandomValues(new Uint8Array(9))) };\n if (!Number.isNaN(after)) c.a = after;\n const id = await mintId(c);\n const s: Stored = { status: 'pending', ...(typeof body.reason === 'string' && body.reason ? { reason: body.reason } : {}) };\n const erasing = t === 'erasure' || t === 'closure';\n if (erasing && c.a !== undefined && c.a > now()) {\n const scheduled: Stored = { ...s, status: 'scheduled', eta: new Date(c.a).toISOString() };\n await putStored(id, scheduled);\n return json(201, view(id, c, scheduled));\n }\n return json(201, view(id, c, await act(id, c, s, cb)));\n }\n\n async function read(id: string, c: IdClaims, signed?: Stored | null): Promise<Response> {\n let s = await getStored(id, signed);\n if (!s) {\n // A genuine id whose state is gone (an emptied store): never act on it, say so.\n return json(200, view(id, c, { status: 'rejected', detail: \"this system no longer holds the request's state; nothing was done. Open it again.\" }));\n }\n // A scheduled erasure waits for POST /run: a GET is safe, it never acts.\n if ((s.status === 'pending' || s.status === 'processing' || s.status === 'blocked') && o.status && !CANARY_SUBJECT.test(c.s)) s = await act(id, c, s, o.status);\n return json(200, view(id, c, s));\n }\n\n /** Run a scheduled erasure whose executeAfter has passed; anything else answers as a read. Safe to repeat. */\n async function run(id: string, c: IdClaims, signed?: Stored | null): Promise<Response> {\n const s = await getStored(id, signed);\n if (s?.status === 'scheduled' && c.a !== undefined && now() >= c.a) return json(200, view(id, c, await act(id, c, s, callbackFor(c.t))));\n return read(id, c, signed);\n }\n\n async function cancel(id: string, c: IdClaims, signed?: Stored | null): Promise<Response> {\n const s = await getStored(id, signed);\n if (!s) return json(409, { error: \"this system no longer holds the request's state\", field: 'id' });\n if (s.status === 'cancelled') return json(200, view(id, c, s));\n if (s.status !== 'scheduled' && s.status !== 'pending') return json(409, { error: `too late to cancel a ${s.status} request`, field: 'id' });\n const next: Stored = { status: 'cancelled', ...(s.reason ? { reason: s.reason } : {}) };\n await putStored(id, next);\n void notify(id, c, next);\n return json(200, view(id, c, next));\n }\n\n async function handle(req: Request): Promise<Response> {\n const m = /^Bearer\\s+(.+)$/i.exec(req.headers.get('authorization') ?? '');\n if (!m || !sameKey(m[1]!.trim(), o.key)) return hidden();\n\n const path = new URL(req.url).pathname.replace(/\\/+$/, '');\n const route = /\\/(lookup|requests)(?:\\/([^/]+)(?:\\/(cancel|run))?)?$/.exec(path);\n const method = req.method.toUpperCase();\n if (!route) return json(404, { error: 'not_found' });\n const [, what, rawId, action] = route;\n\n let body: Record<string, unknown> = {};\n let text = '';\n if (method === 'POST') {\n text = await req.text();\n try {\n const parsed: unknown = text ? JSON.parse(text) : {};\n if (!isObject(parsed)) return bad('body must be a JSON object', 'body');\n body = parsed;\n } catch {\n return bad('body must be JSON', 'body');\n }\n }\n\n // Replay: the same key and body answer what they answered first; another body is a 409.\n const idemKey = method === 'POST' && what === 'requests' ? req.headers.get('idempotency-key') : null;\n if (idemKey !== null) {\n if (idemKey.length < 16 || idemKey.length > 128) return bad('Idempotency-Key must be 16-128 characters', 'Idempotency-Key');\n const seen = await store.get(`idem:${idemKey}`);\n const first = seen ? (JSON.parse(seen) as { body: string; status: number; answer: unknown; at?: number }) : null;\n // Checked here too, so a store that ignores ttlSeconds (a Map) still forgets after 24 hours.\n if (first && first.at !== undefined && now() - first.at >= IDEMPOTENCY_TTL_SECONDS * 1000) await store.delete?.(`idem:${idemKey}`);\n else if (first) {\n return first.body === text ? json(first.status, first.answer) : json(409, { error: 'Idempotency-Key reused with a different body', field: 'Idempotency-Key' });\n }\n }\n\n let res: Response;\n if (what === 'lookup' && !rawId && method === 'POST') res = await lookup(body);\n else if (what === 'requests' && !rawId && method === 'POST') res = await open(body);\n else if (what === 'requests' && rawId) {\n let id: string;\n try {\n id = decodeURIComponent(rawId);\n } catch {\n return json(404, { error: 'unknown request' });\n }\n const c = await readId(id);\n if (!c) return json(404, { error: 'unknown request' });\n const signed = await signedState(req, id);\n if (action === 'cancel' && method === 'POST') res = await cancel(id, c, signed);\n else if (action === 'run' && method === 'POST') res = await run(id, c, signed);\n else if (!action && method === 'GET') res = await read(id, c, signed);\n else return json(404, { error: 'not_found' });\n } else return json(404, { error: 'not_found' });\n\n if (idemKey !== null && res.ok) {\n const answer = { body: text, status: res.status, answer: await res.clone().json(), at: now() };\n await store.set(`idem:${idemKey}`, JSON.stringify(answer), { ttlSeconds: IDEMPOTENCY_TTL_SECONDS });\n }\n return res;\n }\n\n // A throwing callback is a 500 Cookie Munch retries; nothing is recorded for it.\n const fetch = (req: Request) =>\n handle(req).catch((err: unknown) => {\n console.error('createRightsHandlers:', err);\n return json(500, { error: 'internal_error' });\n });\n async function complete(requestId: string, outcome?: RightsOutcome): Promise<{ status: RightsStatus; delivered: boolean }> {\n const c = await readId(requestId);\n if (!c) throw new Error('createRightsHandlers.complete: not a request id these handlers issued');\n // Stateless: your system finished the request, so its state is yours to assert.\n const s = (await getStored(requestId)) ?? (sl ? { status: 'processing' as const } : null);\n if (!s) throw new Error(\"createRightsHandlers.complete: this system no longer holds the request's state\");\n if (FINAL.has(s.status)) return { status: s.status, delivered: await notify(requestId, c, s) };\n const next = await record(requestId, s, outcome ?? { status: 'completed' });\n return { status: next.status, delivered: await notify(requestId, c, next) };\n }\n\n return { fetch, GET: fetch, POST: fetch, complete };\n}\n\n// ---------------------------------------------------------------------------------------------------\n// Durable stores. No dependencies: each adapts something your app already has.\n\ntype DurableStore = RightsStore & { delete(key: string): Promise<void> };\n\n/**\n * One JSON file per key in `dir` (created if missing), named by the key's SHA-256 so any key is a safe\n * filename. Writes go to a temporary file renamed into place, so a crash never leaves half a file. An\n * entry past its TTL reads as missing and is removed. Node, Deno and Bun: `node:fs` is loaded on first\n * use, so importing this entry point on an edge runtime still works.\n */\nexport function fileStore(dir: string): DurableStore {\n // shortcut: an expired idempotency file is removed when read, not swept; prune `dir` by mtime if it ever grows large.\n let fsp: Promise<typeof import('node:fs/promises')> | undefined;\n const fs = () => (fsp ??= import('node:fs/promises').then(async (m) => (await m.mkdir(dir, { recursive: true }), m)));\n const pathOf = async (key: string) => {\n const hash = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', enc.encode(key)));\n return `${dir.replace(/[\\\\/]+$/, '')}/${[...hash].map((b) => b.toString(16).padStart(2, '0')).join('')}.json`;\n };\n const del = async (key: string) => {\n await (await fs()).rm(await pathOf(key), { force: true });\n };\n return {\n async get(key) {\n let raw: string;\n try {\n raw = await (await fs()).readFile(await pathOf(key), 'utf8');\n } catch (e) {\n if ((e as { code?: string }).code === 'ENOENT') return null;\n throw e;\n }\n const rec = JSON.parse(raw) as { v: string; exp?: number };\n if (rec.exp !== undefined && Date.now() >= rec.exp) {\n await del(key);\n return null;\n }\n return rec.v;\n },\n async set(key, value, opts) {\n const m = await fs();\n const file = await pathOf(key);\n const tmp = `${file}.${b64url(globalThis.crypto.getRandomValues(new Uint8Array(6)))}.tmp`;\n await m.writeFile(tmp, JSON.stringify({ v: value, ...(opts?.ttlSeconds ? { exp: Date.now() + opts.ttlSeconds * 1000 } : {}) }));\n await m.rename(tmp, file);\n },\n delete: del,\n };\n}\n\n/** The table `sqlStore` uses (Postgres). Run it once, in a migration. For SQLite: `RIGHTS_STORE_TABLE_SQLITE`. */\nexport const RIGHTS_STORE_TABLE_SQL = `CREATE TABLE IF NOT EXISTS cookiemunch_rights_store (\n key text PRIMARY KEY,\n value text NOT NULL,\n expires_at timestamptz\n)`;\n\n/** The same table for SQLite (`sqlStore({ dialect: 'sqlite' })`): `expires_at` is epoch milliseconds. */\nexport const RIGHTS_STORE_TABLE_SQLITE = `CREATE TABLE IF NOT EXISTS cookiemunch_rights_store (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL,\n expires_at INTEGER\n)`;\n\n/**\n * A store over one SQL table (`RIGHTS_STORE_TABLE_SQL`, or `RIGHTS_STORE_TABLE_SQLITE` with\n * `dialect: 'sqlite'`). `query(sql, params)` runs a parameterised statement and answers `{ rows }` or the\n * rows: `pool.query` from `pg` as it is; for better-sqlite3 (and Drizzle's `db.$client`),\n * `(sql, p) => { const s = db.prepare(sql); return Promise.resolve(s.reader ? s.all(...p) : (s.run(...p), [])); }`.\n * `query` answers the rows for a SELECT; for a write (INSERT … ON CONFLICT, DELETE) its answer is ignored.\n * Prisma: use `prismaStore(prisma)`. An expired row reads as missing; expired rows are purged by the next write that carries a TTL.\n */\nexport function sqlStore(o: { query: (sql: string, params: unknown[]) => Promise<{ rows: unknown[] } | unknown[]>; dialect?: 'postgres' | 'sqlite' }): DurableStore {\n const rows = async (sql: string, params: unknown[]) => {\n const r = await o.query(sql, params);\n return (Array.isArray(r) ? r : r.rows) as Array<{ value?: string }>;\n };\n if (o.dialect === 'sqlite') {\n return {\n async get(key) {\n return (await rows('SELECT value FROM cookiemunch_rights_store WHERE key = ? AND (expires_at IS NULL OR expires_at > ?)', [key, Date.now()]))[0]?.value ?? null;\n },\n async set(key, value, opts) {\n const exp = opts?.ttlSeconds ? Date.now() + opts.ttlSeconds * 1000 : null;\n await rows(\n 'INSERT INTO cookiemunch_rights_store (key, value, expires_at) VALUES (?, ?, ?) '\n + 'ON CONFLICT (key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at',\n [key, value, exp],\n );\n if (exp !== null) await rows('DELETE FROM cookiemunch_rights_store WHERE expires_at <= ?', [Date.now()]);\n },\n async delete(key) {\n await rows('DELETE FROM cookiemunch_rights_store WHERE key = ?', [key]);\n },\n };\n }\n return {\n async get(key) {\n return (await rows('SELECT value FROM cookiemunch_rights_store WHERE key = $1 AND (expires_at IS NULL OR expires_at > now())', [key]))[0]?.value ?? null;\n },\n async set(key, value, opts) {\n const ttl = opts?.ttlSeconds ?? null;\n await rows(\n 'INSERT INTO cookiemunch_rights_store (key, value, expires_at) VALUES ($1, $2, now() + make_interval(secs => $3::integer)) '\n + 'ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, expires_at = EXCLUDED.expires_at',\n [key, value, ttl],\n );\n if (ttl !== null) await rows('DELETE FROM cookiemunch_rights_store WHERE expires_at <= now()', []);\n },\n async delete(key) {\n await rows('DELETE FROM cookiemunch_rights_store WHERE key = $1', [key]);\n },\n };\n}\n\n/**\n * The `sqlStore` table as a Prisma model (Postgres). Paste it into `schema.prisma`, so `prisma db push` and\n * `migrate` create and keep it; a table made with `RIGHTS_STORE_TABLE_SQL` outside the schema is dropped by\n * the next `db push` (LinkHub CM-L2).\n */\nexport const RIGHTS_STORE_PRISMA_MODEL = `model CookiemunchRightsStore {\n key String @id\n value String\n expiresAt DateTime? @map(\"expires_at\") @db.Timestamptz(6)\n\n @@map(\"cookiemunch_rights_store\")\n}`;\n\n/** The part of a Prisma client `prismaStore` uses. */\nexport interface RightsPrismaClient {\n $queryRawUnsafe(sql: string, ...params: unknown[]): Promise<unknown>;\n $executeRawUnsafe(sql: string, ...params: unknown[]): Promise<unknown>;\n}\n\n/**\n * `sqlStore` over a Prisma client on Postgres (model: `RIGHTS_STORE_PRISMA_MODEL`). Reads go through\n * `$queryRawUnsafe`; writes through `$executeRawUnsafe`, which is what Prisma means for them. This is the\n * whole contract of `sqlStore`'s `query`: answer the rows for a SELECT, and anything (here `[]`) for a write.\n */\nexport function prismaStore(prisma: RightsPrismaClient): DurableStore {\n return sqlStore({\n query: async (sql, params) => (/^\\s*select\\b/i.test(sql)\n ? ((await prisma.$queryRawUnsafe(sql, ...params)) as unknown[])\n : (await prisma.$executeRawUnsafe(sql, ...params), [])),\n });\n}\n\n/** The part of a Redis client `redisStore` uses: node-redis v4's shape, `set(key, value, { EX })`. */\nexport interface RightsRedisClient {\n get(key: string): Promise<string | null | undefined>;\n set(key: string, value: string, opts?: { EX: number }): Promise<unknown>;\n del(key: string): Promise<unknown>;\n}\n\n/** Keys under `cookiemunch:rights:`; idempotency answers expire through Redis's own `EX`. */\nexport function redisStore(client: RightsRedisClient): DurableStore {\n const k = (key: string) => `cookiemunch:rights:${key}`;\n return {\n get: (key) => client.get(k(key)),\n async set(key, value, opts) {\n await (opts?.ttlSeconds ? client.set(k(key), value, { EX: opts.ttlSeconds }) : client.set(k(key), value));\n },\n async delete(key) {\n await client.del(k(key));\n },\n };\n}\n\n/** The part of an ioredis client `ioredisStore` uses: `set(key, value, 'EX', seconds)`. */\nexport interface RightsIoredisClient {\n get(key: string): Promise<string | null | undefined>;\n // Two overloads, as ioredis declares them, so a real `Redis` instance type-checks (one signature with optionals does not).\n set(key: string, value: string): Promise<unknown>;\n set(key: string, value: string, ex: 'EX', seconds: number): Promise<unknown>;\n del(key: string): Promise<unknown>;\n}\n\n/** `redisStore` for ioredis: the same keys, the TTL passed as `'EX', seconds`. */\nexport function ioredisStore(client: RightsIoredisClient): DurableStore {\n const k = (key: string) => `cookiemunch:rights:${key}`;\n return {\n get: (key) => client.get(k(key)),\n async set(key, value, opts) {\n await (opts?.ttlSeconds ? client.set(k(key), value, 'EX', opts.ttlSeconds) : client.set(k(key), value));\n },\n async delete(key) {\n await client.del(k(key));\n },\n };\n}\n","/**\n * The cm-standard-v2 executor conformance kit.\n *\n * cm-standard-v2 is an open contract: any system that holds personal data can implement it and\n * be driven by Cookie Munch with no code on our side (docs: cookiemunch.net/docs/executor-contract-v2).\n * This kit checks an implementation rule by rule, and names the rule that fails. It is the same\n * suite Cookie Munch runs on `POST /v1/dsar/executors/{id}/test {conformance: true}`, and the\n * `cookiemunch executors conformance <baseUrl>` command runs it from a terminal or CI.\n *\n * It only ever touches the CANARY subject — an address no real person has. The contract asks every\n * implementation to treat the canary as an existing synthetic person: it is found by its email and\n * by its identity, requests on it move through the full state machine, and nothing real is ever\n * erased (the one exception is `eraseSubjectEmail`, a throwaway subject the caller names). So the kit can check that an erasure waits for `executeAfter`, that a cancel leaves the\n * person in place, and that an identity is never matched to someone else through a shared email —\n * without a real person's data being anywhere near it.\n *\n * No dependencies: `fetch` only, so it runs in Node 18+, a browser, or an edge runtime.\n */\n\n/** `blocked`: not run, because the rule named in `blockedBy` failed first and decides it. */\nexport type ConformanceStatus = 'pass' | 'fail' | 'skip' | 'blocked';\n\nexport interface ConformanceRuleResult {\n /** A stable id, e.g. `requests.execute_after.scheduled`. */\n id: string;\n /** What the rule says, in one sentence. */\n title: string;\n status: ConformanceStatus;\n /** What was seen, when it failed or was skipped. */\n detail?: string;\n /** With status `blocked`: the rule whose failure stopped this one. */\n blockedBy?: string;\n}\n\nexport interface ConformanceReport {\n /** True when no rule failed. */\n ok: boolean;\n passed: number;\n failed: number;\n skipped: number;\n /** Rules not run because an earlier failure decides them. */\n blocked: number;\n /** Set when the credential itself was refused: `missing_scope` (403) or `credential_refused` (401). */\n code?: 'missing_scope' | 'credential_refused';\n /** With `missing_scope`: the scopes the key needs, when known. */\n required?: string[];\n /** With `code`: the one thing to do next. */\n fix?: string;\n rules: ConformanceRuleResult[];\n /** The `X-Version` the executor answered with, when it sent one. */\n version?: string;\n}\n\nexport interface ConformanceOptions {\n /** The executor's base: the contract paths are `{baseUrl}/privacy/lookup` and so on. https (http only for localhost). */\n baseUrl: string;\n /** The credential Cookie Munch would send. */\n secret: string;\n /**\n * The canary address: `canary-<16 hex>@canary.cookiemunch.net`, per organisation\n * (`GET /v1/dsar/executors/presets` → `canaryEmail`).\n */\n canaryEmail: string;\n /** A subject you seeded in your own store. It is looked up and exported (an access request), never erased. Without it, `lookup.test_subject.found` and `requests.access.no_secrets` are skipped. */\n testSubjectEmail?: string;\n /**\n * A THROWAWAY subject you seeded in your own store. It IS erased, for real, through your own erase code, so reseed it\n * before each run. Without it, `requests.erase.removes_subject` does not run and nothing real is touched.\n */\n eraseSubjectEmail?: string;\n /** How long to wait for that erasure to finish, in ms. Default 30000. */\n eraseTimeoutMs?: number;\n /** How the secret is sent. Default `Authorization: Bearer {secret}`. */\n auth?: { header: string; format: string };\n /** Path prefix under baseUrl. Default `/privacy`. */\n prefix?: string;\n fetch?: typeof fetch;\n now?: () => number;\n /** A per-run tag for idempotency keys and case ids. Default random. */\n runId?: string;\n /** The scopes this system's key needs, when the caller knows them. Otherwise read off the system's own 403. */\n requiredScopes?: string[];\n /** Where to get a key with those scopes, added to `fix`. */\n keyHint?: string;\n}\n\n/** The issuer the canary identity carries. */\nexport const CANARY_ISSUER = 'https://canary.cookiemunch.net';\nconst CANARY_EMAIL_RE = /^canary-([0-9a-f]{16})@canary\\.cookiemunch\\.net$/;\n\n/** The canary subject's identity, derived from its address. */\nexport function canaryIdentityFor(canaryEmail: string): { iss: string; sub: string; ext: string } {\n const m = CANARY_EMAIL_RE.exec(canaryEmail.trim().toLowerCase());\n if (!m) throw new Error('canaryEmail must be the canary address canary-<16 hex>@canary.cookiemunch.net');\n return { iss: CANARY_ISSUER, sub: `canary_${m[1]}`, ext: `canary:${m[1]}` };\n}\n\n/** Every rule, in the order they run. */\nexport const CONFORMANCE_RULES: ReadonlyArray<{ id: string; title: string }> = [\n { id: 'auth.required', title: 'A request without the credential is refused (401, 403, or a 404 without X-Version).' },\n { id: 'lookup.email.found', title: 'The canary subject is found by its email.' },\n { id: 'lookup.identity.found', title: 'The canary subject is found by its identity alone (iss + sub), and it is the same subject.' },\n { id: 'lookup.unknown.no_match', title: 'An address nobody has answers { subjectId: null, status: \"no_match\" }.' },\n { id: 'lookup.identity_beats_email', title: 'An identity that matches no one is never matched through the email of someone else.' },\n { id: 'requests.bad_body.400', title: 'A request with an unknown type answers 400 { error, field }.' },\n { id: 'requests.alias.canonical_type', title: 'An alias (erasure) is accepted and answered with canonicalType \"deletion\".' },\n { id: 'requests.execute_after.scheduled', title: 'A deletion with a future executeAfter is \"scheduled\" with eta equal to executeAfter — nothing is deleted before it.' },\n { id: 'requests.idempotency.replay', title: 'The same Idempotency-Key with the same body returns the same request, not a second one.' },\n { id: 'requests.idempotency.mismatch_409', title: 'The same Idempotency-Key with a different body answers 409.' },\n { id: 'requests.get', title: 'GET /privacy/requests/{id} returns the request, still scheduled.' },\n { id: 'requests.unknown.404', title: 'An unknown request id answers 404.' },\n { id: 'requests.cancel.before_execute_after', title: 'A cancel before executeAfter answers status \"cancelled\".' },\n { id: 'requests.cancel.keeps_data', title: 'After a cancel the subject is still there: a lookup finds it.' },\n { id: 'version.header', title: 'Answers carry X-Version (the highest contract version the executor supports).' },\n];\n\n/** Asked for, not assumed: only with `testSubjectEmail`, so a run without one still reads as the 15 rules every receiver is held to. */\nconst TEST_SUBJECT_RULE = { id: 'lookup.test_subject.found', title: 'A real test subject of yours (testSubjectEmail) is found: this rule alone reaches your own store through createRightsHandlers, which answers the canary itself.' };\n\n/** With `testSubjectEmail` too: an access request reads that subject's export, which must carry no credential (Lucida CM6). */\nconst EXPORT_RULE = { id: 'requests.access.no_secrets', title: 'An access request for your test subject (testSubjectEmail) finishes, and its export carries no credential: no password, password hash, secret, API key, token or private key, by field name or by shape.' };\n\n/** Field names that hold a credential, compared lowercased with `_` and `-` removed. */\nconst SECRET_FIELD = /^(password|passwd|passwordhash|passhash|hashedpassword|secret|clientsecret|apikey|apisecret|accesstoken|refreshtoken|sessiontoken|idtoken|authtoken|privatekey|totpsecret|otpsecret|mfasecret|recoverycodes|salt)$/;\n/** Values shaped like a live credential, whatever the field is called. */\nconst SECRET_VALUE = /^(sk_(live|test)_|rk_(live|test)_|cmk_|ghp_|gho_|github_pat_|xox[abpr]-|AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----|\\$2[aby]\\$\\d\\d\\$|\\$argon2)/;\n\n/** The paths in an export that look like credentials (never their values). */\nexport function secretPaths(v: unknown, path = '$', out: string[] = []): string[] {\n if (out.length >= 20) return out;\n if (typeof v === 'string') { if (SECRET_VALUE.test(v.trim())) out.push(path); return out; }\n if (Array.isArray(v)) { v.forEach((x, i) => secretPaths(x, `${path}[${i}]`, out)); return out; }\n if (v && typeof v === 'object') {\n for (const [k, x] of Object.entries(v as Record<string, unknown>)) {\n const p = `${path}.${k}`;\n if (SECRET_FIELD.test(k.toLowerCase().replace(/[_-]/g, '')) && x !== null && x !== '' && x !== undefined) out.push(p);\n else secretPaths(x, p, out);\n }\n }\n return out;\n}\n\n/** Asked for by name: only with `eraseSubjectEmail`, because it really erases that subject. */\nconst ERASE_RULE = { id: 'requests.erase.removes_subject', title: 'A real erasure of your throwaway subject (eraseSubjectEmail) finishes, and a lookup no longer finds them: this rule alone runs your own erase code.' };\n\ntype Answer = { status: number; json: unknown; version: string | null; error?: string };\n\nfunction randomTag(): string {\n const bytes = new Uint8Array(8);\n const c = (globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;\n if (c?.getRandomValues) c.getRandomValues(bytes);\n else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);\n return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction field(json: unknown, key: string): unknown {\n return json && typeof json === 'object' ? (json as Record<string, unknown>)[key] : undefined;\n}\n\n/** Run every rule against one executor. Never throws for an executor's answer; only for bad options. */\nexport async function runExecutorConformance(o: ConformanceOptions): Promise<ConformanceReport> {\n const doFetch = o.fetch ?? fetch;\n const now = o.now ?? (() => Date.now());\n const base = o.baseUrl.replace(/\\/+$/, '') + (o.prefix ?? '/privacy');\n let url: URL;\n try {\n url = new URL(base);\n } catch {\n throw new Error('baseUrl must be an absolute URL');\n }\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && /^(localhost|127\\.0\\.0\\.1|\\[::1\\])$/.test(url.hostname))) {\n throw new Error('baseUrl must be https (http only for localhost)');\n }\n for (const [name, v] of [['testSubjectEmail', o.testSubjectEmail], ['eraseSubjectEmail', o.eraseSubjectEmail]] as const) {\n if (v !== undefined && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(v)) throw new Error(`${name} must be an email address, not \"${v}\"`);\n }\n const lower = (x: string | undefined) => x?.trim().toLowerCase();\n if (o.eraseSubjectEmail && [lower(o.canaryEmail), lower(o.testSubjectEmail)].includes(lower(o.eraseSubjectEmail))) throw new Error('eraseSubjectEmail must be its own throwaway subject, not the canary or testSubjectEmail');\n const identity = canaryIdentityFor(o.canaryEmail);\n const canaryEmail = o.canaryEmail.trim().toLowerCase();\n const auth = o.auth ?? { header: 'Authorization', format: 'Bearer {secret}' };\n const run = o.runId ?? randomTag();\n const results = new Map<string, ConformanceRuleResult>();\n let version: string | undefined;\n\n const set = (id: string, status: ConformanceStatus, detail?: string): void => {\n const rule = [...CONFORMANCE_RULES, TEST_SUBJECT_RULE, EXPORT_RULE, ERASE_RULE].find((r) => r.id === id)!;\n results.set(id, { id, title: rule.title, status, ...(detail ? { detail } : {}) });\n };\n const pass = (id: string) => set(id, 'pass');\n const fail = (id: string, detail: string) => set(id, 'fail', detail);\n const skip = (id: string, detail: string) => set(id, 'skip', detail);\n\n async function call(method: string, path: string, body?: unknown, extra: Record<string, string> = {}, withAuth = true): Promise<Answer> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n 'X-Version': '2',\n ...(withAuth ? { [auth.header]: auth.format.replace('{secret}', o.secret) } : {}),\n ...(body !== undefined ? { 'content-type': 'application/json' } : {}),\n ...extra,\n };\n try {\n const res = await doFetch(base + path, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });\n const text = await res.text().catch(() => '');\n let json: unknown;\n try {\n json = text ? JSON.parse(text) : undefined;\n } catch {\n json = undefined;\n }\n const v = res.headers.get('x-version');\n if (v && !version) version = v;\n return { status: res.status, json, version: v };\n } catch (err) {\n return { status: 0, json: undefined, version: null, error: err instanceof Error ? err.message : String(err) };\n }\n }\n const said = (a: Answer): string => (a.status === 0 ? `unreachable: ${a.error}` : `HTTP ${a.status} ${JSON.stringify(a.json ?? null).slice(0, 200)}`);\n const key = (rule: string) => `conformance:${run}:${rule}`;\n\n // auth.required\n const anon = await call('POST', '/lookup', { emails: [canaryEmail] }, {}, false);\n if (anon.status === 0) {\n // Nothing else can be judged against a system we cannot reach.\n for (const r of CONFORMANCE_RULES) skip(r.id, said(anon));\n fail('auth.required', said(anon));\n return report();\n }\n // A bare 404 (no X-Version) is a refusal that does not even admit the endpoint exists.\n if (anon.status === 401 || anon.status === 403 || (anon.status === 404 && !anon.version)) pass('auth.required');\n else fail('auth.required', `without a credential: ${said(anon)}`);\n\n // lookups\n const byEmail = await call('POST', '/lookup', { emails: [canaryEmail] }, { 'Idempotency-Key': key('lookup-email') });\n // The key itself is refused: every later rule would fail for this one reason, so it is the only failure.\n // A 404 with no X-Version is how createRightsHandlers answers a wrong secret: it does not admit the API exists.\n const hidden = byEmail.status === 404 && !byEmail.version;\n if (byEmail.status === 401 || byEmail.status === 403 || hidden) {\n fail('lookup.email.found', `the canary address: ${said(byEmail)}`);\n for (const r of CONFORMANCE_RULES) if (!results.has(r.id)) results.set(r.id, { id: r.id, title: r.title, status: 'blocked', blockedBy: 'lookup.email.found' });\n const code = byEmail.status === 403 ? 'missing_scope' as const : 'credential_refused' as const;\n const named = [...new Set(JSON.stringify(byEmail.json ?? '').match(/\\b[a-z_]+:[a-z_]+(?::[a-z_]+)*\\b/g) ?? [])];\n const required = o.requiredScopes?.length ? o.requiredScopes : named;\n const hint = o.keyHint ? ` ${o.keyHint}` : '';\n const fix = code === 'missing_scope'\n ? `This key may not call the rights API (HTTP 403).${required.length ? ` It needs ${required.join(' or ')}.` : ' Give it the rights scope that system documents.'}${hint}`\n : hidden\n ? `No rights API answered this key (HTTP 404, no X-Version). createRightsHandlers answers a wrong secret this way, so check the secret first, then the base URL.${hint}`\n : `This key was refused (HTTP 401): it is wrong, expired or revoked. Send a current one.${hint}`;\n return { ...report(), code, ...(code === 'missing_scope' && required.length ? { required } : {}), fix };\n }\n const subjectId = field(byEmail.json, 'subjectId');\n if (byEmail.status === 200 && field(byEmail.json, 'status') === 'found' && typeof subjectId === 'string' && subjectId) pass('lookup.email.found');\n else fail('lookup.email.found', `the canary address: ${said(byEmail)}`);\n\n if (o.testSubjectEmail) {\n const seeded = await call('POST', '/lookup', { emails: [o.testSubjectEmail] }, { 'Idempotency-Key': key('lookup-seeded') });\n if (seeded.status === 200 && field(seeded.json, 'status') === 'found') pass('lookup.test_subject.found');\n else fail('lookup.test_subject.found', `${o.testSubjectEmail}: ${said(seeded)}`);\n const seededId = field(seeded.json, 'subjectId');\n if (typeof seededId === 'string' && seededId) await exportRule(seededId);\n else skip(EXPORT_RULE.id, 'needs the test subject, which the lookup did not find');\n }\n\n // A receiver that takes the two names as alternatives refuses the body every real request is sent in.\n const bothNames = (a: Answer) => (a.status === 400 ? ' A body carries `identity` and `atlas` together, identical, and `emails` can be empty: accept all of that (see the v2 contract).' : '');\n const byIdentity = await call('POST', '/lookup', { emails: [], identity: identity, atlas: identity }, { 'Idempotency-Key': key('lookup-identity') });\n if (byIdentity.status === 200 && field(byIdentity.json, 'status') === 'found' && field(byIdentity.json, 'subjectId') === subjectId && typeof subjectId === 'string') {\n pass('lookup.identity.found');\n } else {\n fail('lookup.identity.found', `the canary identity ${identity.sub}: ${said(byIdentity)}${typeof subjectId === 'string' ? ` (by email it was ${subjectId})` : ''}${bothNames(byIdentity)}`);\n }\n\n const nobody = await call('POST', '/lookup', { emails: [`nobody-${run}@canary.cookiemunch.net`] }, { 'Idempotency-Key': key('lookup-nobody') });\n if (nobody.status === 200 && field(nobody.json, 'status') === 'no_match' && field(nobody.json, 'subjectId') === null) pass('lookup.unknown.no_match');\n else fail('lookup.unknown.no_match', said(nobody));\n\n const stranger = { iss: identity.iss, sub: `canary_other_${run}` };\n const crossed = await call('POST', '/lookup', { emails: [canaryEmail], identity: stranger, atlas: stranger }, { 'Idempotency-Key': key('lookup-crossed') });\n if (crossed.status === 200 && field(crossed.json, 'status') === 'no_match') pass('lookup.identity_beats_email');\n else {\n fail(\n 'lookup.identity_beats_email',\n `an identity nobody has (${stranger.sub}) with the canary's email: ${said(crossed)} — the email belongs to a different identity, so this must be no_match${bothNames(crossed)}`,\n );\n }\n\n // requests\n const bad = await call('POST', '/requests', { subjectId: subjectId ?? 'x', type: 'teleport', caseId: `conformance-${run}` }, { 'Idempotency-Key': key('bad-body') });\n if (bad.status === 400 && typeof field(bad.json, 'error') === 'string' && typeof field(bad.json, 'field') === 'string') pass('requests.bad_body.400');\n else fail('requests.bad_body.400', said(bad));\n\n if (typeof subjectId !== 'string') {\n for (const id of ['requests.alias.canonical_type', 'requests.execute_after.scheduled', 'requests.idempotency.replay', 'requests.idempotency.mismatch_409', 'requests.get', 'requests.cancel.before_execute_after', 'requests.cancel.keeps_data']) {\n skip(id, 'needs the canary subject, which the lookup did not find');\n }\n } else {\n const executeAfter = new Date(Math.ceil((now() + 3_600_000) / 1000) * 1000).toISOString();\n const body = { subjectId, type: 'erasure', executeAfter, caseId: `conformance-${run}`, reason: 'Cookie Munch conformance check (canary subject)' };\n const opened = await call('POST', '/requests', body, { 'Idempotency-Key': key('open') });\n const id = field(opened.json, 'id');\n const st = field(opened.json, 'status');\n if ((opened.status === 200 || opened.status === 201) && field(opened.json, 'canonicalType') === 'deletion') pass('requests.alias.canonical_type');\n else fail('requests.alias.canonical_type', `type \"erasure\": ${said(opened)}`);\n\n const eta = field(opened.json, 'eta');\n if ((opened.status === 200 || opened.status === 201) && st === 'scheduled' && typeof eta === 'string' && Date.parse(eta) === Date.parse(executeAfter)) {\n pass('requests.execute_after.scheduled');\n } else if (st === 'completed' || st === 'completed_with_retention' || st === 'processing') {\n fail('requests.execute_after.scheduled', `executeAfter is ${executeAfter}, an hour away, and the executor answered \"${String(st)}\": it acted before executeAfter`);\n } else {\n fail('requests.execute_after.scheduled', `expected status \"scheduled\" with eta ${executeAfter}: ${said(opened)}`);\n }\n\n const replay = await call('POST', '/requests', body, { 'Idempotency-Key': key('open') });\n if (typeof id === 'string' && (replay.status === 200 || replay.status === 201) && field(replay.json, 'id') === id) pass('requests.idempotency.replay');\n else fail('requests.idempotency.replay', `a retry with the same key: ${said(replay)}${typeof id === 'string' ? ` (first answer id ${id})` : ''}`);\n\n const mismatch = await call('POST', '/requests', { ...body, reason: 'a different body' }, { 'Idempotency-Key': key('open') });\n if (mismatch.status === 409) pass('requests.idempotency.mismatch_409');\n else fail('requests.idempotency.mismatch_409', `the same key with a different body: ${said(mismatch)}`);\n\n if (typeof id !== 'string') {\n skip('requests.get', 'no request id came back');\n skip('requests.cancel.before_execute_after', 'no request id came back');\n skip('requests.cancel.keeps_data', 'no request id came back');\n } else {\n const got = await call('GET', `/requests/${encodeURIComponent(id)}`, undefined, { 'Idempotency-Key': key('get') });\n if (got.status === 200 && field(got.json, 'id') === id && field(got.json, 'status') === 'scheduled') pass('requests.get');\n else fail('requests.get', said(got));\n\n const cancelled = await call('POST', `/requests/${encodeURIComponent(id)}/cancel`, {}, { 'Idempotency-Key': key('cancel') });\n if (cancelled.status === 200 && field(cancelled.json, 'status') === 'cancelled') pass('requests.cancel.before_execute_after');\n else fail('requests.cancel.before_execute_after', said(cancelled));\n\n const after = await call('POST', '/lookup', { emails: [canaryEmail] }, { 'Idempotency-Key': key('lookup-after-cancel') });\n if (after.status === 200 && field(after.json, 'status') === 'found') pass('requests.cancel.keeps_data');\n else fail('requests.cancel.keeps_data', `a lookup after the cancel: ${said(after)} — a cancel before executeAfter must leave the data intact`);\n }\n }\n\n const unknown = await call('GET', `/requests/conformance-missing-${run}`, undefined, { 'Idempotency-Key': key('unknown') });\n if (unknown.status === 404) pass('requests.unknown.404');\n else fail('requests.unknown.404', said(unknown));\n\n if (o.eraseSubjectEmail) await eraseRule(o.eraseSubjectEmail);\n\n if (version) pass('version.header');\n else fail('version.header', 'no answer carried an X-Version header');\n\n return report();\n\n async function eraseRule(email: string): Promise<void> {\n const rule = ERASE_RULE.id;\n const before = await call('POST', '/lookup', { emails: [email] }, { 'Idempotency-Key': key('erase-lookup') });\n const subject = field(before.json, 'subjectId');\n if (before.status !== 200 || field(before.json, 'status') !== 'found' || typeof subject !== 'string') {\n return fail(rule, `${email} must exist before the run, so seed it each time: ${said(before)}`);\n }\n const opened = await call('POST', '/requests', { subjectId: subject, type: 'deletion', caseId: `conformance-erase-${run}`, reason: 'Cookie Munch conformance check (throwaway subject)' }, { 'Idempotency-Key': key('erase') });\n const id = field(opened.json, 'id');\n if ((opened.status !== 200 && opened.status !== 201) || typeof id !== 'string') return fail(rule, `the erasure was not accepted: ${said(opened)}`);\n let st = field(opened.json, 'status');\n const deadline = Date.now() + (o.eraseTimeoutMs ?? 30_000);\n while ((st === 'pending' || st === 'processing') && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 500));\n st = field((await call('GET', `/requests/${encodeURIComponent(id)}`, undefined, { 'Idempotency-Key': key('erase-get') })).json, 'status');\n }\n if (st !== 'completed' && st !== 'completed_with_retention') return fail(rule, `the erasure ended as \"${String(st)}\", not completed`);\n const gone = await call('POST', '/lookup', { emails: [email] }, { 'Idempotency-Key': key('erase-after') });\n // A retention is a declared exception: the contract lets that subject remain.\n if (gone.status === 200 && (field(gone.json, 'status') === 'no_match' || st === 'completed_with_retention')) pass(rule);\n else fail(rule, `the erasure said \"${String(st)}\", but a lookup afterwards: ${said(gone)}`);\n }\n\n async function exportRule(subject: string): Promise<void> {\n const rule = EXPORT_RULE.id;\n const opened = await call('POST', '/requests', { subjectId: subject, type: 'access', caseId: `conformance-access-${run}`, reason: 'Cookie Munch conformance check (test subject export)' }, { 'Idempotency-Key': key('access') });\n const id = field(opened.json, 'id');\n if ((opened.status !== 200 && opened.status !== 201) || typeof id !== 'string') return fail(rule, `the access request was not accepted: ${said(opened)}`);\n let answer = opened;\n const deadline = Date.now() + (o.eraseTimeoutMs ?? 30_000);\n while (['pending', 'processing'].includes(String(field(answer.json, 'status'))) && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 500));\n answer = await call('GET', `/requests/${encodeURIComponent(id)}`, undefined, { 'Idempotency-Key': key('access-get') });\n }\n const st = field(answer.json, 'status');\n if (st !== 'completed' && st !== 'completed_with_retention') return fail(rule, `the access request ended as \"${String(st)}\", not completed`);\n let bundle = field(answer.json, 'result');\n const url = field(bundle, 'downloadUrl');\n if (typeof url === 'string') {\n try {\n const res = await doFetch(url, { headers: { accept: 'application/json' } });\n const text = await res.text();\n if (text.length > 5_000_000) return fail(rule, 'the export is over 5 MB');\n try { bundle = JSON.parse(text); } catch { bundle = text; }\n } catch (err) {\n return fail(rule, `the export's downloadUrl could not be read: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n if (bundle === undefined) return fail(rule, 'the completed access request carried no result (inline, or { downloadUrl })');\n const found = typeof bundle === 'string' ? bundle.split(/\\s+/).filter((w) => SECRET_VALUE.test(w)).map(() => '$ (text)') : secretPaths(bundle);\n if (found.length) fail(rule, `the export carries what looks like a credential at ${[...new Set(found)].join(', ')}; leave credentials out of an access export`);\n else pass(rule);\n }\n\n function report(): ConformanceReport {\n const rules = [...CONFORMANCE_RULES, ...(o.testSubjectEmail ? [TEST_SUBJECT_RULE, EXPORT_RULE] : []), ...(o.eraseSubjectEmail ? [ERASE_RULE] : [])].map((r) => results.get(r.id) ?? { id: r.id, title: r.title, status: 'skip' as const, detail: 'not reached' });\n const count = (s: ConformanceStatus) => rules.filter((r) => r.status === s).length;\n return { ok: count('fail') === 0, passed: count('pass'), failed: count('fail'), skipped: count('skip'), blocked: count('blocked'), rules, ...(version ? { version } : {}) };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;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