@cookiemunch/sdk 0.21.1 → 0.22.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/CHANGELOG.md +11 -0
- package/dist/{chunk-ACZIJ3KB.js → chunk-7Q6XFXKS.js} +1 -1
- package/dist/chunk-7Q6XFXKS.js.map +1 -0
- package/dist/{chunk-OSVTQPQG.js → chunk-OQJYQMQR.js} +1 -1
- package/dist/chunk-OQJYQMQR.js.map +1 -0
- package/dist/consent.cjs.map +1 -1
- package/dist/consent.d.ts +1 -1
- package/dist/consent.js +1 -1
- package/dist/executor-conformance.d.ts +1 -1
- package/dist/index.cjs +9 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +121 -18
- package/dist/index.js +11 -8
- package/dist/index.js.map +1 -1
- package/dist/rights.cjs +59 -16
- package/dist/rights.cjs.map +1 -1
- package/dist/rights.d.ts +25 -14
- package/dist/rights.js +59 -17
- package/dist/rights.js.map +1 -1
- package/dist/token-exchange.d.ts +1 -1
- package/dist/types.d.ts +11 -4
- package/package.json +1 -1
- package/dist/chunk-ACZIJ3KB.js.map +0 -1
- package/dist/chunk-OSVTQPQG.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
Every published release, newest first. Dates are the day the version was cut.
|
|
4
4
|
|
|
5
|
+
## 0.22.0 (2026-11-11)
|
|
6
|
+
|
|
7
|
+
- Added: the rights handlers speak six rights (`access`, `erasure`, `rectification`, `portability`, `restriction`, `closure`); `deletion` and `erase` read as `erasure`, ids minted before read the same, and a `portability` callback falls back to `access`.
|
|
8
|
+
- Added: `POST /requests/{id}/run` on the rights handlers: a scheduled erasure runs on that POST, never inside a `GET`.
|
|
9
|
+
- Added: `sqlStore({ dialect: 'sqlite' })` with `RIGHTS_STORE_TABLE_SQLITE`.
|
|
10
|
+
- Added: `cookies` on `sites.scan` for a signed-in crawl; `scan` (schedule, afterDeploy) on site config; `undeclared` and `stale` on a finished scan.
|
|
11
|
+
- Added: `params` on executor connect and upgrade-preset (Referalli `programId`, cm-standard-v2 `scopeName`/`scopeId`, Lucida `projectId`/`publicKey`, Hermetica `workspaceId`/`storage`).
|
|
12
|
+
- Added: `since` on the audit log; `getExecutorCompletionSecret`; `rightsIdentity.check`; `executorSuggestions`; the `hermetica` mail provider.
|
|
13
|
+
- Added: `channel` and `integrity` on the install snippet (`embedChannel: pinned:<version>`); `clean` on integration health; `hermetica` and `subscription.changed` on partner grants.
|
|
14
|
+
- Changed: requests the SDK sends with no `CookieMunch-Version` stay on API version 2026-10-24 response shapes.
|
|
15
|
+
|
|
5
16
|
## 0.21.1 (2026-11-05)
|
|
6
17
|
|
|
7
18
|
- Fixed: conformance refuses a `testSubjectEmail` or `eraseSubjectEmail` that isn't an email address, and compares subjects without regard to case.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/executor-conformance.ts"],"sourcesContent":["/**\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 only looked up, never erased. Without it, `lookup.test_subject.found` is 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/** 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, 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 }\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 function report(): ConformanceReport {\n const rules = [...CONFORMANCE_RULES, ...(o.testSubjectEmail ? [TEST_SUBJECT_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":";AAuFO,IAAM,gBAAgB;AAC7B,IAAM,kBAAkB;AAGjB,SAAS,kBAAkB,aAAgE;AAChG,QAAM,IAAI,gBAAgB,KAAK,YAAY,KAAK,EAAE,YAAY,CAAC;AAC/D,MAAI,CAAC,EAAG,OAAM,IAAI,MAAM,+EAA+E;AACvG,SAAO,EAAE,KAAK,eAAe,KAAK,UAAU,EA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UAAM,QAAQ,CAAC,MAAyB,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,EAAE;AAC5E,WAAO,EAAE,IAAI,MAAM,MAAM,MAAM,GAAG,QAAQ,MAAM,MAAM,GAAG,QAAQ,MAAM,MAAM,GAAG,SAAS,MAAM,MAAM,GAAG,SAAS,MAAM,SAAS,GAAG,OAAO,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC,EAAG;AAAA,EAC5K;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/consent.ts"],"sourcesContent":["/**\n * Server-side consent reading. The Cookie Munch embed stores the visitor's decision in a\n * first-party `CookieMunch` cookie (URL-encoded JSON). This lets a server / edge worker read\n * that decision from the incoming request — to gate server-rendered tags or SSR'd third-party\n * scripts BEFORE they hit the browser — without shipping the whole embed. Zero-dependency and\n * runtime-agnostic: accepts a raw Cookie header, a Node `req` (`req.headers.cookie`), or a\n * Fetch `Request` (`request.headers.get('cookie')`).\n *\n * import { readConsent, isAllowed } from '@cookiemunch/sdk/consent';\n * const consent = readConsent(req.headers.cookie); // ServerConsent | null\n * if (isAllowed(consent, 'statistics')) { …render analytics tag… }\n *\n * The contract is documented at https://cookiemunch.net/docs/consent-cookie. It accepts\n * exactly what the embed accepts, so a server never grants what the browser would refuse:\n * strict JSON (URL-encoded or not) and the relaxed object literal Cookiebot writes.\n *\n * This module imports nothing — `@cookiemunch/sdk/consent` pulls in no API client.\n */\n\n/** The first-party cookie the embed writes (mirrors @cookiemunch/core COOKIE_NAME). */\nexport const CONSENT_COOKIE_NAME = 'CookieMunch';\n\n/** A visitor's consent decision, read from the request cookie. `necessary` is always true. */\nexport interface ServerConsent {\n necessary: true;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n /** How consent was given. `implied` = not yet an explicit choice. */\n method: 'explicit' | 'implied';\n /** Custom (non-standard) categories, when the site defines any. */\n custom?: Record<string, boolean>;\n /** Consent-policy version the decision was made under (see `minVersion`). */\n ver: number;\n /** When the decision was made, epoch milliseconds (see `expiryDays`). */\n utc: number;\n /** Region code the decision was made in (`unknown` when undetected). */\n region: string;\n /** The anonymous consent-receipt id tying this browser to the consent log. */\n stamp: string;\n /**\n * `<kid>.<base64url>`: the API's Ed25519 signature over this decision, issued when the\n * ledger recorded it. Absent on a decision no ledger holds (a hand-written cookie).\n */\n sig?: string;\n}\n\n/** The site's consent policy, so the server applies the same rules the embed does. */\nexport interface ReadConsentOptions {\n /** Cookie name. Default `CookieMunch`. */\n cookieName?: string;\n /**\n * The site's current consent version (`consent.version`, or the config `ver` when that is\n * higher). A decision made under an older version is not honoured by the embed — the\n * visitor is asked again — so it reads as `null` here too.\n */\n minVersion?: number;\n /** The site's `consent.expiryDays`: a decision older than this reads as `null`. */\n expiryDays?: number;\n /** Clock for `expiryDays`, epoch ms. Default `Date.now()`. */\n now?: number;\n}\n\n/** Where the platform's public signing keys come from, for signatures and consent tokens. */\nexport interface KeySetOptions {\n /** A key set you already hold (`{ keys: [...] }`). Skips the fetch. */\n jwks?: JsonWebKeySet;\n /** Default `https://api.cookiemunch.net/v1/partner/jwks.json`. */\n jwksUrl?: string;\n /** Injectable fetch. Default: the global one. */\n fetch?: typeof fetch;\n}\n\n/** `readConsent` with `requireSigned: true`: only a decision the API signed counts. */\nexport interface ReadSignedConsentOptions extends ReadConsentOptions, KeySetOptions {\n requireSigned: true;\n}\n\n/** Anything we can pull a Cookie header off of. */\nexport type ConsentSource =\n | string\n | null\n | undefined\n | { headers?: { cookie?: string | null; get?(name: string): string | null } | Record<string, unknown> };\n\nfunction cookieHeaderOf(src: ConsentSource): string {\n if (typeof src === 'string') return src;\n if (!src || typeof src !== 'object') return '';\n const h = src.headers;\n if (!h) return '';\n // Fetch Request: headers.get('cookie'); Node: headers.cookie.\n if (typeof (h as { get?(n: string): string | null }).get === 'function') {\n return (h as { get(n: string): string | null }).get('cookie') ?? '';\n }\n const c = (h as Record<string, unknown>).cookie;\n return typeof c === 'string' ? c : '';\n}\n\n/** Extract one cookie's raw value from a Cookie header (no decoding). */\nfunction cookieValue(header: string, name: string): string | null {\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return null;\n}\n\nfunction bool(v: unknown): v is boolean {\n return typeof v === 'boolean';\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw; // not URL-encoded; use as-is\n }\n}\n\n/** The embed's own validation (core cookie.ts `normalize`), field for field. */\nfunction normalize(o: unknown): ServerConsent | null {\n if (!o || typeof o !== 'object') return null;\n const r = o as Record<string, unknown>;\n if (!bool(r.preferences) || !bool(r.statistics) || !bool(r.marketing)) return null;\n if (r.method !== 'explicit' && r.method !== 'implied') return null;\n if (typeof r.ver !== 'number' || typeof r.utc !== 'number') return null;\n if (typeof r.stamp !== 'string' && typeof r.stamp !== 'number') return null;\n if (typeof r.region !== 'string') return null;\n const out: ServerConsent = {\n necessary: true, // never trust a cookie that claims necessary:false\n preferences: r.preferences,\n statistics: r.statistics,\n marketing: r.marketing,\n method: r.method,\n ver: r.ver,\n utc: r.utc,\n region: r.region,\n stamp: String(r.stamp),\n };\n if (r.custom && typeof r.custom === 'object' && !Array.isArray(r.custom)) {\n const custom: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(r.custom as Record<string, unknown>)) if (bool(v)) custom[k] = v;\n if (Object.keys(custom).length > 0) out.custom = custom;\n }\n if (typeof r.sig === 'string') out.sig = r.sig;\n return out;\n}\n\n/**\n * Parse a raw cookie value into a validated ServerConsent, or null. Accepts the two formats\n * the embed reads: URL-encoded (or plain) strict JSON, and Cookiebot's relaxed object\n * literal — `{stamp:'…',necessary:true,…}` — left behind by a site migrating from Cookiebot.\n */\nexport function parseConsentValue(raw: string): ServerConsent | null {\n if (!raw) return null;\n const decoded = decode(raw);\n try {\n return normalize(JSON.parse(decoded));\n } catch {\n /* not strict JSON — try the Cookiebot literal */\n }\n if (!decoded.includes('necessary')) return null;\n const json = decoded.replace(/'/g, '\"').replace(/([{,]\\s*)([A-Za-z_][\\w]*)\\s*:/g, '$1\"$2\":');\n try {\n return normalize(JSON.parse(json));\n } catch {\n return null;\n }\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Read the visitor's consent from a request: a raw `Cookie` header, a Node `req`, or a Fetch\n * `Request`. Returns null when there is no decision the embed would honour — no cookie, an\n * unparseable one, or (with the options) one made under an older version or past expiry.\n */\nexport function readConsent(source: ConsentSource, opts: ReadSignedConsentOptions): Promise<ServerConsent | null>;\nexport function readConsent(source: ConsentSource, opts?: ReadConsentOptions & { requireSigned?: false }): ServerConsent | null;\nexport function readConsent(\n source: ConsentSource,\n opts: ReadConsentOptions & { requireSigned?: boolean } & KeySetOptions = {},\n): ServerConsent | null | Promise<ServerConsent | null> {\n const consent = readUnsigned(source, opts);\n if (opts.requireSigned !== true) return consent;\n // A decision counts only when the API's signature over it verifies against the\n // published key set. A hand-written cookie (no sig) or a forged one reads as no decision.\n if (!consent?.sig) return Promise.resolve(null);\n return verifyDecisionSignature(consent, opts).then((ok) => (ok ? consent : null));\n}\n\nfunction readUnsigned(source: ConsentSource, opts: ReadConsentOptions): ServerConsent | null {\n const raw = cookieValue(cookieHeaderOf(source), opts.cookieName ?? CONSENT_COOKIE_NAME);\n const consent = raw ? parseConsentValue(raw) : null;\n if (!consent) return null;\n if (typeof opts.minVersion === 'number' && consent.ver < opts.minVersion) return null;\n if (typeof opts.expiryDays === 'number' && opts.expiryDays > 0) {\n if ((opts.now ?? Date.now()) - consent.utc > opts.expiryDays * DAY_MS) return null;\n }\n return consent;\n}\n\n/**\n * Read the visitor's consent from a request. The original spelling of {@link readConsent},\n * kept for existing callers; the second argument is the cookie name.\n */\nexport function getConsent(source: ConsentSource, cookieName: string = CONSENT_COOKIE_NAME): ServerConsent | null {\n return readConsent(source, { cookieName });\n}\n\n/** Standard + custom consent categories. */\nexport type ConsentCategory = 'necessary' | 'preferences' | 'statistics' | 'marketing' | (string & {});\n\n/**\n * Whether a category is allowed for this visitor. `necessary` is always allowed. A missing\n * consent (`null` — visitor hasn't decided) is treated as NOT allowed for non-necessary\n * categories (fail-closed / prior-blocking posture), matching the embed.\n */\nexport function isAllowed(consent: ServerConsent | null, category: ConsentCategory): boolean {\n if (category === 'necessary') return true;\n if (!consent) return false;\n // Explicit per-literal access rather than `consent[category]`: the `(string & {})` arm of\n // ConsentCategory defeats control-flow narrowing, so a dynamic index is typed as an\n // implicit-any index into ServerConsent (TS7053, which fails the tsup DTS build).\n if (category === 'preferences') return consent.preferences === true;\n if (category === 'statistics') return consent.statistics === true;\n if (category === 'marketing') return consent.marketing === true;\n return consent.custom?.[category] === true;\n}\n\n// ---- signatures and consent tokens ----\n\nexport const DEFAULT_JWKS_URL = 'https://api.cookiemunch.net/v1/partner/jwks.json';\n\n/** The fields of a decision its signature covers. */\nexport interface SignableDecision {\n stamp: string;\n ver: number;\n utc: number;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n custom?: Record<string, boolean> | undefined;\n}\n\n/**\n * The exact line the API signs for a recorded decision. Identical to @cookiemunch/core's\n * `consentSignaturePayload` (a server test pins the two together).\n */\nexport function consentSignaturePayload(d: SignableDecision): string {\n const b = (v: boolean | undefined): string => (v ? '1' : '0');\n const custom = d.custom ?? {};\n const named = Object.keys(custom)\n .sort()\n .map((k) => `${k}=${b(custom[k])}`)\n .join(',');\n return `cmc1|${d.stamp}|${d.ver}|${d.utc}|${b(d.preferences)}${b(d.statistics)}${b(d.marketing)}|${named}`;\n}\n\ninterface Jwk {\n kty?: string;\n crv?: string;\n x?: string;\n kid?: string;\n alg?: string;\n}\nexport interface JsonWebKeySet {\n keys: Jwk[];\n}\n\nconst jwksCache = new Map<string, { at: number; set: JsonWebKeySet }>();\nconst JWKS_TTL_MS = 60 * 60 * 1000;\n\nasync function keySet(opts: KeySetOptions, kid: string): Promise<JsonWebKeySet> {\n if (opts.jwks) return opts.jwks;\n const url = opts.jwksUrl ?? DEFAULT_JWKS_URL;\n const hit = jwksCache.get(url);\n // An unknown kid refetches: the key may have rotated since the cached copy.\n if (hit && Date.now() - hit.at < JWKS_TTL_MS && hit.set.keys.some((k) => k.kid === kid)) return hit.set;\n const f = opts.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch;\n if (!f) throw new Error('no fetch available to load the key set; pass `jwks`');\n const res = await f(url);\n if (!res.ok) throw new Error(`key set ${url} answered ${res.status}`);\n const set = (await res.json()) as JsonWebKeySet;\n if (!set || !Array.isArray(set.keys)) throw new Error(`key set ${url} is not a JWKS`);\n jwksCache.set(url, { at: Date.now(), set });\n return set;\n}\n\nfunction b64urlBytes(s: string): Uint8Array {\n const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4);\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n/** Ed25519 verify with WebCrypto (Node 20+, Deno, Bun, workers, browsers). */\nasync function edVerify(jwk: Jwk, data: string, signature: string): Promise<boolean> {\n const subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle;\n if (!subtle) throw new Error('WebCrypto is unavailable in this runtime');\n if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || !jwk.x) return false;\n const key = await subtle.importKey('jwk', { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, { name: 'Ed25519' }, false, ['verify']);\n return subtle.verify({ name: 'Ed25519' }, key, b64urlBytes(signature) as BufferSource, new TextEncoder().encode(data) as BufferSource);\n}\n\n/** Does the cookie's `sig` verify for this decision? False on anything malformed. */\nexport async function verifyDecisionSignature(consent: ServerConsent, opts: KeySetOptions = {}): Promise<boolean> {\n const dot = consent.sig?.lastIndexOf('.') ?? -1;\n if (!consent.sig || dot <= 0) return false;\n const kid = consent.sig.slice(0, dot);\n try {\n const jwk = (await keySet(opts, kid)).keys.find((k) => k.kid === kid);\n if (!jwk) return false;\n return await edVerify(jwk, consentSignaturePayload(consent), consent.sig.slice(dot + 1));\n } catch {\n return false;\n }\n}\n\n/** What a consent token (`CookieMunch.getConsentToken()`) asserts. */\nexport interface ConsentTokenClaims {\n iss: string;\n /** The decision's stamp. */\n sub: string;\n /** `cookiemunch:<cbid>`. */\n aud: string;\n token_use: 'consent';\n cbid: string;\n stamp: string;\n /** Every category the decision answered, `necessary` included. */\n choices: Record<string, boolean>;\n ver: number;\n /** When the decision was made, epoch ms. */\n decidedAt: number;\n cause?: string;\n iat: number;\n exp: number;\n}\n\nexport interface VerifyTokenOptions extends KeySetOptions {\n /** Require the token to be for this site. */\n cbid?: string;\n /** Clock, epoch ms. Default `Date.now()`. */\n now?: number;\n /** Allowed clock skew, seconds. Default 30. */\n leewaySeconds?: number;\n}\n\n/**\n * Verify a consent token from `CookieMunch.getConsentToken()` against the published\n * key set and return its claims. Throws on a bad signature, a wrong site, or an expired token.\n */\nexport async function verifyToken(token: string, opts: VerifyTokenOptions = {}): Promise<ConsentTokenClaims> {\n const parts = typeof token === 'string' ? token.split('.') : [];\n if (parts.length !== 3) throw new Error('not a JWT');\n const [h, p, s] = parts as [string, string, string];\n let header: { alg?: string; kid?: string };\n let claims: ConsentTokenClaims;\n try {\n header = JSON.parse(new TextDecoder().decode(b64urlBytes(h)));\n claims = JSON.parse(new TextDecoder().decode(b64urlBytes(p)));\n } catch {\n throw new Error('malformed token');\n }\n if (header.alg !== 'EdDSA' || !header.kid) throw new Error('unexpected token algorithm');\n const jwk = (await keySet(opts, header.kid)).keys.find((k) => k.kid === header.kid);\n if (!jwk || !(await edVerify(jwk, `${h}.${p}`, s))) throw new Error('bad signature');\n if (claims.token_use !== 'consent') throw new Error('not a consent token');\n const now = (opts.now ?? Date.now()) / 1000;\n const leeway = opts.leewaySeconds ?? 30;\n if (typeof claims.exp !== 'number' || now > claims.exp + leeway) throw new Error('expired');\n if (typeof claims.iat === 'number' && claims.iat > now + leeway) throw new Error('issued in the future');\n if (opts.cbid !== undefined && (claims.cbid !== opts.cbid || claims.aud !== `cookiemunch:${opts.cbid}`)) throw new Error('token is for another site');\n return claims;\n}\n"],"mappings":";AAoBO,IAAM,sBAAsB;AAiEnC,SAAS,eAAe,KAA4B;AAClD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,IAAI,IAAI;AACd,MAAI,CAAC,EAAG,QAAO;AAEf,MAAI,OAAQ,EAAyC,QAAQ,YAAY;AACvE,WAAQ,EAAwC,IAAI,QAAQ,KAAK;AAAA,EACnE;AACA,QAAM,IAAK,EAA8B;AACzC,SAAO,OAAO,MAAM,WAAW,IAAI;AACrC;AAGA,SAAS,YAAY,QAAgB,MAA6B;AAChE,aAAW,QAAQ,OAAO,MAAM,GAAG,GAAG;AACpC,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,QAAI,OAAO,GAAI;AACf,QAAI,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK,MAAM,KAAM,QAAO,KAAK,MAAM,KAAK,CAAC,EAAE,KAAK;AAAA,EACxE;AACA,SAAO;AACT;AAEA,SAAS,KAAK,GAA0B;AACtC,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,OAAO,KAAqB;AACnC,MAAI;AACF,WAAO,mBAAmB,GAAG;AAAA,EAC/B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,UAAU,GAAkC;AACnD,MAAI,CAAC,KAAK,OAAO,MAAM,SAAU,QAAO;AACxC,QAAM,IAAI;AACV,MAAI,CAAC,KAAK,EAAE,WAAW,KAAK,CAAC,KAAK,EAAE,UAAU,KAAK,CAAC,KAAK,EAAE,SAAS,EAAG,QAAO;AAC9E,MAAI,EAAE,WAAW,cAAc,EAAE,WAAW,UAAW,QAAO;AAC9D,MAAI,OAAO,EAAE,QAAQ,YAAY,OAAO,EAAE,QAAQ,SAAU,QAAO;AACnE,MAAI,OAAO,EAA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AAC;AAC5D,aAAS,KAAK,MAAM,IAAI,YAAY,EAAE,OAAO,YAAY,CAAC,CAAC,CAAC;AAAA,EAC9D,QAAQ;AACN,UAAM,IAAI,MAAM,iBAAiB;AAAA,EACnC;AACA,MAAI,OAAO,QAAQ,WAAW,CAAC,OAAO,IAAK,OAAM,IAAI,MAAM,4BAA4B;AACvF,QAAM,OAAO,MAAM,OAAO,MAAM,OAAO,GAAG,GAAG,KAAK,KAAK,CAAC,MAAM,EAAE,QAAQ,OAAO,GAAG;AAClF,MAAI,CAAC,OAAO,CAAE,MAAM,SAAS,KAAK,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAI,OAAM,IAAI,MAAM,eAAe;AACnF,MAAI,OAAO,cAAc,UAAW,OAAM,IAAI,MAAM,qBAAqB;AACzE,QAAM,OAAO,KAAK,OAAO,KAAK,IAAI,KAAK;AACvC,QAAM,SAAS,KAAK,iBAAiB;AACrC,MAAI,OAAO,OAAO,QAAQ,YAAY,MAAM,OAAO,MAAM,OAAQ,OAAM,IAAI,MAAM,SAAS;AAC1F,MAAI,OAAO,OAAO,QAAQ,YAAY,OAAO,MAAM,MAAM,OAAQ,OAAM,IAAI,MAAM,sBAAsB;AACvG,MAAI,KAAK,SAAS,WAAc,OAAO,SAAS,KAAK,QAAQ,OAAO,QAAQ,eAAe,KAAK,IAAI,IAAK,OAAM,IAAI,MAAM,2BAA2B;AACpJ,SAAO;AACT;","names":[]}
|
package/dist/consent.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/consent.ts"],"sourcesContent":["/**\n * Server-side consent reading. The Cookie Munch embed stores the visitor's decision in a\n * first-party `CookieMunch` cookie (URL-encoded JSON). This lets a server / edge worker read\n * that decision from the incoming request — to gate server-rendered tags or SSR'd third-party\n * scripts BEFORE they hit the browser — without shipping the whole embed. Zero-dependency and\n * runtime-agnostic: accepts a raw Cookie header, a Node `req` (`req.headers.cookie`), or a\n * Fetch `Request` (`request.headers.get('cookie')`).\n *\n * import { readConsent, isAllowed } from '@cookiemunch/sdk/consent';\n * const consent = readConsent(req.headers.cookie); // ServerConsent | null\n * if (isAllowed(consent, 'statistics')) { …render analytics tag… }\n *\n * The contract is documented at https://cookiemunch.net/docs/consent-cookie. It accepts\n * exactly what the embed accepts, so a server never grants what the browser would refuse:\n * strict JSON (URL-encoded or not) and the relaxed object literal Cookiebot writes.\n *\n * This module imports nothing — `@cookiemunch/sdk/consent` pulls in no API client.\n */\n\n/** The first-party cookie the embed writes (mirrors @cookiemunch/core COOKIE_NAME). */\nexport const CONSENT_COOKIE_NAME = 'CookieMunch';\n\n/** A visitor's consent decision, read from the request cookie. `necessary` is always true. */\nexport interface ServerConsent {\n necessary: true;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n /** How consent was given. `implied` = not yet an explicit choice. */\n method: 'explicit' | 'implied';\n /** Custom (non-standard) categories, when the site defines any. */\n custom?: Record<string, boolean>;\n /** Consent-policy version the decision was made under (see `minVersion`). */\n ver: number;\n /** When the decision was made, epoch milliseconds (see `expiryDays`). */\n utc: number;\n /** Region code the decision was made in (`unknown` when undetected). */\n region: string;\n /** The anonymous consent-receipt id tying this browser to the consent log. */\n stamp: string;\n /**\n * `<kid>.<base64url>`: the API's Ed25519 signature over this decision, issued when the\n * ledger recorded it. Absent on a decision no ledger holds (a hand-written cookie).\n */\n sig?: string;\n}\n\n/** The site's consent policy, so the server applies the same rules the embed does. */\nexport interface ReadConsentOptions {\n /** Cookie name. Default `CookieMunch`. */\n cookieName?: string;\n /**\n * The site's current consent version (`consent.version`, or the config `ver` when that is\n * higher). A decision made under an older version is not honoured by the embed — the\n * visitor is asked again — so it reads as `null` here too.\n */\n minVersion?: number;\n /** The site's `consent.expiryDays`: a decision older than this reads as `null`. */\n expiryDays?: number;\n /** Clock for `expiryDays`, epoch ms. Default `Date.now()`. */\n now?: number;\n}\n\n/** Where the platform's public signing keys come from, for signatures and consent tokens. */\nexport interface KeySetOptions {\n /** A key set you already hold (`{ keys: [...] }`). Skips the fetch. */\n jwks?: JsonWebKeySet;\n /** Default `https://api.cookiemunch.net/v1/partner/jwks.json`. */\n jwksUrl?: string;\n /** Injectable fetch. Default: the global one. */\n fetch?: typeof fetch;\n}\n\n/** `readConsent` with `requireSigned: true`: only a decision the API signed counts. */\nexport interface ReadSignedConsentOptions extends ReadConsentOptions, KeySetOptions {\n requireSigned: true;\n}\n\n/** Anything we can pull a Cookie header off of. */\nexport type ConsentSource =\n | string\n | null\n | undefined\n | { headers?: { cookie?: string | null; get?(name: string): string | null } | Record<string, unknown> };\n\nfunction cookieHeaderOf(src: ConsentSource): string {\n if (typeof src === 'string') return src;\n if (!src || typeof src !== 'object') return '';\n const h = src.headers;\n if (!h) return '';\n // Fetch Request: headers.get('cookie'); Node: headers.cookie.\n if (typeof (h as { get?(n: string): string | null }).get === 'function') {\n return (h as { get(n: string): string | null }).get('cookie') ?? '';\n }\n const c = (h as Record<string, unknown>).cookie;\n return typeof c === 'string' ? c : '';\n}\n\n/** Extract one cookie's raw value from a Cookie header (no decoding). */\nfunction cookieValue(header: string, name: string): string | null {\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return null;\n}\n\nfunction bool(v: unknown): v is boolean {\n return typeof v === 'boolean';\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw; // not URL-encoded; use as-is\n }\n}\n\n/** The embed's own validation (core cookie.ts `normalize`), field for field. */\nfunction normalize(o: unknown): ServerConsent | null {\n if (!o || typeof o !== 'object') return null;\n const r = o as Record<string, unknown>;\n if (!bool(r.preferences) || !bool(r.statistics) || !bool(r.marketing)) return null;\n if (r.method !== 'explicit' && r.method !== 'implied') return null;\n if (typeof r.ver !== 'number' || typeof r.utc !== 'number') return null;\n if (typeof r.stamp !== 'string' && typeof r.stamp !== 'number') return null;\n if (typeof r.region !== 'string') return null;\n const out: ServerConsent = {\n necessary: true, // never trust a cookie that claims necessary:false\n preferences: r.preferences,\n statistics: r.statistics,\n marketing: r.marketing,\n method: r.method,\n ver: r.ver,\n utc: r.utc,\n region: r.region,\n stamp: String(r.stamp),\n };\n if (r.custom && typeof r.custom === 'object' && !Array.isArray(r.custom)) {\n const custom: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(r.custom as Record<string, unknown>)) if (bool(v)) custom[k] = v;\n if (Object.keys(custom).length > 0) out.custom = custom;\n }\n if (typeof r.sig === 'string') out.sig = r.sig;\n return out;\n}\n\n/**\n * Parse a raw cookie value into a validated ServerConsent, or null. Accepts the two formats\n * the embed reads: URL-encoded (or plain) strict JSON, and Cookiebot's relaxed object\n * literal — `{stamp:'…',necessary:true,…}` — left behind by a site migrating from Cookiebot.\n */\nexport function parseConsentValue(raw: string): ServerConsent | null {\n if (!raw) return null;\n const decoded = decode(raw);\n try {\n return normalize(JSON.parse(decoded));\n } catch {\n /* not strict JSON — try the Cookiebot literal */\n }\n if (!decoded.includes('necessary')) return null;\n const json = decoded.replace(/'/g, '\"').replace(/([{,]\\s*)([A-Za-z_][\\w]*)\\s*:/g, '$1\"$2\":');\n try {\n return normalize(JSON.parse(json));\n } catch {\n return null;\n }\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Read the visitor's consent from a request: a raw `Cookie` header, a Node `req`, or a Fetch\n * `Request`. Returns null when there is no decision the embed would honour — no cookie, an\n * unparseable one, or (with the options) one made under an older version or past expiry.\n */\nexport function readConsent(source: ConsentSource, opts: ReadSignedConsentOptions): Promise<ServerConsent | null>;\nexport function readConsent(source: ConsentSource, opts?: ReadConsentOptions & { requireSigned?: false }): ServerConsent | null;\nexport function readConsent(\n source: ConsentSource,\n opts: ReadConsentOptions & { requireSigned?: boolean } & KeySetOptions = {},\n): ServerConsent | null | Promise<ServerConsent | null> {\n const consent = readUnsigned(source, opts);\n if (opts.requireSigned !== true) return consent;\n // CMU-S04: a decision counts only when the API's signature over it verifies against the\n // published key set. A hand-written cookie (no sig) or a forged one reads as no decision.\n if (!consent?.sig) return Promise.resolve(null);\n return verifyDecisionSignature(consent, opts).then((ok) => (ok ? consent : null));\n}\n\nfunction readUnsigned(source: ConsentSource, opts: ReadConsentOptions): ServerConsent | null {\n const raw = cookieValue(cookieHeaderOf(source), opts.cookieName ?? CONSENT_COOKIE_NAME);\n const consent = raw ? parseConsentValue(raw) : null;\n if (!consent) return null;\n if (typeof opts.minVersion === 'number' && consent.ver < opts.minVersion) return null;\n if (typeof opts.expiryDays === 'number' && opts.expiryDays > 0) {\n if ((opts.now ?? Date.now()) - consent.utc > opts.expiryDays * DAY_MS) return null;\n }\n return consent;\n}\n\n/**\n * Read the visitor's consent from a request. The original spelling of {@link readConsent},\n * kept for existing callers; the second argument is the cookie name.\n */\nexport function getConsent(source: ConsentSource, cookieName: string = CONSENT_COOKIE_NAME): ServerConsent | null {\n return readConsent(source, { cookieName });\n}\n\n/** Standard + custom consent categories. */\nexport type ConsentCategory = 'necessary' | 'preferences' | 'statistics' | 'marketing' | (string & {});\n\n/**\n * Whether a category is allowed for this visitor. `necessary` is always allowed. A missing\n * consent (`null` — visitor hasn't decided) is treated as NOT allowed for non-necessary\n * categories (fail-closed / prior-blocking posture), matching the embed.\n */\nexport function isAllowed(consent: ServerConsent | null, category: ConsentCategory): boolean {\n if (category === 'necessary') return true;\n if (!consent) return false;\n // Explicit per-literal access rather than `consent[category]`: the `(string & {})` arm of\n // ConsentCategory defeats control-flow narrowing, so a dynamic index is typed as an\n // implicit-any index into ServerConsent (TS7053, which fails the tsup DTS build).\n if (category === 'preferences') return consent.preferences === true;\n if (category === 'statistics') return consent.statistics === true;\n if (category === 'marketing') return consent.marketing === true;\n return consent.custom?.[category] === true;\n}\n\n// ---- signatures (CMU-S04) and consent tokens (CMU-F06) ----\n\nexport const DEFAULT_JWKS_URL = 'https://api.cookiemunch.net/v1/partner/jwks.json';\n\n/** The fields of a decision its signature covers. */\nexport interface SignableDecision {\n stamp: string;\n ver: number;\n utc: number;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n custom?: Record<string, boolean> | undefined;\n}\n\n/**\n * The exact line the API signs for a recorded decision. Identical to @cookiemunch/core's\n * `consentSignaturePayload` (a server test pins the two together).\n */\nexport function consentSignaturePayload(d: SignableDecision): string {\n const b = (v: boolean | undefined): string => (v ? '1' : '0');\n const custom = d.custom ?? {};\n const named = Object.keys(custom)\n .sort()\n .map((k) => `${k}=${b(custom[k])}`)\n .join(',');\n return `cmc1|${d.stamp}|${d.ver}|${d.utc}|${b(d.preferences)}${b(d.statistics)}${b(d.marketing)}|${named}`;\n}\n\ninterface Jwk {\n kty?: string;\n crv?: string;\n x?: string;\n kid?: string;\n alg?: string;\n}\nexport interface JsonWebKeySet {\n keys: Jwk[];\n}\n\nconst jwksCache = new Map<string, { at: number; set: JsonWebKeySet }>();\nconst JWKS_TTL_MS = 60 * 60 * 1000;\n\nasync function keySet(opts: KeySetOptions, kid: string): Promise<JsonWebKeySet> {\n if (opts.jwks) return opts.jwks;\n const url = opts.jwksUrl ?? DEFAULT_JWKS_URL;\n const hit = jwksCache.get(url);\n // An unknown kid refetches: the key may have rotated since the cached copy.\n if (hit && Date.now() - hit.at < JWKS_TTL_MS && hit.set.keys.some((k) => k.kid === kid)) return hit.set;\n const f = opts.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch;\n if (!f) throw new Error('no fetch available to load the key set; pass `jwks`');\n const res = await f(url);\n if (!res.ok) throw new Error(`key set ${url} answered ${res.status}`);\n const set = (await res.json()) as JsonWebKeySet;\n if (!set || !Array.isArray(set.keys)) throw new Error(`key set ${url} is not a JWKS`);\n jwksCache.set(url, { at: Date.now(), set });\n return set;\n}\n\nfunction b64urlBytes(s: string): Uint8Array {\n const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4);\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n/** Ed25519 verify with WebCrypto (Node 20+, Deno, Bun, workers, browsers). */\nasync function edVerify(jwk: Jwk, data: string, signature: string): Promise<boolean> {\n const subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle;\n if (!subtle) throw new Error('WebCrypto is unavailable in this runtime');\n if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || !jwk.x) return false;\n const key = await subtle.importKey('jwk', { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, { name: 'Ed25519' }, false, ['verify']);\n return subtle.verify({ name: 'Ed25519' }, key, b64urlBytes(signature) as BufferSource, new TextEncoder().encode(data) as BufferSource);\n}\n\n/** Does the cookie's `sig` verify for this decision? False on anything malformed. */\nexport async function verifyDecisionSignature(consent: ServerConsent, opts: KeySetOptions = {}): Promise<boolean> {\n const dot = consent.sig?.lastIndexOf('.') ?? -1;\n if (!consent.sig || dot <= 0) return false;\n const kid = consent.sig.slice(0, dot);\n try {\n const jwk = (await keySet(opts, kid)).keys.find((k) => k.kid === kid);\n if (!jwk) return false;\n return await edVerify(jwk, consentSignaturePayload(consent), consent.sig.slice(dot + 1));\n } catch {\n return false;\n }\n}\n\n/** What a consent token (`CookieMunch.getConsentToken()`) asserts. */\nexport interface ConsentTokenClaims {\n iss: string;\n /** The decision's stamp. */\n sub: string;\n /** `cookiemunch:<cbid>`. */\n aud: string;\n token_use: 'consent';\n cbid: string;\n stamp: string;\n /** Every category the decision answered, `necessary` included. */\n choices: Record<string, boolean>;\n ver: number;\n /** When the decision was made, epoch ms. */\n decidedAt: number;\n cause?: string;\n iat: number;\n exp: number;\n}\n\nexport interface VerifyTokenOptions extends KeySetOptions {\n /** Require the token to be for this site. */\n cbid?: string;\n /** Clock, epoch ms. Default `Date.now()`. */\n now?: number;\n /** Allowed clock skew, seconds. Default 30. */\n leewaySeconds?: number;\n}\n\n/**\n * Verify a consent token from `CookieMunch.getConsentToken()` (CMU-F06) against the published\n * key set and return its claims. Throws on a bad signature, a wrong site, or an expired token.\n */\nexport async function verifyToken(token: string, opts: VerifyTokenOptions = {}): Promise<ConsentTokenClaims> {\n const parts = typeof token === 'string' ? token.split('.') : [];\n if (parts.length !== 3) throw new Error('not a JWT');\n const [h, p, s] = parts as [string, string, string];\n let header: { alg?: string; kid?: string };\n let claims: ConsentTokenClaims;\n try {\n header = JSON.parse(new TextDecoder().decode(b64urlBytes(h)));\n claims = JSON.parse(new TextDecoder().decode(b64urlBytes(p)));\n } catch {\n throw new Error('malformed token');\n }\n if (header.alg !== 'EdDSA' || !header.kid) throw new Error('unexpected token algorithm');\n const jwk = (await keySet(opts, header.kid)).keys.find((k) => k.kid === header.kid);\n if (!jwk || !(await edVerify(jwk, `${h}.${p}`, s))) throw new Error('bad signature');\n if (claims.token_use !== 'consent') throw new Error('not a consent token');\n const now = (opts.now ?? Date.now()) / 1000;\n const leeway = opts.leewaySeconds ?? 30;\n if (typeof claims.exp !== 'number' || now > claims.exp + leeway) throw new Error('expired');\n if (typeof claims.iat === 'number' && claims.iat > now + leeway) throw new Error('issued in the future');\n if (opts.cbid !== undefined && (claims.cbid !== opts.cbid || claims.aud !== `cookiemunch:${opts.cbid}`)) throw new Error('token is for another site');\n return claims;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBO,IAAM,sBAAsB;AAiEnC,SAAS,eAAe,KAA4B;AAClD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,IAAI,IAAI;AACd,MAAI,CAAC,EAAG,QAAO;AAEf,MAAI,OAAQ,EAAyC,QAAQ,YAAY;AACvE,WAAQ,EAAwC,IAAI,QAAQ,KAAK;AAAA,EACnE;AACA,QAAM,IAAK,EAA8B;AACzC,SAAO,OAAO,MAAM,WAAW,IAAI;AACrC;AAGA,SAAS,YAAY,QAA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MAAM,qBAAqB;AACzE,QAAM,OAAO,KAAK,OAAO,KAAK,IAAI,KAAK;AACvC,QAAM,SAAS,KAAK,iBAAiB;AACrC,MAAI,OAAO,OAAO,QAAQ,YAAY,MAAM,OAAO,MAAM,OAAQ,OAAM,IAAI,MAAM,SAAS;AAC1F,MAAI,OAAO,OAAO,QAAQ,YAAY,OAAO,MAAM,MAAM,OAAQ,OAAM,IAAI,MAAM,sBAAsB;AACvG,MAAI,KAAK,SAAS,WAAc,OAAO,SAAS,KAAK,QAAQ,OAAO,QAAQ,eAAe,KAAK,IAAI,IAAK,OAAM,IAAI,MAAM,2BAA2B;AACpJ,SAAO;AACT;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/consent.ts"],"sourcesContent":["/**\n * Server-side consent reading. The Cookie Munch embed stores the visitor's decision in a\n * first-party `CookieMunch` cookie (URL-encoded JSON). This lets a server / edge worker read\n * that decision from the incoming request — to gate server-rendered tags or SSR'd third-party\n * scripts BEFORE they hit the browser — without shipping the whole embed. Zero-dependency and\n * runtime-agnostic: accepts a raw Cookie header, a Node `req` (`req.headers.cookie`), or a\n * Fetch `Request` (`request.headers.get('cookie')`).\n *\n * import { readConsent, isAllowed } from '@cookiemunch/sdk/consent';\n * const consent = readConsent(req.headers.cookie); // ServerConsent | null\n * if (isAllowed(consent, 'statistics')) { …render analytics tag… }\n *\n * The contract is documented at https://cookiemunch.net/docs/consent-cookie. It accepts\n * exactly what the embed accepts, so a server never grants what the browser would refuse:\n * strict JSON (URL-encoded or not) and the relaxed object literal Cookiebot writes.\n *\n * This module imports nothing — `@cookiemunch/sdk/consent` pulls in no API client.\n */\n\n/** The first-party cookie the embed writes (mirrors @cookiemunch/core COOKIE_NAME). */\nexport const CONSENT_COOKIE_NAME = 'CookieMunch';\n\n/** A visitor's consent decision, read from the request cookie. `necessary` is always true. */\nexport interface ServerConsent {\n necessary: true;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n /** How consent was given. `implied` = not yet an explicit choice. */\n method: 'explicit' | 'implied';\n /** Custom (non-standard) categories, when the site defines any. */\n custom?: Record<string, boolean>;\n /** Consent-policy version the decision was made under (see `minVersion`). */\n ver: number;\n /** When the decision was made, epoch milliseconds (see `expiryDays`). */\n utc: number;\n /** Region code the decision was made in (`unknown` when undetected). */\n region: string;\n /** The anonymous consent-receipt id tying this browser to the consent log. */\n stamp: string;\n /**\n * `<kid>.<base64url>`: the API's Ed25519 signature over this decision, issued when the\n * ledger recorded it. Absent on a decision no ledger holds (a hand-written cookie).\n */\n sig?: string;\n}\n\n/** The site's consent policy, so the server applies the same rules the embed does. */\nexport interface ReadConsentOptions {\n /** Cookie name. Default `CookieMunch`. */\n cookieName?: string;\n /**\n * The site's current consent version (`consent.version`, or the config `ver` when that is\n * higher). A decision made under an older version is not honoured by the embed — the\n * visitor is asked again — so it reads as `null` here too.\n */\n minVersion?: number;\n /** The site's `consent.expiryDays`: a decision older than this reads as `null`. */\n expiryDays?: number;\n /** Clock for `expiryDays`, epoch ms. Default `Date.now()`. */\n now?: number;\n}\n\n/** Where the platform's public signing keys come from, for signatures and consent tokens. */\nexport interface KeySetOptions {\n /** A key set you already hold (`{ keys: [...] }`). Skips the fetch. */\n jwks?: JsonWebKeySet;\n /** Default `https://api.cookiemunch.net/v1/partner/jwks.json`. */\n jwksUrl?: string;\n /** Injectable fetch. Default: the global one. */\n fetch?: typeof fetch;\n}\n\n/** `readConsent` with `requireSigned: true`: only a decision the API signed counts. */\nexport interface ReadSignedConsentOptions extends ReadConsentOptions, KeySetOptions {\n requireSigned: true;\n}\n\n/** Anything we can pull a Cookie header off of. */\nexport type ConsentSource =\n | string\n | null\n | undefined\n | { headers?: { cookie?: string | null; get?(name: string): string | null } | Record<string, unknown> };\n\nfunction cookieHeaderOf(src: ConsentSource): string {\n if (typeof src === 'string') return src;\n if (!src || typeof src !== 'object') return '';\n const h = src.headers;\n if (!h) return '';\n // Fetch Request: headers.get('cookie'); Node: headers.cookie.\n if (typeof (h as { get?(n: string): string | null }).get === 'function') {\n return (h as { get(n: string): string | null }).get('cookie') ?? '';\n }\n const c = (h as Record<string, unknown>).cookie;\n return typeof c === 'string' ? c : '';\n}\n\n/** Extract one cookie's raw value from a Cookie header (no decoding). */\nfunction cookieValue(header: string, name: string): string | null {\n for (const part of header.split(';')) {\n const eq = part.indexOf('=');\n if (eq === -1) continue;\n if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();\n }\n return null;\n}\n\nfunction bool(v: unknown): v is boolean {\n return typeof v === 'boolean';\n}\n\nfunction decode(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw; // not URL-encoded; use as-is\n }\n}\n\n/** The embed's own validation (core cookie.ts `normalize`), field for field. */\nfunction normalize(o: unknown): ServerConsent | null {\n if (!o || typeof o !== 'object') return null;\n const r = o as Record<string, unknown>;\n if (!bool(r.preferences) || !bool(r.statistics) || !bool(r.marketing)) return null;\n if (r.method !== 'explicit' && r.method !== 'implied') return null;\n if (typeof r.ver !== 'number' || typeof r.utc !== 'number') return null;\n if (typeof r.stamp !== 'string' && typeof r.stamp !== 'number') return null;\n if (typeof r.region !== 'string') return null;\n const out: ServerConsent = {\n necessary: true, // never trust a cookie that claims necessary:false\n preferences: r.preferences,\n statistics: r.statistics,\n marketing: r.marketing,\n method: r.method,\n ver: r.ver,\n utc: r.utc,\n region: r.region,\n stamp: String(r.stamp),\n };\n if (r.custom && typeof r.custom === 'object' && !Array.isArray(r.custom)) {\n const custom: Record<string, boolean> = {};\n for (const [k, v] of Object.entries(r.custom as Record<string, unknown>)) if (bool(v)) custom[k] = v;\n if (Object.keys(custom).length > 0) out.custom = custom;\n }\n if (typeof r.sig === 'string') out.sig = r.sig;\n return out;\n}\n\n/**\n * Parse a raw cookie value into a validated ServerConsent, or null. Accepts the two formats\n * the embed reads: URL-encoded (or plain) strict JSON, and Cookiebot's relaxed object\n * literal — `{stamp:'…',necessary:true,…}` — left behind by a site migrating from Cookiebot.\n */\nexport function parseConsentValue(raw: string): ServerConsent | null {\n if (!raw) return null;\n const decoded = decode(raw);\n try {\n return normalize(JSON.parse(decoded));\n } catch {\n /* not strict JSON — try the Cookiebot literal */\n }\n if (!decoded.includes('necessary')) return null;\n const json = decoded.replace(/'/g, '\"').replace(/([{,]\\s*)([A-Za-z_][\\w]*)\\s*:/g, '$1\"$2\":');\n try {\n return normalize(JSON.parse(json));\n } catch {\n return null;\n }\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Read the visitor's consent from a request: a raw `Cookie` header, a Node `req`, or a Fetch\n * `Request`. Returns null when there is no decision the embed would honour — no cookie, an\n * unparseable one, or (with the options) one made under an older version or past expiry.\n */\nexport function readConsent(source: ConsentSource, opts: ReadSignedConsentOptions): Promise<ServerConsent | null>;\nexport function readConsent(source: ConsentSource, opts?: ReadConsentOptions & { requireSigned?: false }): ServerConsent | null;\nexport function readConsent(\n source: ConsentSource,\n opts: ReadConsentOptions & { requireSigned?: boolean } & KeySetOptions = {},\n): ServerConsent | null | Promise<ServerConsent | null> {\n const consent = readUnsigned(source, opts);\n if (opts.requireSigned !== true) return consent;\n // A decision counts only when the API's signature over it verifies against the\n // published key set. A hand-written cookie (no sig) or a forged one reads as no decision.\n if (!consent?.sig) return Promise.resolve(null);\n return verifyDecisionSignature(consent, opts).then((ok) => (ok ? consent : null));\n}\n\nfunction readUnsigned(source: ConsentSource, opts: ReadConsentOptions): ServerConsent | null {\n const raw = cookieValue(cookieHeaderOf(source), opts.cookieName ?? CONSENT_COOKIE_NAME);\n const consent = raw ? parseConsentValue(raw) : null;\n if (!consent) return null;\n if (typeof opts.minVersion === 'number' && consent.ver < opts.minVersion) return null;\n if (typeof opts.expiryDays === 'number' && opts.expiryDays > 0) {\n if ((opts.now ?? Date.now()) - consent.utc > opts.expiryDays * DAY_MS) return null;\n }\n return consent;\n}\n\n/**\n * Read the visitor's consent from a request. The original spelling of {@link readConsent},\n * kept for existing callers; the second argument is the cookie name.\n */\nexport function getConsent(source: ConsentSource, cookieName: string = CONSENT_COOKIE_NAME): ServerConsent | null {\n return readConsent(source, { cookieName });\n}\n\n/** Standard + custom consent categories. */\nexport type ConsentCategory = 'necessary' | 'preferences' | 'statistics' | 'marketing' | (string & {});\n\n/**\n * Whether a category is allowed for this visitor. `necessary` is always allowed. A missing\n * consent (`null` — visitor hasn't decided) is treated as NOT allowed for non-necessary\n * categories (fail-closed / prior-blocking posture), matching the embed.\n */\nexport function isAllowed(consent: ServerConsent | null, category: ConsentCategory): boolean {\n if (category === 'necessary') return true;\n if (!consent) return false;\n // Explicit per-literal access rather than `consent[category]`: the `(string & {})` arm of\n // ConsentCategory defeats control-flow narrowing, so a dynamic index is typed as an\n // implicit-any index into ServerConsent (TS7053, which fails the tsup DTS build).\n if (category === 'preferences') return consent.preferences === true;\n if (category === 'statistics') return consent.statistics === true;\n if (category === 'marketing') return consent.marketing === true;\n return consent.custom?.[category] === true;\n}\n\n// ---- signatures and consent tokens ----\n\nexport const DEFAULT_JWKS_URL = 'https://api.cookiemunch.net/v1/partner/jwks.json';\n\n/** The fields of a decision its signature covers. */\nexport interface SignableDecision {\n stamp: string;\n ver: number;\n utc: number;\n preferences: boolean;\n statistics: boolean;\n marketing: boolean;\n custom?: Record<string, boolean> | undefined;\n}\n\n/**\n * The exact line the API signs for a recorded decision. Identical to @cookiemunch/core's\n * `consentSignaturePayload` (a server test pins the two together).\n */\nexport function consentSignaturePayload(d: SignableDecision): string {\n const b = (v: boolean | undefined): string => (v ? '1' : '0');\n const custom = d.custom ?? {};\n const named = Object.keys(custom)\n .sort()\n .map((k) => `${k}=${b(custom[k])}`)\n .join(',');\n return `cmc1|${d.stamp}|${d.ver}|${d.utc}|${b(d.preferences)}${b(d.statistics)}${b(d.marketing)}|${named}`;\n}\n\ninterface Jwk {\n kty?: string;\n crv?: string;\n x?: string;\n kid?: string;\n alg?: string;\n}\nexport interface JsonWebKeySet {\n keys: Jwk[];\n}\n\nconst jwksCache = new Map<string, { at: number; set: JsonWebKeySet }>();\nconst JWKS_TTL_MS = 60 * 60 * 1000;\n\nasync function keySet(opts: KeySetOptions, kid: string): Promise<JsonWebKeySet> {\n if (opts.jwks) return opts.jwks;\n const url = opts.jwksUrl ?? DEFAULT_JWKS_URL;\n const hit = jwksCache.get(url);\n // An unknown kid refetches: the key may have rotated since the cached copy.\n if (hit && Date.now() - hit.at < JWKS_TTL_MS && hit.set.keys.some((k) => k.kid === kid)) return hit.set;\n const f = opts.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch;\n if (!f) throw new Error('no fetch available to load the key set; pass `jwks`');\n const res = await f(url);\n if (!res.ok) throw new Error(`key set ${url} answered ${res.status}`);\n const set = (await res.json()) as JsonWebKeySet;\n if (!set || !Array.isArray(set.keys)) throw new Error(`key set ${url} is not a JWKS`);\n jwksCache.set(url, { at: Date.now(), set });\n return set;\n}\n\nfunction b64urlBytes(s: string): Uint8Array {\n const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4);\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\n/** Ed25519 verify with WebCrypto (Node 20+, Deno, Bun, workers, browsers). */\nasync function edVerify(jwk: Jwk, data: string, signature: string): Promise<boolean> {\n const subtle = (globalThis as { crypto?: Crypto }).crypto?.subtle;\n if (!subtle) throw new Error('WebCrypto is unavailable in this runtime');\n if (jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || !jwk.x) return false;\n const key = await subtle.importKey('jwk', { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, { name: 'Ed25519' }, false, ['verify']);\n return subtle.verify({ name: 'Ed25519' }, key, b64urlBytes(signature) as BufferSource, new TextEncoder().encode(data) as BufferSource);\n}\n\n/** Does the cookie's `sig` verify for this decision? False on anything malformed. */\nexport async function verifyDecisionSignature(consent: ServerConsent, opts: KeySetOptions = {}): Promise<boolean> {\n const dot = consent.sig?.lastIndexOf('.') ?? -1;\n if (!consent.sig || dot <= 0) return false;\n const kid = consent.sig.slice(0, dot);\n try {\n const jwk = (await keySet(opts, kid)).keys.find((k) => k.kid === kid);\n if (!jwk) return false;\n return await edVerify(jwk, consentSignaturePayload(consent), consent.sig.slice(dot + 1));\n } catch {\n return false;\n }\n}\n\n/** What a consent token (`CookieMunch.getConsentToken()`) asserts. */\nexport interface ConsentTokenClaims {\n iss: string;\n /** The decision's stamp. */\n sub: string;\n /** `cookiemunch:<cbid>`. */\n aud: string;\n token_use: 'consent';\n cbid: string;\n stamp: string;\n /** Every category the decision answered, `necessary` included. */\n choices: Record<string, boolean>;\n ver: number;\n /** When the decision was made, epoch ms. */\n decidedAt: number;\n cause?: string;\n iat: number;\n exp: number;\n}\n\nexport interface VerifyTokenOptions extends KeySetOptions {\n /** Require the token to be for this site. */\n cbid?: string;\n /** Clock, epoch ms. Default `Date.now()`. */\n now?: number;\n /** Allowed clock skew, seconds. Default 30. */\n leewaySeconds?: number;\n}\n\n/**\n * Verify a consent token from `CookieMunch.getConsentToken()` against the published\n * key set and return its claims. Throws on a bad signature, a wrong site, or an expired token.\n */\nexport async function verifyToken(token: string, opts: VerifyTokenOptions = {}): Promise<ConsentTokenClaims> {\n const parts = typeof token === 'string' ? token.split('.') : [];\n if (parts.length !== 3) throw new Error('not a JWT');\n const [h, p, s] = parts as [string, string, string];\n let header: { alg?: string; kid?: string };\n let claims: ConsentTokenClaims;\n try {\n header = JSON.parse(new TextDecoder().decode(b64urlBytes(h)));\n claims = JSON.parse(new TextDecoder().decode(b64urlBytes(p)));\n } catch {\n throw new Error('malformed token');\n }\n if (header.alg !== 'EdDSA' || !header.kid) throw new Error('unexpected token algorithm');\n const jwk = (await keySet(opts, header.kid)).keys.find((k) => k.kid === header.kid);\n if (!jwk || !(await edVerify(jwk, `${h}.${p}`, s))) throw new Error('bad signature');\n if (claims.token_use !== 'consent') throw new Error('not a consent token');\n const now = (opts.now ?? Date.now()) / 1000;\n const leeway = opts.leewaySeconds ?? 30;\n if (typeof claims.exp !== 'number' || now > claims.exp + leeway) throw new Error('expired');\n if (typeof claims.iat === 'number' && claims.iat > now + leeway) throw new Error('issued in the future');\n if (opts.cbid !== undefined && (claims.cbid !== opts.cbid || claims.aud !== `cookiemunch:${opts.cbid}`)) throw new Error('token is for another site');\n return claims;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBO,IAAM,sBAAsB;AAiEnC,SAAS,eAAe,KAA4B;AAClD,MAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,QAAM,IAAI,IAAI;AACd,MAAI,CAAC,EAAG,QAAO;AAEf,MAAI,OAAQ,EAAyC,QAAQ,YAAY;AACvE,WAAQ,EAAwC,IAAI,QAAQ,KAAK;AAAA,EACnE;AACA,QAAM,IAAK,EAA8B;AACzC,SAAO,OAAO,MAAM,WAAW,IAAI;AACrC;AAGA,SAAS,YAAY,QAAgB,MAA6B;AAChE,aAAW,QAAQ,OAAO,MAAM,GAAG,GAAG;AACpC,UAAM,KAAK,KAAK,QAAQ,GAAG;AAC3B,QAAI,OAAO,GAAI;AACf,QAAI,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK,MAAM,KAAM,QAAO,KAAK,MAAM,KAAK,CAAC,EAAE,KAAK;AAAA,EACxE;AACA,SAAO;AACT;AAEA,SAAS,KAAK,GAA0B;AACtC,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,OAAO,KAAqB;AACnC,MAAI;AACF,WAAO,mBAAmB,GAAG;AAAA,EAC/B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,UAAU,GAAkC;AACnD,MAAI,CAAC,KAAK,OAAO,MAAM,SAAU,QAAO;AACxC,QAAM,IAAI;AACV,MAAI,CAAC,KAAK,EAAE,WAAW,KAAK,CAAC,KAAK,EAAE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|
-
* Verify a consent token from `CookieMunch.getConsentToken()`
|
|
164
|
+
* Verify a consent token from `CookieMunch.getConsentToken()` against the published
|
|
165
165
|
* key set and return its claims. Throws on a bad signature, a wrong site, or an expired token.
|
|
166
166
|
*/
|
|
167
167
|
export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<ConsentTokenClaims>;
|
package/dist/consent.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The cm-standard-v2 executor conformance kit
|
|
2
|
+
* The cm-standard-v2 executor conformance kit.
|
|
3
3
|
*
|
|
4
4
|
* cm-standard-v2 is an open contract: any system that holds personal data can implement it and
|
|
5
5
|
* be driven by Cookie Munch with no code on our side (docs: cookiemunch.net/docs/executor-contract-v2).
|
package/dist/index.cjs
CHANGED
|
@@ -511,7 +511,7 @@ async function exchangeOperatorToken(input) {
|
|
|
511
511
|
}
|
|
512
512
|
|
|
513
513
|
// src/index.ts
|
|
514
|
-
var SDK_VERSION = "0.
|
|
514
|
+
var SDK_VERSION = "0.22.0";
|
|
515
515
|
var CookieMunchApiError = class extends Error {
|
|
516
516
|
constructor(status, message, code, body) {
|
|
517
517
|
super(message);
|
|
@@ -635,7 +635,7 @@ function createCookieMunch(opts) {
|
|
|
635
635
|
),
|
|
636
636
|
lintConfig: (cbid, config, opts2) => request("POST", `/sites/${enc(cbid)}/config/lint${qs({ replace: opts2?.replace ? 1 : void 0 })}`, config),
|
|
637
637
|
cookies: (cbid) => get(`/sites/${enc(cbid)}/cookies`),
|
|
638
|
-
scan: (cbid, o) => request("POST", `/sites/${enc(cbid)}/scan${qs({ wait: o?.wait })}
|
|
638
|
+
scan: (cbid, o) => request("POST", `/sites/${enc(cbid)}/scan${qs({ wait: o?.wait })}`, o?.cookies !== void 0 ? { cookies: o.cookies } : void 0),
|
|
639
639
|
scanStatus: (cbid, o) => get(`/sites/${enc(cbid)}/scan${qs({ wait: o?.wait })}`),
|
|
640
640
|
waitForScan: async (cbid, o) => {
|
|
641
641
|
const until = Date.now() + (o?.timeoutMs ?? 12e4);
|
|
@@ -652,7 +652,7 @@ function createCookieMunch(opts) {
|
|
|
652
652
|
ab: (cbid) => get(`/sites/${enc(cbid)}/ab`),
|
|
653
653
|
policy: (cbid, o) => request(
|
|
654
654
|
"GET",
|
|
655
|
-
`/sites/${enc(cbid)}/policy${qs({ contactEmail: o?.contactEmail, effectiveDate: o?.effectiveDate, jurisdictions: o?.jurisdictions?.join(","), fragment: o?.fragment, format: o?.format, lang: o?.lang })}`,
|
|
655
|
+
`/sites/${enc(cbid)}/policy${qs({ contactEmail: o?.contactEmail, effectiveDate: o?.effectiveDate, jurisdictions: o?.jurisdictions?.join(","), fragment: o?.fragment, format: o?.format, include: o?.include, lang: o?.lang })}`,
|
|
656
656
|
void 0,
|
|
657
657
|
true
|
|
658
658
|
),
|
|
@@ -863,6 +863,7 @@ function createCookieMunch(opts) {
|
|
|
863
863
|
upsertExecutor: (input, o) => request("PUT", `/dsar/executors${qs({ verify: o?.verify === true ? "1" : o?.verify })}`, input),
|
|
864
864
|
dryRunConnectExecutor: (input) => request("POST", "/dsar/executors?dryRun=1", input),
|
|
865
865
|
executorPresets: () => get("/dsar/executors/presets"),
|
|
866
|
+
executorSuggestions: (cbid) => get(`/dsar/executors/suggestions${qs({ cbid })}`),
|
|
866
867
|
upgradeExecutorPreset: (id, input = {}) => request("POST", `/dsar/executors/${enc(id)}/upgrade-preset`, input),
|
|
867
868
|
dryRunUpgradeExecutorPreset: (id, input = {}) => request("POST", `/dsar/executors/${enc(id)}/upgrade-preset?dryRun=1`, input),
|
|
868
869
|
dryRunUpdateExecutor: (id, patch) => request("PATCH", `/dsar/executors/${enc(id)}?dryRun=1`, patch),
|
|
@@ -879,6 +880,7 @@ function createCookieMunch(opts) {
|
|
|
879
880
|
recheckExecutor: (id) => request("POST", `/dsar/executors/${enc(id)}/recheck`),
|
|
880
881
|
executorHealthHistory: (id, opts2 = {}) => get(`/dsar/executors/${enc(id)}/health/history${qs({ limit: opts2.limit })}`),
|
|
881
882
|
executorConformance: (id) => request("POST", `/dsar/executors/${enc(id)}/test`, { conformance: true }),
|
|
883
|
+
getExecutorCompletionSecret: (id) => request("GET", `/dsar/executors/${enc(id)}/completion-secret`),
|
|
882
884
|
rollExecutorCompletionSecret: (id) => request("POST", `/dsar/executors/${enc(id)}/completion-secret/roll`)
|
|
883
885
|
},
|
|
884
886
|
preferences: {
|
|
@@ -963,7 +965,7 @@ function createCookieMunch(opts) {
|
|
|
963
965
|
remove: () => request("DELETE", "/org/rights-identity")
|
|
964
966
|
}
|
|
965
967
|
},
|
|
966
|
-
audit: (limit, opts2) => get(`/audit${qs({ limit, actor: opts2?.actor })}`),
|
|
968
|
+
audit: (limit, opts2) => get(`/audit${qs({ limit, actor: opts2?.actor, since: opts2?.since })}`),
|
|
967
969
|
auditSink: {
|
|
968
970
|
get: () => get("/audit/sink"),
|
|
969
971
|
set: (input) => request("PUT", "/audit/sink", input),
|
|
@@ -1020,8 +1022,9 @@ function createCookieMunch(opts) {
|
|
|
1020
1022
|
},
|
|
1021
1023
|
rightsIdentity: {
|
|
1022
1024
|
get: (cbid) => get(`/sites/${enc(cbid)}/rights-identity`),
|
|
1023
|
-
set: (cbid, input) => request("PUT", `/sites/${enc(cbid)}/rights-identity`, input),
|
|
1024
|
-
remove: (cbid) => request("DELETE", `/sites/${enc(cbid)}/rights-identity`)
|
|
1025
|
+
set: ((cbid, input, o) => request("PUT", `/sites/${enc(cbid)}/rights-identity${qs({ dryRun: o?.dryRun ? "1" : void 0 })}`, input)),
|
|
1026
|
+
remove: (cbid) => request("DELETE", `/sites/${enc(cbid)}/rights-identity`),
|
|
1027
|
+
check: (cbid, token) => request("POST", `/sites/${enc(cbid)}/rights-identity/check`, { token })
|
|
1025
1028
|
},
|
|
1026
1029
|
dsarSettings: {
|
|
1027
1030
|
get: (cbid) => get(`/sites/${enc(cbid)}/dsar-settings`),
|