@kya-os/checkpoint-shared 1.9.0 → 1.11.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 (207) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/README.md +1 -1
  3. package/dist/base64url-BbVG8f-v.js +65 -0
  4. package/dist/base64url-D2MvsR20.mjs +49 -0
  5. package/dist/base64url-D2MvsR20.mjs.map +1 -0
  6. package/dist/beacon-forward-secret/index.d.mts +4 -0
  7. package/dist/beacon-forward-secret/index.d.mts.map +1 -0
  8. package/dist/beacon-forward-secret/index.d.ts +4 -0
  9. package/dist/beacon-forward-secret/index.d.ts.map +1 -0
  10. package/dist/beacon-forward-secret/index.js +15 -0
  11. package/dist/beacon-forward-secret/index.mjs +15 -0
  12. package/dist/beacon-forward-secret/index.mjs.map +1 -0
  13. package/dist/beacon-types/index.d.mts +53 -1
  14. package/dist/beacon-types/index.d.mts.map +1 -1
  15. package/dist/beacon-types/index.d.ts +53 -1
  16. package/dist/beacon-types/index.d.ts.map +1 -1
  17. package/dist/beacon-types/index.js +86 -1
  18. package/dist/beacon-types/index.mjs +77 -2
  19. package/dist/beacon-types/index.mjs.map +1 -1
  20. package/dist/{browser-posture-5fPrsxx7.d.mts → browser-posture-WPk0kl9u.d.mts} +18 -1
  21. package/dist/browser-posture-WPk0kl9u.d.mts.map +1 -0
  22. package/dist/{browser-posture-CCR1kh5e.d.ts → browser-posture-_y6BcdXw.d.ts} +18 -1
  23. package/dist/browser-posture-_y6BcdXw.d.ts.map +1 -0
  24. package/dist/browser-posture-cookie.mjs.map +1 -1
  25. package/dist/browser-posture-proof-verifier.js +136 -5
  26. package/dist/browser-posture-proof-verifier.mjs +134 -2
  27. package/dist/browser-posture-proof-verifier.mjs.map +1 -0
  28. package/dist/browser-posture-proof.d.mts +1 -1
  29. package/dist/browser-posture-proof.d.ts +1 -1
  30. package/dist/browser-posture-proof.js +1 -1
  31. package/dist/browser-posture-proof.mjs +1 -1
  32. package/dist/browser-posture-report.d.mts +17 -0
  33. package/dist/browser-posture-report.d.mts.map +1 -1
  34. package/dist/browser-posture-report.d.ts +17 -0
  35. package/dist/browser-posture-report.d.ts.map +1 -1
  36. package/dist/browser-posture.d.mts +1 -1
  37. package/dist/browser-posture.d.ts +1 -1
  38. package/dist/browser-posture.js +53 -5
  39. package/dist/browser-posture.mjs +53 -5
  40. package/dist/browser-posture.mjs.map +1 -1
  41. package/dist/browser.d.mts +10 -0
  42. package/dist/browser.d.mts.map +1 -1
  43. package/dist/browser.d.ts +10 -0
  44. package/dist/browser.d.ts.map +1 -1
  45. package/dist/browser.js +1 -1
  46. package/dist/browser.mjs +1 -1
  47. package/dist/browser.mjs.map +1 -1
  48. package/dist/canonical-signer/index.d.mts.map +1 -1
  49. package/dist/canonical-signer/index.d.ts.map +1 -1
  50. package/dist/canonical-signer/index.js +0 -4
  51. package/dist/canonical-signer/index.mjs +0 -4
  52. package/dist/canonical-signer/index.mjs.map +1 -1
  53. package/dist/{client-ip-B7w-uHfS.d.ts → client-ip-8KneiMK0.d.mts} +12 -2
  54. package/dist/{client-ip-B7w-uHfS.d.mts.map → client-ip-8KneiMK0.d.mts.map} +1 -1
  55. package/dist/{client-ip-B7w-uHfS.d.mts → client-ip-8KneiMK0.d.ts} +12 -2
  56. package/dist/{client-ip-B7w-uHfS.d.ts.map → client-ip-8KneiMK0.d.ts.map} +1 -1
  57. package/dist/{client-ip-B8wFzJ5f.js → client-ip-BEmLC4I4.js} +71 -0
  58. package/dist/{client-ip-DIJyr6px.mjs → client-ip-DlHx7GGh.mjs} +61 -2
  59. package/dist/client-ip-DlHx7GGh.mjs.map +1 -0
  60. package/dist/client-ip.d.mts +2 -2
  61. package/dist/client-ip.d.ts +2 -2
  62. package/dist/client-ip.js +3 -1
  63. package/dist/client-ip.mjs +2 -2
  64. package/dist/deploy/index.d.mts +1 -0
  65. package/dist/deploy/index.d.mts.map +1 -1
  66. package/dist/deploy/index.d.ts +1 -0
  67. package/dist/deploy/index.d.ts.map +1 -1
  68. package/dist/deploy/index.js +14 -2
  69. package/dist/deploy/index.mjs +14 -2
  70. package/dist/deploy/index.mjs.map +1 -1
  71. package/dist/{detection-reason-mapping-CQexNvR7.d.ts → detection-reason-mapping-BemDaDED.d.mts} +5 -2
  72. package/dist/detection-reason-mapping-BemDaDED.d.mts.map +1 -0
  73. package/dist/{detection-reason-mapping-CQexNvR7.d.mts → detection-reason-mapping-BemDaDED.d.ts} +5 -2
  74. package/dist/detection-reason-mapping-BemDaDED.d.ts.map +1 -0
  75. package/dist/{detection-reason-mapping-B9RSkOs8.js → detection-reason-mapping-BxYaQ8kb.js} +33 -8
  76. package/dist/{detection-reason-mapping-BGymWIPl.mjs → detection-reason-mapping-j-7bXsVb.mjs} +29 -10
  77. package/dist/detection-reason-mapping-j-7bXsVb.mjs.map +1 -0
  78. package/dist/errors/index.d.mts +4 -0
  79. package/dist/errors/index.d.mts.map +1 -1
  80. package/dist/errors/index.d.ts +4 -0
  81. package/dist/errors/index.d.ts.map +1 -1
  82. package/dist/errors/index.js +24 -8
  83. package/dist/errors/index.mjs +24 -8
  84. package/dist/errors/index.mjs.map +1 -1
  85. package/dist/{fetcher-D2vjr7jB.d.mts → fetcher-CTKz07jg.d.mts} +13 -3
  86. package/dist/fetcher-CTKz07jg.d.mts.map +1 -0
  87. package/dist/{fetcher-C8qvwdnA.d.ts → fetcher-DCr920hx.d.ts} +13 -3
  88. package/dist/fetcher-DCr920hx.d.ts.map +1 -0
  89. package/dist/gateway-client-ip.js +1 -1
  90. package/dist/gateway-client-ip.mjs +1 -1
  91. package/dist/host-adapter/index.d.mts +1 -1
  92. package/dist/host-adapter/index.d.ts +1 -1
  93. package/dist/identity-cookie/index.d.mts +14 -0
  94. package/dist/identity-cookie/index.d.mts.map +1 -0
  95. package/dist/identity-cookie/index.d.ts +14 -0
  96. package/dist/identity-cookie/index.d.ts.map +1 -0
  97. package/dist/identity-cookie/index.js +45 -0
  98. package/dist/identity-cookie/index.mjs +43 -0
  99. package/dist/identity-cookie/index.mjs.map +1 -0
  100. package/dist/{index-DnFsmr_o.d.ts → index-Cdv_FH0H.d.ts} +2 -2
  101. package/dist/{index-DnFsmr_o.d.ts.map → index-Cdv_FH0H.d.ts.map} +1 -1
  102. package/dist/{index-rvw5Bz-r.d.mts → index-DL_dmQBY.d.mts} +2 -2
  103. package/dist/{index-rvw5Bz-r.d.mts.map → index-DL_dmQBY.d.mts.map} +1 -1
  104. package/dist/index.d.mts +641 -169
  105. package/dist/index.d.mts.map +1 -1
  106. package/dist/index.d.ts +641 -169
  107. package/dist/index.d.ts.map +1 -1
  108. package/dist/index.js +819 -210
  109. package/dist/index.mjs +765 -200
  110. package/dist/index.mjs.map +1 -1
  111. package/dist/kya-http.d.mts +2 -2
  112. package/dist/kya-http.d.ts +2 -2
  113. package/dist/kya-http.js +7 -2
  114. package/dist/kya-http.mjs +2 -2
  115. package/dist/mcpi/dashboard-config/index.mjs.map +1 -1
  116. package/dist/patterns-CdTh7LU2.d.mts +35 -0
  117. package/dist/patterns-CdTh7LU2.d.mts.map +1 -0
  118. package/dist/patterns-CdTh7LU2.d.ts +35 -0
  119. package/dist/patterns-CdTh7LU2.d.ts.map +1 -0
  120. package/dist/{patterns-CiMpbdAF.js → patterns-CnNxRnaK.js} +3 -130
  121. package/dist/{patterns-D4OAsNQY.mjs → patterns-CpRk9R3M.mjs} +5 -96
  122. package/dist/patterns-CpRk9R3M.mjs.map +1 -0
  123. package/dist/patterns.d.mts +2 -2
  124. package/dist/patterns.d.ts +2 -2
  125. package/dist/patterns.js +1 -7
  126. package/dist/patterns.mjs +2 -2
  127. package/dist/policy/fetcher.d.mts +2 -2
  128. package/dist/policy/fetcher.d.ts +2 -2
  129. package/dist/policy/fetcher.js +100 -8
  130. package/dist/policy/fetcher.mjs +99 -9
  131. package/dist/policy/fetcher.mjs.map +1 -1
  132. package/dist/policy/schemas.d.mts +1 -1
  133. package/dist/policy/schemas.d.ts +1 -1
  134. package/dist/proxy-assertion-mapping-BVwXVSMZ.mjs +81 -0
  135. package/dist/proxy-assertion-mapping-BVwXVSMZ.mjs.map +1 -0
  136. package/dist/proxy-assertion-mapping-BxhENrcY.d.mts +70 -0
  137. package/dist/proxy-assertion-mapping-BxhENrcY.d.mts.map +1 -0
  138. package/dist/proxy-assertion-mapping-D64AyZfG.js +85 -0
  139. package/dist/proxy-assertion-mapping-DhAynFqG.d.ts +70 -0
  140. package/dist/proxy-assertion-mapping-DhAynFqG.d.ts.map +1 -0
  141. package/dist/proxy-assertions.d.mts +2 -0
  142. package/dist/proxy-assertions.d.ts +2 -0
  143. package/dist/proxy-assertions.js +4 -0
  144. package/dist/proxy-assertions.mjs +3 -0
  145. package/dist/reason-codes.d.mts +2 -2
  146. package/dist/reason-codes.d.ts +2 -2
  147. package/dist/reason-codes.js +3 -2
  148. package/dist/reason-codes.mjs +2 -2
  149. package/dist/{registered-sid-D6KCaT1E.d.ts → registered-sid-BgDhdj2l.d.mts} +24 -2
  150. package/dist/registered-sid-BgDhdj2l.d.mts.map +1 -0
  151. package/dist/{registered-sid-D6KCaT1E.d.mts → registered-sid-BgDhdj2l.d.ts} +24 -2
  152. package/dist/registered-sid-BgDhdj2l.d.ts.map +1 -0
  153. package/dist/{registered-sid-DVGTSH0L.js → registered-sid-DG1tSSvl.js} +162 -4
  154. package/dist/{registered-sid-26hNxp6t.mjs → registered-sid-D__xiDPu.mjs} +134 -6
  155. package/dist/registered-sid-D__xiDPu.mjs.map +1 -0
  156. package/dist/{schemas-m-GqyfyO.d.mts → schemas-BhC88D1-.d.mts} +5 -5
  157. package/dist/{schemas-m-GqyfyO.d.mts.map → schemas-BhC88D1-.d.mts.map} +1 -1
  158. package/dist/{schemas-CGKHzcMV.d.ts → schemas-DZa1ouGs.d.ts} +5 -5
  159. package/dist/{schemas-CGKHzcMV.d.ts.map → schemas-DZa1ouGs.d.ts.map} +1 -1
  160. package/dist/signals/index.d.mts.map +1 -1
  161. package/dist/signals/index.d.ts.map +1 -1
  162. package/dist/signals/index.js +4 -0
  163. package/dist/signals/index.mjs +4 -0
  164. package/dist/signals/index.mjs.map +1 -1
  165. package/dist/timezone-country-B6PkDyNP.d.mts +15 -0
  166. package/dist/timezone-country-B6PkDyNP.d.mts.map +1 -0
  167. package/dist/timezone-country-B6PkDyNP.d.ts +15 -0
  168. package/dist/timezone-country-B6PkDyNP.d.ts.map +1 -0
  169. package/dist/timezone-country-CROxU2Tl.js +505 -0
  170. package/dist/timezone-country-CrrnkOdy.mjs +489 -0
  171. package/dist/timezone-country-CrrnkOdy.mjs.map +1 -0
  172. package/dist/timezone-country.d.mts +2 -0
  173. package/dist/timezone-country.d.ts +2 -0
  174. package/dist/timezone-country.js +6 -0
  175. package/dist/timezone-country.mjs +3 -0
  176. package/dist/tool-protection/index.mjs.map +1 -1
  177. package/fixtures/detection/cloudflare-alias-parity.json +383 -0
  178. package/fixtures/detection/reason-codes.json +3 -1
  179. package/fixtures/detection/signal-exposure-example.json +1 -1
  180. package/fixtures/iana-tzdata/backward +375 -0
  181. package/fixtures/iana-tzdata/renamed-zones.json +21 -0
  182. package/fixtures/iana-tzdata/version +1 -0
  183. package/fixtures/iana-tzdata/zone.tab +448 -0
  184. package/fixtures/workbench/management-session.v1.json +20 -0
  185. package/fixtures/workbench/model-credentials.v1.json +8 -0
  186. package/fixtures/workbench/task-grant.v1.json +37 -0
  187. package/package.json +25 -3
  188. package/src/data/compiled/merged-rules.json +9 -7
  189. package/dist/browser-posture-5fPrsxx7.d.mts.map +0 -1
  190. package/dist/browser-posture-CCR1kh5e.d.ts.map +0 -1
  191. package/dist/browser-posture-proof-verifier-DvsOmFrM.js +0 -202
  192. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs +0 -180
  193. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs.map +0 -1
  194. package/dist/client-ip-DIJyr6px.mjs.map +0 -1
  195. package/dist/detection-reason-mapping-BGymWIPl.mjs.map +0 -1
  196. package/dist/detection-reason-mapping-CQexNvR7.d.mts.map +0 -1
  197. package/dist/detection-reason-mapping-CQexNvR7.d.ts.map +0 -1
  198. package/dist/fetcher-C8qvwdnA.d.ts.map +0 -1
  199. package/dist/fetcher-D2vjr7jB.d.mts.map +0 -1
  200. package/dist/patterns-Bp40cwh2.d.mts +0 -110
  201. package/dist/patterns-Bp40cwh2.d.mts.map +0 -1
  202. package/dist/patterns-Bp40cwh2.d.ts +0 -110
  203. package/dist/patterns-Bp40cwh2.d.ts.map +0 -1
  204. package/dist/patterns-D4OAsNQY.mjs.map +0 -1
  205. package/dist/registered-sid-26hNxp6t.mjs.map +0 -1
  206. package/dist/registered-sid-D6KCaT1E.d.mts.map +0 -1
  207. package/dist/registered-sid-D6KCaT1E.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/base64url.ts","../../src/beacon-types/session-commitment.ts","../../src/beacon-types/index.ts"],"sourcesContent":["/**\n * Base64url (RFC 4648 § 5) built on `atob` and `btoa` rather than Node's\n * buffer API, so it runs on every runtime the SDKs support, Cloudflare Workers\n * without `nodejs_compat` included.\n */\n\nconst BASE64URL_UNPADDED = /^[A-Za-z0-9_-]*$/;\nconst PADDING = 61; // '='\n\n/**\n * `text` without its trailing `=` padding. A backward scan, not\n * `replace(/=+$/, '')`: that regex retries from every `=` in a long run that\n * does not reach the end, which is quadratic on hostile input.\n */\nfunction withoutPadding(text: string): string {\n let end = text.length;\n while (end > 0 && text.charCodeAt(end - 1) === PADDING) end -= 1;\n return text.slice(0, end);\n}\n\n/**\n * Decode base64url, with or without `=` padding.\n *\n * Strict where Node's buffer decoder is lenient: a character outside the\n * alphabet, or a length no encoder produces (one character past a multiple of\n * four), throws a `TypeError` instead of being skipped or truncated. This\n * matches the engine's decoder.\n */\nexport function base64UrlToBytes(text: string): Uint8Array<ArrayBuffer> {\n const unpadded = withoutPadding(text);\n if (!BASE64URL_UNPADDED.test(unpadded) || unpadded.length % 4 === 1) {\n throw new TypeError('not valid base64url (RFC 4648 § 5)');\n }\n const base64 = unpadded.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/** Decode base64url to a string as UTF-8, replacing invalid sequences with U+FFFD. */\nexport function base64UrlToString(text: string): string {\n return new TextDecoder().decode(base64UrlToBytes(text));\n}\n\n/** Encode bytes as base64url without padding. */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return withoutPadding(btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_'));\n}\n","import { base64UrlToBytes } from '../utils/base64url';\n\nconst COMMITMENT_BYTES = 9;\nconst THUMBPRINT_BYTES = 32;\nconst COMMITTED_SESSION_ID =\n /^([0-9a-f]{8})-([0-9a-f]{4})-8([0-9a-f]{3})-[89ab]([0-9a-f]{3})-[0-9a-f]{12}$/;\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nexport function thumbprintCommitment(thumbprint: Uint8Array): string {\n return toHex(thumbprint.subarray(0, COMMITMENT_BYTES));\n}\n\nexport function sessionIdFromCommitment(commitment: string, uuidV4: string): string {\n return `${commitment.slice(0, 8)}-${commitment.slice(8, 12)}-8${commitment.slice(12, 15)}-${uuidV4[19]}${commitment.slice(15)}-${uuidV4.slice(24)}`;\n}\n\nexport function committedSessionId(thumbprint: Uint8Array, uuidV4: string): string {\n return sessionIdFromCommitment(thumbprintCommitment(thumbprint), uuidV4);\n}\n\nexport function sessionKeyCommitment(sessionId: string): string | undefined {\n const match = COMMITTED_SESSION_ID.exec(sessionId.toLowerCase());\n return match ? match.slice(1).join('') : undefined;\n}\n\nexport function sessionCommitsToThumbprint(sessionId: string, thumbprint: Uint8Array): boolean {\n const commitment = sessionKeyCommitment(sessionId);\n return commitment !== undefined && thumbprintCommitment(thumbprint) === commitment;\n}\n\nexport function sessionCommitsToJkt(sessionId: string, jkt: string): boolean {\n let thumbprint: Uint8Array;\n try {\n thumbprint = base64UrlToBytes(jkt);\n } catch {\n return false;\n }\n return (\n thumbprint.length === THUMBPRINT_BYTES && sessionCommitsToThumbprint(sessionId, thumbprint)\n );\n}\n\nexport function keyMayActForSession(sessionId: string, jkt: string | undefined): boolean {\n return (\n sessionKeyCommitment(sessionId) === undefined ||\n (jkt !== undefined && sessionCommitsToJkt(sessionId, jkt))\n );\n}\n","/**\n * Public TypeScript types for Checkpoint Beacon\n *\n * This package contains only the public API types needed by beacon consumers.\n * No implementation details or detection rules are included.\n */\n\nexport * from './session-commitment';\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue | undefined };\nexport type BeaconPrimitive = JsonPrimitive;\nexport type BeaconJsonValue = JsonValue;\nexport type BeaconCustomData = Record<string, JsonValue | undefined>;\nexport type BeaconPayload = BeaconCollectorData | BeaconCustomData | null;\nexport type WorkerPayload = unknown;\ntype UnknownRecord = Record<string, unknown>;\n\nfunction isRecord(input: unknown): input is UnknownRecord {\n return typeof input === 'object' && input !== null && !Array.isArray(input);\n}\n\nfunction toRecord(input: unknown): UnknownRecord {\n return isRecord(input) ? input : {};\n}\n\nfunction numberOr<Fallback extends number | undefined>(\n value: unknown,\n fallback: Fallback\n): number | Fallback {\n return typeof value === 'number' && Number.isFinite(value) && value !== 0 ? value : fallback;\n}\n\n/**\n * Validates a numeric config value against `ok`, falling back to `fallback`\n * when it fails. Only calls `onReject` when the caller actually supplied a\n * value (an `undefined` field, the common case, is not a rejection, it just\n * never overrode the default): H0BB5 (PR #5095 review, item 4) — a rejected\n * value used to fall back silently, with no way for a host to discover a\n * config typo.\n */\nfunction boundedNumberOr(\n value: unknown,\n fallback: number,\n ok: (n: number) => boolean,\n onReject?: (received: unknown) => void\n): number {\n if (typeof value === 'number' && Number.isFinite(value) && ok(value)) return value;\n if (value !== undefined) onReject?.(value);\n return fallback;\n}\n\n/** Same as `boundedNumberOr`, but an absent/rejected value stays `undefined` rather than defaulting. */\nfunction optionalPositiveNumber(\n value: unknown,\n onReject?: (received: unknown) => void\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;\n onReject?.(value);\n return undefined;\n}\n\n/** Same as `optionalPositiveNumber`, without the positivity requirement (a jitter seed may be any finite number). */\nfunction optionalFiniteNumber(\n value: unknown,\n onReject?: (received: unknown) => void\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n onReject?.(value);\n return undefined;\n}\n\n/** Same shape as `boundedNumberOr`/`optionalPositiveNumber`, for a boolean config flag. */\nfunction booleanOr(\n value: unknown,\n fallback: boolean,\n onReject?: (received: unknown) => void\n): boolean {\n if (value === undefined) return fallback;\n if (typeof value === 'boolean') return value;\n onReject?.(value);\n return fallback;\n}\n\n/** Ingest's own `sessionId` bound (1-255), limited to characters a cookie value carries unescaped. */\nconst RESUMABLE_SESSION_ID = /^[A-Za-z0-9._~-]{1,255}$/;\n\nfunction resumableSessionId(\n value: unknown,\n onReject?: (received: unknown) => void\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'string' && RESUMABLE_SESSION_ID.test(value)) return value;\n onReject?.(value);\n return undefined;\n}\n\nfunction receiptCallback(\n value: unknown,\n onReject?: (received: unknown) => void\n): BeaconConfig['onReceipt'] {\n if (value === undefined) return undefined;\n if (typeof value === 'function') return value as BeaconConfig['onReceipt'];\n onReject?.(value);\n return undefined;\n}\n\nconst DISPATCH_TRIGGER_NAMES = [\n 'arrival',\n 'signals',\n 'interaction',\n 'untrusted',\n 'posture',\n 'unload',\n 'navigation',\n] as const satisfies readonly (keyof BeaconDispatchTriggers)[];\n\n/**\n * Keeps only the known trigger names with a real boolean; anything else is\n * dropped and, when the caller actually named a known trigger with a\n * non-boolean value (`triggers: { posture: 0 }`, say), reported through\n * `onReject` — H0BB5 (PR #5095 review, item 4): a numeric `0` used to be\n * dropped silently and that trigger stayed at its default-enabled state,\n * the opposite of what the \"0 is falsy\" convention suggests.\n */\nfunction pickTriggers(\n value: unknown,\n onReject?: (name: string, received: unknown) => void\n): BeaconDispatchTriggers | undefined {\n if (!isRecord(value)) return undefined;\n const picked: BeaconDispatchTriggers = {};\n for (const name of DISPATCH_TRIGGER_NAMES) {\n const raw = value[name];\n if (typeof raw === 'boolean') {\n picked[name] = raw;\n } else if (raw !== undefined) {\n onReject?.(name, raw);\n }\n }\n return picked;\n}\n\nfunction stringOr(value: unknown, fallback?: string): string | undefined {\n return typeof value === 'string' ? value : fallback;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\n/**\n * Non-empty on purpose: an empty schedule would mean \"zero posture-recovery\n * attempts\", silently disabling recovery rather than configuring it. A\n * deployment that actually wants no retries sets `flushInterval` instead.\n */\nfunction isPositiveNumberArray(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((entry) => typeof entry === 'number' && Number.isFinite(entry) && entry > 0)\n );\n}\n\nfunction isBeaconTags(value: unknown): value is Record<string, string | number | boolean> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (entry) =>\n typeof entry === 'string' || typeof entry === 'number' || typeof entry === 'boolean'\n )\n );\n}\n\n/**\n * Exported because `parseBeaconConfig` is an allowlist: a key it does not\n * name is dropped, silently. The beacon's other public entry point\n * (`checkpoint-shared/browser`) carries its own copy of that allowlist, so\n * the CHECK at least lives in one place even while the two parsers do not —\n * see the note on `BeaconConfig.identity`.\n *\n * Rejects an identity with no usable `userId` rather than passing through a\n * half-formed object: downstream this becomes `detections.user_id`, and an\n * empty string there is worse than an absent one — it reads as \"identified\"\n * while naming nobody.\n */\nexport function isBeaconIdentity(value: unknown): value is BeaconIdentity {\n return isRecord(value) && typeof value.userId === 'string' && value.userId.length > 0;\n}\n\nfunction isLogLevel(value: unknown): value is BeaconConfig['logLevel'] {\n return value === 'error' || value === 'warn' || value === 'info' || value === 'debug';\n}\n\nfunction isBeaconWorkerMessageType(value: unknown): value is BeaconWorkerMessageType {\n return (\n value === 'init' ||\n value === 'collect' ||\n value === 'flush' ||\n value === 'config' ||\n value === 'status' ||\n value === 'error' ||\n // `beacon.worker.ts`'s `respond()` has always sent this on every\n // successful request (init/collect/flush/config/status) — the allowlist\n // just never named it, so `parseBeaconWorkerMessage` silently coerced\n // every success response to `'init'` (see that function's fallback).\n value === 'response' ||\n value === 'posture'\n );\n}\n\n/**\n * Resolves whether a beacon should use its Web Worker transport.\n *\n * `enableWebWorker` is accepted as an alias for `useWorker`: the package's\n * own test suite (`checkpoint-beacon/src/index.test.ts`) has always\n * constructed with `enableWebWorker: false`, but `parseBeaconConfig`'s\n * allowlist only ever named `useWorker`, so that key was silently dropped —\n * the beacon kept auto-detecting worker support regardless of what the\n * caller passed. `useWorker` wins when both are set, since it's the\n * canonical name every other config field (`workerUrl`, `workerConfig`)\n * pairs with.\n */\nfunction resolveUseWorker(config: UnknownRecord): boolean {\n if (typeof config.useWorker === 'boolean') {\n return config.useWorker;\n }\n if (typeof config.enableWebWorker === 'boolean') {\n return config.enableWebWorker;\n }\n return true;\n}\n\nexport interface NetworkInformationLike extends EventTarget {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\nexport interface NavigatorWithNetworkInformation extends Navigator {\n connection?: NetworkInformationLike;\n mozConnection?: NetworkInformationLike;\n webkitConnection?: NetworkInformationLike;\n deviceMemory?: number;\n vendorSub: string;\n doNotTrack: string | null;\n msDoNotTrack?: string | null;\n}\n\nexport interface WindowWithBeaconMetadata extends Window {\n doNotTrack?: string | null;\n __NEXT_DATA__?: {\n buildId?: string;\n };\n}\n\nexport interface TrustedTypePolicyLike {\n createScriptURL(url: string): string;\n createScript(script: string): string;\n}\n\nexport interface WindowWithTrustedTypes extends Window {\n trustedTypes?: {\n createPolicy(\n name: string,\n rules: {\n createScriptURL?: (url: string) => string;\n createScript?: (script: string) => string;\n }\n ): TrustedTypePolicyLike;\n };\n}\n\nexport interface PerformanceMemoryInfo {\n usedJSHeapSize: number;\n totalJSHeapSize: number;\n jsHeapSizeLimit: number;\n}\n\nexport interface PerformanceWithMemory extends Performance {\n memory?: PerformanceMemoryInfo;\n measureUserAgentSpecificMemory?: () => Promise<unknown>;\n}\n\nexport interface LargestContentfulPaintEntry extends PerformanceEntry {\n renderTime?: number;\n loadTime?: number;\n}\n\n// ============================================================================\n// BEACON CONFIGURATION\n// ============================================================================\n\n/**\n * Who the current visitor is, when the host site knows.\n *\n * Deliberately just the id. The pixel's `identify` call also carries\n * `previousId` and `userTraits`, but those drive the server's profile and\n * alias-graph pipeline (tenant salt, profile-copy, write advisory locks),\n * which the beacon ingest route does not run — accepting them here would mean\n * collecting personal data the beacon path then silently discards. Both are\n * additive later: this is an optional field on an optional object.\n */\nexport interface BeaconIdentity {\n /**\n * The host site's own id for the signed-in user. Capped at 255 characters\n * to match `detections.user_id`; a longer value is rejected at ingest.\n */\n userId: string;\n}\n\n/** The beacon's automatic sends, each switchable off. See `BeaconConfig.triggers`. */\nexport interface BeaconDispatchTriggers {\n /** The `pageview` at construction and on consent restore. */\n arrival?: boolean;\n /** The follow-up send when the lazy signals chunk resolves after arrival missed it. */\n signals?: boolean;\n /** First interaction, first timing sample, and evidence growth. */\n interaction?: boolean;\n /** The first script-dispatched (untrusted) input. */\n untrusted?: boolean;\n /** An interaction after the posture token has gone stale. */\n posture?: boolean;\n /** The SDK-wired `visibilitychange` and `pagehide` critical send. */\n unload?: boolean;\n /**\n * The `pageview` for a page the visitor arrives at without a full load: a\n * back/forward-cache restore (`pageshow` with `persisted`, trigger\n * `bfcache_restore`) and a soft navigation that changes the path\n * (History API or Navigation API, trigger `soft_navigation`). Turn it off\n * when the host already calls `collect('pageview')` on its own route\n * changes, or each one sends twice.\n */\n navigation?: boolean;\n}\n\nexport interface BeaconConfig {\n /** Project ID for tracking (same as pixel data-project-id) */\n projectId: string;\n\n /**\n * Who the visitor is, when the page already knows at construction time.\n * When identity only becomes known later (a login part-way through the\n * session), call `identify()` instead.\n */\n identity?: BeaconIdentity;\n\n /**\n * Where batches are POSTed. Defaults to the hosted ingest endpoint declared\n * in `NETWORK_CONTRACT.md`.\n *\n * Set it to send somewhere else — a self-hosted deployment, a regional\n * install, or a test origin. An override means the destination is the\n * integrator's, not ours, so `NETWORK_CONTRACT.md` describes the DEFAULT and\n * says so explicitly.\n *\n * @default 'https://kya.vouched.id/api/v1/beacon'\n */\n endpoint?: string;\n\n /** Optional environment tag for data segmentation */\n environment?: 'development' | 'staging' | 'production' | string;\n\n /** Optional tags for custom data segmentation */\n tags?: Record<string, string | number | boolean>;\n\n /**\n * Not read by the SDK. Construct the beacon only when it should run, and\n * call `destroy()` to stop it.\n *\n * @deprecated\n */\n enabled?: boolean;\n\n /**\n * Verbose console logging.\n *\n * @default false\n */\n debug?: boolean;\n\n /**\n * Log verbosity.\n *\n * @default 'error'\n */\n logLevel?: 'error' | 'warn' | 'info' | 'debug';\n\n /**\n * When the browser sends Do Not Track, the beacon collects and sends nothing.\n *\n * @default true\n */\n respectDoNotTrack?: boolean;\n\n /**\n * Accepted and ignored. The beacon no longer withholds anything on\n * consent; only Do Not Track stops collection.\n *\n * @deprecated has no effect\n * @default false\n */\n requireConsent?: boolean;\n\n /**\n * Truncate the stored IP to /24 (IPv4) or /48 (IPv6) before persistence.\n *\n * @default false\n */\n anonymizeIp?: boolean;\n\n /**\n * Strip the `#fragment` from the `url`/`referrer` collector fields before\n * they leave the page. Defaults to `true`: a fragment is never sent to\n * the server by the browser in the first place for any OTHER surface\n * (it is script-visible only), so a beacon that forwards it is the one\n * place it can leak — and it is also the highest-risk part of the URL,\n * since SPA routers, magic-link auth, and OAuth implicit-flow responses\n * all put tokens there. Set to `false` only if a project genuinely\n * consumes `url`'s fragment server-side.\n *\n * @default true\n */\n stripUrlFragment?: boolean;\n\n /**\n * Query parameter names (matched case-insensitively) to redact from the\n * `url`/`referrer` collector fields before they leave the page. Each\n * matching value is replaced with the literal string `\"[redacted]\"`; the\n * parameter itself stays present so the URL's shape is unchanged. Empty\n * by default — nothing is scrubbed unless a project opts in with the\n * param names it puts tokens/PII behind (e.g. `[\"token\", \"email\"]`).\n * Ignored for a parameter when `dropQueryParams` is also `true`, since\n * there is no query string left to scrub.\n *\n * @default []\n */\n scrubQueryParams?: string[];\n\n /**\n * Drop the entire query string from the `url`/`referrer` collector\n * fields before they leave the page. Off by default. Takes priority over\n * `scrubQueryParams` when both are set — there is nothing left to scrub\n * once the whole query string is gone.\n *\n * @default false\n */\n dropQueryParams?: boolean;\n\n /**\n * Idle-gap override in milliseconds, at most six hours. Unset: one hour on\n * phones, six hours elsewhere. Every send extends it.\n */\n sessionTimeout?: number;\n\n /**\n * Name of the visitor session cookie shared by pixel, beacon, gateway, and\n * SDK rows. Query it with `?sessionId=` on the\n * [detections endpoint](/docs/api-reference#get-project-detections).\n *\n * @default '_as_beacon_session'\n */\n sessionCookieName?: string;\n\n /**\n * Resume a browser session id the page stored earlier (a receipt's\n * `browserSessionId`, see `onReceipt`) instead of reading the session\n * cookie or minting a new id. With cookies off this is the only way two\n * page loads stay one session, and a posture token verifies only against\n * the session id it was issued to. 1 to 255 characters of\n * `A-Z a-z 0-9 . _ ~ -`; anything else is ignored with a warning.\n * `updateConfig({ browserSessionId })` switches a running beacon to it.\n */\n browserSessionId?: string;\n\n /**\n * Called with every ingest receipt: the server's session id, the browser\n * session id the batch was sent under, and the posture token or the reason\n * there is none. Runs on the main thread in worker mode too, after the\n * posture cookie write. An error it throws is logged at `warn` and never\n * affects delivery.\n */\n onReceipt?: (receipt: BeaconReceipt) => void;\n\n /**\n * @deprecated The beacon no longer batches; every dispatch sends\n * immediately. Accepted and ignored so a caller upgrading from an older\n * SDK version keeps compiling and does not need to touch its config.\n */\n batchSize?: number;\n\n /**\n * @deprecated The beacon no longer polls on an interval; it dispatches on\n * evidence transitions instead (arrival, first interaction, evidence\n * doubling, untrusted input, posture staleness, hidden/pagehide). Accepted\n * and ignored so a caller upgrading from an older SDK version keeps\n * compiling and does not need to touch its config.\n */\n flushInterval?: number;\n\n /**\n * How much `keyDwellCount + pressCount + untrustedEvents` has to grow, as a\n * multiple of its value at the last send, before an interaction sends\n * again. 2 sends at 1, 2, 4, 8, 16 samples; 1.5 sends more often, 3 less.\n * A value at or below 1 falls back to the default.\n *\n * @default 2\n */\n evidenceGrowthFactor?: number;\n\n /**\n * Fraction of the posture token's lifetime after which a counted\n * interaction sends again, so the token stays fresh under a live hand.\n * 0.5 refreshes the 120 s token once an interaction lands more than 60 s\n * after the last send. A value outside (0, 1] falls back to the default.\n *\n * @default 0.5\n */\n postureRefreshFraction?: number;\n\n /**\n * Which automatic sends fire. Every trigger is on unless set to `false`.\n * Turning `unload` off leaves `trackPageUnload()` available for a host\n * that wires its own listener; turning `arrival` off leaves `collect()`.\n */\n triggers?: BeaconDispatchTriggers;\n\n /**\n * Low-frequency backstop that refreshes posture on a jittered timer,\n * independent of interaction, so a visitor who goes idle past the posture\n * TTL with no counted interaction is not one stale click on a critical\n * action away from an expired token (H0BB5, PR #5095 review). The actual\n * interval on each tick is `proactiveRefreshMinIntervalMs` plus a random\n * `[0, max - min)` jitter, so a fleet of clients loaded at the same moment\n * does not all refresh on the same wall-clock boundary. Paused while the\n * page is hidden, resumed on `visibilitychange`. Gated by\n * `triggers.posture`, the same switch that already turns off the\n * interaction-triggered staleness check — this timer is that same\n * `'posture'` trigger firing proactively, not a second mechanism. A\n * non-positive value falls back to the default.\n *\n * @default 30000\n */\n proactiveRefreshMinIntervalMs?: number;\n\n /**\n * The upper bound of the proactive-refresh jitter window; see\n * `proactiveRefreshMinIntervalMs`. A non-positive value falls back to the\n * default; a value below `proactiveRefreshMinIntervalMs` degrades to the\n * minimum on every tick rather than throwing.\n *\n * @default 60000\n */\n proactiveRefreshMaxIntervalMs?: number;\n\n /**\n * How old the last send must be, in milliseconds, before a visibility\n * resume forces an immediate posture refresh. Defaults to the same\n * threshold the interaction-triggered check already uses\n * (`postureRefreshFraction` of the posture token's lifetime), so the two\n * stay in lockstep unless a host deliberately wants the visibility check\n * to be stricter or looser. A non-positive value falls back to that\n * default.\n */\n proactiveRefreshFreshnessMs?: number;\n\n /**\n * On `visibilitychange` back to visible, force an immediate posture\n * refresh when it is stale (see `proactiveRefreshFreshnessMs`); a fresh\n * tab regaining focus does not get an unnecessary send either way. Set to\n * `false` to leave visibility resume to the plain interval alone.\n *\n * @default true\n */\n proactiveRefreshOnVisibilityResume?: boolean;\n\n /**\n * Refresh posture (and drain anything the offline queue is still holding)\n * when the browser fires `online`. Set to `false` to leave reconnection\n * recovery to the offline queue's own `online` listener alone.\n *\n * @default true\n */\n proactiveRefreshOnOnline?: boolean;\n\n /**\n * A fixed seed for the proactive-refresh jitter roll, for deterministic\n * tests. Omit in production for real `Math.random()` jitter.\n */\n proactiveRefreshJitterSeed?: number;\n\n /**\n * Per-collector deadline in milliseconds. A collector still running past\n * this deadline is dropped from the current collection round rather than\n * awaited further — see `collectWithDeadline` in checkpoint-beacon.\n * Default and rationale documented in checkpoint-beacon's\n * `src/budget/thresholds.ts`.\n *\n * @default 1600\n */\n collectorDeadlineMs?: number;\n\n /**\n * Maximum number of queued events.\n *\n * @default 100\n */\n maxQueueSize?: number;\n\n /**\n * Retry count for failed sends.\n *\n * @default 3\n */\n retryAttempts?: number;\n\n /**\n * Base retry delay in milliseconds.\n *\n * @default 2000\n */\n retryDelay?: number;\n\n /**\n * Delays in milliseconds between posture-recovery attempts after a\n * durably-queued ingest response that carried no posture verdict. The\n * array's length is the attempt ceiling. Defaults to the shipped ladder;\n * override only in tests and in a self-hosted deployment with a\n * different outage profile.\n */\n postureRetryScheduleMs?: number[];\n\n /**\n * Prefer a Web Worker for event processing, batching, and transport.\n * Page-dependent collection remains on the main thread. Unsupported\n * browsers fall back to the main thread; SSR never starts a worker.\n * Set false to disable the processing worker.\n *\n * @default true\n */\n useWorker?: boolean;\n\n /**\n * Alias for `useWorker`, accepted for callers using the older option\n * name. When both are set, `useWorker` wins — see `resolveUseWorker`.\n */\n enableWebWorker?: boolean;\n\n /**\n * URL of the worker script (`beacon.worker.js`, exported as\n * `@kya-os/checkpoint-beacon/worker`). Classic workers must be same-origin.\n * When unset, the beacon derives `beacon.worker.js` next to the `<script>`\n * tag that loaded `beacon.min.js`, else `/beacon.worker.js` at the site root.\n */\n workerUrl?: string;\n\n /**\n * Worker lifecycle tuning: `initTimeoutMs` (3000), `messageTimeout` (30000),\n * `heartbeatInterval` (5000), `maxRetries` (3), `retryDelay` (1000),\n * `compressionThreshold` (5120), `allowFallback` (true).\n */\n workerConfig?: WorkerConfig;\n\n lazySignalsUrl?: string;\n}\n\n// ============================================================================\n// BEACON EVENTS\n// ============================================================================\n\nexport interface BeaconEvent {\n /** Event type identifier */\n type: BeaconEventType;\n\n /** Event data payload */\n data: BeaconCollectorData;\n\n /** Event metadata */\n metadata: BeaconMetadata;\n}\n\nexport interface BeaconMetadata {\n /** Session ID */\n sessionId: string;\n\n /** Event timestamp */\n timestamp: number;\n\n /** Optional event name */\n eventName?: string;\n\n /** Present only once the host site has told us who the visitor is. */\n identity?: BeaconIdentity;\n\n /** Allow additional metadata */\n [key: string]: unknown;\n}\n\n// ============================================================================\n// BEACON API\n// ============================================================================\n\nexport interface IAgentShieldBeacon {\n /**\n * Collect a generic event\n */\n collect(eventType: string, data?: BeaconPayload): Promise<void>;\n\n /**\n * Track a custom event\n */\n trackEvent(eventName: string, eventData?: BeaconPayload): Promise<void>;\n\n /**\n * Track a pageview\n */\n trackPageview(pageData?: BeaconPayload): Promise<void>;\n\n /**\n * Track page unload\n */\n trackPageUnload(): Promise<void>;\n\n /**\n * Update configuration\n */\n updateConfig(updates: Partial<BeaconConfig>): void;\n\n /**\n * Destroy the beacon and clean up\n */\n destroy(): Promise<void>;\n}\n\n// ============================================================================\n// RESPONSE TYPES\n// ============================================================================\n\nexport interface BeaconResponse {\n /** Response status */\n status: 'success' | 'error';\n\n /** Optional message */\n message?: string;\n\n /** Optional error details */\n error?: {\n code: string;\n message: string;\n };\n}\n\n// ============================================================================\n// BROWSER CONTEXT\n// ============================================================================\n\nexport interface BrowserContext {\n /** Browser name and version */\n browser: {\n name: string;\n version: string;\n engine: string;\n };\n\n /** Operating system */\n os: {\n name: string;\n version: string;\n };\n\n /** Device information */\n device: {\n type: 'desktop' | 'mobile' | 'tablet' | 'tv' | 'unknown';\n vendor?: string;\n model?: string;\n };\n\n /** Screen information */\n screen: {\n width: number;\n height: number;\n pixelRatio: number;\n colorDepth: number;\n };\n\n /** Connection information */\n connection?: {\n type: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown';\n effectiveType?: '2g' | '3g' | '4g' | '5g';\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n };\n}\n\n// ============================================================================\n// PERFORMANCE METRICS\n// ============================================================================\n\nexport interface PerformanceMetrics {\n /** Page load time in milliseconds */\n pageLoadTime?: number;\n\n /** DOM content loaded time */\n domContentLoadedTime?: number;\n\n /** Time to interactive */\n timeToInteractive?: number;\n\n /** First paint time */\n firstPaintTime?: number;\n\n /** First contentful paint time */\n firstContentfulPaintTime?: number;\n\n /** Largest contentful paint time */\n largestContentfulPaintTime?: number;\n\n /** DNS lookup time */\n dnsLookupTime?: number;\n\n /** TCP connection time */\n tcpConnectionTime?: number;\n\n /** Server response time */\n serverResponseTime?: number;\n\n /** Resource timing */\n resources?: {\n scripts: number;\n stylesheets: number;\n images: number;\n fonts: number;\n total: number;\n };\n}\n\n// ============================================================================\n// SESSION TYPES\n// ============================================================================\n\nexport interface SessionData {\n /** Unique session ID */\n id: string;\n\n /** Session start timestamp */\n startTime: number;\n\n /** Last activity timestamp */\n lastActivity: number;\n\n /** Page view count in session */\n pageViews: number;\n\n /** Event count in session */\n eventCount: number;\n\n /** Session duration in milliseconds */\n duration: number;\n\n /** Is this a new session */\n isNew: boolean;\n}\n\n// ============================================================================\n// TRANSPORT TYPES\n// ============================================================================\n\nexport interface TransportConfig {\n maxRetries: number;\n retryDelayBase: number;\n offlineQueueSize: number;\n useCompression: boolean;\n compressionThreshold: number;\n /** Build item 6: carried onto every outgoing `BeaconBatch` — see `BeaconConfig.anonymizeIp`. */\n anonymizeIp?: boolean;\n}\n\nexport interface TransportOptions {\n immediate?: boolean;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n retry?: boolean;\n timeout?: number;\n publicJwk?: EcPublicJwk;\n keyless?: BeaconKeyless;\n deviceId?: string;\n handoffToken?: string;\n batch?: QueuedBatchIdentity;\n}\n\nexport interface TransportResponse {\n success: boolean;\n timestamp: number;\n batchId?: string;\n error?: string;\n queued?: boolean;\n}\n\nexport type TransportState = 'idle' | 'sending' | 'offline' | 'paused' | 'error';\n\nexport interface TransportMetrics {\n eventsSent: number;\n eventsFailed: number;\n eventsQueued: number;\n batchesSent: number;\n batchesFailed: number;\n bytesTransferred: number;\n compressionRatio?: number;\n averageLatency?: number;\n lastSuccessTimestamp?: number;\n lastErrorTimestamp?: number;\n eventsEvicted?: number;\n eventsExpired?: number;\n entriesCorrupt?: number;\n}\n\nexport type ConnectionType =\n | 'bluetooth'\n | 'cellular'\n | 'ethernet'\n | 'none'\n | 'wifi'\n | 'wimax'\n | 'other'\n | 'unknown';\n\nexport interface NetworkInfo {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\n// ============================================================================\n// WORKER TYPES\n// ============================================================================\n\nexport type MessagePriority = 'low' | 'normal' | 'high' | 'critical';\nexport type WorkerErrorType =\n | 'initialization'\n | 'runtime'\n | 'communication'\n | 'timeout'\n | 'memory'\n | 'network'\n | 'permission'\n | 'validation'\n | 'processing'\n | 'unknown';\nexport type WorkerAction =\n | 'process'\n | 'init'\n | 'terminate'\n | 'pause'\n | 'resume'\n | 'status'\n | 'health';\nexport type WorkerMessageType = 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n\nexport interface WorkerMessage {\n id: string;\n type: 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n action?: string;\n payload?: WorkerPayload;\n timestamp: number;\n compressed?: boolean;\n priority?: MessagePriority;\n correlationId?: string;\n}\n\nexport type WorkerState =\n | 'idle'\n | 'initializing'\n | 'ready'\n | 'processing'\n | 'busy'\n | 'error'\n | 'terminating'\n | 'terminated';\n\nexport type WorkerHealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\nexport interface WorkerMetrics {\n tasksProcessed: number;\n tasksFailed: number;\n averageProcessingTime?: number;\n memoryUsage?: number;\n cpuUsage?: number;\n healthStatus: WorkerHealthStatus;\n lastHealthCheck: number;\n restartCount: number;\n errorRate?: number;\n errorCount: number;\n messageQueueSize: number;\n startTime: number;\n uptime: number;\n averageTaskTime?: number;\n lastTaskTime?: number;\n}\n\nexport interface WorkerError {\n type: WorkerErrorType;\n code?: string;\n message: string;\n stack?: string;\n timestamp: number;\n recoverable: boolean;\n retryAfter?: number;\n context?: Record<string, unknown>;\n}\n\nexport interface WorkerCapabilities {\n workerAPI: boolean;\n sharedArrayBuffer: boolean;\n transferableObjects: boolean;\n offscreenCanvas: boolean;\n webAssembly: boolean;\n atomics: boolean;\n bigInt: boolean;\n csp: {\n workerSrc: boolean;\n scriptSrc: boolean;\n blobUrls: boolean;\n inlineWorkers: boolean;\n };\n performance: {\n memory: boolean;\n measureUserAgentSpecificMemory: boolean;\n };\n}\n\nexport interface WorkerTask {\n id: string;\n type: string;\n data: WorkerPayload;\n priority: 'low' | 'normal' | 'high' | 'critical';\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n error?: WorkerError;\n maxRetries?: number;\n retries?: number;\n timeout?: number;\n}\n\nexport interface FallbackOptions {\n useRequestIdleCallback: boolean;\n idleTimeout: number;\n chunkSize: number;\n throttleMs: number;\n maxExecutionTime: number;\n}\n\nexport interface ResourceUsage {\n memory: {\n used: number;\n limit: number;\n percentage: number;\n };\n cpu: {\n usage: number;\n limit: number;\n };\n tasks: {\n pending: number;\n active: number;\n completed: number;\n failed: number;\n };\n activeWorkers: number;\n}\n\nexport interface WorkerPoolConfig {\n maxWorkers: number;\n minWorkers: number;\n workerIdleTimeout: number;\n taskQueueSize: number;\n resourceLimits: Record<string, number>;\n autoScale?: boolean;\n scaleUpThreshold?: number;\n scaleDownThreshold?: number;\n}\n\nexport type BeaconWorkerMessageType =\n | 'init'\n | 'collect'\n | 'flush'\n | 'config'\n | 'status'\n | 'error'\n | 'response'\n // Unsolicited worker -> main relay of a 202 ingest body (posture cookie\n // delivery needs `document`, which the worker lacks).\n | 'posture';\nexport type ProtocolVersion = '1.0' | '1.1' | '2.0';\n\nexport interface BeaconWorkerMessage {\n type: BeaconWorkerMessageType;\n data?: WorkerPayload;\n payload?: WorkerPayload;\n messageId: string;\n timestamp: number;\n id: string;\n}\n\nexport interface WorkerConfig {\n enabled?: boolean;\n url?: string;\n heartbeatInterval?: number;\n maxUnhealthyCount?: number;\n maxRetries?: number;\n retryDelay?: number;\n restartDelay?: number;\n messageTimeout?: number;\n compressionThreshold?: number;\n allowFallback?: boolean;\n crossOriginIsolated?: boolean;\n maxRestartAttempts?: number;\n terminationTimeout?: number;\n taskTimeout?: number;\n fallbackDelay?: number;\n enableFallback?: boolean;\n /**\n * Hard ceiling on how long worker startup (script load + init handshake)\n * gets before the caller gives up and falls back to the main-thread\n * transport. Deliberately separate from `taskTimeout`/`messageTimeout`\n * (which govern steady-state message round trips once the worker is\n * already up): a slow or hung worker script would otherwise hold up\n * every event for the full 30s message timeout before anything left the\n * page. A few seconds is enough for a healthy worker to load and answer\n * its init message; anything slower isn't worth waiting on.\n */\n initTimeoutMs?: number;\n}\n\n// ============================================================================\n// CIRCUIT BREAKER & RETRY\n// ============================================================================\n\nexport interface CircuitBreakerConfig {\n threshold: number;\n timeout: number;\n resetTimeout: number;\n}\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half-open';\n\nexport interface RetryStrategy {\n maxAttempts: number;\n baseDelay: number;\n maxDelay: number;\n factor: number;\n jitter: boolean;\n}\n\n// ============================================================================\n// OFFLINE QUEUE\n// ============================================================================\n\nexport interface QueuedBatchIdentity {\n batchId: string;\n sessionId: string;\n timestamp: number;\n projectId?: string;\n handoffToken?: string;\n}\n\nexport interface OfflineQueueEntry {\n id: string;\n events: BeaconEvent[];\n timestamp: number;\n expiresAt: number;\n retryCount: number;\n size: number;\n batch?: QueuedBatchIdentity;\n}\n\n// ============================================================================\n// BEACON BATCH\n// ============================================================================\n\n/** The minimal EC-P256 public JWK shape the beacon can construct without\n * a JOSE library dependency (see P37's findings on bundle-size discipline).\n * Structurally compatible with `jose`'s wider `JWK` type on the server side. */\nexport interface EcPublicJwk {\n kty: 'EC';\n crv: 'P-256';\n x: string;\n y: string;\n}\n\n/** What `BeaconConfig.onReceipt` receives for each 202 ingest response. */\nexport interface BeaconReceipt {\n /**\n * The server's session id for this visit, the key\n * `GET /api/v1/projects/{id}/sessions/{sessionId}` reads. On a receipt from\n * the queue-only edge it is present once the origin has answered for the\n * session, and absent before (`postureStatus: 'pending'`).\n */\n sessionId?: string;\n /**\n * The beacon's own session id the batch was sent under: what a posture\n * token is bound to, and what `BeaconConfig.browserSessionId` resumes.\n */\n browserSessionId: string;\n /** The signed posture token, when ingest issued one. `expiresAt` is Unix seconds. */\n posture?: { token: string; expiresAt: number };\n /** Why `posture` is absent: `'pending'` while a queued batch awaits replay, otherwise the withheld reason. */\n postureStatus?: string;\n}\n\nexport interface BeaconBatch {\n projectId: string;\n events: BeaconEvent[];\n sessionId: string;\n handoffToken?: string;\n deviceId?: string;\n batchId: string;\n timestamp: number;\n anonymizeIp?: boolean;\n nonce?: string;\n nonceEcho?: boolean;\n publicJwk?: EcPublicJwk;\n keyless?: BeaconKeyless;\n queueEvictions?: number;\n queueExpirations?: number;\n queueCorruptions?: number;\n}\n\nexport type BeaconKeyless = 1 | 2;\n\nexport interface BeaconCollectorData {\n // Browser collector data\n userAgent?: string;\n language?: string;\n platform?: string;\n screenResolution?: string;\n viewport?: string;\n cookiesEnabled?: boolean;\n doNotTrack?: boolean;\n timezone?: string;\n referrer?: string;\n url?: string;\n title?: string;\n vendor?: string;\n\n // Performance collector data\n pageLoadTime?: number;\n domContentLoadedTime?: number;\n firstPaintTime?: number;\n firstContentfulPaintTime?: number;\n connectionType?: string;\n\n // Session data\n sessionId?: string;\n timestamp?: number;\n\n // Allow additional properties\n [key: string]: unknown;\n}\n\nexport type BeaconEventType =\n | 'pageview'\n | 'pageunload'\n | 'heartbeat'\n | 'evidence'\n | 'custom'\n | 'error'\n | 'performance';\n\n// ============================================================================\n// PARSER FUNCTIONS\n// ============================================================================\n\nexport function parseRetryStrategy(input: unknown): RetryStrategy {\n const strategy = toRecord(input);\n return {\n maxAttempts: numberOr(strategy.maxAttempts, 3),\n baseDelay: numberOr(strategy.baseDelay, 1000),\n maxDelay: numberOr(strategy.maxDelay, 30000),\n factor: numberOr(strategy.factor, 2),\n jitter: strategy.jitter !== false,\n };\n}\n\nexport function parseCircuitBreakerConfig(input: unknown): CircuitBreakerConfig {\n const config = toRecord(input);\n return {\n threshold: numberOr(config.threshold, 5),\n timeout: numberOr(config.timeout, 60000),\n resetTimeout: numberOr(config.resetTimeout, 30000),\n };\n}\n\nfunction parseQueuedBatchIdentity(input: unknown): QueuedBatchIdentity | undefined {\n if (!isRecord(input)) return undefined;\n const { batchId, sessionId, timestamp, projectId, handoffToken } = input;\n if (\n typeof batchId !== 'string' ||\n batchId.length < 1 ||\n batchId.length > BEACON_MAX_BATCH_ID_LENGTH ||\n typeof sessionId !== 'string' ||\n sessionId.length < 1 ||\n typeof timestamp !== 'number' ||\n !Number.isFinite(timestamp)\n ) {\n return undefined;\n }\n return {\n batchId,\n sessionId,\n timestamp,\n ...(typeof projectId === 'string' && projectId.length > 0 && { projectId }),\n ...(typeof handoffToken === 'string' && handoffToken.length > 0 && { handoffToken }),\n };\n}\n\nexport function parseOfflineQueueEntry(input: unknown): OfflineQueueEntry {\n if (!isRecord(input)) {\n throw new Error('Invalid offline queue entry');\n }\n\n const entry = input;\n const batch = parseQueuedBatchIdentity(entry.batch);\n return {\n id: stringOr(\n entry.id,\n `${Date.now()}_${Array.from(crypto.getRandomValues(new Uint8Array(6)), (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n )!,\n events: Array.isArray(entry.events) ? (entry.events as BeaconEvent[]) : [],\n timestamp: numberOr(entry.timestamp, Date.now()),\n expiresAt: numberOr(entry.expiresAt, Date.now() + 86400000), // 24 hours\n retryCount: numberOr(entry.retryCount, 0),\n size: numberOr(entry.size, 0),\n ...(batch ? { batch } : {}),\n };\n}\n\nfunction randomId(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nexport function parseBeaconWorkerMessage(input: unknown): BeaconWorkerMessage {\n if (!isRecord(input)) {\n throw new Error('Invalid beacon worker message');\n }\n\n const msg = input;\n const messageId = stringOr(msg.messageId) ?? stringOr(msg.id) ?? randomId();\n return {\n type: isBeaconWorkerMessageType(msg.type) ? msg.type : 'init',\n data: msg.data,\n payload: msg.payload,\n messageId,\n timestamp: numberOr(msg.timestamp, Date.now()),\n id: stringOr(msg.id, messageId)!,\n };\n}\n\nfunction isMessagePriority(value: unknown): value is MessagePriority {\n return value === 'low' || value === 'normal' || value === 'high' || value === 'critical';\n}\n\nfunction isWorkerMessageType(value: unknown): value is WorkerMessageType {\n return (\n value === 'request' ||\n value === 'response' ||\n value === 'error' ||\n value === 'heartbeat' ||\n value === 'status'\n );\n}\n\nfunction isWorkerErrorType(value: unknown): value is WorkerErrorType {\n return (\n value === 'initialization' ||\n value === 'runtime' ||\n value === 'communication' ||\n value === 'timeout' ||\n value === 'memory' ||\n value === 'network' ||\n value === 'permission' ||\n value === 'validation' ||\n value === 'processing' ||\n value === 'unknown'\n );\n}\n\nexport function parseWorkerMessage(input: unknown): WorkerMessage {\n const msg = (input && typeof input === 'object' ? input : null) as Partial<WorkerMessage> | null;\n if (!msg) {\n throw new Error('Invalid worker message');\n }\n\n return {\n id: msg.id || randomId(),\n type: isWorkerMessageType(msg.type) ? msg.type : 'request',\n action: msg.action,\n payload: msg.payload,\n timestamp: msg.timestamp || Date.now(),\n compressed: msg.compressed,\n priority: isMessagePriority(msg.priority) ? msg.priority : 'normal',\n correlationId: msg.correlationId,\n };\n}\n\nexport function parseWorkerError(input: unknown): WorkerError {\n const error = (input && typeof input === 'object' ? input : {}) as Partial<WorkerError>;\n return {\n type: isWorkerErrorType(error.type) ? error.type : 'unknown',\n code: typeof error.code === 'string' ? error.code : undefined,\n message: typeof error.message === 'string' ? error.message : 'Worker error',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n timestamp: typeof error.timestamp === 'number' ? error.timestamp : Date.now(),\n recoverable: error.recoverable !== false,\n retryAfter: typeof error.retryAfter === 'number' ? error.retryAfter : undefined,\n context: error.context,\n };\n}\n\nexport function parseWorkerPoolConfig(input: unknown): WorkerPoolConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Partial<WorkerPoolConfig>;\n return {\n maxWorkers: config.maxWorkers ?? 4,\n minWorkers: config.minWorkers ?? 1,\n workerIdleTimeout: config.workerIdleTimeout ?? 30000,\n taskQueueSize: config.taskQueueSize ?? 100,\n resourceLimits: config.resourceLimits ?? {},\n autoScale: config.autoScale ?? true,\n scaleUpThreshold: config.scaleUpThreshold ?? 75,\n scaleDownThreshold: config.scaleDownThreshold ?? 25,\n };\n}\n\nexport function parseResourceUsage(input: unknown): ResourceUsage {\n const usage = (input && typeof input === 'object' ? input : {}) as Partial<ResourceUsage>;\n return {\n memory: usage.memory ?? { used: 0, limit: 0, percentage: 0 },\n cpu: usage.cpu ?? { usage: 0, limit: 100 },\n tasks: usage.tasks ?? { pending: 0, active: 0, completed: 0, failed: 0 },\n activeWorkers: usage.activeWorkers ?? 0,\n };\n}\n\nexport const ResourceUsageSchema = {\n parse: parseResourceUsage,\n};\n\nexport const WorkerPoolConfigSchema = {\n parse: parseWorkerPoolConfig,\n};\n\nexport function parseWorkerCapabilities(input: unknown): WorkerCapabilities {\n const cap = toRecord(input);\n const csp = toRecord(cap.csp);\n const performance = toRecord(cap.performance);\n\n return {\n workerAPI: cap.workerAPI !== false,\n sharedArrayBuffer: cap.sharedArrayBuffer === true,\n transferableObjects: cap.transferableObjects === true,\n offscreenCanvas: cap.offscreenCanvas === true,\n webAssembly: cap.webAssembly === true,\n atomics: cap.atomics === true,\n bigInt: cap.bigInt === true,\n csp: {\n workerSrc: csp.workerSrc === true,\n scriptSrc: csp.scriptSrc === true,\n blobUrls: csp.blobUrls === true,\n inlineWorkers: csp.inlineWorkers === true,\n },\n performance: {\n memory: performance.memory === true,\n measureUserAgentSpecificMemory: performance.measureUserAgentSpecificMemory === true,\n },\n };\n}\n\n/**\n * @param onWarn Called once per rejected config value (a supplied value that\n * failed validation and fell back to its default), for a caller that wants\n * to surface it — `BeaconConfigManager.validateAndMergeConfig` wires this to\n * `log('warn', ...)`. Never called for an omitted field; only for one the\n * caller actually set to something invalid.\n */\nexport function parseBeaconConfig(\n input: unknown,\n onWarn?: (message: string) => void\n): BeaconConfig {\n const config = toRecord(input);\n\n if (typeof config.projectId !== 'string' || config.projectId.length === 0) {\n throw new Error('Project ID is required');\n }\n\n return {\n projectId: config.projectId,\n environment: stringOr(config.environment),\n tags: isBeaconTags(config.tags) ? config.tags : undefined,\n identity: isBeaconIdentity(config.identity) ? config.identity : undefined,\n // `parseBeaconConfig` is an allowlist: a key it does not name is dropped\n // silently, which is how `identity` first shipped inert.\n endpoint: stringOr(config.endpoint),\n enabled: config.enabled !== false,\n debug: config.debug === true,\n logLevel: isLogLevel(config.logLevel) ? config.logLevel : 'error',\n respectDoNotTrack: config.respectDoNotTrack !== false,\n requireConsent: config.requireConsent === true,\n anonymizeIp: config.anonymizeIp === true,\n stripUrlFragment: config.stripUrlFragment !== false,\n scrubQueryParams: isStringArray(config.scrubQueryParams) ? config.scrubQueryParams : undefined,\n dropQueryParams: config.dropQueryParams === true,\n sessionTimeout: numberOr(config.sessionTimeout, undefined),\n sessionCookieName: stringOr(config.sessionCookieName, '_as_beacon_session'),\n browserSessionId: resumableSessionId(config.browserSessionId, (received) =>\n onWarn?.(\n `browserSessionId must match ${RESUMABLE_SESSION_ID} (received ${JSON.stringify(received)}); ignoring it`\n )\n ),\n onReceipt: receiptCallback(config.onReceipt, (received) =>\n onWarn?.(`onReceipt must be a function (received ${typeof received}); ignoring it`)\n ),\n // Deprecated no-ops (see BeaconConfig.batchSize/flushInterval): passed\n // through when a caller sets them so a stale value round-trips through\n // `get()`, never defaulted, since nothing reads them anymore.\n batchSize: typeof config.batchSize === 'number' ? config.batchSize : undefined,\n flushInterval: typeof config.flushInterval === 'number' ? config.flushInterval : undefined,\n collectorDeadlineMs: numberOr(config.collectorDeadlineMs, 1600),\n evidenceGrowthFactor: boundedNumberOr(\n config.evidenceGrowthFactor,\n 2,\n (n) => n > 1,\n (received) =>\n onWarn?.(\n `evidenceGrowthFactor must be a number greater than 1 (received ${JSON.stringify(received)}); using default 2`\n )\n ),\n postureRefreshFraction: boundedNumberOr(\n config.postureRefreshFraction,\n 0.5,\n (n) => n > 0 && n <= 1,\n (received) =>\n onWarn?.(\n `postureRefreshFraction must be a number in (0, 1] (received ${JSON.stringify(received)}); using default 0.5`\n )\n ),\n triggers: pickTriggers(config.triggers, (name, received) =>\n onWarn?.(\n `triggers.${name} must be a boolean (received ${JSON.stringify(received)}); ignoring it and keeping its default`\n )\n ),\n maxQueueSize: numberOr(config.maxQueueSize, Infinity),\n retryAttempts: numberOr(config.retryAttempts, 3),\n retryDelay: numberOr(config.retryDelay, 2000),\n postureRetryScheduleMs: isPositiveNumberArray(config.postureRetryScheduleMs)\n ? config.postureRetryScheduleMs\n : undefined,\n useWorker: resolveUseWorker(config),\n workerUrl: stringOr(config.workerUrl),\n workerConfig: isRecord(config.workerConfig) ? (config.workerConfig as WorkerConfig) : undefined,\n lazySignalsUrl: stringOr(config.lazySignalsUrl),\n proactiveRefreshMinIntervalMs: boundedNumberOr(\n config.proactiveRefreshMinIntervalMs,\n 30_000,\n (n) => n > 0,\n (received) =>\n onWarn?.(\n `proactiveRefreshMinIntervalMs must be a positive number (received ${JSON.stringify(received)}); using default 30000`\n )\n ),\n proactiveRefreshMaxIntervalMs: boundedNumberOr(\n config.proactiveRefreshMaxIntervalMs,\n 60_000,\n (n) => n > 0,\n (received) =>\n onWarn?.(\n `proactiveRefreshMaxIntervalMs must be a positive number (received ${JSON.stringify(received)}); using default 60000`\n )\n ),\n proactiveRefreshFreshnessMs: optionalPositiveNumber(\n config.proactiveRefreshFreshnessMs,\n (received) =>\n onWarn?.(\n `proactiveRefreshFreshnessMs must be a positive number (received ${JSON.stringify(received)}); ignoring it and inheriting postureRefreshFraction's threshold`\n )\n ),\n proactiveRefreshOnVisibilityResume: booleanOr(\n config.proactiveRefreshOnVisibilityResume,\n true,\n (received) =>\n onWarn?.(\n `proactiveRefreshOnVisibilityResume must be a boolean (received ${JSON.stringify(received)}); using default true`\n )\n ),\n proactiveRefreshOnOnline: booleanOr(config.proactiveRefreshOnOnline, true, (received) =>\n onWarn?.(\n `proactiveRefreshOnOnline must be a boolean (received ${JSON.stringify(received)}); using default true`\n )\n ),\n proactiveRefreshJitterSeed: optionalFiniteNumber(\n config.proactiveRefreshJitterSeed,\n (received) =>\n onWarn?.(\n `proactiveRefreshJitterSeed must be a finite number (received ${JSON.stringify(received)}); ignoring it, jitter will use Math.random()`\n )\n ),\n };\n}\n\n// ============================================================================\n// EXPORT MAIN CLASS TYPE\n// ============================================================================\n\nexport declare class AgentShieldBeacon implements IAgentShieldBeacon {\n constructor(config: BeaconConfig);\n collect(eventType: string, data?: BeaconPayload): Promise<void>;\n trackEvent(eventName: string, eventData?: BeaconPayload): Promise<void>;\n trackPageview(pageData?: BeaconPayload): Promise<void>;\n trackPageUnload(): Promise<void>;\n updateConfig(updates: Partial<BeaconConfig>): void;\n destroy(): Promise<void>;\n}\n\n/**\n * The most events one beacon POST may carry. The ingest route's\n * `BeaconBatchSchema` refuses a larger batch whole (a 400, not a retry), so\n * the SDK's offline drain never dequeues more than this per request.\n */\nexport const BEACON_MAX_EVENTS_PER_BATCH = 100;\n\nexport const SESSION_IDLE_GAP_MAX_MS = 21_600_000;\nexport const BEACON_MAX_BATCH_ID_LENGTH = 255;\n\nexport const BEACON_ORIGIN_CONTRACT_VERSION = 1;\n\nexport const BEACON_ORIGIN_CAPABILITIES = [\n 'batch-replay-v1',\n 'receipt-status-v1',\n 'receipt-posture-v1',\n 'batch-identity-digest-v1',\n] as const;\n\nexport const BEACON_EDGE_CAPABILITIES_HEADER = 'x-checkpoint-beacon-capabilities';\n\nexport const BEACON_EDGE_CAPABILITIES = ['key-pending-v1'] as const;\n\nexport type BeaconEdgeCapability = (typeof BEACON_EDGE_CAPABILITIES)[number];\n\nexport function beaconEdgeCapabilitiesHeaderValue(): string {\n return BEACON_EDGE_CAPABILITIES.join(',');\n}\n\nexport function parseBeaconEdgeCapabilities(\n value: string | null | undefined\n): BeaconEdgeCapability[] {\n const offered = (value ?? '').split(',').map((token) => token.trim());\n return BEACON_EDGE_CAPABILITIES.filter((capability) => offered.includes(capability));\n}\n\nexport function withAdoptedSession<\n B extends { sessionId: string; events: ReadonlyArray<Record<string, unknown>> },\n>(batch: B, sessionId: string): B {\n return {\n ...batch,\n sessionId,\n events: batch.events.map((event) => ({\n ...event,\n metadata: { ...(isRecord(event.metadata) ? event.metadata : {}), sessionId },\n })),\n };\n}\n\nconst BODY_IDENTITY_BLANKED_FIELDS = [\n 'nonce',\n 'nonceEcho',\n 'deviceId',\n 'anonymizeIp',\n 'publicJwk',\n 'handoffToken',\n 'queueEvictions',\n 'queueExpirations',\n 'queueCorruptions',\n] as const;\n\nfunction bodyIdentity(body: object, blanked: readonly string[]): string {\n const identity: Record<string, unknown> = { ...body };\n for (const field of blanked) identity[field] = undefined;\n return JSON.stringify(identity);\n}\n\nexport function beaconBodyIdentity(body: object): string {\n return bodyIdentity(body, [...BODY_IDENTITY_BLANKED_FIELDS, 'keyless']);\n}\n\nexport function beaconBodyIdentityWithKeyless(body: object): string {\n return bodyIdentity(body, BODY_IDENTITY_BLANKED_FIELDS);\n}\n\n/**\n * Lifetime of the signed browser posture token, in seconds. Defined here and\n * re-exported by `browser-posture.ts` (which imports `jose`) so the\n * size-budgeted beacon bundle can read it without pulling in a JWT library.\n */\nexport const POSTURE_TTL_SECONDS = 120;\n\nexport interface CachedPosture {\n token: string;\n expiresAt: number;\n}\n\nexport interface PostureAnswer {\n posture?: CachedPosture;\n postureStatus?: string;\n postureReason?: string;\n sessionId?: string;\n answeredAtMs?: number;\n}\n\nexport function parsePostureAnswer(value: unknown): PostureAnswer {\n if (!isRecord(value)) return {};\n const answer: PostureAnswer = {};\n if (\n isRecord(value.posture) &&\n typeof value.posture.token === 'string' &&\n value.posture.token.length > 0 &&\n typeof value.posture.expiresAt === 'number' &&\n Number.isFinite(value.posture.expiresAt)\n ) {\n answer.posture = { token: value.posture.token, expiresAt: value.posture.expiresAt };\n } else if (typeof value.postureStatus === 'string' && value.postureStatus.length <= 64) {\n answer.postureStatus = value.postureStatus;\n }\n if (typeof value.postureReason === 'string' && value.postureReason.length <= 64) {\n answer.postureReason = value.postureReason;\n }\n if (typeof value.sessionId === 'string' && value.sessionId.length <= 255) {\n answer.sessionId = value.sessionId;\n }\n if (typeof value.answeredAtMs === 'number' && Number.isFinite(value.answeredAtMs)) {\n answer.answeredAtMs = value.answeredAtMs;\n }\n return answer;\n}\n"],"mappings":";;;;;;AAMA,MAAM,qBAAqB;AAC3B,MAAM,UAAU;;;;;;AAOhB,SA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AM,SAAS,SAAS,SAAS,SAAS;CAC/C,OAAO,KAAK,UAAU,QAAQ;AAChC;AAEA,SAAgB,mBAAmB,MAAsB;CACvD,OAAO,aAAa,MAAM,CAAC,GAAG,8BAA8B,SAAS,CAAC;AACxE;AAEA,SAAgB,8BAA8B,MAAsB;CAClE,OAAO,aAAa,MAAM,4BAA4B;AACxD;;;;;;AAOA,MAAa,sBAAsB;AAenC,SAAgB,mBAAmB,OAA+B;CAChE,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO,CAAC;CAC9B,MAAM,SAAwB,CAAC;CAC/B,IACE,SAAS,MAAM,OAAO,KACtB,OAAO,MAAM,QAAQ,UAAU,YAC/B,MAAM,QAAQ,MAAM,SAAS,KAC7B,OAAO,MAAM,QAAQ,cAAc,YACnC,OAAO,SAAS,MAAM,QAAQ,SAAS,GAEvC,OAAO,UAAU;EAAE,OAAO,MAAM,QAAQ;EAAO,WAAW,MAAM,QAAQ;CAAU;MAC7E,IAAI,OAAO,MAAM,kBAAkB,YAAY,MAAM,cAAc,UAAU,IAClF,OAAO,gBAAgB,MAAM;CAE/B,IAAI,OAAO,MAAM,kBAAkB,YAAY,MAAM,cAAc,UAAU,IAC3E,OAAO,gBAAgB,MAAM;CAE/B,IAAI,OAAO,MAAM,cAAc,YAAY,MAAM,UAAU,UAAU,KACnE,OAAO,YAAY,MAAM;CAE3B,IAAI,OAAO,MAAM,iBAAiB,YAAY,OAAO,SAAS,MAAM,YAAY,GAC9E,OAAO,eAAe,MAAM;CAE9B,OAAO;AACT"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/utils/base64url.ts","../../src/beacon-types/session-commitment.ts","../../src/beacon-types/index.ts"],"sourcesContent":["/**\n * Base64url (RFC 4648 § 5) built on `atob` and `btoa` rather than Node's\n * buffer API, so it runs on every runtime the SDKs support, Cloudflare Workers\n * without `nodejs_compat` included.\n */\n\nconst BASE64URL_UNPADDED = /^[A-Za-z0-9_-]*$/;\nconst PADDING = 61; // '='\n\n/**\n * `text` without its trailing `=` padding. A backward scan, not\n * `replace(/=+$/, '')`: that regex retries from every `=` in a long run that\n * does not reach the end, which is quadratic on hostile input.\n */\nfunction withoutPadding(text: string): string {\n let end = text.length;\n while (end > 0 && text.charCodeAt(end - 1) === PADDING) end -= 1;\n return text.slice(0, end);\n}\n\n/**\n * Decode base64url, with or without `=` padding.\n *\n * Strict where Node's buffer decoder is lenient: a character outside the\n * alphabet, or a length no encoder produces (one character past a multiple of\n * four), throws a `TypeError` instead of being skipped or truncated. This\n * matches the engine's decoder.\n */\nexport function base64UrlToBytes(text: string): Uint8Array<ArrayBuffer> {\n const unpadded = withoutPadding(text);\n if (!BASE64URL_UNPADDED.test(unpadded) || unpadded.length % 4 === 1) {\n throw new TypeError('not valid base64url (RFC 4648 § 5)');\n }\n const base64 = unpadded.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/** Decode base64url to a string as UTF-8, replacing invalid sequences with U+FFFD. */\nexport function base64UrlToString(text: string): string {\n return new TextDecoder().decode(base64UrlToBytes(text));\n}\n\n/** Encode bytes as base64url without padding. */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return withoutPadding(btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_'));\n}\n","import { base64UrlToBytes } from '../utils/base64url';\n\nconst COMMITMENT_BYTES = 9;\nconst THUMBPRINT_BYTES = 32;\nconst COMMITTED_SESSION_ID =\n /^([0-9a-f]{8})-([0-9a-f]{4})-8([0-9a-f]{3})-[89ab]([0-9a-f]{3})-[0-9a-f]{12}$/;\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nexport function thumbprintCommitment(thumbprint: Uint8Array): string {\n return toHex(thumbprint.subarray(0, COMMITMENT_BYTES));\n}\n\nexport function sessionIdFromCommitment(commitment: string, uuidV4: string): string {\n return `${commitment.slice(0, 8)}-${commitment.slice(8, 12)}-8${commitment.slice(12, 15)}-${uuidV4[19]}${commitment.slice(15)}-${uuidV4.slice(24)}`;\n}\n\nexport function committedSessionId(thumbprint: Uint8Array, uuidV4: string): string {\n return sessionIdFromCommitment(thumbprintCommitment(thumbprint), uuidV4);\n}\n\nexport function sessionKeyCommitment(sessionId: string): string | undefined {\n const match = COMMITTED_SESSION_ID.exec(sessionId.toLowerCase());\n return match ? match.slice(1).join('') : undefined;\n}\n\nexport function sessionCommitsToThumbprint(sessionId: string, thumbprint: Uint8Array): boolean {\n const commitment = sessionKeyCommitment(sessionId);\n return commitment !== undefined && thumbprintCommitment(thumbprint) === commitment;\n}\n\nexport function sessionCommitsToJkt(sessionId: string, jkt: string): boolean {\n let thumbprint: Uint8Array;\n try {\n thumbprint = base64UrlToBytes(jkt);\n } catch {\n return false;\n }\n return (\n thumbprint.length === THUMBPRINT_BYTES && sessionCommitsToThumbprint(sessionId, thumbprint)\n );\n}\n\nexport function keyMayActForSession(sessionId: string, jkt: string | undefined): boolean {\n return (\n sessionKeyCommitment(sessionId) === undefined ||\n (jkt !== undefined && sessionCommitsToJkt(sessionId, jkt))\n );\n}\n","/**\n * Public TypeScript types for Checkpoint Beacon\n *\n * This package contains only the public API types needed by beacon consumers.\n * No implementation details or detection rules are included.\n */\n\nexport * from './session-commitment';\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue | undefined };\nexport type BeaconPrimitive = JsonPrimitive;\nexport type BeaconJsonValue = JsonValue;\nexport type BeaconCustomData = Record<string, JsonValue | undefined>;\nexport type BeaconPayload = BeaconCollectorData | BeaconCustomData | null;\nexport type WorkerPayload = unknown;\ntype UnknownRecord = Record<string, unknown>;\n\nexport const BATCH_COMMIT_STAGES = [\n 'poolWaitMs',\n 'receiptLockMs',\n 'ledgerLookupMs',\n 'detectionInsertMs',\n 'secondaryOutboxInsertMs',\n 'transactionCommitMs',\n 'afterCommitMs',\n 'postCommitMs',\n] as const;\n\nexport type BatchCommitStages = Record<(typeof BATCH_COMMIT_STAGES)[number], number>;\n\nexport const BEACON_COMMIT_STAGE_SAMPLE_HEADER = 'x-checkpoint-beacon-commit-stage-sample';\n\nfunction isRecord(input: unknown): input is UnknownRecord {\n return typeof input === 'object' && input !== null && !Array.isArray(input);\n}\n\nfunction toRecord(input: unknown): UnknownRecord {\n return isRecord(input) ? input : {};\n}\n\nfunction numberOr<Fallback extends number | undefined>(\n value: unknown,\n fallback: Fallback\n): number | Fallback {\n return typeof value === 'number' && Number.isFinite(value) && value !== 0 ? value : fallback;\n}\n\n/**\n * Validates a numeric config value against `ok`, falling back to `fallback`\n * when it fails. Only calls `onReject` when the caller actually supplied a\n * value (an `undefined` field, the common case, is not a rejection, it just\n * never overrode the default): H0BB5 (PR #5095 review, item 4) — a rejected\n * value used to fall back silently, with no way for a host to discover a\n * config typo.\n */\nfunction boundedNumberOr(\n value: unknown,\n fallback: number,\n ok: (n: number) => boolean,\n onReject?: (received: unknown) => void\n): number {\n if (typeof value === 'number' && Number.isFinite(value) && ok(value)) return value;\n if (value !== undefined) onReject?.(value);\n return fallback;\n}\n\n/** Same as `boundedNumberOr`, but an absent/rejected value stays `undefined` rather than defaulting. */\nfunction optionalPositiveNumber(\n value: unknown,\n onReject?: (received: unknown) => void\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;\n onReject?.(value);\n return undefined;\n}\n\n/** Same as `optionalPositiveNumber`, without the positivity requirement (a jitter seed may be any finite number). */\nfunction optionalFiniteNumber(\n value: unknown,\n onReject?: (received: unknown) => void\n): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n onReject?.(value);\n return undefined;\n}\n\n/** Same shape as `boundedNumberOr`/`optionalPositiveNumber`, for a boolean config flag. */\nfunction booleanOr(\n value: unknown,\n fallback: boolean,\n onReject?: (received: unknown) => void\n): boolean {\n if (value === undefined) return fallback;\n if (typeof value === 'boolean') return value;\n onReject?.(value);\n return fallback;\n}\n\n/** Ingest's own `sessionId` bound (1-255), limited to characters a cookie value carries unescaped. */\nconst RESUMABLE_SESSION_ID = /^[A-Za-z0-9._~-]{1,255}$/;\n\nfunction resumableSessionId(\n value: unknown,\n onReject?: (received: unknown) => void\n): string | undefined {\n if (value === undefined) return undefined;\n if (typeof value === 'string' && RESUMABLE_SESSION_ID.test(value)) return value;\n onReject?.(value);\n return undefined;\n}\n\nfunction receiptCallback(\n value: unknown,\n onReject?: (received: unknown) => void\n): BeaconConfig['onReceipt'] {\n if (value === undefined) return undefined;\n if (typeof value === 'function') return value as BeaconConfig['onReceipt'];\n onReject?.(value);\n return undefined;\n}\n\nconst DISPATCH_TRIGGER_NAMES = [\n 'arrival',\n 'signals',\n 'interaction',\n 'untrusted',\n 'posture',\n 'unload',\n 'navigation',\n] as const satisfies readonly (keyof BeaconDispatchTriggers)[];\n\n/**\n * Keeps only the known trigger names with a real boolean; anything else is\n * dropped and, when the caller actually named a known trigger with a\n * non-boolean value (`triggers: { posture: 0 }`, say), reported through\n * `onReject` — H0BB5 (PR #5095 review, item 4): a numeric `0` used to be\n * dropped silently and that trigger stayed at its default-enabled state,\n * the opposite of what the \"0 is falsy\" convention suggests.\n */\nfunction pickTriggers(\n value: unknown,\n onReject?: (name: string, received: unknown) => void\n): BeaconDispatchTriggers | undefined {\n if (!isRecord(value)) return undefined;\n const picked: BeaconDispatchTriggers = {};\n for (const name of DISPATCH_TRIGGER_NAMES) {\n const raw = value[name];\n if (typeof raw === 'boolean') {\n picked[name] = raw;\n } else if (raw !== undefined) {\n onReject?.(name, raw);\n }\n }\n return picked;\n}\n\nfunction stringOr(value: unknown, fallback?: string): string | undefined {\n return typeof value === 'string' ? value : fallback;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\n/**\n * Non-empty on purpose: an empty schedule would mean \"zero posture-recovery\n * attempts\", silently disabling recovery rather than configuring it. A\n * deployment that actually wants no retries sets `flushInterval` instead.\n */\nfunction isPositiveNumberArray(value: unknown): value is number[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every((entry) => typeof entry === 'number' && Number.isFinite(entry) && entry > 0)\n );\n}\n\nfunction isBeaconTags(value: unknown): value is Record<string, string | number | boolean> {\n return (\n isRecord(value) &&\n Object.values(value).every(\n (entry) =>\n typeof entry === 'string' || typeof entry === 'number' || typeof entry === 'boolean'\n )\n );\n}\n\n/**\n * Exported because `parseBeaconConfig` is an allowlist: a key it does not\n * name is dropped, silently. The beacon's other public entry point\n * (`checkpoint-shared/browser`) carries its own copy of that allowlist, so\n * the CHECK at least lives in one place even while the two parsers do not —\n * see the note on `BeaconConfig.identity`.\n *\n * Rejects an identity with no usable `userId` rather than passing through a\n * half-formed object: downstream this becomes `detections.user_id`, and an\n * empty string there is worse than an absent one — it reads as \"identified\"\n * while naming nobody.\n */\nexport function isBeaconIdentity(value: unknown): value is BeaconIdentity {\n return isRecord(value) && typeof value.userId === 'string' && value.userId.length > 0;\n}\n\nfunction isLogLevel(value: unknown): value is BeaconConfig['logLevel'] {\n return value === 'error' || value === 'warn' || value === 'info' || value === 'debug';\n}\n\nfunction isBeaconWorkerMessageType(value: unknown): value is BeaconWorkerMessageType {\n return (\n value === 'init' ||\n value === 'collect' ||\n value === 'flush' ||\n value === 'config' ||\n value === 'status' ||\n value === 'error' ||\n // `beacon.worker.ts`'s `respond()` has always sent this on every\n // successful request (init/collect/flush/config/status) — the allowlist\n // just never named it, so `parseBeaconWorkerMessage` silently coerced\n // every success response to `'init'` (see that function's fallback).\n value === 'response' ||\n value === 'posture'\n );\n}\n\n/**\n * Resolves whether a beacon should use its Web Worker transport.\n *\n * `enableWebWorker` is accepted as an alias for `useWorker`: the package's\n * own test suite (`checkpoint-beacon/src/index.test.ts`) has always\n * constructed with `enableWebWorker: false`, but `parseBeaconConfig`'s\n * allowlist only ever named `useWorker`, so that key was silently dropped —\n * the beacon kept auto-detecting worker support regardless of what the\n * caller passed. `useWorker` wins when both are set, since it's the\n * canonical name every other config field (`workerUrl`, `workerConfig`)\n * pairs with.\n */\nfunction resolveUseWorker(config: UnknownRecord): boolean {\n if (typeof config.useWorker === 'boolean') {\n return config.useWorker;\n }\n if (typeof config.enableWebWorker === 'boolean') {\n return config.enableWebWorker;\n }\n return true;\n}\n\nexport interface NetworkInformationLike extends EventTarget {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\nexport interface NavigatorWithNetworkInformation extends Navigator {\n connection?: NetworkInformationLike;\n mozConnection?: NetworkInformationLike;\n webkitConnection?: NetworkInformationLike;\n deviceMemory?: number;\n vendorSub: string;\n doNotTrack: string | null;\n msDoNotTrack?: string | null;\n}\n\nexport interface WindowWithBeaconMetadata extends Window {\n doNotTrack?: string | null;\n __NEXT_DATA__?: {\n buildId?: string;\n };\n}\n\nexport interface TrustedTypePolicyLike {\n createScriptURL(url: string): string;\n createScript(script: string): string;\n}\n\nexport interface WindowWithTrustedTypes extends Window {\n trustedTypes?: {\n createPolicy(\n name: string,\n rules: {\n createScriptURL?: (url: string) => string;\n createScript?: (script: string) => string;\n }\n ): TrustedTypePolicyLike;\n };\n}\n\nexport interface PerformanceMemoryInfo {\n usedJSHeapSize: number;\n totalJSHeapSize: number;\n jsHeapSizeLimit: number;\n}\n\nexport interface PerformanceWithMemory extends Performance {\n memory?: PerformanceMemoryInfo;\n measureUserAgentSpecificMemory?: () => Promise<unknown>;\n}\n\nexport interface LargestContentfulPaintEntry extends PerformanceEntry {\n renderTime?: number;\n loadTime?: number;\n}\n\n// ============================================================================\n// BEACON CONFIGURATION\n// ============================================================================\n\n/**\n * Who the current visitor is, when the host site knows.\n *\n * Deliberately just the id. The pixel's `identify` call also carries\n * `previousId` and `userTraits`, but those drive the server's profile and\n * alias-graph pipeline (tenant salt, profile-copy, write advisory locks),\n * which the beacon ingest route does not run — accepting them here would mean\n * collecting personal data the beacon path then silently discards. Both are\n * additive later: this is an optional field on an optional object.\n */\nexport interface BeaconIdentity {\n /**\n * The host site's own id for the signed-in user. Capped at 255 characters\n * to match `detections.user_id`; a longer value is rejected at ingest.\n */\n userId: string;\n}\n\n/** The beacon's automatic sends, each switchable off. See `BeaconConfig.triggers`. */\nexport interface BeaconDispatchTriggers {\n /** The `pageview` at construction and on consent restore. */\n arrival?: boolean;\n /** The follow-up send when the lazy signals chunk resolves after arrival missed it. */\n signals?: boolean;\n /** First interaction, first timing sample, and evidence growth. */\n interaction?: boolean;\n /** The first script-dispatched (untrusted) input. */\n untrusted?: boolean;\n /** An interaction after the posture token has gone stale. */\n posture?: boolean;\n /** The SDK-wired `visibilitychange` and `pagehide` critical send. */\n unload?: boolean;\n /**\n * The `pageview` for a page the visitor arrives at without a full load: a\n * back/forward-cache restore (`pageshow` with `persisted`, trigger\n * `bfcache_restore`) and a soft navigation that changes the path\n * (History API or Navigation API, trigger `soft_navigation`). Turn it off\n * when the host already calls `collect('pageview')` on its own route\n * changes, or each one sends twice.\n */\n navigation?: boolean;\n}\n\nexport interface BeaconConfig {\n /** Project ID for tracking (same as pixel data-project-id) */\n projectId: string;\n\n /**\n * Who the visitor is, when the page already knows at construction time.\n * When identity only becomes known later (a login part-way through the\n * session), call `identify()` instead.\n */\n identity?: BeaconIdentity;\n\n /**\n * Where batches are POSTed. Defaults to the hosted ingest endpoint declared\n * in `NETWORK_CONTRACT.md`.\n *\n * Set it to send somewhere else — a self-hosted deployment, a regional\n * install, or a test origin. An override means the destination is the\n * integrator's, not ours, so `NETWORK_CONTRACT.md` describes the DEFAULT and\n * says so explicitly.\n *\n * @default 'https://kya.vouched.id/api/v1/beacon'\n */\n endpoint?: string;\n\n /** Optional environment tag for data segmentation */\n environment?: 'development' | 'staging' | 'production' | string;\n\n /** Optional tags for custom data segmentation */\n tags?: Record<string, string | number | boolean>;\n\n /**\n * Not read by the SDK. Construct the beacon only when it should run, and\n * call `destroy()` to stop it.\n *\n * @deprecated\n */\n enabled?: boolean;\n\n /**\n * Verbose console logging.\n *\n * @default false\n */\n debug?: boolean;\n\n /**\n * Log verbosity.\n *\n * @default 'error'\n */\n logLevel?: 'error' | 'warn' | 'info' | 'debug';\n\n /**\n * When the browser sends Do Not Track, the beacon collects and sends nothing.\n *\n * @default true\n */\n respectDoNotTrack?: boolean;\n\n /**\n * Accepted and ignored. The beacon no longer withholds anything on\n * consent; only Do Not Track stops collection.\n *\n * @deprecated has no effect\n * @default false\n */\n requireConsent?: boolean;\n\n /**\n * Truncate the stored IP to /24 (IPv4) or /48 (IPv6) before persistence.\n *\n * @default false\n */\n anonymizeIp?: boolean;\n\n /**\n * Strip the `#fragment` from the `url`/`referrer` collector fields before\n * they leave the page. Defaults to `true`: a fragment is never sent to\n * the server by the browser in the first place for any OTHER surface\n * (it is script-visible only), so a beacon that forwards it is the one\n * place it can leak — and it is also the highest-risk part of the URL,\n * since SPA routers, magic-link auth, and OAuth implicit-flow responses\n * all put tokens there. Set to `false` only if a project genuinely\n * consumes `url`'s fragment server-side.\n *\n * @default true\n */\n stripUrlFragment?: boolean;\n\n /**\n * Query parameter names (matched case-insensitively) to redact from the\n * `url`/`referrer` collector fields before they leave the page. Each\n * matching value is replaced with the literal string `\"[redacted]\"`; the\n * parameter itself stays present so the URL's shape is unchanged. Empty\n * by default — nothing is scrubbed unless a project opts in with the\n * param names it puts tokens/PII behind (e.g. `[\"token\", \"email\"]`).\n * Ignored for a parameter when `dropQueryParams` is also `true`, since\n * there is no query string left to scrub.\n *\n * @default []\n */\n scrubQueryParams?: string[];\n\n /**\n * Drop the entire query string from the `url`/`referrer` collector\n * fields before they leave the page. Off by default. Takes priority over\n * `scrubQueryParams` when both are set — there is nothing left to scrub\n * once the whole query string is gone.\n *\n * @default false\n */\n dropQueryParams?: boolean;\n\n /**\n * Idle-gap override in milliseconds, at most six hours. Unset: one hour on\n * phones, six hours elsewhere. Every send extends it.\n */\n sessionTimeout?: number;\n\n /**\n * Name of the visitor session cookie shared by pixel, beacon, gateway, and\n * SDK rows. Query it with `?sessionId=` on the\n * [detections endpoint](/docs/api-reference#get-project-detections).\n *\n * @default '_as_beacon_session'\n */\n sessionCookieName?: string;\n\n /**\n * Resume a browser session id the page stored earlier (a receipt's\n * `browserSessionId`, see `onReceipt`) instead of reading the session\n * cookie or minting a new id. With cookies off this is the only way two\n * page loads stay one session, and a posture token verifies only against\n * the session id it was issued to. 1 to 255 characters of\n * `A-Z a-z 0-9 . _ ~ -`; anything else is ignored with a warning.\n * `updateConfig({ browserSessionId })` switches a running beacon to it.\n */\n browserSessionId?: string;\n\n /**\n * Called with every ingest receipt: the server's session id, the browser\n * session id the batch was sent under, and the posture token or the reason\n * there is none. Runs on the main thread in worker mode too, after the\n * posture cookie write. An error it throws is logged at `warn` and never\n * affects delivery.\n */\n onReceipt?: (receipt: BeaconReceipt) => void;\n\n /**\n * @deprecated The beacon no longer batches; every dispatch sends\n * immediately. Accepted and ignored so a caller upgrading from an older\n * SDK version keeps compiling and does not need to touch its config.\n */\n batchSize?: number;\n\n /**\n * @deprecated The beacon no longer polls on an interval; it dispatches on\n * evidence transitions instead (arrival, first interaction, evidence\n * doubling, untrusted input, posture staleness, hidden/pagehide). Accepted\n * and ignored so a caller upgrading from an older SDK version keeps\n * compiling and does not need to touch its config.\n */\n flushInterval?: number;\n\n /**\n * How much `keyDwellCount + pressCount + untrustedEvents` has to grow, as a\n * multiple of its value at the last send, before an interaction sends\n * again. 2 sends at 1, 2, 4, 8, 16 samples; 1.5 sends more often, 3 less.\n * A value at or below 1 falls back to the default.\n *\n * @default 2\n */\n evidenceGrowthFactor?: number;\n\n /**\n * Fraction of the posture token's lifetime after which a counted\n * interaction sends again, so the token stays fresh under a live hand.\n * 0.5 refreshes the 120 s token once an interaction lands more than 60 s\n * after the last send. A value outside (0, 1] falls back to the default.\n *\n * @default 0.5\n */\n postureRefreshFraction?: number;\n\n /**\n * Which automatic sends fire. Every trigger is on unless set to `false`.\n * Turning `unload` off leaves `trackPageUnload()` available for a host\n * that wires its own listener; turning `arrival` off leaves `collect()`.\n */\n triggers?: BeaconDispatchTriggers;\n\n /**\n * Low-frequency backstop that refreshes posture on a jittered timer,\n * independent of interaction, so a visitor who goes idle past the posture\n * TTL with no counted interaction is not one stale click on a critical\n * action away from an expired token (H0BB5, PR #5095 review). The actual\n * interval on each tick is `proactiveRefreshMinIntervalMs` plus a random\n * `[0, max - min)` jitter, so a fleet of clients loaded at the same moment\n * does not all refresh on the same wall-clock boundary. Paused while the\n * page is hidden, resumed on `visibilitychange`. Gated by\n * `triggers.posture`, the same switch that already turns off the\n * interaction-triggered staleness check — this timer is that same\n * `'posture'` trigger firing proactively, not a second mechanism. A\n * non-positive value falls back to the default.\n *\n * @default 30000\n */\n proactiveRefreshMinIntervalMs?: number;\n\n /**\n * The upper bound of the proactive-refresh jitter window; see\n * `proactiveRefreshMinIntervalMs`. A non-positive value falls back to the\n * default; a value below `proactiveRefreshMinIntervalMs` degrades to the\n * minimum on every tick rather than throwing.\n *\n * @default 60000\n */\n proactiveRefreshMaxIntervalMs?: number;\n\n /**\n * How old the last send must be, in milliseconds, before a visibility\n * resume forces an immediate posture refresh. Defaults to the same\n * threshold the interaction-triggered check already uses\n * (`postureRefreshFraction` of the posture token's lifetime), so the two\n * stay in lockstep unless a host deliberately wants the visibility check\n * to be stricter or looser. A non-positive value falls back to that\n * default.\n */\n proactiveRefreshFreshnessMs?: number;\n\n /**\n * On `visibilitychange` back to visible, force an immediate posture\n * refresh when it is stale (see `proactiveRefreshFreshnessMs`); a fresh\n * tab regaining focus does not get an unnecessary send either way. Set to\n * `false` to leave visibility resume to the plain interval alone.\n *\n * @default true\n */\n proactiveRefreshOnVisibilityResume?: boolean;\n\n /**\n * Refresh posture (and drain anything the offline queue is still holding)\n * when the browser fires `online`. Set to `false` to leave reconnection\n * recovery to the offline queue's own `online` listener alone.\n *\n * @default true\n */\n proactiveRefreshOnOnline?: boolean;\n\n /**\n * A fixed seed for the proactive-refresh jitter roll, for deterministic\n * tests. Omit in production for real `Math.random()` jitter.\n */\n proactiveRefreshJitterSeed?: number;\n\n /**\n * Per-collector deadline in milliseconds. A collector still running past\n * this deadline is dropped from the current collection round rather than\n * awaited further — see `collectWithDeadline` in checkpoint-beacon.\n * Default and rationale documented in checkpoint-beacon's\n * `src/budget/thresholds.ts`.\n *\n * @default 1600\n */\n collectorDeadlineMs?: number;\n\n /**\n * Maximum number of queued events.\n *\n * @default 100\n */\n maxQueueSize?: number;\n\n /**\n * Retry count for failed sends.\n *\n * @default 3\n */\n retryAttempts?: number;\n\n /**\n * Base retry delay in milliseconds.\n *\n * @default 2000\n */\n retryDelay?: number;\n\n /**\n * Delays in milliseconds between posture-recovery attempts after a\n * durably-queued ingest response that carried no posture verdict. The\n * array's length is the attempt ceiling. Defaults to the shipped ladder;\n * override only in tests and in a self-hosted deployment with a\n * different outage profile.\n */\n postureRetryScheduleMs?: number[];\n\n /**\n * Prefer a Web Worker for event processing, batching, and transport.\n * Page-dependent collection remains on the main thread. Unsupported\n * browsers fall back to the main thread; SSR never starts a worker.\n * Set false to disable the processing worker.\n *\n * @default true\n */\n useWorker?: boolean;\n\n /**\n * Alias for `useWorker`, accepted for callers using the older option\n * name. When both are set, `useWorker` wins — see `resolveUseWorker`.\n */\n enableWebWorker?: boolean;\n\n /**\n * URL of the worker script (`beacon.worker.js`, exported as\n * `@kya-os/checkpoint-beacon/worker`). Classic workers must be same-origin.\n * When unset, the beacon derives `beacon.worker.js` next to the `<script>`\n * tag that loaded `beacon.min.js`, else `/beacon.worker.js` at the site root.\n */\n workerUrl?: string;\n\n /**\n * Worker lifecycle tuning: `initTimeoutMs` (3000), `messageTimeout` (30000),\n * `heartbeatInterval` (5000), `maxRetries` (3), `retryDelay` (1000),\n * `compressionThreshold` (5120), `allowFallback` (true).\n */\n workerConfig?: WorkerConfig;\n\n lazySignalsUrl?: string;\n}\n\n// ============================================================================\n// BEACON EVENTS\n// ============================================================================\n\nexport interface BeaconEvent {\n /** Event type identifier */\n type: BeaconEventType;\n\n /** Event data payload */\n data: BeaconCollectorData;\n\n /** Event metadata */\n metadata: BeaconMetadata;\n}\n\nexport interface BeaconMetadata {\n /** Session ID */\n sessionId: string;\n\n /** Event timestamp */\n timestamp: number;\n\n /** Optional event name */\n eventName?: string;\n\n /** Present only once the host site has told us who the visitor is. */\n identity?: BeaconIdentity;\n\n /** Allow additional metadata */\n [key: string]: unknown;\n}\n\n// ============================================================================\n// BEACON API\n// ============================================================================\n\nexport interface IAgentShieldBeacon {\n /**\n * Collect a generic event\n */\n collect(eventType: string, data?: BeaconPayload): Promise<void>;\n\n /**\n * Track a custom event\n */\n trackEvent(eventName: string, eventData?: BeaconPayload): Promise<void>;\n\n /**\n * Track a pageview\n */\n trackPageview(pageData?: BeaconPayload): Promise<void>;\n\n /**\n * Track page unload\n */\n trackPageUnload(): Promise<void>;\n\n /**\n * Update configuration\n */\n updateConfig(updates: Partial<BeaconConfig>): void;\n\n /**\n * Destroy the beacon and clean up\n */\n destroy(): Promise<void>;\n}\n\n// ============================================================================\n// RESPONSE TYPES\n// ============================================================================\n\nexport interface BeaconResponse {\n /** Response status */\n status: 'success' | 'error';\n\n /** Optional message */\n message?: string;\n\n /** Optional error details */\n error?: {\n code: string;\n message: string;\n };\n}\n\n// ============================================================================\n// BROWSER CONTEXT\n// ============================================================================\n\nexport interface BrowserContext {\n /** Browser name and version */\n browser: {\n name: string;\n version: string;\n engine: string;\n };\n\n /** Operating system */\n os: {\n name: string;\n version: string;\n };\n\n /** Device information */\n device: {\n type: 'desktop' | 'mobile' | 'tablet' | 'tv' | 'unknown';\n vendor?: string;\n model?: string;\n };\n\n /** Screen information */\n screen: {\n width: number;\n height: number;\n pixelRatio: number;\n colorDepth: number;\n };\n\n /** Connection information */\n connection?: {\n type: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown';\n effectiveType?: '2g' | '3g' | '4g' | '5g';\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n };\n}\n\n// ============================================================================\n// PERFORMANCE METRICS\n// ============================================================================\n\nexport interface PerformanceMetrics {\n /** Page load time in milliseconds */\n pageLoadTime?: number;\n\n /** DOM content loaded time */\n domContentLoadedTime?: number;\n\n /** Time to interactive */\n timeToInteractive?: number;\n\n /** First paint time */\n firstPaintTime?: number;\n\n /** First contentful paint time */\n firstContentfulPaintTime?: number;\n\n /** Largest contentful paint time */\n largestContentfulPaintTime?: number;\n\n /** DNS lookup time */\n dnsLookupTime?: number;\n\n /** TCP connection time */\n tcpConnectionTime?: number;\n\n /** Server response time */\n serverResponseTime?: number;\n\n /** Resource timing */\n resources?: {\n scripts: number;\n stylesheets: number;\n images: number;\n fonts: number;\n total: number;\n };\n}\n\n// ============================================================================\n// SESSION TYPES\n// ============================================================================\n\nexport interface SessionData {\n /** Unique session ID */\n id: string;\n\n /** Session start timestamp */\n startTime: number;\n\n /** Last activity timestamp */\n lastActivity: number;\n\n /** Page view count in session */\n pageViews: number;\n\n /** Event count in session */\n eventCount: number;\n\n /** Session duration in milliseconds */\n duration: number;\n\n /** Is this a new session */\n isNew: boolean;\n}\n\n// ============================================================================\n// TRANSPORT TYPES\n// ============================================================================\n\nexport interface TransportConfig {\n maxRetries: number;\n retryDelayBase: number;\n offlineQueueSize: number;\n useCompression: boolean;\n compressionThreshold: number;\n /** Build item 6: carried onto every outgoing `BeaconBatch` — see `BeaconConfig.anonymizeIp`. */\n anonymizeIp?: boolean;\n}\n\nexport interface TransportOptions {\n immediate?: boolean;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n retry?: boolean;\n timeout?: number;\n publicJwk?: EcPublicJwk;\n keyless?: BeaconKeyless;\n deviceId?: string;\n handoffToken?: string;\n batch?: QueuedBatchIdentity;\n reflexiveIp?: string;\n environment?: BeaconEnvironmentSignals;\n}\n\nexport interface TransportResponse {\n success: boolean;\n timestamp: number;\n batchId?: string;\n error?: string;\n queued?: boolean;\n}\n\nexport type TransportState = 'idle' | 'sending' | 'offline' | 'paused' | 'error';\n\nexport interface TransportMetrics {\n eventsSent: number;\n eventsFailed: number;\n eventsQueued: number;\n batchesSent: number;\n batchesFailed: number;\n bytesTransferred: number;\n compressionRatio?: number;\n averageLatency?: number;\n lastSuccessTimestamp?: number;\n lastErrorTimestamp?: number;\n eventsEvicted?: number;\n eventsExpired?: number;\n entriesCorrupt?: number;\n}\n\nexport type ConnectionType =\n | 'bluetooth'\n | 'cellular'\n | 'ethernet'\n | 'none'\n | 'wifi'\n | 'wimax'\n | 'other'\n | 'unknown';\n\nexport interface NetworkInfo {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\n// ============================================================================\n// WORKER TYPES\n// ============================================================================\n\nexport type MessagePriority = 'low' | 'normal' | 'high' | 'critical';\nexport type WorkerErrorType =\n | 'initialization'\n | 'runtime'\n | 'communication'\n | 'timeout'\n | 'memory'\n | 'network'\n | 'permission'\n | 'validation'\n | 'processing'\n | 'unknown';\nexport type WorkerAction =\n | 'process'\n | 'init'\n | 'terminate'\n | 'pause'\n | 'resume'\n | 'status'\n | 'health';\nexport type WorkerMessageType = 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n\nexport interface WorkerMessage {\n id: string;\n type: 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n action?: string;\n payload?: WorkerPayload;\n timestamp: number;\n compressed?: boolean;\n priority?: MessagePriority;\n correlationId?: string;\n}\n\nexport type WorkerState =\n | 'idle'\n | 'initializing'\n | 'ready'\n | 'processing'\n | 'busy'\n | 'error'\n | 'terminating'\n | 'terminated';\n\nexport type WorkerHealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\nexport interface WorkerMetrics {\n tasksProcessed: number;\n tasksFailed: number;\n averageProcessingTime?: number;\n memoryUsage?: number;\n cpuUsage?: number;\n healthStatus: WorkerHealthStatus;\n lastHealthCheck: number;\n restartCount: number;\n errorRate?: number;\n errorCount: number;\n messageQueueSize: number;\n startTime: number;\n uptime: number;\n averageTaskTime?: number;\n lastTaskTime?: number;\n}\n\nexport interface WorkerError {\n type: WorkerErrorType;\n code?: string;\n message: string;\n stack?: string;\n timestamp: number;\n recoverable: boolean;\n retryAfter?: number;\n context?: Record<string, unknown>;\n}\n\nexport interface WorkerCapabilities {\n workerAPI: boolean;\n sharedArrayBuffer: boolean;\n transferableObjects: boolean;\n offscreenCanvas: boolean;\n webAssembly: boolean;\n atomics: boolean;\n bigInt: boolean;\n csp: {\n workerSrc: boolean;\n scriptSrc: boolean;\n blobUrls: boolean;\n inlineWorkers: boolean;\n };\n performance: {\n memory: boolean;\n measureUserAgentSpecificMemory: boolean;\n };\n}\n\nexport interface WorkerTask {\n id: string;\n type: string;\n data: WorkerPayload;\n priority: 'low' | 'normal' | 'high' | 'critical';\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n error?: WorkerError;\n maxRetries?: number;\n retries?: number;\n timeout?: number;\n}\n\nexport interface FallbackOptions {\n useRequestIdleCallback: boolean;\n idleTimeout: number;\n chunkSize: number;\n throttleMs: number;\n maxExecutionTime: number;\n}\n\nexport interface ResourceUsage {\n memory: {\n used: number;\n limit: number;\n percentage: number;\n };\n cpu: {\n usage: number;\n limit: number;\n };\n tasks: {\n pending: number;\n active: number;\n completed: number;\n failed: number;\n };\n activeWorkers: number;\n}\n\nexport interface WorkerPoolConfig {\n maxWorkers: number;\n minWorkers: number;\n workerIdleTimeout: number;\n taskQueueSize: number;\n resourceLimits: Record<string, number>;\n autoScale?: boolean;\n scaleUpThreshold?: number;\n scaleDownThreshold?: number;\n}\n\nexport type BeaconWorkerMessageType =\n | 'init'\n | 'collect'\n | 'flush'\n | 'config'\n | 'status'\n | 'error'\n | 'response'\n // Unsolicited worker -> main relay of a 202 ingest body (posture cookie\n // delivery needs `document`, which the worker lacks).\n | 'posture';\nexport type ProtocolVersion = '1.0' | '1.1' | '2.0';\n\nexport interface BeaconWorkerMessage {\n type: BeaconWorkerMessageType;\n data?: WorkerPayload;\n payload?: WorkerPayload;\n messageId: string;\n timestamp: number;\n id: string;\n}\n\nexport interface WorkerConfig {\n enabled?: boolean;\n url?: string;\n heartbeatInterval?: number;\n maxUnhealthyCount?: number;\n maxRetries?: number;\n retryDelay?: number;\n restartDelay?: number;\n messageTimeout?: number;\n compressionThreshold?: number;\n allowFallback?: boolean;\n crossOriginIsolated?: boolean;\n maxRestartAttempts?: number;\n terminationTimeout?: number;\n taskTimeout?: number;\n fallbackDelay?: number;\n enableFallback?: boolean;\n /**\n * Hard ceiling on how long worker startup (script load + init handshake)\n * gets before the caller gives up and falls back to the main-thread\n * transport. Deliberately separate from `taskTimeout`/`messageTimeout`\n * (which govern steady-state message round trips once the worker is\n * already up): a slow or hung worker script would otherwise hold up\n * every event for the full 30s message timeout before anything left the\n * page. A few seconds is enough for a healthy worker to load and answer\n * its init message; anything slower isn't worth waiting on.\n */\n initTimeoutMs?: number;\n}\n\n// ============================================================================\n// CIRCUIT BREAKER & RETRY\n// ============================================================================\n\nexport interface CircuitBreakerConfig {\n threshold: number;\n timeout: number;\n resetTimeout: number;\n}\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half-open';\n\nexport interface RetryStrategy {\n maxAttempts: number;\n baseDelay: number;\n maxDelay: number;\n factor: number;\n jitter: boolean;\n}\n\n// ============================================================================\n// OFFLINE QUEUE\n// ============================================================================\n\nexport interface QueuedBatchIdentity {\n batchId: string;\n sessionId: string;\n timestamp: number;\n projectId?: string;\n handoffToken?: string;\n}\n\nexport interface OfflineQueueEntry {\n id: string;\n events: BeaconEvent[];\n timestamp: number;\n expiresAt: number;\n retryCount: number;\n size: number;\n batch?: QueuedBatchIdentity;\n}\n\n// ============================================================================\n// BEACON BATCH\n// ============================================================================\n\n/** The minimal EC-P256 public JWK shape the beacon can construct without\n * a JOSE library dependency (see P37's findings on bundle-size discipline).\n * Structurally compatible with `jose`'s wider `JWK` type on the server side. */\nexport interface EcPublicJwk {\n kty: 'EC';\n crv: 'P-256';\n x: string;\n y: string;\n}\n\n/** What `BeaconConfig.onReceipt` receives for each 202 ingest response. */\nexport interface BeaconReceipt {\n /**\n * The server's session id for this visit, the key\n * `GET /api/v1/projects/{id}/sessions/{sessionId}` reads. On a receipt from\n * the queue-only edge it is present once the origin has answered for the\n * session, and absent before (`postureStatus: 'pending'`).\n */\n sessionId?: string;\n /**\n * The beacon's own session id the batch was sent under: what a posture\n * token is bound to, and what `BeaconConfig.browserSessionId` resumes.\n */\n browserSessionId: string;\n /** The signed posture token, when ingest issued one. `expiresAt` is Unix seconds. */\n posture?: { token: string; expiresAt: number };\n /** Why `posture` is absent: `'pending'` while a queued batch awaits replay, otherwise the withheld reason. */\n postureStatus?: string;\n}\n\nexport interface BeaconNetworkSignals {\n reflexiveIp?: string;\n timezone?: string;\n languages?: string[];\n rttMs?: number;\n}\n\nexport interface BeaconEnvironmentSignals {\n incognito?: boolean;\n privacySettings?: boolean;\n virtualMachine?: boolean;\n developerTools?: boolean;\n tampering?: boolean;\n antiDetect?: boolean;\n osMismatch?: boolean;\n}\n\nexport interface BeaconBatch {\n projectId: string;\n events: BeaconEvent[];\n sessionId: string;\n handoffToken?: string;\n deviceId?: string;\n batchId: string;\n timestamp: number;\n anonymizeIp?: boolean;\n nonce?: string;\n nonceEcho?: boolean;\n publicJwk?: EcPublicJwk;\n keyless?: BeaconKeyless;\n queueEvictions?: number;\n queueExpirations?: number;\n queueCorruptions?: number;\n network?: BeaconNetworkSignals;\n environment?: BeaconEnvironmentSignals;\n}\n\nexport type BeaconKeyless = 1 | 2;\n\nexport interface BeaconCollectorData {\n // Browser collector data\n userAgent?: string;\n language?: string;\n platform?: string;\n screenResolution?: string;\n viewport?: string;\n cookiesEnabled?: boolean;\n doNotTrack?: boolean;\n timezone?: string;\n referrer?: string;\n url?: string;\n title?: string;\n vendor?: string;\n\n // Performance collector data\n pageLoadTime?: number;\n domContentLoadedTime?: number;\n firstPaintTime?: number;\n firstContentfulPaintTime?: number;\n connectionType?: string;\n\n // Session data\n sessionId?: string;\n timestamp?: number;\n\n // Allow additional properties\n [key: string]: unknown;\n}\n\nexport type BeaconEventType =\n | 'pageview'\n | 'pageunload'\n | 'heartbeat'\n | 'evidence'\n | 'custom'\n | 'error'\n | 'performance';\n\n// ============================================================================\n// PARSER FUNCTIONS\n// ============================================================================\n\nexport function parseRetryStrategy(input: unknown): RetryStrategy {\n const strategy = toRecord(input);\n return {\n maxAttempts: numberOr(strategy.maxAttempts, 3),\n baseDelay: numberOr(strategy.baseDelay, 1000),\n maxDelay: numberOr(strategy.maxDelay, 30000),\n factor: numberOr(strategy.factor, 2),\n jitter: strategy.jitter !== false,\n };\n}\n\nexport function parseCircuitBreakerConfig(input: unknown): CircuitBreakerConfig {\n const config = toRecord(input);\n return {\n threshold: numberOr(config.threshold, 5),\n timeout: numberOr(config.timeout, 60000),\n resetTimeout: numberOr(config.resetTimeout, 30000),\n };\n}\n\nfunction parseQueuedBatchIdentity(input: unknown): QueuedBatchIdentity | undefined {\n if (!isRecord(input)) return undefined;\n const { batchId, sessionId, timestamp, projectId, handoffToken } = input;\n if (\n typeof batchId !== 'string' ||\n batchId.length < 1 ||\n batchId.length > BEACON_MAX_BATCH_ID_LENGTH ||\n typeof sessionId !== 'string' ||\n sessionId.length < 1 ||\n typeof timestamp !== 'number' ||\n !Number.isFinite(timestamp)\n ) {\n return undefined;\n }\n return {\n batchId,\n sessionId,\n timestamp,\n ...(typeof projectId === 'string' && projectId.length > 0 && { projectId }),\n ...(typeof handoffToken === 'string' && handoffToken.length > 0 && { handoffToken }),\n };\n}\n\nexport function parseOfflineQueueEntry(input: unknown): OfflineQueueEntry {\n if (!isRecord(input)) {\n throw new Error('Invalid offline queue entry');\n }\n\n const entry = input;\n const batch = parseQueuedBatchIdentity(entry.batch);\n return {\n id: stringOr(\n entry.id,\n `${Date.now()}_${Array.from(crypto.getRandomValues(new Uint8Array(6)), (byte) => byte.toString(16).padStart(2, '0')).join('')}`\n )!,\n events: Array.isArray(entry.events) ? (entry.events as BeaconEvent[]) : [],\n timestamp: numberOr(entry.timestamp, Date.now()),\n expiresAt: numberOr(entry.expiresAt, Date.now() + 86400000), // 24 hours\n retryCount: numberOr(entry.retryCount, 0),\n size: numberOr(entry.size, 0),\n ...(batch ? { batch } : {}),\n };\n}\n\nfunction randomId(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nexport function parseBeaconWorkerMessage(input: unknown): BeaconWorkerMessage {\n if (!isRecord(input)) {\n throw new Error('Invalid beacon worker message');\n }\n\n const msg = input;\n const messageId = stringOr(msg.messageId) ?? stringOr(msg.id) ?? randomId();\n return {\n type: isBeaconWorkerMessageType(msg.type) ? msg.type : 'init',\n data: msg.data,\n payload: msg.payload,\n messageId,\n timestamp: numberOr(msg.timestamp, Date.now()),\n id: stringOr(msg.id, messageId)!,\n };\n}\n\nfunction isMessagePriority(value: unknown): value is MessagePriority {\n return value === 'low' || value === 'normal' || value === 'high' || value === 'critical';\n}\n\nfunction isWorkerMessageType(value: unknown): value is WorkerMessageType {\n return (\n value === 'request' ||\n value === 'response' ||\n value === 'error' ||\n value === 'heartbeat' ||\n value === 'status'\n );\n}\n\nfunction isWorkerErrorType(value: unknown): value is WorkerErrorType {\n return (\n value === 'initialization' ||\n value === 'runtime' ||\n value === 'communication' ||\n value === 'timeout' ||\n value === 'memory' ||\n value === 'network' ||\n value === 'permission' ||\n value === 'validation' ||\n value === 'processing' ||\n value === 'unknown'\n );\n}\n\nexport function parseWorkerMessage(input: unknown): WorkerMessage {\n const msg = (input && typeof input === 'object' ? input : null) as Partial<WorkerMessage> | null;\n if (!msg) {\n throw new Error('Invalid worker message');\n }\n\n return {\n id: msg.id || randomId(),\n type: isWorkerMessageType(msg.type) ? msg.type : 'request',\n action: msg.action,\n payload: msg.payload,\n timestamp: msg.timestamp || Date.now(),\n compressed: msg.compressed,\n priority: isMessagePriority(msg.priority) ? msg.priority : 'normal',\n correlationId: msg.correlationId,\n };\n}\n\nexport function parseWorkerError(input: unknown): WorkerError {\n const error = (input && typeof input === 'object' ? input : {}) as Partial<WorkerError>;\n return {\n type: isWorkerErrorType(error.type) ? error.type : 'unknown',\n code: typeof error.code === 'string' ? error.code : undefined,\n message: typeof error.message === 'string' ? error.message : 'Worker error',\n stack: typeof error.stack === 'string' ? error.stack : undefined,\n timestamp: typeof error.timestamp === 'number' ? error.timestamp : Date.now(),\n recoverable: error.recoverable !== false,\n retryAfter: typeof error.retryAfter === 'number' ? error.retryAfter : undefined,\n context: error.context,\n };\n}\n\nexport function parseWorkerPoolConfig(input: unknown): WorkerPoolConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Partial<WorkerPoolConfig>;\n return {\n maxWorkers: config.maxWorkers ?? 4,\n minWorkers: config.minWorkers ?? 1,\n workerIdleTimeout: config.workerIdleTimeout ?? 30000,\n taskQueueSize: config.taskQueueSize ?? 100,\n resourceLimits: config.resourceLimits ?? {},\n autoScale: config.autoScale ?? true,\n scaleUpThreshold: config.scaleUpThreshold ?? 75,\n scaleDownThreshold: config.scaleDownThreshold ?? 25,\n };\n}\n\nexport function parseResourceUsage(input: unknown): ResourceUsage {\n const usage = (input && typeof input === 'object' ? input : {}) as Partial<ResourceUsage>;\n return {\n memory: usage.memory ?? { used: 0, limit: 0, percentage: 0 },\n cpu: usage.cpu ?? { usage: 0, limit: 100 },\n tasks: usage.tasks ?? { pending: 0, active: 0, completed: 0, failed: 0 },\n activeWorkers: usage.activeWorkers ?? 0,\n };\n}\n\nexport const ResourceUsageSchema = {\n parse: parseResourceUsage,\n};\n\nexport const WorkerPoolConfigSchema = {\n parse: parseWorkerPoolConfig,\n};\n\nexport function parseWorkerCapabilities(input: unknown): WorkerCapabilities {\n const cap = toRecord(input);\n const csp = toRecord(cap.csp);\n const performance = toRecord(cap.performance);\n\n return {\n workerAPI: cap.workerAPI !== false,\n sharedArrayBuffer: cap.sharedArrayBuffer === true,\n transferableObjects: cap.transferableObjects === true,\n offscreenCanvas: cap.offscreenCanvas === true,\n webAssembly: cap.webAssembly === true,\n atomics: cap.atomics === true,\n bigInt: cap.bigInt === true,\n csp: {\n workerSrc: csp.workerSrc === true,\n scriptSrc: csp.scriptSrc === true,\n blobUrls: csp.blobUrls === true,\n inlineWorkers: csp.inlineWorkers === true,\n },\n performance: {\n memory: performance.memory === true,\n measureUserAgentSpecificMemory: performance.measureUserAgentSpecificMemory === true,\n },\n };\n}\n\n/**\n * @param onWarn Called once per rejected config value (a supplied value that\n * failed validation and fell back to its default), for a caller that wants\n * to surface it — `BeaconConfigManager.validateAndMergeConfig` wires this to\n * `log('warn', ...)`. Never called for an omitted field; only for one the\n * caller actually set to something invalid.\n */\nexport function parseBeaconConfig(\n input: unknown,\n onWarn?: (message: string) => void\n): BeaconConfig {\n const config = toRecord(input);\n\n if (typeof config.projectId !== 'string' || config.projectId.length === 0) {\n throw new Error('Project ID is required');\n }\n\n return {\n projectId: config.projectId,\n environment: stringOr(config.environment),\n tags: isBeaconTags(config.tags) ? config.tags : undefined,\n identity: isBeaconIdentity(config.identity) ? config.identity : undefined,\n // `parseBeaconConfig` is an allowlist: a key it does not name is dropped\n // silently, which is how `identity` first shipped inert.\n endpoint: stringOr(config.endpoint),\n enabled: config.enabled !== false,\n debug: config.debug === true,\n logLevel: isLogLevel(config.logLevel) ? config.logLevel : 'error',\n respectDoNotTrack: config.respectDoNotTrack !== false,\n requireConsent: config.requireConsent === true,\n anonymizeIp: config.anonymizeIp === true,\n stripUrlFragment: config.stripUrlFragment !== false,\n scrubQueryParams: isStringArray(config.scrubQueryParams) ? config.scrubQueryParams : undefined,\n dropQueryParams: config.dropQueryParams === true,\n sessionTimeout: numberOr(config.sessionTimeout, undefined),\n sessionCookieName: stringOr(config.sessionCookieName, '_as_beacon_session'),\n browserSessionId: resumableSessionId(config.browserSessionId, (received) =>\n onWarn?.(\n `browserSessionId must match ${RESUMABLE_SESSION_ID} (received ${JSON.stringify(received)}); ignoring it`\n )\n ),\n onReceipt: receiptCallback(config.onReceipt, (received) =>\n onWarn?.(`onReceipt must be a function (received ${typeof received}); ignoring it`)\n ),\n // Deprecated no-ops (see BeaconConfig.batchSize/flushInterval): passed\n // through when a caller sets them so a stale value round-trips through\n // `get()`, never defaulted, since nothing reads them anymore.\n batchSize: typeof config.batchSize === 'number' ? config.batchSize : undefined,\n flushInterval: typeof config.flushInterval === 'number' ? config.flushInterval : undefined,\n collectorDeadlineMs: numberOr(config.collectorDeadlineMs, 1600),\n evidenceGrowthFactor: boundedNumberOr(\n config.evidenceGrowthFactor,\n 2,\n (n) => n > 1,\n (received) =>\n onWarn?.(\n `evidenceGrowthFactor must be a number greater than 1 (received ${JSON.stringify(received)}); using default 2`\n )\n ),\n postureRefreshFraction: boundedNumberOr(\n config.postureRefreshFraction,\n 0.5,\n (n) => n > 0 && n <= 1,\n (received) =>\n onWarn?.(\n `postureRefreshFraction must be a number in (0, 1] (received ${JSON.stringify(received)}); using default 0.5`\n )\n ),\n triggers: pickTriggers(config.triggers, (name, received) =>\n onWarn?.(\n `triggers.${name} must be a boolean (received ${JSON.stringify(received)}); ignoring it and keeping its default`\n )\n ),\n maxQueueSize: numberOr(config.maxQueueSize, Infinity),\n retryAttempts: numberOr(config.retryAttempts, 3),\n retryDelay: numberOr(config.retryDelay, 2000),\n postureRetryScheduleMs: isPositiveNumberArray(config.postureRetryScheduleMs)\n ? config.postureRetryScheduleMs\n : undefined,\n useWorker: resolveUseWorker(config),\n workerUrl: stringOr(config.workerUrl),\n workerConfig: isRecord(config.workerConfig) ? (config.workerConfig as WorkerConfig) : undefined,\n lazySignalsUrl: stringOr(config.lazySignalsUrl),\n proactiveRefreshMinIntervalMs: boundedNumberOr(\n config.proactiveRefreshMinIntervalMs,\n 30_000,\n (n) => n > 0,\n (received) =>\n onWarn?.(\n `proactiveRefreshMinIntervalMs must be a positive number (received ${JSON.stringify(received)}); using default 30000`\n )\n ),\n proactiveRefreshMaxIntervalMs: boundedNumberOr(\n config.proactiveRefreshMaxIntervalMs,\n 60_000,\n (n) => n > 0,\n (received) =>\n onWarn?.(\n `proactiveRefreshMaxIntervalMs must be a positive number (received ${JSON.stringify(received)}); using default 60000`\n )\n ),\n proactiveRefreshFreshnessMs: optionalPositiveNumber(\n config.proactiveRefreshFreshnessMs,\n (received) =>\n onWarn?.(\n `proactiveRefreshFreshnessMs must be a positive number (received ${JSON.stringify(received)}); ignoring it and inheriting postureRefreshFraction's threshold`\n )\n ),\n proactiveRefreshOnVisibilityResume: booleanOr(\n config.proactiveRefreshOnVisibilityResume,\n true,\n (received) =>\n onWarn?.(\n `proactiveRefreshOnVisibilityResume must be a boolean (received ${JSON.stringify(received)}); using default true`\n )\n ),\n proactiveRefreshOnOnline: booleanOr(config.proactiveRefreshOnOnline, true, (received) =>\n onWarn?.(\n `proactiveRefreshOnOnline must be a boolean (received ${JSON.stringify(received)}); using default true`\n )\n ),\n proactiveRefreshJitterSeed: optionalFiniteNumber(\n config.proactiveRefreshJitterSeed,\n (received) =>\n onWarn?.(\n `proactiveRefreshJitterSeed must be a finite number (received ${JSON.stringify(received)}); ignoring it, jitter will use Math.random()`\n )\n ),\n };\n}\n\n// ============================================================================\n// EXPORT MAIN CLASS TYPE\n// ============================================================================\n\nexport declare class AgentShieldBeacon implements IAgentShieldBeacon {\n constructor(config: BeaconConfig);\n collect(eventType: string, data?: BeaconPayload): Promise<void>;\n trackEvent(eventName: string, eventData?: BeaconPayload): Promise<void>;\n trackPageview(pageData?: BeaconPayload): Promise<void>;\n trackPageUnload(): Promise<void>;\n updateConfig(updates: Partial<BeaconConfig>): void;\n destroy(): Promise<void>;\n}\n\n/**\n * The most events one beacon POST may carry. The ingest route's\n * `BeaconBatchSchema` refuses a larger batch whole (a 400, not a retry), so\n * the SDK's offline drain never dequeues more than this per request.\n */\nexport const BEACON_MAX_EVENTS_PER_BATCH = 100;\n\nexport const BEACON_MAX_BATCH_ENVELOPES = 100;\n\nexport const SESSION_IDLE_GAP_MAX_MS = 21_600_000;\nexport const BEACON_MAX_BATCH_ID_LENGTH = 255;\n\nexport const BEACON_RECEIPT_ID_PATTERN = /^bri_[0-9a-f]{64}$/;\nexport const BEACON_BODY_DIGEST_PATTERN = /^[0-9a-f]{64}$/;\nexport const BEACON_PROJECT_UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\nfunction matchesReceiptPattern(pattern: RegExp, value: unknown): boolean {\n return typeof value === 'string' && pattern.test(value);\n}\n\nfunction isOptionalReceiptDigest(value: unknown): boolean {\n return value === undefined || matchesReceiptPattern(BEACON_BODY_DIGEST_PATTERN, value);\n}\n\nexport function isBeaconReceiptLookupItem(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) return false;\n const item = value as Record<string, unknown>;\n const { batchId, eventCount, acceptedAt } = item;\n return (\n matchesReceiptPattern(BEACON_RECEIPT_ID_PATTERN, item.receiptId) &&\n matchesReceiptPattern(BEACON_BODY_DIGEST_PATTERN, item.bodySha256) &&\n isOptionalReceiptDigest(item.alternateBodySha256) &&\n isOptionalReceiptDigest(item.clientBodySha256) &&\n matchesReceiptPattern(BEACON_PROJECT_UUID_PATTERN, item.projectId) &&\n typeof batchId === 'string' &&\n batchId.length >= 1 &&\n batchId.length <= BEACON_MAX_BATCH_ID_LENGTH &&\n Number.isInteger(eventCount) &&\n (eventCount as number) >= 1 &&\n (eventCount as number) <= BEACON_MAX_EVENTS_PER_BATCH &&\n (acceptedAt === undefined ||\n (typeof acceptedAt === 'string' && !Number.isNaN(Date.parse(acceptedAt))))\n );\n}\n\nexport const BEACON_ORIGIN_CONTRACT_VERSION = 1;\n\nexport const BEACON_ORIGIN_CAPABILITIES = [\n 'batch-replay-v1',\n 'receipt-status-v1',\n 'receipt-posture-v1',\n 'receipt-posture-journal-v1',\n 'batch-identity-digest-v1',\n 'project-admission-v1',\n 'gzip-request-bodies-v1',\n] as const;\n\nexport const BEACON_EDGE_CAPABILITIES_HEADER = 'x-checkpoint-beacon-capabilities';\n\nexport const BEACON_EDGE_CAPABILITIES = ['key-pending-v1'] as const;\n\nexport type BeaconEdgeCapability = (typeof BEACON_EDGE_CAPABILITIES)[number];\n\nexport function beaconEdgeCapabilitiesHeaderValue(): string {\n return BEACON_EDGE_CAPABILITIES.join(',');\n}\n\nexport function parseBeaconEdgeCapabilities(\n value: string | null | undefined\n): BeaconEdgeCapability[] {\n const offered = (value ?? '').split(',').map((token) => token.trim());\n return BEACON_EDGE_CAPABILITIES.filter((capability) => offered.includes(capability));\n}\n\nexport function withAdoptedSession<\n B extends { sessionId: string; events: ReadonlyArray<Record<string, unknown>> },\n>(batch: B, sessionId: string): B {\n return {\n ...batch,\n sessionId,\n events: batch.events.map((event) => ({\n ...event,\n metadata: { ...(isRecord(event.metadata) ? event.metadata : {}), sessionId },\n })),\n };\n}\n\nconst BODY_IDENTITY_BLANKED_FIELDS = [\n 'nonce',\n 'nonceEcho',\n 'deviceId',\n 'anonymizeIp',\n 'publicJwk',\n 'handoffToken',\n 'queueEvictions',\n 'queueExpirations',\n 'queueCorruptions',\n] as const;\n\nfunction bodyIdentity(body: object, blanked: readonly string[]): string {\n const identity: Record<string, unknown> = { ...body };\n for (const field of blanked) identity[field] = undefined;\n return JSON.stringify(identity);\n}\n\nexport function beaconBodyIdentity(body: object): string {\n return bodyIdentity(body, [...BODY_IDENTITY_BLANKED_FIELDS, 'keyless']);\n}\n\nexport function beaconBodyIdentityWithKeyless(body: object): string {\n return bodyIdentity(body, BODY_IDENTITY_BLANKED_FIELDS);\n}\n\n/**\n * Lifetime of the signed browser posture token, in seconds. Defined here and\n * re-exported by `browser-posture.ts` (which imports `jose`) so the\n * size-budgeted beacon bundle can read it without pulling in a JWT library.\n */\nexport const POSTURE_TTL_SECONDS = 120;\n\nexport interface CachedPosture {\n token: string;\n expiresAt: number;\n}\n\nexport interface PostureAnswer {\n posture?: CachedPosture;\n postureStatus?: string;\n postureReason?: string;\n sessionId?: string;\n answeredAtMs?: number;\n}\n\nexport function parsePostureAnswer(value: unknown): PostureAnswer {\n if (!isRecord(value)) return {};\n const answer: PostureAnswer = {};\n if (\n isRecord(value.posture) &&\n typeof value.posture.token === 'string' &&\n value.posture.token.length > 0 &&\n typeof value.posture.expiresAt === 'number' &&\n Number.isFinite(value.posture.expiresAt)\n ) {\n answer.posture = { token: value.posture.token, expiresAt: value.posture.expiresAt };\n } else if (typeof value.postureStatus === 'string' && value.postureStatus.length <= 64) {\n answer.postureStatus = value.postureStatus;\n }\n if (typeof value.postureReason === 'string' && value.postureReason.length <= 64) {\n answer.postureReason = value.postureReason;\n }\n if (typeof value.sessionId === 'string' && value.sessionId.length <= 255) {\n answer.sessionId = value.sessionId;\n }\n if (typeof value.answeredAtMs === 'number' && Number.isFinite(value.answeredAtMs)) {\n answer.answeredAtMs = value.answeredAtMs;\n }\n return answer;\n}\n\nexport const POSTURE_RECOVERY_FORMAT_VERSION = 1;\n\nexport type PostureRecovery =\n | {\n state: 'ready';\n answerFormatVersion: number;\n answer: PostureAnswer;\n answeredAtMs: number;\n expiresAtMs: number;\n }\n | { state: 'expired'; expiresAtMs?: number }\n | { state: 'not-required' }\n | { state: 'legacy' }\n | { state: 'unavailable' };\n\nexport function parsePostureRecovery(value: unknown): PostureRecovery | undefined {\n if (!isRecord(value) || typeof value.state !== 'string') return undefined;\n if (value.state === 'not-required' || value.state === 'legacy' || value.state === 'unavailable') {\n return { state: value.state };\n }\n if (value.state === 'expired') {\n return typeof value.expiresAtMs === 'number' && Number.isFinite(value.expiresAtMs)\n ? { state: 'expired', expiresAtMs: value.expiresAtMs }\n : { state: 'expired' };\n }\n if (\n value.state !== 'ready' ||\n value.answerFormatVersion !== POSTURE_RECOVERY_FORMAT_VERSION ||\n typeof value.answeredAtMs !== 'number' ||\n !Number.isFinite(value.answeredAtMs) ||\n typeof value.expiresAtMs !== 'number' ||\n !Number.isFinite(value.expiresAtMs)\n ) {\n return undefined;\n }\n const answer = parsePostureAnswer(value.answer);\n if (!answer.posture && !answer.postureStatus && !answer.sessionId) return undefined;\n if (value.answeredAtMs > value.expiresAtMs) return undefined;\n return {\n state: 'ready',\n answerFormatVersion: POSTURE_RECOVERY_FORMAT_VERSION,\n answer,\n answeredAtMs: value.answeredAtMs,\n expiresAtMs: value.expiresAtMs,\n };\n}\n\nfunction postureTokenClaims(token: string): unknown {\n const [, payload, , extra] = token.split('.');\n if (payload === undefined || extra !== undefined) return undefined;\n const binary = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));\n return JSON.parse(\n new TextDecoder().decode(Uint8Array.from(binary, (character) => character.charCodeAt(0)))\n );\n}\n\nasync function postureSessionBinding(sessionId: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(sessionId));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\nfunction keyBindingHolds(\n actualJkt: unknown,\n { proofJkt, batchKeyJkt }: { proofJkt: string | undefined; batchKeyJkt: string | undefined }\n): boolean {\n if (proofJkt !== undefined) return actualJkt === proofJkt;\n return actualJkt === undefined || actualJkt === batchKeyJkt;\n}\n\nexport async function postureAnswerMatchesBinding(\n answer: PostureAnswer,\n binding: {\n projectId: string;\n browserSessionId: string;\n origin: string | undefined;\n proofJkt: string | undefined;\n batchKeyJkt: string | undefined;\n }\n): Promise<boolean> {\n if (!answer.posture) return true;\n try {\n const claims = postureTokenClaims(answer.posture.token);\n if (!isRecord(claims)) return false;\n const actualJkt = isRecord(claims.cnf) ? claims.cnf.jkt : undefined;\n return (\n claims.project_id === binding.projectId &&\n claims.origin === binding.origin &&\n claims.binding === (await postureSessionBinding(binding.browserSessionId)) &&\n keyBindingHolds(actualJkt, binding)\n );\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;AAMA,MAAM,qBAAqB;AAC3B,MAAM,UAAU;;;;;;AAOhB,SAAS,eAAe,MAAsB;CAC5C,IAAI,MAAM,KAAK;CACf,OAAO,MAAM,KAAK,KAAK,WAAW,MAAM,CAAC,MAAM,SAAS,OAAO;CAC/D,OAAO,KAAK,MAAM,GAAG,GAAG;AAC1B;;;;;;;;;AAUA,SAAgB,iBAAiB,MAAuC;CACtE,MAAM,WAAW,eAAe,IAAI;CACpC,IAAI,CAAC,mBAAmB,KAAK,QAAQ,KAAK,SAAS,SAAS,MAAM,GAChE,MAAM,IAAI,UAAU,oCAAoC;CAE1D,MAAM,SAAS,SAAS,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG;CAC5D,MAAM,SAAS,KAAK,SAAS,IAAI,QAAQ,IAAK,OAAO,SAAS,KAAM,CAAC,CAAC;CACtE,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAClD,MAAM,SAAS,OAAO,WAAW,KAAK;CAExC,OAAO;AACT;;;;ACtCA,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,uBACJ;AAEF,SAAS,MAAM,OAA2B;CACxC,OAAO,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAChF;AAEA,SAAgB,qBAAqB,YAAgC;CACnE,OAAO,MAAM,WAAW,SAAS,GAAG,gBAAgB,CAAC;AACvD;AAEA,SAAgB,wBAAwB,YAAoB,QAAwB;CAClF,OAAO,GAAG,WAAW,MAAM,GAAG,CAAC,EAAE,GAAG,WAAW,MAAM,GAAG,EAAE,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AAe,QAAQ,aAC9B,OAAO,WAAW,QAAQ,UAC1B,OAAO,YAAa,MAAM,sBAAsB,QAAQ,gBAAgB,KACxE,gBAAgB,WAAW,OAAO;CAEtC,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -34,6 +34,23 @@ declare const BrowserPostureSchema: ZodObject<{
