@kya-os/checkpoint-shared 1.4.0 → 1.5.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.
Files changed (161) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/beacon-types/index.d.mts +441 -432
  3. package/dist/beacon-types/index.d.mts.map +1 -0
  4. package/dist/beacon-types/index.d.ts +441 -432
  5. package/dist/beacon-types/index.d.ts.map +1 -0
  6. package/dist/beacon-types/index.js +198 -182
  7. package/dist/beacon-types/index.mjs +197 -179
  8. package/dist/beacon-types/index.mjs.map +1 -0
  9. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +5 -0
  10. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +1 -0
  11. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +5 -0
  12. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +1 -0
  13. package/dist/browser-posture-cookie.d.mts +2 -0
  14. package/dist/browser-posture-cookie.d.ts +2 -0
  15. package/dist/browser-posture-cookie.js +1 -0
  16. package/dist/browser-posture-cookie.mjs +2 -0
  17. package/dist/browser-posture-cookie.mjs.map +1 -0
  18. package/dist/browser-posture-report.d.mts +48 -44
  19. package/dist/browser-posture-report.d.mts.map +1 -0
  20. package/dist/browser-posture-report.d.ts +48 -44
  21. package/dist/browser-posture-report.d.ts.map +1 -0
  22. package/dist/browser-posture-report.js +1 -1
  23. package/dist/browser-posture-report.mjs +2 -1
  24. package/dist/browser-posture-report.mjs.map +1 -0
  25. package/dist/browser-posture.d.mts +80 -75
  26. package/dist/browser-posture.d.mts.map +1 -0
  27. package/dist/browser-posture.d.ts +80 -75
  28. package/dist/browser-posture.d.ts.map +1 -0
  29. package/dist/browser-posture.js +159 -18993
  30. package/dist/browser-posture.mjs +158 -18990
  31. package/dist/browser-posture.mjs.map +1 -0
  32. package/dist/browser.d.mts +323 -316
  33. package/dist/browser.d.mts.map +1 -0
  34. package/dist/browser.d.ts +323 -316
  35. package/dist/browser.d.ts.map +1 -0
  36. package/dist/browser.js +1 -1
  37. package/dist/browser.mjs +2 -1
  38. package/dist/browser.mjs.map +1 -0
  39. package/dist/canonical-signer/index.d.mts +38 -33
  40. package/dist/canonical-signer/index.d.mts.map +1 -0
  41. package/dist/canonical-signer/index.d.ts +38 -33
  42. package/dist/canonical-signer/index.d.ts.map +1 -0
  43. package/dist/canonical-signer/index.js +411 -181
  44. package/dist/canonical-signer/index.mjs +383 -175
  45. package/dist/canonical-signer/index.mjs.map +1 -0
  46. package/dist/clearance.d.mts +30 -0
  47. package/dist/clearance.d.mts.map +1 -0
  48. package/dist/clearance.d.ts +30 -0
  49. package/dist/clearance.d.ts.map +1 -0
  50. package/dist/clearance.js +120 -0
  51. package/dist/clearance.mjs +112 -0
  52. package/dist/clearance.mjs.map +1 -0
  53. package/dist/client-ip-1y2iXAYW.js +237 -0
  54. package/dist/client-ip-HOfe6ucV.mjs +215 -0
  55. package/dist/client-ip-HOfe6ucV.mjs.map +1 -0
  56. package/dist/deploy/index.d.mts +339 -339
  57. package/dist/deploy/index.d.mts.map +1 -0
  58. package/dist/deploy/index.d.ts +339 -339
  59. package/dist/deploy/index.d.ts.map +1 -0
  60. package/dist/deploy/index.js +505 -413
  61. package/dist/deploy/index.mjs +504 -410
  62. package/dist/deploy/index.mjs.map +1 -0
  63. package/dist/errors/index.d.mts +101 -101
  64. package/dist/errors/index.d.mts.map +1 -0
  65. package/dist/errors/index.d.ts +101 -101
  66. package/dist/errors/index.d.ts.map +1 -0
  67. package/dist/errors/index.js +341 -314
  68. package/dist/errors/index.mjs +340 -311
  69. package/dist/errors/index.mjs.map +1 -0
  70. package/dist/external-jr_S4iSS.d.mts +4187 -0
  71. package/dist/external-jr_S4iSS.d.mts.map +1 -0
  72. package/dist/external-jr_S4iSS.d.ts +4187 -0
  73. package/dist/external-jr_S4iSS.d.ts.map +1 -0
  74. package/dist/gateway/index.d.mts +138 -132
  75. package/dist/gateway/index.d.mts.map +1 -0
  76. package/dist/gateway/index.d.ts +138 -132
  77. package/dist/gateway/index.d.ts.map +1 -0
  78. package/dist/gateway/index.js +117 -81
  79. package/dist/gateway/index.mjs +116 -78
  80. package/dist/gateway/index.mjs.map +1 -0
  81. package/dist/gateway-client-ip.d.mts +59 -0
  82. package/dist/gateway-client-ip.d.mts.map +1 -0
  83. package/dist/gateway-client-ip.d.ts +59 -0
  84. package/dist/gateway-client-ip.d.ts.map +1 -0
  85. package/dist/gateway-client-ip.js +149 -0
  86. package/dist/gateway-client-ip.mjs +139 -0
  87. package/dist/gateway-client-ip.mjs.map +1 -0
  88. package/dist/index.d.mts +14895 -14240
  89. package/dist/index.d.mts.map +1 -0
  90. package/dist/index.d.ts +14895 -14240
  91. package/dist/index.d.ts.map +1 -0
  92. package/dist/index.js +15180 -31025
  93. package/dist/index.mjs +15065 -30942
  94. package/dist/index.mjs.map +1 -0
  95. package/dist/mcpi/agentshield-api/index.d.mts +45 -44
  96. package/dist/mcpi/agentshield-api/index.d.mts.map +1 -0
  97. package/dist/mcpi/agentshield-api/index.d.ts +45 -44
  98. package/dist/mcpi/agentshield-api/index.d.ts.map +1 -0
  99. package/dist/mcpi/agentshield-api/index.js +0 -2
  100. package/dist/mcpi/agentshield-api/index.mjs +1 -1
  101. package/dist/mcpi/approval-grant/index.d.mts +63 -61
  102. package/dist/mcpi/approval-grant/index.d.mts.map +1 -0
  103. package/dist/mcpi/approval-grant/index.d.ts +63 -61
  104. package/dist/mcpi/approval-grant/index.d.ts.map +1 -0
  105. package/dist/mcpi/approval-grant/index.js +220 -140
  106. package/dist/mcpi/approval-grant/index.mjs +219 -137
  107. package/dist/mcpi/approval-grant/index.mjs.map +1 -0
  108. package/dist/mcpi/dashboard-config/index.d.mts +2323 -2318
  109. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -0
  110. package/dist/mcpi/dashboard-config/index.d.ts +2323 -2318
  111. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -0
  112. package/dist/mcpi/dashboard-config/index.js +605 -458
  113. package/dist/mcpi/dashboard-config/index.mjs +604 -455
  114. package/dist/mcpi/dashboard-config/index.mjs.map +1 -0
  115. package/dist/mcpi/multibase-ed25519.d.mts +10 -8
  116. package/dist/mcpi/multibase-ed25519.d.mts.map +1 -0
  117. package/dist/mcpi/multibase-ed25519.d.ts +10 -8
  118. package/dist/mcpi/multibase-ed25519.d.ts.map +1 -0
  119. package/dist/mcpi/multibase-ed25519.js +182 -106
  120. package/dist/mcpi/multibase-ed25519.mjs +181 -103
  121. package/dist/mcpi/multibase-ed25519.mjs.map +1 -0
  122. package/dist/patterns-CkRVOdtV.js +243 -0
  123. package/dist/patterns-DzkGy_qk.mjs +173 -0
  124. package/dist/patterns-DzkGy_qk.mjs.map +1 -0
  125. package/dist/project-verification-key-C3L5rd8a.js +41 -0
  126. package/dist/project-verification-key-CgSVX9_m.mjs +37 -0
  127. package/dist/project-verification-key-CgSVX9_m.mjs.map +1 -0
  128. package/dist/rolldown-runtime-iY2fYEqi.mjs +19 -0
  129. package/dist/schemas-BmjNLAE7.js +5677 -0
  130. package/dist/schemas-DxY-dk9y.mjs +5511 -0
  131. package/dist/schemas-DxY-dk9y.mjs.map +1 -0
  132. package/dist/signals/index.d.mts +125 -115
  133. package/dist/signals/index.d.mts.map +1 -0
  134. package/dist/signals/index.d.ts +125 -115
  135. package/dist/signals/index.d.ts.map +1 -0
  136. package/dist/signals/index.js +1693 -1536
  137. package/dist/signals/index.mjs +1692 -1533
  138. package/dist/signals/index.mjs.map +1 -0
  139. package/dist/test-fixtures/index.d.mts +124 -119
  140. package/dist/test-fixtures/index.d.mts.map +1 -0
  141. package/dist/test-fixtures/index.d.ts +124 -119
  142. package/dist/test-fixtures/index.d.ts.map +1 -0
  143. package/dist/test-fixtures/index.js +460 -228
  144. package/dist/test-fixtures/index.mjs +459 -225
  145. package/dist/test-fixtures/index.mjs.map +1 -0
  146. package/dist/tool-protection/index.d.mts +343 -343
  147. package/dist/tool-protection/index.d.mts.map +1 -0
  148. package/dist/tool-protection/index.d.ts +343 -343
  149. package/dist/tool-protection/index.d.ts.map +1 -0
  150. package/dist/tool-protection/index.js +366 -285
  151. package/dist/tool-protection/index.mjs +365 -282
  152. package/dist/tool-protection/index.mjs.map +1 -0
  153. package/fixtures/bot-signal-resolution.json +142 -0
  154. package/fixtures/browser-posture-claims.json +421 -0
  155. package/fixtures/browser-posture-headers.json +46 -0
  156. package/fixtures/detection/reason-codes.json +10 -1
  157. package/fixtures/kya-http/challenge.delegation.fetcher-200.json +9 -3
  158. package/fixtures/kya-http/challenge.delegation.full.json +9 -3
  159. package/fixtures/kya-http/challenge.delegation.minimal.json +9 -3
  160. package/fixtures/kya-http/error-codes.json +7 -2
  161. package/package.json +20 -6
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/mcpi/did-key.ts","../../src/canonical-signer/key.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"sourcesContent":["/**\n * Canonical KYA-OS signing payload (RFC 8785 / JCS).\n *\n * TS half of the cross-runtime parity contract pinned in\n * `rust/crates/kya-os-engine/src/signing.rs`. Same `McpIPayload` struct,\n * same JCS canonicalization, byte-identical output. The Rust engine's\n * `signing_payload` golden vector at `tests/fixtures/reference_payload.jcs`\n * is the firewall this module asserts against — if these bytes diverge,\n * every downstream signature verification claim is suspect.\n *\n * Field set is locked to KYA-OS spec § 7.4 (eight required claims) +\n * § 7.2 (ProofMeta). Wire format is camelCase per the KYA-OS JSON schema.\n *\n * Sign-1 (#2500). Do NOT extend without ratification through\n * mcp-i-core → D-design → here.\n *\n * @see rust/crates/kya-os-engine/src/signing.rs — Rust struct + JCS function\n * @see rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs — golden vector\n */\n\nimport canonicalize from 'canonicalize';\n\n/**\n * Structured KYA-OS payload signed by an Ed25519 key.\n *\n * Mirrors `kya_os_engine::signing::McpIPayload` field-for-field. Wire\n * format uses camelCase (matches Rust's `#[serde(rename_all = \"camelCase\")]`).\n *\n * Lexicographic key order on the wire (the JCS member-ordering rule):\n * `aud, iss, nonce, requestHash, responseHash, sessionId, sub, ts`\n */\nexport interface McpIPayload {\n /** Audience — the intended recipient DID or URL. */\n aud: string;\n /** Issuer — the signing principal's DID. */\n iss: string;\n /** Subject — the principal this proof is about (often equal to `iss`). */\n sub: string;\n /** Session nonce — binds the proof to the handshake that established the session. */\n nonce: string;\n /** Session identifier from the handshake response. */\n sessionId: string;\n /** Unix epoch seconds when the proof was generated. */\n ts: number;\n /** SHA-256 hash of the JCS-canonicalized request, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n requestHash: string;\n /** SHA-256 hash of the JCS-canonicalized response, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n responseHash: string;\n}\n\n/**\n * Canonicalize an `McpIPayload` into the byte sequence the Ed25519\n * signature is computed over.\n *\n * **Determinism contract.** Same input MUST produce byte-identical\n * output, every time, every runtime. This function is the cross-runtime\n * parity contract — TS, .NET, Go, Python, and Rust runtimes all\n * implement it independently and MUST agree on the golden vector\n * pinned at `rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs`.\n *\n * The output is RFC 8785 (JCS) canonical JSON: keys sorted\n * lexicographically by UTF-16 code units, integers serialized without\n * a decimal point, strings escaped only as required, no whitespace.\n *\n * Implementation note: `canonicalize` (npm) is Erdtman's RFC 8785\n * reference implementation. If a future TS host reaches for a\n * different library, the parity firewall test (`canonical-signer.parity.test.ts`)\n * will catch the byte drift before it reaches production.\n */\nexport function canonicalSigningPayload(payload: McpIPayload): Uint8Array {\n const json = canonicalize(payload);\n if (json === undefined) {\n // canonicalize returns undefined for non-serializable inputs\n // (functions, symbols, etc.). McpIPayload's typed fields preclude\n // this, but the runtime check guards against `as McpIPayload` casts\n // at consumer call-sites that bypass the type contract.\n throw new Error('canonicalSigningPayload: payload contains non-serializable values');\n }\n return new TextEncoder().encode(json);\n}\n\n/**\n * Field set that MUST be present for an `McpIPayload` to be valid.\n *\n * Source of truth for `validateMcpIPayload`. The list mirrors the TS\n * `McpIPayload` interface — adding a field there without adding it\n * here is a hidden bypass for the runtime contract. New required\n * fields land in lockstep; new optional fields (post-Scope-1) get\n * a sibling list with a `typeof === 'undefined' || ...` predicate.\n */\nconst REQUIRED_STRING_FIELDS = [\n 'aud',\n 'iss',\n 'sub',\n 'nonce',\n 'sessionId',\n 'requestHash',\n 'responseHash',\n] as const;\n\n/**\n * Runtime type guard: confirms a `JSON.parse` output actually matches\n * `McpIPayload`. Required because `JSON.parse` returns `unknown`, and\n * casting `as McpIPayload` is a *compile-time* assertion that the\n * runtime can't honor — a payload missing required fields silently\n * surfaces as `undefined` at consumer call-sites and bypasses field-\n * presence checks (e.g., the bouncer's replay-window comparison\n * `meta.ts < now - 300` evaluates `false` for `undefined`, skipping\n * the timestamp defense entirely).\n *\n * Throws on the FIRST missing or wrong-typed field — no error\n * accumulation, since one missing claim is enough to reject the\n * envelope and producers should re-issue the entire proof rather than\n * patch field-by-field.\n *\n * @throws Error with a descriptive message identifying the offending\n * field. `parseJwsCompact` translates this into a structured\n * `JwsParseError('InvalidPayloadShape', ...)` for consumers branching\n * on the discriminant.\n */\nexport function validateMcpIPayload(value: unknown): McpIPayload {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n for (const field of REQUIRED_STRING_FIELDS) {\n if (typeof obj[field] !== 'string') {\n throw new Error(`missing or non-string required field \"${field}\" (got ${typeof obj[field]})`);\n }\n }\n\n // ts is the load-bearing exception — number, not string. The bug\n // cursor-bot caught on PR #2546 (replay-window check silently\n // skipped on missing ts) lived on this exact field check.\n if (typeof obj.ts !== 'number' || !Number.isFinite(obj.ts)) {\n throw new Error(`missing or non-finite-number required field \"ts\" (got ${typeof obj.ts})`);\n }\n\n // Validated above: every required field is present and well-typed.\n // The double cast through `unknown` is the standard TS idiom for\n // returning a narrowed type from a `Record<string, unknown>` after\n // runtime checks — necessary because TS doesn't infer narrowing\n // across a for-of loop with dynamic keys.\n return obj as unknown as McpIPayload;\n}\n","/**\n * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).\n *\n * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`\n * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase\n * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,\n * so the decoded multikey is always 34 bytes and the did:key always begins\n * `z6Mk` (a fixed consequence of the `0xed01` prefix).\n *\n * This is a PURE-JS port of the base58btc decoder in\n * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division\n * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS\n * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with\n * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare\n * Workers, and the browser). The encoder is the inverse, for tests and any\n * caller that emits a `did:key` from raw key bytes.\n */\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: Record<string, number> = (() => {\n const idx: Record<string, number> = {};\n for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;\n return idx;\n})();\n\nconst DID_KEY_PREFIX = 'did:key:';\nconst ED25519_MULTICODEC = [0xed, 0x01] as const; // ed25519-pub\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Decode a base58btc string to bytes using the repeated-division algorithm.\n * Returns null if the string contains a character outside the base58btc\n * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`\n * (kept algorithm-identical to avoid cross-runtime drift).\n */\nexport function base58btcDecode(str: string): Uint8Array | null {\n if (str.length === 0) return new Uint8Array(0);\n\n let zeros = 0;\n while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;\n\n // Sentinel-seeded little-endian byte accumulator.\n const bytes: number[] = [0];\n for (let i = 0; i < str.length; i++) {\n const value = BASE58_INDEX[str[i]];\n if (value === undefined) return null;\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Drop the trailing zero sentinel(s).\n let high = bytes.length;\n while (high > 0 && bytes[high - 1] === 0) high--;\n\n const out = new Uint8Array(zeros + high);\n for (let i = 0; i < high; i++) {\n out[zeros + high - 1 - i] = bytes[i];\n }\n return out;\n}\n\n/**\n * Encode bytes to a base58btc string — the exact inverse of\n * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value\n * is accumulated as little-endian base58 digits (×256 + byte) and emitted\n * big-endian. The high-order zero sentinel is dropped the same way the decoder\n * drops its trailing zeros, so a single `0x00` byte encodes to `\"1\"`, not `\"11\"`.\n */\nexport function base58btcEncode(bytes: Uint8Array): string {\n if (bytes.length === 0) return '';\n\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\n const digits: number[] = [0];\n for (let i = 0; i < bytes.length; i++) {\n let carry = bytes[i];\n for (let j = 0; j < digits.length; j++) {\n carry += digits[j] * 256;\n digits[j] = carry % 58;\n carry = Math.floor(carry / 58);\n }\n while (carry > 0) {\n digits.push(carry % 58);\n carry = Math.floor(carry / 58);\n }\n }\n\n // Drop the high-order zero sentinel(s); leading zero bytes become '1's.\n let high = digits.length;\n while (high > 0 && digits[high - 1] === 0) high--;\n\n let out = BASE58_ALPHABET[0].repeat(zeros);\n for (let i = high - 1; i >= 0; i--) {\n out += BASE58_ALPHABET[digits[i]];\n }\n return out;\n}\n\n/**\n * Recover the raw 32-byte Ed25519 public key from a `did:key:z6Mk…` string.\n * Returns null for any malformed input: wrong method, wrong multibase, invalid\n * base58, wrong decoded length, or a non-Ed25519 multicodec. Never throws —\n * callers treat null as \"not a verifiable Ed25519 did:key\".\n */\nexport function decodeDidKeyEd25519(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(DID_KEY_PREFIX)) return null;\n\n const suffix = did.slice(DID_KEY_PREFIX.length);\n if (!suffix.startsWith('z')) return null; // base58btc multibase prefix\n\n // A legit Ed25519 did:key body is fixed at 47 base58 chars. Cap the length\n // BEFORE the O(n^2) repeated-division decode: this keyid arrives from an\n // attacker-controlled Signature-Input header on the public pickup endpoint, so\n // an over-long body (which the 34-byte length check would reject anyway) must\n // not be allowed to burn quadratic event-loop CPU first.\n const body = suffix.slice(1);\n if (body.length > 64) return null;\n\n const decoded = base58btcDecode(body);\n if (!decoded || decoded.length !== ED25519_MULTIKEY_LENGTH) return null;\n if (decoded[0] !== ED25519_MULTICODEC[0] || decoded[1] !== ED25519_MULTICODEC[1]) return null;\n\n return decoded.slice(ED25519_MULTICODEC.length);\n}\n\n/** Recover the compressed SEC1 point from the HTTP profile's p256-pub\n * multicodec (0x1200). This runtime-independent codec validates carriage only;\n * the cryptographic consumer MUST validate that the point lies on P-256 before\n * trusting it or deriving a confirmation thumbprint. */\nexport function decodeDidKeyP256(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(`${DID_KEY_PREFIX}z`)) return null;\n const body = did.slice(DID_KEY_PREFIX.length + 1);\n // Bound the quadratic base58 decoder before processing untrusted keyids.\n if (body.length > 64) return null;\n const decoded = base58btcDecode(body);\n if (\n !decoded ||\n decoded.length !== 35 ||\n decoded[0] !== 0x80 ||\n decoded[1] !== 0x24 ||\n (decoded[2] !== 2 && decoded[2] !== 3)\n )\n return null;\n return decoded.slice(2);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a `did:key:z6Mk…` string. Throws\n * if the key is not exactly 32 bytes — an emitter handing in the wrong length\n * is a programming error, not untrusted input (unlike {@link decodeDidKeyEd25519}).\n */\nexport function encodeDidKeyEd25519(publicKey: Uint8Array): string {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `encodeDidKeyEd25519: expected a ${ED25519_PUBKEY_LENGTH}-byte Ed25519 public key, got ${\n publicKey instanceof Uint8Array ? `${publicKey.length} bytes` : typeof publicKey\n }`\n );\n }\n\n const multikey = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n multikey[0] = ED25519_MULTICODEC[0];\n multikey[1] = ED25519_MULTICODEC[1];\n multikey.set(publicKey, ED25519_MULTICODEC.length);\n\n return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;\n}\n","/**\n * Ed25519 keypair derivation for KYA-OS detached proofs.\n *\n * Derives a `KeyMaterial` bundle (signing key, public key, did:key, kid)\n * from a 32-byte seed. The derivation MUST agree byte-for-byte with\n * Rust's `ed25519_dalek::SigningKey::from_bytes` + did:key formatter so\n * H-1's committed test fixtures (`signer.seed` + `signer.public_key`)\n * derive identically across runtimes.\n *\n * `kid` form follows mcp-i-core PR #16 (multibase-as-fragment):\n * `did:key:z6Mk...#z6Mk...`. NOT `#keys-1`. NOT `#1`. The H-1\n * `stage2_did_key_fragment_resolution` test pins this on the verifier\n * side; this module pins it on the producer side.\n *\n * Sign-1 (#2500).\n */\n\nimport { getPublicKeyAsync } from '@noble/ed25519';\n// Pure-JS base58btc encode (not multiformats' `bases/base58` subpath):\n// that subpath's package.json `exports` map ships an `import` condition\n// only, no `require` — reaching it from this subpath's own CJS build\n// crashes with ERR_PACKAGE_PATH_NOT_EXPORTED before any application code\n// runs. `base58btcEncode` is the same dependency-free codec did:key\n// verification already uses elsewhere in this package.\nimport { base58btcEncode } from '../mcpi/did-key';\n\n/**\n * Multicodec prefix for Ed25519 verifying keys per the W3C did:key spec\n * (`0xed01` varint). Prepended to the 32-byte public key, base58btc-\n * encoded with the `z` multibase prefix to produce the did:key suffix.\n */\nconst ED25519_MULTICODEC_PREFIX = new Uint8Array([0xed, 0x01]);\n\n/**\n * Bundle of derived key material. Carries the signing key, the public\n * key, the canonical did:key DID, and the verification-method `kid`\n * (multibase-as-fragment per mcp-i-core PR #16).\n *\n * `signingKey` is a **copy** of the input seed, not a reference — see\n * `parseSigningKey` for the rationale. Treat the bundle as the owning\n * holder of the key material; the caller's original seed buffer is\n * safe to zero out after `parseSigningKey` returns.\n */\nexport interface KeyMaterial {\n /** The 32-byte Ed25519 secret seed (defensive copy of the input). */\n signingKey: Uint8Array;\n /** The 32-byte Ed25519 public verifying key. */\n publicKey: Uint8Array;\n /** The canonical did:key DID — `did:key:z6Mk...`. */\n did: string;\n /**\n * The verification-method id for this DID — multibase as fragment per\n * mcp-i-core PR #16 (`did:key:z6Mk...#z6Mk...`). Goes into the JWS\n * header `kid` field.\n */\n kid: string;\n}\n\n/**\n * Derive a `KeyMaterial` bundle from a 32-byte Ed25519 seed.\n *\n * The seed IS the signing key (per RFC 8032 § 5.1.5 — Ed25519 secret\n * keys are 32-byte seeds; the expanded scalar is computed at sign time).\n * Same seed → same `(publicKey, did, kid)` deterministically across\n * any RFC 8032 implementation.\n *\n * The input seed is **defensively copied** into the returned\n * `KeyMaterial.signingKey`. Subsequent mutations of the caller's\n * buffer (zeroization, key rotation, fixture reuse) do NOT affect\n * the key bundle. Callers that own the seed are free to scrub it\n * after this function returns.\n *\n * @throws if the seed is not exactly 32 bytes.\n */\nexport async function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial> {\n if (seed.length !== 32) {\n throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);\n }\n\n const publicKey = await getPublicKeyAsync(seed);\n\n // did:key z-encoded multibase per W3C spec: 0xed01 || pubkey, then\n // base58btc-encoded. The 'z' prefix is part of base58btc's multibase\n // alphabet; encode() returns it already prepended.\n const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);\n multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);\n multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);\n const multibase = `z${base58btcEncode(multibaseBytes)}`;\n const did = `did:key:${multibase}`;\n\n return {\n // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1\n // tests assert that mutating the input seed after this call does NOT\n // mutate the held key material.\n signingKey: Uint8Array.from(seed),\n publicKey,\n did,\n // mcp-i-core PR #16: the verification-method id is the multibase value\n // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's\n // stage2_did_key_fragment_resolution.\n kid: `${did}#${multibase}`,\n };\n}\n","/**\n * JWS-compact envelope construction for KYA-OS detached proofs.\n *\n * Produces wire bytes the engine's H-1 parser (#2486) accepts:\n *\n * BASE64URL(header) \".\" BASE64URL(payload) \".\" BASE64URL(signature)\n *\n * where the header is `{ \"alg\": \"EdDSA\", \"kid\": \"<verification-method-id>\" }`,\n * the payload is the JCS-canonicalized `McpIPayload`, and the signature is\n * Ed25519 over `BASE64URL(header) || '.' || BASE64URL(payload)` per\n * RFC 7515 § 5.1.\n *\n * Sign-1 (#2500). Output of this function is what every TS producer in the\n * org emits — bouncer middleware (Envelope-1), Sites-1/2 e2e helpers, future\n * Sites-4 parity drivers, the Adobe trial.\n */\n\nimport { signAsync } from '@noble/ed25519';\nimport { canonicalSigningPayload, type McpIPayload } from './payload';\nimport type { KeyMaterial } from './key';\n\n/**\n * URL-safe base64 encoding without padding (RFC 4648 § 5).\n *\n * **Node-only.** Uses Node's `Buffer` API because every current consumer\n * of this module runs on Node (Vercel functions, Sites-1/2 Playwright\n * suites, future SDKs that bundle for Node + bundler-polyfilled runtimes\n * like Vercel Edge with `nodejs_compat`). If a future consumer needs a\n * pure-Web-API runtime (Cloudflare Workers without `nodejs_compat`,\n * Deno's stricter modes), swap to `Uint8Array.toBase64()` (Stage 4 as\n * of mid-2026) or a small inline encoder — but verify against the\n * envelope.test.ts round-trip first; the `base64url` character\n * substitution path is the part that has historically tripped polyfills.\n */\nfunction base64UrlEncode(bytes: Uint8Array): string {\n return Buffer.from(bytes)\n .toString('base64')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\n/**\n * Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop\n * into `_meta.proof.jws` of the request body per KYA-OS spec § 7.4.\n *\n * The signing input is `BASE64URL(header) || '.' || BASE64URL(payload)`,\n * NOT the canonical-JSON bytes. The canonicalization happens *inside* the\n * payload base64url segment; the Ed25519 signature happens *over* the dot-\n * separated structure. This is the RFC 7515 § 5.1 contract that H-1's\n * `verify_strict` checks against.\n *\n * @param payload — the structured KYA-OS claims (eight required fields).\n * @param key — derived via `parseSigningKey(seed)`. The header `kid` is\n * set from `key.kid` (multibase-as-fragment per mcp-i-core PR #16).\n * @returns the compact-JWS string `<headerB64>.<payloadB64>.<signatureB64>`.\n */\nexport async function signMcpiEnvelope(payload: McpIPayload, key: KeyMaterial): Promise<string> {\n const header = { alg: 'EdDSA', kid: key.kid };\n const headerJson = JSON.stringify(header);\n const headerB64 = base64UrlEncode(new TextEncoder().encode(headerJson));\n\n const payloadB64 = base64UrlEncode(canonicalSigningPayload(payload));\n\n // RFC 7515 § 5.1: signing input is the ASCII bytes of the dot-separated\n // header and payload. `TextEncoder` produces UTF-8, which is identical to\n // ASCII for the base64url alphabet (`A-Za-z0-9-_`) and the literal '.'.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n const signature = await signAsync(signingInput, key.signingKey);\n const signatureB64 = base64UrlEncode(signature);\n\n return `${headerB64}.${payloadB64}.${signatureB64}`;\n}\n","/**\n * Compact-JWS parser for KYA-OS detached proofs.\n *\n * Producer-side counterpart to Sign-1's `signMcpiEnvelope`: takes the\n * wire string the engine's H-1 parser would consume and decomposes it\n * into the same logical pieces (header, payload, signature, signing\n * input). Lives in `checkpoint-shared/canonical-signer/` so producer\n * AND consumer share one wire-format implementation — the JCS / base64\n * subtleties are handled in one place, not three.\n *\n * Consumed by:\n * - `@kya-os/bouncer-middleware` (Envelope-1 / #2537)\n * - any future TS host that needs to introspect a JWS without going\n * through the WASM bridge\n *\n * The Rust engine's `jws::parse_jws_compact` is the structural mirror\n * (`rust/crates/kya-os-engine/src/jws.rs`); this module produces the\n * same logical decomposition. Cross-runtime parity here is implicit:\n * if both parsers consume the same JWS string and disagree on what's\n * inside, the H-1 fixtures would catch it.\n *\n * Sign-1 (#2500). Anti-pattern: don't write a parallel parser\n * elsewhere in the org — import from here.\n */\n\nimport type { McpIPayload } from './payload';\nimport { validateMcpIPayload } from './payload';\n\n/**\n * The decomposed compact-JWS envelope.\n *\n * `signingInput` is stored separately so callers don't have to re-encode\n * the header + payload to verify the signature — re-encoding through a\n * different base64url implementation is a known source of \"should-be-\n * identical bytes drift differently\" canonicalization bugs (the same\n * class of risk that Sign-1's JCS parity firewall guards against on the\n * payload side).\n */\nexport interface ParsedJws {\n /** Decoded JWS Protected Header. Phase 1 only supports `alg: \"EdDSA\"`. */\n header: {\n alg: 'EdDSA';\n /** Verification-method id — multibase-as-fragment for did:key per\n * mcp-i-core PR #16 (`did:key:z...#z...`); whatever the DID\n * document declares for did:web (typically `#key-1`). */\n kid: string;\n /** Optional `typ` per RFC 7515. Bouncer ignores; preserved for\n * forward-compat with future header extensions. */\n typ?: string;\n };\n /** Decoded KYA-OS payload — the eight-field signing struct. */\n payload: McpIPayload;\n /** Raw 64-byte ed25519 signature segment. */\n signatureBytes: Uint8Array;\n /**\n * `header_b64 + \".\" + payload_b64` as ASCII bytes — the signing\n * input ed25519 verifies against per RFC 7515 § 5.1. Stored\n * verbatim from the input string (no re-encode round-trip).\n */\n signingInput: Uint8Array;\n}\n\n/**\n * Discriminated error type so consumers can map parse failures to\n * appropriate response codes (400 for malformed shape, 422 for\n * unsupported alg) without string-matching error messages.\n */\nexport class JwsParseError extends Error {\n constructor(\n /** Machine-readable failure category. */\n public readonly code:\n | 'WrongSegmentCount'\n | 'InvalidBase64'\n | 'InvalidJson'\n | 'InvalidHeaderShape'\n | 'InvalidPayloadShape'\n | 'UnsupportedAlgorithm'\n | 'InvalidSignatureLength',\n message: string\n ) {\n super(message);\n this.name = 'JwsParseError';\n }\n}\n\n/**\n * Wider intermediate shape returned by `validateJwsHeader`.\n *\n * Deliberately keeps `alg` as `string` (not `'EdDSA'`) — the validator\n * only proves it's a non-empty string, not that it's the supported\n * algorithm. Narrowing to the literal type happens at the alg-check\n * site in `parseJwsCompact`, where the failure can be surfaced under\n * the correct discriminant (`UnsupportedAlgorithm`, not\n * `InvalidHeaderShape`).\n *\n * Cursor-bot review on PR #2551: the previous version returned the\n * narrowed `ParsedJws['header']` via a double cast, which lied about\n * the runtime guarantee. Strict linters (`@typescript-eslint/no-\n * unnecessary-condition`) would have flagged the downstream\n * `header.alg !== 'EdDSA'` check as always-false and suggested\n * removing it — silently letting non-EdDSA algorithms through.\n */\ninterface ValidatedJwsHeaderShape {\n alg: string;\n kid: string;\n typ?: string;\n}\n\n/**\n * Runtime type guard for the JWS Protected Header (RFC 7515 § 4).\n *\n * Mirror of `validateMcpIPayload` for the header side of the envelope.\n * Cursor-bot review on PR #2546 caught two classes of bug the unguarded\n * `JSON.parse → cast` flow let through:\n *\n * 1. **Missing `kid`** — header parses, `header.kid === undefined`\n * typed as string, propagates into the bouncer's sidecar and gets\n * dropped by JSON.stringify → malformed payload at the remote.\n * 2. **Null JSON header** (`bnVsbA` base64url) — `JSON.parse` returns\n * `null`, `header.alg` access throws TypeError, escapes the\n * bouncer's `instanceof JwsParseError` guard → leaks as 500. Easy\n * DoS/probe vector.\n *\n * Both go away by validating before any property access. Throws plain\n * Error; `parseJwsCompact` translates into `JwsParseError('InvalidHeaderShape', …)`.\n *\n * Returns `ValidatedJwsHeaderShape` with `alg: string` (not `'EdDSA'`).\n * The literal-type narrowing is the caller's responsibility — keeping\n * the failure-category boundary clean: shape failures from this\n * validator surface as `InvalidHeaderShape`; algorithm-support failures\n * surface separately as `UnsupportedAlgorithm`.\n */\nfunction validateJwsHeader(value: unknown): ValidatedJwsHeaderShape {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n if (typeof obj.alg !== 'string' || obj.alg.length === 0) {\n throw new Error(`missing or non-string required field \"alg\" (got ${typeof obj.alg})`);\n }\n if (typeof obj.kid !== 'string' || obj.kid.length === 0) {\n throw new Error(`missing or non-string required field \"kid\" (got ${typeof obj.kid})`);\n }\n if (obj.typ !== undefined && typeof obj.typ !== 'string') {\n throw new Error(`optional field \"typ\" must be a string when present (got ${typeof obj.typ})`);\n }\n\n return obj as unknown as ValidatedJwsHeaderShape;\n}\n\n/**\n * Parse a compact-JWS string per RFC 7515 § 3.1 + § 5.1.\n *\n * Three segments separated by `.`, each base64url-encoded\n * (`A-Za-z0-9-_`, no padding). Header is JSON with at minimum\n * `alg: \"EdDSA\"` + `kid`. Payload is the JCS-canonicalized\n * `McpIPayload`. Signature segment decodes to exactly 64 bytes\n * (Ed25519 fixed-length per RFC 8032 § 5.1.6).\n *\n * @throws {@link JwsParseError} with a structured `code` for malformed\n * shape, invalid base64url, invalid JSON, unsupported algorithm, or\n * wrong signature length. Cryptographic verification is OUT of scope\n * — the engine (or `@noble/ed25519` round-trip) does that against\n * `signatureBytes` over `signingInput`.\n */\nexport function parseJwsCompact(jws: string): ParsedJws {\n const parts = jws.split('.');\n if (parts.length !== 3) {\n throw new JwsParseError(\n 'WrongSegmentCount',\n `Expected 3 dot-separated segments per RFC 7515 § 3.1; got ${parts.length}`\n );\n }\n const [headerB64, payloadB64, signatureB64] = parts;\n\n let headerJson: unknown;\n try {\n headerJson = JSON.parse(base64UrlDecodeToString(headerB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS header is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation for the header. Two cursor-bot findings on\n // PR #2546 motivate this:\n //\n // 1. A header with `{\"alg\":\"EdDSA\"}` (no `kid`) parsed successfully\n // and surfaced `header.kid === undefined` typed as string. The\n // bouncer's sidecar synthesis copied that into `meta.kid`, which\n // JSON.stringify silently drops, producing a malformed `{jws,\n // meta}` payload at the remote endpoint.\n //\n // 2. A header that decodes to JSON literal `null` (base64url of\n // `\"null\"` → `bnVsbA`) made `JSON.parse` succeed and assign\n // `null` to `header`. The subsequent `header.alg` access threw\n // a TypeError, which the bouncer's `instanceof JwsParseError`\n // guard let through — a 500 API_ERROR instead of a clean 401.\n // Trivially exploitable by an attacker.\n //\n // Both classes go away by validating the shape before any property\n // access. Same pattern as `validateMcpIPayload`.\n //\n // `validatedHeader` holds the wider `ValidatedJwsHeaderShape` (alg as\n // string) so the algorithm-support check below isn't redundant from\n // TS's perspective. After the check passes, we narrow to the final\n // `ParsedJws['header']` (alg as the 'EdDSA' literal). Cursor-bot\n // review on PR #2551: returning the narrowed type from the validator\n // would lie about the runtime guarantee and let strict linters\n // remove the alg check as \"always-false.\"\n let validatedHeader: ValidatedJwsHeaderShape;\n try {\n validatedHeader = validateJwsHeader(headerJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidHeaderShape',\n `JWS header does not match expected shape: ${(cause as Error).message}`\n );\n }\n if (validatedHeader.alg !== 'EdDSA') {\n throw new JwsParseError(\n 'UnsupportedAlgorithm',\n `Unsupported JWS alg \"${validatedHeader.alg}\"; Phase 1 only supports EdDSA`\n );\n }\n // Safe narrowing: alg has been runtime-checked === 'EdDSA' above.\n const header: ParsedJws['header'] = {\n alg: 'EdDSA',\n kid: validatedHeader.kid,\n ...(validatedHeader.typ !== undefined ? { typ: validatedHeader.typ } : {}),\n };\n\n let payloadJson: unknown;\n try {\n payloadJson = JSON.parse(base64UrlDecodeToString(payloadB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS payload is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation. Cursor-bot review on PR #2546: parsing\n // and casting `as McpIPayload` is a TS-only assertion the runtime\n // can't honor. A crafted JWS missing required fields (notably `ts`)\n // would surface as `undefined` at consumer call-sites and silently\n // skip field-presence checks (e.g., the bouncer's replay-window\n // comparison evaluates `false` on an undefined operand). Validating\n // here means every consumer of `parseJwsCompact` gets a payload\n // whose runtime guarantee matches its TypeScript guarantee.\n let payload: McpIPayload;\n try {\n payload = validateMcpIPayload(payloadJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidPayloadShape',\n `JWS payload does not match McpIPayload shape: ${(cause as Error).message}`\n );\n }\n\n // Validate the base64url alphabet on the signature segment BEFORE\n // decoding. Cursor-bot review on PR #2546: Node's `Buffer.from(s,\n // 'base64')` silently drops invalid characters rather than throwing,\n // so without this check `InvalidBase64` would be unreachable and a\n // signature with stray punctuation would surface as the wrong error\n // code (`InvalidSignatureLength` from the silent truncation). The\n // header/payload segments are validated implicitly by the JSON.parse\n // step that follows them, so they don't need their own alphabet check.\n if (!BASE64URL_ALPHABET.test(signatureB64)) {\n throw new JwsParseError(\n 'InvalidBase64',\n `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 § 5)`\n );\n }\n const signatureBytes = base64UrlDecodeToBytes(signatureB64);\n if (signatureBytes.length !== 64) {\n throw new JwsParseError(\n 'InvalidSignatureLength',\n `Ed25519 signatures are 64 bytes (RFC 8032 § 5.1.6); got ${signatureBytes.length}`\n );\n }\n\n // Signing input is the ASCII bytes of the dot-separated header + payload.\n // Stored verbatim from the input string so callers don't have to re-encode\n // through a (potentially-different) base64url implementation to verify.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n\n return { header, payload, signatureBytes, signingInput };\n}\n\n/**\n * Strict base64url alphabet check (RFC 4648 § 5). The set is\n * `A-Za-z0-9-_` plus optional `=` padding. We use this to validate\n * input BEFORE handing to Node's `Buffer.from(s, 'base64')`, which\n * silently drops invalid characters rather than throwing — bypassing\n * the discriminated `InvalidBase64` error code consumers rely on for\n * HTTP-status mapping.\n *\n * The empty-string case is rejected by the regex (`+` requires ≥1\n * char), which is the desired behavior — an empty segment is a\n * different bug class from \"non-base64 characters in a non-empty\n * segment\" but both warrant the same `InvalidBase64` response.\n */\nconst BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;\n\n/**\n * Decode URL-safe base64 (with optional padding) to bytes. RFC 4648 § 5.\n * Tolerates the no-padding form Sign-1 produces AND the padded form\n * some external producers emit.\n *\n * **Caller must validate the input alphabet first** if they want\n * `InvalidBase64` reported as a distinct error class — Node's underlying\n * `Buffer.from(s, 'base64')` silently truncates on invalid characters\n * rather than throwing.\n */\nfunction base64UrlDecodeToBytes(s: string): Uint8Array {\n const padded = s.replace(/-/g, '+').replace(/_/g, '/');\n const padLen = padded.length % 4 === 0 ? 0 : 4 - (padded.length % 4);\n return new Uint8Array(Buffer.from(padded + '='.repeat(padLen), 'base64'));\n}\n\nfunction base64UrlDecodeToString(s: string): string {\n return Buffer.from(base64UrlDecodeToBytes(s)).toString('utf-8');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,wBAAwB,SAAkC;CACxE,MAAM,OAAO,aAAa,OAAO;CACjC,IAAI,SAAS,QAKX,MAAM,IAAI,MAAM,mEAAmE;CAErF,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI;AACtC;;;;;;;;;;AAWA,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,oBAAoB,OAA6B;CAC/D,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,MAAM,IAAI,MAAM,6BAA6B,UAAU,OAAO,SAAS,OAAO,OAAO;CAEvF,MAAM,MAAM;CAEZ,KAAK,MAAM,SAAS,wBAClB,IAAI,OAAO,IAAI,WAAW,UACxB,MAAM,IAAI,MAAM,yCAAyC,MAAM,SAAS,OAAO,IAAI,OAAO,EAAE;CAOhG,IAAI,OAAO,IAAI,OAAO,YAAY,CAAC,OAAO,SAAS,IAAI,EAAE,GACvD,MAAM,IAAI,MAAM,yDAAyD,OAAO,IAAI,GAAG,EAAE;CAQ3F,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;AC/HA,MAAM,kBAAkB;A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I;EACF,UAAU,oBAAoB,WAAW;CAC3C,SAAS,OAAO;EACd,MAAM,IAAI,cACR,uBACA,iDAAkD,MAAgB,SACpE;CACF;CAUA,IAAI,CAAC,mBAAmB,KAAK,YAAY,GACvC,MAAM,IAAI,cACR,iBACA,yFACF;CAEF,MAAM,iBAAiB,uBAAuB,YAAY;CAC1D,IAAI,eAAe,WAAW,IAC5B,MAAM,IAAI,cACR,0BACA,2DAA2D,eAAe,QAC5E;CAMF,MAAM,eAAe,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG,UAAU,GAAG,YAAY;CAE1E,OAAO;EAAE;EAAQ;EAAS;EAAgB;CAAa;AACzD;;;;;;;;;;;;;;AAeA,MAAM,qBAAqB;;;;;;;;;;;AAY3B,SAAS,uBAAuB,GAAuB;CACrD,MAAM,SAAS,EAAE,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG;CACrD,MAAM,SAAS,OAAO,SAAS,MAAM,IAAI,IAAI,IAAK,OAAO,SAAS;CAClE,OAAO,IAAI,WAAW,OAAO,KAAK,SAAS,IAAI,OAAO,MAAM,GAAG,QAAQ,CAAC;AAC1E;AAEA,SAAS,wBAAwB,GAAmB;CAClD,OAAO,OAAO,KAAK,uBAAuB,CAAC,CAAC,CAAC,CAAC,SAAS,OAAO;AAChE"}
@@ -0,0 +1,30 @@
1
+ import { C as ZodObject, O as ZodString, P as output, R as $strip, S as ZodNumber, b as ZodLiteral, t as external_d_exports } from "./external-jr_S4iSS.mjs";
2
+ import { JWK } from "jose";
3
+ //#region src/clearance.d.ts
4
+ export declare const CLEARANCE_TTL_SECONDS = 600;
5
+ export declare const CLEARANCE_ISSUER = "checkpoint:human-step-up:v1";
6
+ export declare const CLEARANCE_TYPE = "checkpoint-clearance+jwt";
7
+ export declare const CLEARANCE_COOKIE_NAME = "__Host-kya_clearance";
8
+ export declare const ClearanceSchema: ZodObject<{
9
+ v: ZodLiteral<1>;
10
+ project_id: ZodString;
11
+ origin: ZodString;
12
+ binding: ZodString;
13
+ iat: ZodNumber;
14
+ exp: ZodNumber;
15
+ }, $strip>;
16
+ export type Clearance = output<typeof ClearanceSchema>;
17
+ export interface ClearanceKeyConfig {
18
+ publicKey: JWK;
19
+ keyId: string;
20
+ origin: string;
21
+ }
22
+ export interface ClearanceSigningConfig extends ClearanceKeyConfig {
23
+ privateKey: JWK;
24
+ }
25
+ export declare function clearanceSessionBinding(sessionCookieValue: string): Promise<string>;
26
+ export declare function signClearance(config: ClearanceSigningConfig, projectId: string, sessionCookieValue: string, now?: number): Promise<string>;
27
+ export declare function verifyClearance(token: string | undefined, config: ClearanceKeyConfig, projectId: string, sessionCookieValue: string | undefined, now?: number): Promise<boolean>;
28
+ export declare function readNamedCookie(header: string | null | undefined, name: string): string | undefined;
29
+ //#endregion
30
+ //# sourceMappingURL=clearance.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clearance.d.mts","names":[],"sources":["../src/clearance.ts"],"mappings":";;;qBAqBa;qBACA;qBACA;qBACA;qBAEA,iBAAe;;;;;;;GAW1B;YACU,YAAY,cAAe;iBAEtB;EAEf,WAAW;EACX;EACA;;iBAGe,+BAA+B;EAG9C,YAAY;;wBAeQ,wBAAwB,6BAA6B;wBAOrD,cACpB,QAAQ,wBACR,mBACA,4BACA,eACC;wBA8BmB,gBACpB,2BACA,QAAQ,oBACR,mBACA,wCACA,eACC;wBAwCa,gBACd,mCACA"}
@@ -0,0 +1,30 @@
1
+ import { C as ZodObject, O as ZodString, P as output, R as $strip, S as ZodNumber, b as ZodLiteral, t as external_d_exports } from "./external-jr_S4iSS.js";
2
+ import { JWK } from "jose";
3
+ //#region src/clearance.d.ts
4
+ export declare const CLEARANCE_TTL_SECONDS = 600;
5
+ export declare const CLEARANCE_ISSUER = "checkpoint:human-step-up:v1";
6
+ export declare const CLEARANCE_TYPE = "checkpoint-clearance+jwt";
7
+ export declare const CLEARANCE_COOKIE_NAME = "__Host-kya_clearance";
8
+ export declare const ClearanceSchema: ZodObject<{
9
+ v: ZodLiteral<1>;
10
+ project_id: ZodString;
11
+ origin: ZodString;
12
+ binding: ZodString;
13
+ iat: ZodNumber;
14
+ exp: ZodNumber;
15
+ }, $strip>;
16
+ export type Clearance = output<typeof ClearanceSchema>;
17
+ export interface ClearanceKeyConfig {
18
+ publicKey: JWK;
19
+ keyId: string;
20
+ origin: string;
21
+ }
22
+ export interface ClearanceSigningConfig extends ClearanceKeyConfig {
23
+ privateKey: JWK;
24
+ }
25
+ export declare function clearanceSessionBinding(sessionCookieValue: string): Promise<string>;
26
+ export declare function signClearance(config: ClearanceSigningConfig, projectId: string, sessionCookieValue: string, now?: number): Promise<string>;
27
+ export declare function verifyClearance(token: string | undefined, config: ClearanceKeyConfig, projectId: string, sessionCookieValue: string | undefined, now?: number): Promise<boolean>;
28
+ export declare function readNamedCookie(header: string | null | undefined, name: string): string | undefined;
29
+ //#endregion
30
+ //# sourceMappingURL=clearance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clearance.d.ts","names":[],"sources":["../src/clearance.ts"],"mappings":";;;qBAqBa;qBACA;qBACA;qBACA;qBAEA,iBAAe;;;;;;;GAW1B;YACU,YAAY,cAAe;iBAEtB;EAEf,WAAW;EACX;EACA;;iBAGe,+BAA+B;EAG9C,YAAY;;wBAeQ,wBAAwB,6BAA6B;wBAOrD,cACpB,QAAQ,wBACR,mBACA,4BACA,eACC;wBA8BmB,gBACpB,2BACA,QAAQ,oBACR,mBACA,wCACA,eACC;wBAwCa,gBACd,mCACA"}
@@ -0,0 +1,120 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_schemas = require('./schemas-BmjNLAE7.js');
3
+ const require_project_verification_key = require('./project-verification-key-C3L5rd8a.js');
4
+ let jose = require("jose");
5
+
6
+ //#region src/clearance.ts
7
+ /**
8
+ * Human step-up clearance (gateway-enforcement-step-up, roadmap item 5).
9
+ *
10
+ * A `human_step_up` Cedar challenge (`@challenge_type("human_step_up")`) is
11
+ * rendered by the gateway as a hosted Turnstile page. When Cloudflare
12
+ * siteverify confirms the token, the gateway mints `__Host-kya_clearance`:
13
+ * an ES256 JWT signed with the project's posture key (the SAME EC P-256
14
+ * keypair `browser-posture.ts` uses — one project keypair, two roles: the
15
+ * public half verifies inbound posture attestations, the private half
16
+ * signs this outbound clearance), bound to the session cookie, 10-minute
17
+ * lifetime. A request carrying a valid clearance reaches Cedar with
18
+ * `context.integrity = "cleared"`.
19
+ *
20
+ * Mirrors `browser-posture.ts`'s shape deliberately (same TTL-boundedness,
21
+ * same `sign`/`verify` pair, same session-binding-by-hash trick) so the two
22
+ * modules read as one family rather than two ad hoc JWT schemes.
23
+ */
24
+ const CLEARANCE_TTL_SECONDS = 600;
25
+ const CLEARANCE_ISSUER = "checkpoint:human-step-up:v1";
26
+ const CLEARANCE_TYPE = "checkpoint-clearance+jwt";
27
+ const CLEARANCE_COOKIE_NAME = "__Host-kya_clearance";
28
+ const ClearanceSchema = require_schemas.object({
29
+ v: require_schemas.literal(1),
30
+ project_id: require_schemas.string().min(1).max(128),
31
+ origin: require_schemas.string().url(),
32
+ /** SHA-256 hex of the session cookie this clearance is bound to — see
33
+ * `postureSessionBinding`'s identical trick in `browser-posture.ts`, so a
34
+ * stolen clearance token is useless without the session cookie it was
35
+ * minted alongside. */
36
+ binding: require_schemas.string().regex(/^[a-f0-9]{64}$/),
37
+ iat: require_schemas.number().int().nonnegative(),
38
+ exp: require_schemas.number().int().positive()
39
+ });
40
+ function validOrigin(origin) {
41
+ try {
42
+ const url = new URL(origin);
43
+ return url.protocol === "https:" && url.origin === origin;
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+ /** Same binding trick as `postureSessionBinding` — a plain SHA-256 of the
49
+ * session cookie value, so the clearance is worthless if replayed without
50
+ * the session cookie it was minted alongside. */
51
+ async function clearanceSessionBinding(sessionCookieValue) {
52
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(sessionCookieValue));
53
+ return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join("");
54
+ }
55
+ /** Mint a clearance JWT after Cloudflare siteverify accepts the Turnstile
56
+ * token. Called ONLY on `/__kya/challenge`'s verification path. */
57
+ async function signClearance(config, projectId, sessionCookieValue, now = Math.floor(Date.now() / 1e3)) {
58
+ if (!validOrigin(config.origin) || config.privateKey.kty !== "EC" || config.privateKey.crv !== "P-256" || !config.privateKey.d || !config.keyId) throw new Error("Invalid clearance signing configuration");
59
+ const claims = ClearanceSchema.parse({
60
+ v: 1,
61
+ project_id: projectId,
62
+ origin: config.origin,
63
+ binding: await clearanceSessionBinding(sessionCookieValue),
64
+ iat: now,
65
+ exp: now + 600
66
+ });
67
+ const key = await (0, jose.importJWK)(config.privateKey, "ES256");
68
+ return new jose.SignJWT(claims).setProtectedHeader({
69
+ alg: "ES256",
70
+ typ: CLEARANCE_TYPE,
71
+ kid: config.keyId
72
+ }).setIssuer(CLEARANCE_ISSUER).setAudience(claims.origin).sign(key);
73
+ }
74
+ /** Verify a presented clearance JWT is valid, unexpired, and bound to
75
+ * THIS session cookie. Returns `undefined` (never throws) on any failure —
76
+ * an absent/invalid clearance is always safe: `context.integrity` simply
77
+ * stays unset instead of `"cleared"`. */
78
+ async function verifyClearance(token, config, projectId, sessionCookieValue, now = Math.floor(Date.now() / 1e3)) {
79
+ if (!token || token.length > 2e3 || !sessionCookieValue || !validOrigin(config.origin) || config.publicKey.d || config.publicKey.kty !== "EC" || config.publicKey.crv !== "P-256") return false;
80
+ try {
81
+ const publicKey = require_project_verification_key.projectVerificationKey(token, config, now);
82
+ if (!publicKey) return false;
83
+ const key = await (0, jose.importJWK)(publicKey, "ES256");
84
+ const { payload } = await (0, jose.jwtVerify)(token, key, {
85
+ algorithms: ["ES256"],
86
+ issuer: CLEARANCE_ISSUER,
87
+ audience: config.origin,
88
+ typ: CLEARANCE_TYPE,
89
+ currentDate: /* @__PURE__ */ new Date(now * 1e3)
90
+ });
91
+ const parsed = ClearanceSchema.safeParse(payload);
92
+ if (!parsed.success) return false;
93
+ const claims = parsed.data;
94
+ return claims.project_id === projectId && claims.origin === config.origin && claims.iat <= now + 5 && claims.exp > now && claims.exp - claims.iat <= 600 && claims.binding === await clearanceSessionBinding(sessionCookieValue);
95
+ } catch {
96
+ return false;
97
+ }
98
+ }
99
+ /** Read one named cookie from a raw `Cookie` header. Duplicate cookies are
100
+ * ambiguous, so none is trusted — same posture as `readPostureCookie`. */
101
+ function readNamedCookie(header, name) {
102
+ const matches = (header ?? "").split(";").map((s) => s.trim()).filter((s) => s.startsWith(`${name}=`));
103
+ if (matches.length !== 1) return void 0;
104
+ try {
105
+ return decodeURIComponent(matches[0].slice(name.length + 1));
106
+ } catch {
107
+ return;
108
+ }
109
+ }
110
+
111
+ //#endregion
112
+ exports.CLEARANCE_COOKIE_NAME = CLEARANCE_COOKIE_NAME;
113
+ exports.CLEARANCE_ISSUER = CLEARANCE_ISSUER;
114
+ exports.CLEARANCE_TTL_SECONDS = CLEARANCE_TTL_SECONDS;
115
+ exports.CLEARANCE_TYPE = CLEARANCE_TYPE;
116
+ exports.ClearanceSchema = ClearanceSchema;
117
+ exports.clearanceSessionBinding = clearanceSessionBinding;
118
+ exports.readNamedCookie = readNamedCookie;
119
+ exports.signClearance = signClearance;
120
+ exports.verifyClearance = verifyClearance;
@@ -0,0 +1,112 @@
1
+ import { _ as number, h as literal, v as object, x as string } from "./schemas-DxY-dk9y.mjs";
2
+ import { t as projectVerificationKey } from "./project-verification-key-CgSVX9_m.mjs";
3
+ import { SignJWT, importJWK, jwtVerify } from "jose";
4
+
5
+ //#region src/clearance.ts
6
+ /**
7
+ * Human step-up clearance (gateway-enforcement-step-up, roadmap item 5).
8
+ *
9
+ * A `human_step_up` Cedar challenge (`@challenge_type("human_step_up")`) is
10
+ * rendered by the gateway as a hosted Turnstile page. When Cloudflare
11
+ * siteverify confirms the token, the gateway mints `__Host-kya_clearance`:
12
+ * an ES256 JWT signed with the project's posture key (the SAME EC P-256
13
+ * keypair `browser-posture.ts` uses — one project keypair, two roles: the
14
+ * public half verifies inbound posture attestations, the private half
15
+ * signs this outbound clearance), bound to the session cookie, 10-minute
16
+ * lifetime. A request carrying a valid clearance reaches Cedar with
17
+ * `context.integrity = "cleared"`.
18
+ *
19
+ * Mirrors `browser-posture.ts`'s shape deliberately (same TTL-boundedness,
20
+ * same `sign`/`verify` pair, same session-binding-by-hash trick) so the two
21
+ * modules read as one family rather than two ad hoc JWT schemes.
22
+ */
23
+ const CLEARANCE_TTL_SECONDS = 600;
24
+ const CLEARANCE_ISSUER = "checkpoint:human-step-up:v1";
25
+ const CLEARANCE_TYPE = "checkpoint-clearance+jwt";
26
+ const CLEARANCE_COOKIE_NAME = "__Host-kya_clearance";
27
+ const ClearanceSchema = object({
28
+ v: literal(1),
29
+ project_id: string().min(1).max(128),
30
+ origin: string().url(),
31
+ /** SHA-256 hex of the session cookie this clearance is bound to — see
32
+ * `postureSessionBinding`'s identical trick in `browser-posture.ts`, so a
33
+ * stolen clearance token is useless without the session cookie it was
34
+ * minted alongside. */
35
+ binding: string().regex(/^[a-f0-9]{64}$/),
36
+ iat: number().int().nonnegative(),
37
+ exp: number().int().positive()
38
+ });
39
+ function validOrigin(origin) {
40
+ try {
41
+ const url = new URL(origin);
42
+ return url.protocol === "https:" && url.origin === origin;
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+ /** Same binding trick as `postureSessionBinding` — a plain SHA-256 of the
48
+ * session cookie value, so the clearance is worthless if replayed without
49
+ * the session cookie it was minted alongside. */
50
+ async function clearanceSessionBinding(sessionCookieValue) {
51
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(sessionCookieValue));
52
+ return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join("");
53
+ }
54
+ /** Mint a clearance JWT after Cloudflare siteverify accepts the Turnstile
55
+ * token. Called ONLY on `/__kya/challenge`'s verification path. */
56
+ async function signClearance(config, projectId, sessionCookieValue, now = Math.floor(Date.now() / 1e3)) {
57
+ if (!validOrigin(config.origin) || config.privateKey.kty !== "EC" || config.privateKey.crv !== "P-256" || !config.privateKey.d || !config.keyId) throw new Error("Invalid clearance signing configuration");
58
+ const claims = ClearanceSchema.parse({
59
+ v: 1,
60
+ project_id: projectId,
61
+ origin: config.origin,
62
+ binding: await clearanceSessionBinding(sessionCookieValue),
63
+ iat: now,
64
+ exp: now + 600
65
+ });
66
+ const key = await importJWK(config.privateKey, "ES256");
67
+ return new SignJWT(claims).setProtectedHeader({
68
+ alg: "ES256",
69
+ typ: CLEARANCE_TYPE,
70
+ kid: config.keyId
71
+ }).setIssuer(CLEARANCE_ISSUER).setAudience(claims.origin).sign(key);
72
+ }
73
+ /** Verify a presented clearance JWT is valid, unexpired, and bound to
74
+ * THIS session cookie. Returns `undefined` (never throws) on any failure —
75
+ * an absent/invalid clearance is always safe: `context.integrity` simply
76
+ * stays unset instead of `"cleared"`. */
77
+ async function verifyClearance(token, config, projectId, sessionCookieValue, now = Math.floor(Date.now() / 1e3)) {
78
+ if (!token || token.length > 2e3 || !sessionCookieValue || !validOrigin(config.origin) || config.publicKey.d || config.publicKey.kty !== "EC" || config.publicKey.crv !== "P-256") return false;
79
+ try {
80
+ const publicKey = projectVerificationKey(token, config, now);
81
+ if (!publicKey) return false;
82
+ const key = await importJWK(publicKey, "ES256");
83
+ const { payload } = await jwtVerify(token, key, {
84
+ algorithms: ["ES256"],
85
+ issuer: CLEARANCE_ISSUER,
86
+ audience: config.origin,
87
+ typ: CLEARANCE_TYPE,
88
+ currentDate: /* @__PURE__ */ new Date(now * 1e3)
89
+ });
90
+ const parsed = ClearanceSchema.safeParse(payload);
91
+ if (!parsed.success) return false;
92
+ const claims = parsed.data;
93
+ return claims.project_id === projectId && claims.origin === config.origin && claims.iat <= now + 5 && claims.exp > now && claims.exp - claims.iat <= 600 && claims.binding === await clearanceSessionBinding(sessionCookieValue);
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+ /** Read one named cookie from a raw `Cookie` header. Duplicate cookies are
99
+ * ambiguous, so none is trusted — same posture as `readPostureCookie`. */
100
+ function readNamedCookie(header, name) {
101
+ const matches = (header ?? "").split(";").map((s) => s.trim()).filter((s) => s.startsWith(`${name}=`));
102
+ if (matches.length !== 1) return void 0;
103
+ try {
104
+ return decodeURIComponent(matches[0].slice(name.length + 1));
105
+ } catch {
106
+ return;
107
+ }
108
+ }
109
+
110
+ //#endregion
111
+ export { CLEARANCE_COOKIE_NAME, CLEARANCE_ISSUER, CLEARANCE_TTL_SECONDS, CLEARANCE_TYPE, ClearanceSchema, clearanceSessionBinding, readNamedCookie, signClearance, verifyClearance };
112
+ //# sourceMappingURL=clearance.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clearance.mjs","names":["z.object","z.literal","z.string","z.number"],"sources":["../src/clearance.ts"],"sourcesContent":["/**\n * Human step-up clearance (gateway-enforcement-step-up, roadmap item 5).\n *\n * A `human_step_up` Cedar challenge (`@challenge_type(\"human_step_up\")`) is\n * rendered by the gateway as a hosted Turnstile page. When Cloudflare\n * siteverify confirms the token, the gateway mints `__Host-kya_clearance`:\n * an ES256 JWT signed with the project's posture key (the SAME EC P-256\n * keypair `browser-posture.ts` uses — one project keypair, two roles: the\n * public half verifies inbound posture attestations, the private half\n * signs this outbound clearance), bound to the session cookie, 10-minute\n * lifetime. A request carrying a valid clearance reaches Cedar with\n * `context.integrity = \"cleared\"`.\n *\n * Mirrors `browser-posture.ts`'s shape deliberately (same TTL-boundedness,\n * same `sign`/`verify` pair, same session-binding-by-hash trick) so the two\n * modules read as one family rather than two ad hoc JWT schemes.\n */\nimport { importJWK, jwtVerify, SignJWT, type JWK } from 'jose';\nimport { z } from 'zod';\nimport { projectVerificationKey } from './project-verification-key';\n\nexport const CLEARANCE_TTL_SECONDS = 600; // 10 minutes\nexport const CLEARANCE_ISSUER = 'checkpoint:human-step-up:v1';\nexport const CLEARANCE_TYPE = 'checkpoint-clearance+jwt';\nexport const CLEARANCE_COOKIE_NAME = '__Host-kya_clearance';\n\nexport const ClearanceSchema = z.object({\n v: z.literal(1),\n project_id: z.string().min(1).max(128),\n origin: z.string().url(),\n /** SHA-256 hex of the session cookie this clearance is bound to — see\n * `postureSessionBinding`'s identical trick in `browser-posture.ts`, so a\n * stolen clearance token is useless without the session cookie it was\n * minted alongside. */\n binding: z.string().regex(/^[a-f0-9]{64}$/),\n iat: z.number().int().nonnegative(),\n exp: z.number().int().positive(),\n});\nexport type Clearance = z.infer<typeof ClearanceSchema>;\n\nexport interface ClearanceKeyConfig {\n /** Project's posture keypair public half — verify only. */\n publicKey: JWK;\n keyId: string;\n origin: string;\n}\n\nexport interface ClearanceSigningConfig extends ClearanceKeyConfig {\n /** Project's posture keypair private half — sign only. Never accepted\n * from a cookie, header, or any request-controlled input. */\n privateKey: JWK;\n}\n\nfunction validOrigin(origin: string): boolean {\n try {\n const url = new URL(origin);\n return url.protocol === 'https:' && url.origin === origin;\n } catch {\n return false;\n }\n}\n\n/** Same binding trick as `postureSessionBinding` — a plain SHA-256 of the\n * session cookie value, so the clearance is worthless if replayed without\n * the session cookie it was minted alongside. */\nexport async function clearanceSessionBinding(sessionCookieValue: string): Promise<string> {\n const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(sessionCookieValue));\n return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** Mint a clearance JWT after Cloudflare siteverify accepts the Turnstile\n * token. Called ONLY on `/__kya/challenge`'s verification path. */\nexport async function signClearance(\n config: ClearanceSigningConfig,\n projectId: string,\n sessionCookieValue: string,\n now = Math.floor(Date.now() / 1000)\n): Promise<string> {\n if (\n !validOrigin(config.origin) ||\n config.privateKey.kty !== 'EC' ||\n config.privateKey.crv !== 'P-256' ||\n !config.privateKey.d ||\n !config.keyId\n ) {\n throw new Error('Invalid clearance signing configuration');\n }\n const claims: Clearance = ClearanceSchema.parse({\n v: 1,\n project_id: projectId,\n origin: config.origin,\n binding: await clearanceSessionBinding(sessionCookieValue),\n iat: now,\n exp: now + CLEARANCE_TTL_SECONDS,\n });\n const key = await importJWK(config.privateKey, 'ES256');\n return new SignJWT(claims)\n .setProtectedHeader({ alg: 'ES256', typ: CLEARANCE_TYPE, kid: config.keyId })\n .setIssuer(CLEARANCE_ISSUER)\n .setAudience(claims.origin)\n .sign(key);\n}\n\n/** Verify a presented clearance JWT is valid, unexpired, and bound to\n * THIS session cookie. Returns `undefined` (never throws) on any failure —\n * an absent/invalid clearance is always safe: `context.integrity` simply\n * stays unset instead of `\"cleared\"`. */\nexport async function verifyClearance(\n token: string | undefined,\n config: ClearanceKeyConfig,\n projectId: string,\n sessionCookieValue: string | undefined,\n now = Math.floor(Date.now() / 1000)\n): Promise<boolean> {\n if (\n !token ||\n token.length > 2000 ||\n !sessionCookieValue ||\n !validOrigin(config.origin) ||\n config.publicKey.d ||\n config.publicKey.kty !== 'EC' ||\n config.publicKey.crv !== 'P-256'\n )\n return false;\n try {\n const publicKey = projectVerificationKey(token, config, now);\n if (!publicKey) return false;\n const key = await importJWK(publicKey, 'ES256');\n const { payload } = await jwtVerify(token, key, {\n algorithms: ['ES256'],\n issuer: CLEARANCE_ISSUER,\n audience: config.origin,\n typ: CLEARANCE_TYPE,\n currentDate: new Date(now * 1000),\n });\n const parsed = ClearanceSchema.safeParse(payload);\n if (!parsed.success) return false;\n const claims = parsed.data;\n return (\n claims.project_id === projectId &&\n claims.origin === config.origin &&\n claims.iat <= now + 5 &&\n claims.exp > now &&\n claims.exp - claims.iat <= CLEARANCE_TTL_SECONDS &&\n claims.binding === (await clearanceSessionBinding(sessionCookieValue))\n );\n } catch {\n return false;\n }\n}\n\n/** Read one named cookie from a raw `Cookie` header. Duplicate cookies are\n * ambiguous, so none is trusted — same posture as `readPostureCookie`. */\nexport function readNamedCookie(\n header: string | null | undefined,\n name: string\n): string | undefined {\n const matches = (header ?? '')\n .split(';')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(`${name}=`));\n if (matches.length !== 1) return undefined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