34
34
  cnf: ZodOptional<ZodObject<{
35
35
  jkt: ZodString;
36
36
  }, $strip>>;
37
+ network: ZodOptional<ZodObject<{
38
+ reflexive_ip: ZodOptional<ZodString>;
39
+ ip_masked: ZodOptional<ZodBoolean>;
40
+ timezone: ZodOptional<ZodString>;
41
+ languages: ZodOptional<ZodArray<ZodString>>;
42
+ rtt_ms: ZodOptional<ZodNumber>;
43
+ serving_region: ZodOptional<ZodString>;
44
+ }, $strip>>;
45
+ environment: ZodOptional<ZodObject<{
46
+ incognito: ZodOptional<ZodBoolean>;
47
+ privacy_settings: ZodOptional<ZodBoolean>;
48
+ virtual_machine: ZodOptional<ZodBoolean>;
49
+ developer_tools: ZodOptional<ZodBoolean>;
50
+ tampering: ZodOptional<ZodBoolean>;
51
+ anti_detect: ZodOptional<ZodBoolean>;
52
+ os_mismatch: ZodOptional<ZodBoolean>;
53
+ }, $strip>>;
37
54
  iat: ZodNumber;
38
55
  exp: ZodNumber;
39
56
  }, $strip>;
@@ -166,4 +183,4 @@ declare function postureRequiredScopes(config: BrowserPostureConfig, path: strin
166
183
  declare function validateBrowserPostureConfig(config: BrowserPostureConfig, projectId: string | undefined): void;
167
184
  //#endregion
168
185
  export { POSTURE_VERIFICATION_STATUSES as A, verifyBrowserPosture as C, BrowserPostureRejectionReason as D, BrowserPostureOutcomeSchema as E, POSTURE_TTL_SECONDS as F, postureCookieName as I, browserPostureReport as M, BrowserPosture as N, BrowserPostureReportIngestSchema as O, BrowserPostureSchema as P, validateBrowserPostureConfig as S, BrowserPostureOutcome as T, postureRequiredScopes as _, POSTURE_SESSION_HEADER as a, readPostureCookie as b, PostureVerification as c, inspectBrowserPosture as d, postureFromCookies as f, postureRequestFromHeaders as g, postureOutcomeReport as h, POSTURE_ISSUER as i, PostureVerificationStatus as j, BrowserPostureReportSchema as k, UNSIGNED_BROWSER_AGENT as l, postureOutcomeFromRequest as m, JWK$1 as n, POSTURE_TYPE as o, postureFromRequest as p, POSTURE_HEADER as r, PostureRequest as s, BrowserPostureConfig as t, behavioralConfidence as u, postureSessionBinding as v, BROWSER_POSTURE_REJECTION_REASONS as w, signBrowserPosture as x, postureUpgrade as y };
169
- //# sourceMappingURL=browser-posture-5fPrsxx7.d.mts.map
186
+ //# sourceMappingURL=browser-posture-WPk0kl9u.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-posture-WPk0kl9u.d.mts","names":[],"sources":["../src/browser-posture-cookie.ts","../src/beacon-types/index.ts","../src/browser-posture-schema.ts","../src/browser-posture-report.ts","../src/browser-posture.ts"],"mappings":";;;iBAgBgB,kBAAkB;;;cC0uDrB;;;cCxvDA,sBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgE/B;KAGU,iBAAiB,cAAe;;;cClE/B;KACD,oCAAoC;cAGnC,4BAA0B;;;;;;;;;;;;;;GAWrC;cAEW;KAaD,wCAAwC;cAEvC,6BAA2B;;;;;;;;;;;;;;;;;;;GAQpC;KACQ,wBAAwB,cAAe;cA2BtC,kCAAgC;;;;;;;;;;;;;;GAE3C;iBAEc,qBAAqB,SAAS;;;;;;;;;;;;;cClDjC;;;;;cAKA,uBAAwB;UAG3B;EACR;EACA;EACA;EACA;EACA;EACA;;iBAGc,eAAe,SAAS,iBAAiB;cAyC5C;cAGA;UAEI;EAEf,WAAW;EACX;EAEA;EACA;EACA;EAEA,kBAAkB;IAAQ;IAAc;;;iBAI1B,kBACd,mCACA;iBAcoB,sBAAsB,oBAAoB;iBAc1C,mBACpB,SAAS,gBACT,YAAY,KACZ,gBACC;KAqBS;EACN;EAAoB,SAAS;;EAC7B;;EACA;EAAoB,QAAQ;;cAOrB,uBAAwB,SAAS,wBAAsB;iBAM9C,sBACpB,2BACA,QAAQ,sBACR,mBACA,sCACA,eACC,QAAQ;iBA2EW,qBACpB,2BACA,QAAQ,sBACR,mBACA,sCACA,eACC,QAAQ;cAYE;cACA;UAGI;EACf;EAEA;EAEA;;iBAIc,0BACd,MAAM,iEACL;iBA6BmB,0BACpB,SAAS,gBACT,QAAQ,sBACR,mBACA,eACC,QAAQ;iBAcW,mBACpB,SAAS,gBACT,QAAQ,sBACR,mBACA,eACC,QAAQ;iBAIW,mBACpB,mCACA,QAAQ,sBACR,oBACC,QAAQ;iBA2CK,sBACd,QAAQ,sBACR;iBAiBc,6BACd,QAAQ,sBACR"}
@@ -34,6 +34,23 @@ declare const BrowserPostureSchema: ZodObject<{
34
34
  cnf: ZodOptional<ZodObject<{
35
35
  jkt: ZodString;
36
36
  }, $strip>>;
37
+ network: ZodOptional<ZodObject<{
38
+ reflexive_ip: ZodOptional<ZodString>;
39
+ ip_masked: ZodOptional<ZodBoolean>;
40
+ timezone: ZodOptional<ZodString>;
41
+ languages: ZodOptional<ZodArray<ZodString>>;
42
+ rtt_ms: ZodOptional<ZodNumber>;
43
+ serving_region: ZodOptional<ZodString>;
44
+ }, $strip>>;
45
+ environment: ZodOptional<ZodObject<{
46
+ incognito: ZodOptional<ZodBoolean>;
47
+ privacy_settings: ZodOptional<ZodBoolean>;
48
+ virtual_machine: ZodOptional<ZodBoolean>;
49
+ developer_tools: ZodOptional<ZodBoolean>;
50
+ tampering: ZodOptional<ZodBoolean>;
51
+ anti_detect: ZodOptional<ZodBoolean>;
52
+ os_mismatch: ZodOptional<ZodBoolean>;
53
+ }, $strip>>;
37
54
  iat: ZodNumber;
38
55
  exp: ZodNumber;
39
56
  }, $strip>;
@@ -166,4 +183,4 @@ declare function postureRequiredScopes(config: BrowserPostureConfig, path: strin
166
183
  declare function validateBrowserPostureConfig(config: BrowserPostureConfig, projectId: string | undefined): void;
167
184
  //#endregion
168
185
  export { POSTURE_VERIFICATION_STATUSES as A, verifyBrowserPosture as C, BrowserPostureRejectionReason as D, BrowserPostureOutcomeSchema as E, POSTURE_TTL_SECONDS as F, postureCookieName as I, browserPostureReport as M, BrowserPosture as N, BrowserPostureReportIngestSchema as O, BrowserPostureSchema as P, validateBrowserPostureConfig as S, BrowserPostureOutcome as T, postureRequiredScopes as _, POSTURE_SESSION_HEADER as a, readPostureCookie as b, PostureVerification as c, inspectBrowserPosture as d, postureFromCookies as f, postureRequestFromHeaders as g, postureOutcomeReport as h, POSTURE_ISSUER as i, PostureVerificationStatus as j, BrowserPostureReportSchema as k, UNSIGNED_BROWSER_AGENT as l, postureOutcomeFromRequest as m, JWK$1 as n, POSTURE_TYPE as o, postureFromRequest as p, POSTURE_HEADER as r, PostureRequest as s, BrowserPostureConfig as t, behavioralConfidence as u, postureSessionBinding as v, BROWSER_POSTURE_REJECTION_REASONS as w, signBrowserPosture as x, postureUpgrade as y };
169
- //# sourceMappingURL=browser-posture-CCR1kh5e.d.ts.map
186
+ //# sourceMappingURL=browser-posture-_y6BcdXw.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-posture-_y6BcdXw.d.ts","names":[],"sources":["../src/browser-posture-cookie.ts","../src/beacon-types/index.ts","../src/browser-posture-schema.ts","../src/browser-posture-report.ts","../src/browser-posture.ts"],"mappings":";;;iBAgBgB,kBAAkB;;;cC0uDrB;;;cCxvDA,sBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgE/B;KAGU,iBAAiB,cAAe;;;cClE/B;KACD,oCAAoC;cAGnC,4BAA0B;;;;;;;;;;;;;;GAWrC;cAEW;KAaD,wCAAwC;cAEvC,6BAA2B;;;;;;;;;;;;;;;;;;;GAQpC;KACQ,wBAAwB,cAAe;cA2BtC,kCAAgC;;;;;;;;;;;;;;GAE3C;iBAEc,qBAAqB,SAAS;;;;;;;;;;;;;cClDjC;;;;;cAKA,uBAAwB;UAG3B;EACR;EACA;EACA;EACA;EACA;EACA;;iBAGc,eAAe,SAAS,iBAAiB;cAyC5C;cAGA;UAEI;EAEf,WAAW;EACX;EAEA;EACA;EACA;EAEA,kBAAkB;IAAQ;IAAc;;;iBAI1B,kBACd,mCACA;iBAcoB,sBAAsB,oBAAoB;iBAc1C,mBACpB,SAAS,gBACT,YAAY,KACZ,gBACC;KAqBS;EACN;EAAoB,SAAS;;EAC7B;;EACA;EAAoB,QAAQ;;cAOrB,uBAAwB,SAAS,wBAAsB;iBAM9C,sBACpB,2BACA,QAAQ,sBACR,mBACA,sCACA,eACC,QAAQ;iBA2EW,qBACpB,2BACA,QAAQ,sBACR,mBACA,sCACA,eACC,QAAQ;cAYE;cACA;UAGI;EACf;EAEA;EAEA;;iBAIc,0BACd,MAAM,iEACL;iBA6BmB,0BACpB,SAAS,gBACT,QAAQ,sBACR,mBACA,eACC,QAAQ;iBAcW,mBACpB,SAAS,gBACT,QAAQ,sBACR,mBACA,eACC,QAAQ;iBAIW,mBACpB,mCACA,QAAQ,sBACR,oBACC,QAAQ;iBA2CK,sBACd,QAAQ,sBACR;iBAiBc,6BACd,QAAQ,sBACR"}
@@ -1 +1 @@
1
- {"version":3,"file":"browser-posture-cookie.mjs","names":[],"sources":["../src/constants/patterns.ts","../src/browser-posture-cookie.ts"],"sourcesContent":["/**\n * Regular Expression Patterns\n *\n * Common regex patterns used for validation and detection\n */\n\n/**\n * Validation Patterns\n */\n// Hoisted out of the object literal below so bundle-size-critical leaves can\n// import JUST this one pattern. `VALIDATION_PATTERNS` re-exports it, so there\n// is still exactly one definition and no drift.\n//\n// Why it matters: rolldown (via tsdown) does not do property-level DCE on a\n// const object literal the way esbuild did. `browser-posture-cookie.ts` uses\n// only `.UUID`, but importing the whole object dragged every pattern —\n// ULID, SLUG, IPV4, IPV6 — into that leaf, taking it from 272 to 2,870 bytes.\nexport const UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport const VALIDATION_PATTERNS = {\n // Identifiers\n UUID: UUID_PATTERN,\n ULID: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n SLUG: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,\n\n // Network\n IPV4: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,\n IPV6: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,\n IP: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,\n // eslint-disable-next-line no-useless-escape\n // CIDR pattern: uses IPV4 pattern and restricts mask to 0-32\n CIDR: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\/(?:[0-9]|[12][0-9]|3[0-2])$/,\n // eslint-disable-next-line no-useless-escape\n DOMAIN: /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i,\n HOSTNAME:\n /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/,\n // eslint-disable-next-line no-useless-escape\n URL: /^https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/,\n\n // Contact\n // Email pattern: stricter validation (rejects consecutive dots, requires TLD)\n // Local part: alphanumeric start/end, dots allowed but not consecutive\n EMAIL:\n /^[a-zA-Z0-9](?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]|\\.(?!\\.))*[a-zA-Z0-9]?@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,\n PHONE: /^[+]?[(]?[0-9]{3}[)]?[-\\s.]?[0-9]{3}[-\\s.]?[0-9]{4,6}$/,\n\n // Security\n // JWT pattern: requires 3 parts (header.payload.signature) - signature cannot be empty\n JWT: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+$/,\n // eslint-disable-next-line no-useless-escape\n BASE64: /^[A-Za-z0-9+\\/]*={0,2}$/,\n HEX: /^[0-9a-fA-F]+$/,\n MD5: /^[a-f0-9]{32}$/i,\n SHA1: /^[a-f0-9]{40}$/i,\n SHA256: /^[a-f0-9]{64}$/i,\n\n // Versions\n SEMVER:\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/,\n\n // Files\n FILENAME: /^[a-zA-Z0-9](?:[a-zA-Z0-9 ._-]*[a-zA-Z0-9])?\\.[a-zA-Z0-9_-]+$/,\n PATH: /^(\\/[^/ ]*)+\\/?$/,\n\n // Keys\n API_KEY: /^[A-Za-z0-9_-]{32,}$/,\n SECRET_KEY: /^[A-Za-z0-9_-]{64,}$/,\n PIXEL_ID: /^px_[A-Za-z0-9]{16}$/,\n} as const;\n\n/**\n * User Agent Patterns for Agent Detection\n */\nexport const USER_AGENT_PATTERNS = {\n // AI Agents\n OPENAI: /(?:GPTBot|ChatGPT-User|OpenAI)/i,\n ANTHROPIC: /(?:Claude-Web|Claude-User|anthropic-ai|claude-web|claude-user|ClaudeBot)/i,\n PERPLEXITY: /(?:PerplexityBot|Perplexica)/i,\n GOOGLE_AI: /(?:Bard|Google-InspectionTool)/i,\n MICROSOFT_AI: /(?:BingPreview\\/.*ChatGPT|Copilot)/i,\n\n // Search Bots\n GOOGLEBOT: /Googlebot/i,\n BINGBOT: /(?:bingbot|BingPreview|msnbot)/i,\n DUCKDUCKBOT: /DuckDuckBot/i,\n BAIDUBOT: /Baiduspider/i,\n YANDEXBOT: /YandexBot/i,\n\n // Social Media Bots\n FACEBOOK: /(?:facebookexternalhit|facebookcatalog)/i,\n TWITTER: /(?:Twitterbot|TwitterImageProxy)/i,\n LINKEDIN: /LinkedInBot/i,\n WHATSAPP: /WhatsApp/i,\n TELEGRAM: /TelegramBot/i,\n DISCORD: /Discordbot/i,\n SLACK: /Slackbot/i,\n\n // Crawlers and Scrapers\n GENERIC_BOT: /(?:bot|crawler|spider|scraper|agent)/i,\n SCRAPY: /Scrapy/i,\n PUPPETEER: /(?:HeadlessChrome|Puppeteer)/i,\n PLAYWRIGHT: /Playwright/i,\n SELENIUM: /(?:selenium|webdriver)/i,\n\n // Development Tools\n POSTMAN: /PostmanRuntime/i,\n INSOMNIA: /insomnia/i,\n CURL: /curl/i,\n WGET: /Wget/i,\n HTTPIE: /HTTPie/i,\n\n // Monitoring Services\n UPTIMEROBOT: /UptimeRobot/i,\n PINGDOM: /Pingdom/i,\n NEWRELIC: /NewRelicPinger/i,\n DATADOG: /Datadog/i,\n} as const;\n\n/**\n * Header Patterns for Agent Detection\n */\nexport const HEADER_PATTERNS = {\n // AI-specific headers\n AI_HEADERS: /^(?:X-(?:OpenAI|Anthropic|AI|Bot|Agent|LLM))/i,\n\n // Automation headers\n AUTOMATION_HEADERS: /^(?:X-(?:Automated|Robot|Crawler|Scraper))/i,\n\n // Missing standard headers\n MISSING_ACCEPT: /^$/,\n MISSING_ACCEPT_LANGUAGE: /^$/,\n MISSING_ACCEPT_ENCODING: /^$/,\n\n // Suspicious patterns\n GENERIC_ACCEPT: /^\\*\\/\\*$/,\n NO_COOKIES: /^$/,\n\n // Known proxy headers\n PROXY_HEADERS: /^(?:X-Forwarded-|X-Real-IP|X-Originating-IP|Via|Forwarded)/i,\n\n // Cloud provider headers\n CLOUD_HEADERS: /^(?:X-(?:AWS|Azure|GCP|Cloudflare))/i,\n} as const;\n\n/**\n * Browser Patterns\n */\nexport const BROWSER_PATTERNS = {\n CHROME: /Chrome\\/([0-9.]+)/,\n FIREFOX: /Firefox\\/([0-9.]+)/,\n SAFARI: /Version\\/([0-9.]+).*Safari/,\n EDGE: /Edg\\/([0-9.]+)/,\n OPERA: /OPR\\/([0-9.]+)/,\n IE: /MSIE ([0-9.]+)/,\n} as const;\n\n/**\n * Operating System Patterns\n */\nexport const OS_PATTERNS = {\n WINDOWS: /Windows NT ([0-9.]+)/,\n MACOS: /Mac OS X ([0-9_]+)/,\n LINUX: /Linux/,\n ANDROID: /Android ([0-9.]+)/,\n IOS: /OS ([0-9_]+) like Mac OS X/,\n} as const;\n\n/**\n * Mobile Device Patterns\n */\nexport const MOBILE_PATTERNS = {\n MOBILE: /(?:Mobile|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini)/i,\n TABLET: /(?:iPad|Android.*Tablet|Tablet.*Android|Kindle|Silk)/i,\n DESKTOP: /(?:Windows NT|Mac OS X|Linux|CrOS)/i,\n} as const;\n\n/**\n * Suspicious Behavior Patterns\n */\nexport const SUSPICIOUS_PATTERNS = {\n // Rapid requests\n RAPID_REQUESTS: /^[0-9]{1,3}$/,\n\n // Sequential access\n SEQUENTIAL_URLS: /\\?(?:page|offset|id)=[0-9]+/,\n\n // Data extraction\n API_ENDPOINTS: /\\/api\\/|\\.json$|\\.xml$/i,\n\n // Form submission without interaction\n DIRECT_POST: /^POST$/,\n\n // Known attack patterns\n SQL_INJECTION:\n /(?:union|select|insert|update|delete|drop|create|alter|exec|script|javascript|onerror|onload|eval|src=)/i,\n XSS_ATTEMPT: /(?:<script|javascript:|onerror=|onclick=|<iframe|<embed|<object)/i,\n PATH_TRAVERSAL: /(?:\\.\\.\\/|\\.\\.\\\\|%2e%2e%2f|%252e%252e%252f)/i,\n\n // Encoding attempts\n URL_ENCODED: /%[0-9a-f]{2}/i,\n BASE64_DATA: /data:[^;]+;base64,/i,\n} as const;\n\n/**\n * Maximum input length for pattern matching. UAs, header values, and\n * detection payloads are bounded in practice (<4KB even for the most\n * verbose Chrome/Firefox UAs). Caps worst-case complexity for any\n * polynomial-shaped pattern an external caller might supply to\n * `testPattern` / `extractMatch`; CodeQL flagged the unbounded path\n * (js/polynomial-redos) on PR #2576.\n */\nconst MAX_PATTERN_INPUT_LENGTH = 4096;\n\n/**\n * Helper function to test a pattern. Returns `false` on inputs longer\n * than {@link MAX_PATTERN_INPUT_LENGTH} — an abuse signal we'd rather\n * reject than process.\n */\nexport function testPattern(pattern: RegExp, value: string): boolean {\n if (value.length > MAX_PATTERN_INPUT_LENGTH) return false;\n return pattern.test(value);\n}\n\n/**\n * Helper function to extract match from pattern. Returns `null` on\n * over-long inputs (same ReDoS defense as `testPattern`).\n */\nexport function extractMatch(pattern: RegExp, value: string): string | null {\n if (value.length > MAX_PATTERN_INPUT_LENGTH) return null;\n const match = value.match(pattern);\n return match ? match[1] || match[0] : null;\n}\n\n/**\n * Helper function to test multiple patterns\n */\nexport function testPatterns(patterns: RegExp[], value: string): boolean {\n return patterns.some((pattern) => testPattern(pattern, value));\n}\n\n/**\n * Helper function to find matching pattern\n */\nexport function findMatchingPattern(\n patterns: Record<string, RegExp>,\n value: string\n): string | null {\n for (const [name, pattern] of Object.entries(patterns)) {\n if (testPattern(pattern, value)) {\n return name;\n }\n }\n return null;\n}\n","// Imports the single hoisted pattern, not the whole `VALIDATION_PATTERNS`\n// object — same definition, but it keeps this leaf actually dependency-free\n// under rolldown, which does not property-shake object literals.\nimport { UUID_PATTERN } from './constants/patterns';\n\n/**\n * The browser-posture cookie name. Kept in its own dependency-free leaf so the\n * beacon (bundle-size budgeted, no `jose`) derives the name from the SAME\n * function every SDK reader uses via `./browser-posture`; two independent\n * derivations of this name is exactly the drift that dropped the cookie.\n *\n * The lowercase UUID only: the issuer signs `project_id` as the database's\n * lowercase project UUID and cookie names compare case-sensitively, so a\n * friendly id, or the same UUID in upper case, can never name a cookie a\n * reader will look for.\n */\nexport function postureCookieName(projectId: string): string {\n if (!UUID_PATTERN.test(projectId) || projectId !== projectId.toLowerCase())\n throw new Error('Invalid posture project id');\n return `__Host-checkpoint_posture_${projectId}`;\n}\n"],"mappings":"AAiBA,MAAa,EACX,6ECFF,SAAgB,EAAkB,EAA2B,CAC3D,GAAI,CAAC,EAAa,KAAK,CAAS,GAAK,IAAc,EAAU,YAAY,EACvE,MAAU,MAAM,4BAA4B,EAC9C,MAAO,6BAA6B,GACtC"}
1
+ {"version":3,"file":"browser-posture-cookie.mjs","names":[],"sources":["../src/constants/patterns.ts","../src/browser-posture-cookie.ts"],"sourcesContent":["/**\n * Regular Expression Patterns\n *\n * Common regex patterns used for validation, and helpers that match bounded\n * input against them. Request classification belongs to the detection\n * engine, so no detection patterns live here.\n */\n\n/**\n * Validation Patterns\n */\n// Hoisted out of the object literal below so bundle-size-critical leaves can\n// import JUST this one pattern. `VALIDATION_PATTERNS` re-exports it, so there\n// is still exactly one definition and no drift.\n//\n// Why it matters: rolldown (via tsdown) does not do property-level DCE on a\n// const object literal the way esbuild did. `browser-posture-cookie.ts` uses\n// only `.UUID`, but importing the whole object dragged every pattern —\n// ULID, SLUG, IPV4, IPV6 — into that leaf, taking it from 272 to 2,870 bytes.\nexport const UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nexport const VALIDATION_PATTERNS = {\n // Identifiers\n UUID: UUID_PATTERN,\n ULID: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n SLUG: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,\n\n // Network\n IPV4: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,\n IPV6: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a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{1,4}){1,7}|:))$/,\n // eslint-disable-next-line no-useless-escape\n // CIDR pattern: uses IPV4 pattern and restricts mask to 0-32\n CIDR: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\/(?:[0-9]|[12][0-9]|3[0-2])$/,\n // eslint-disable-next-line no-useless-escape\n DOMAIN: /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i,\n HOSTNAME:\n /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/,\n // eslint-disable-next-line no-useless-escape\n URL: /^https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/,\n\n // Contact\n // Email pattern: stricter validation (rejects consecutive dots, requires TLD)\n // Local part: alphanumeric start/end, dots allowed but not consecutive\n EMAIL:\n /^[a-zA-Z0-9](?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]|\\.(?!\\.))*[a-zA-Z0-9]?@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,\n PHONE: /^[+]?[(]?[0-9]{3}[)]?[-\\s.]?[0-9]{3}[-\\s.]?[0-9]{4,6}$/,\n\n // Security\n // JWT pattern: requires 3 parts (header.payload.signature) - signature cannot be empty\n JWT: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+$/,\n // eslint-disable-next-line no-useless-escape\n BASE64: /^[A-Za-z0-9+\\/]*={0,2}$/,\n HEX: /^[0-9a-fA-F]+$/,\n MD5: /^[a-f0-9]{32}$/i,\n SHA1: /^[a-f0-9]{40}$/i,\n SHA256: /^[a-f0-9]{64}$/i,\n\n // Versions\n SEMVER:\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/,\n\n // Files\n FILENAME: /^[a-zA-Z0-9](?:[a-zA-Z0-9 ._-]*[a-zA-Z0-9])?\\.[a-zA-Z0-9_-]+$/,\n PATH: /^(\\/[^/ ]*)+\\/?$/,\n\n // Keys\n API_KEY: /^[A-Za-z0-9_-]{32,}$/,\n SECRET_KEY: /^[A-Za-z0-9_-]{64,}$/,\n PIXEL_ID: /^px_[A-Za-z0-9]{16}$/,\n} as const;\n\n/**\n * Maximum input length for pattern matching. UAs, header values, and\n * detection payloads are bounded in practice (<4KB even for the most\n * verbose Chrome/Firefox UAs). Caps worst-case complexity for any\n * polynomial-shaped pattern an external caller might supply to\n * `testPattern` / `extractMatch`; CodeQL flagged the unbounded path\n * (js/polynomial-redos) on PR #2576.\n */\nconst MAX_PATTERN_INPUT_LENGTH = 4096;\n\n/**\n * Helper function to test a pattern. Returns `false` on inputs longer\n * than {@link MAX_PATTERN_INPUT_LENGTH} — an abuse signal we'd rather\n * reject than process.\n */\nexport function testPattern(pattern: RegExp, value: string): boolean {\n if (value.length > MAX_PATTERN_INPUT_LENGTH) return false;\n return pattern.test(value);\n}\n\n/**\n * Helper function to extract match from pattern. Returns `null` on\n * over-long inputs (same ReDoS defense as `testPattern`).\n */\nexport function extractMatch(pattern: RegExp, value: string): string | null {\n if (value.length > MAX_PATTERN_INPUT_LENGTH) return null;\n const match = value.match(pattern);\n return match ? match[1] || match[0] : null;\n}\n\n/**\n * Helper function to test multiple patterns\n */\nexport function testPatterns(patterns: RegExp[], value: string): boolean {\n return patterns.some((pattern) => testPattern(pattern, value));\n}\n\n/**\n * Helper function to find matching pattern\n */\nexport function findMatchingPattern(\n patterns: Record<string, RegExp>,\n value: string\n): string | null {\n for (const [name, pattern] of Object.entries(patterns)) {\n if (testPattern(pattern, value)) {\n return name;\n }\n }\n return null;\n}\n","// Imports the single hoisted pattern, not the whole `VALIDATION_PATTERNS`\n// object — same definition, but it keeps this leaf actually dependency-free\n// under rolldown, which does not property-shake object literals.\nimport { UUID_PATTERN } from './constants/patterns';\n\n/**\n * The browser-posture cookie name. Kept in its own dependency-free leaf so the\n * beacon (bundle-size budgeted, no `jose`) derives the name from the SAME\n * function every SDK reader uses via `./browser-posture`; two independent\n * derivations of this name is exactly the drift that dropped the cookie.\n *\n * The lowercase UUID only: the issuer signs `project_id` as the database's\n * lowercase project UUID and cookie names compare case-sensitively, so a\n * friendly id, or the same UUID in upper case, can never name a cookie a\n * reader will look for.\n */\nexport function postureCookieName(projectId: string): string {\n if (!UUID_PATTERN.test(projectId) || projectId !== projectId.toLowerCase())\n throw new Error('Invalid posture project id');\n return `__Host-checkpoint_posture_${projectId}`;\n}\n"],"mappings":"AAmBA,MAAa,EACX,6ECJF,SAAgB,EAAkB,EAA2B,CAC3D,GAAI,CAAC,EAAa,KAAK,CAAS,GAAK,IAAc,EAAU,YAAY,EACvE,MAAU,MAAM,4BAA4B,EAC9C,MAAO,6BAA6B,GACtC"}