@kya-os/checkpoint-shared 1.8.0 → 1.9.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 (132) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/agent-catalog.d.mts +12 -0
  3. package/dist/agent-catalog.d.mts.map +1 -0
  4. package/dist/agent-catalog.d.ts +12 -0
  5. package/dist/agent-catalog.d.ts.map +1 -0
  6. package/dist/agent-catalog.js +105 -0
  7. package/dist/agent-catalog.mjs +105 -0
  8. package/dist/agent-catalog.mjs.map +1 -0
  9. package/dist/beacon-types/index.d.mts +18 -0
  10. package/dist/beacon-types/index.d.mts.map +1 -1
  11. package/dist/beacon-types/index.d.ts +18 -0
  12. package/dist/beacon-types/index.d.ts.map +1 -1
  13. package/dist/beacon-types/index.js +116 -12
  14. package/dist/beacon-types/index.mjs +105 -13
  15. package/dist/beacon-types/index.mjs.map +1 -1
  16. package/dist/browser-posture-5fPrsxx7.d.mts.map +1 -1
  17. package/dist/browser-posture-CCR1kh5e.d.ts.map +1 -1
  18. package/dist/browser-posture-cookie.js +1 -1
  19. package/dist/browser-posture-cookie.mjs +1 -1
  20. package/dist/browser-posture-cookie.mjs.map +1 -1
  21. package/dist/browser-posture-proof-verifier-DvsOmFrM.js +202 -0
  22. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs +180 -0
  23. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs.map +1 -0
  24. package/dist/browser-posture-proof-verifier.d.mts +25 -0
  25. package/dist/browser-posture-proof-verifier.d.mts.map +1 -0
  26. package/dist/browser-posture-proof-verifier.d.ts +25 -0
  27. package/dist/browser-posture-proof-verifier.d.ts.map +1 -0
  28. package/dist/browser-posture-proof-verifier.js +7 -0
  29. package/dist/browser-posture-proof-verifier.mjs +3 -0
  30. package/dist/browser-posture-proof.d.mts +3 -18
  31. package/dist/browser-posture-proof.d.mts.map +1 -1
  32. package/dist/browser-posture-proof.d.ts +3 -18
  33. package/dist/browser-posture-proof.d.ts.map +1 -1
  34. package/dist/browser-posture-proof.js +6 -131
  35. package/dist/browser-posture-proof.mjs +1 -126
  36. package/dist/browser-posture-proof.mjs.map +1 -1
  37. package/dist/browser-posture.js +1 -1
  38. package/dist/browser-posture.mjs +1 -1
  39. package/dist/browser-posture.mjs.map +1 -1
  40. package/dist/browser.d.mts +0 -282
  41. package/dist/browser.d.mts.map +1 -1
  42. package/dist/browser.d.ts +0 -282
  43. package/dist/browser.d.ts.map +1 -1
  44. package/dist/browser.js +1 -1
  45. package/dist/browser.mjs +1 -1
  46. package/dist/browser.mjs.map +1 -1
  47. package/dist/canonical-signer/index.mjs.map +1 -1
  48. package/dist/consent-handoff.d.mts +0 -3
  49. package/dist/consent-handoff.d.mts.map +1 -1
  50. package/dist/consent-handoff.d.ts +0 -3
  51. package/dist/consent-handoff.d.ts.map +1 -1
  52. package/dist/consent-handoff.mjs.map +1 -1
  53. package/dist/default-sign-in-host.d.mts +10 -0
  54. package/dist/default-sign-in-host.d.mts.map +1 -0
  55. package/dist/default-sign-in-host.d.ts +10 -0
  56. package/dist/default-sign-in-host.d.ts.map +1 -0
  57. package/dist/default-sign-in-host.js +72 -0
  58. package/dist/default-sign-in-host.mjs +66 -0
  59. package/dist/default-sign-in-host.mjs.map +1 -0
  60. package/dist/errors/index.d.mts +1 -0
  61. package/dist/errors/index.d.mts.map +1 -1
  62. package/dist/errors/index.d.ts +1 -0
  63. package/dist/errors/index.d.ts.map +1 -1
  64. package/dist/errors/index.js +5 -2
  65. package/dist/errors/index.mjs +5 -2
  66. package/dist/errors/index.mjs.map +1 -1
  67. package/dist/{fetcher-CivUCbhL.d.ts → fetcher-C8qvwdnA.d.ts} +2 -2
  68. package/dist/{fetcher-CivUCbhL.d.ts.map → fetcher-C8qvwdnA.d.ts.map} +1 -1
  69. package/dist/{fetcher-cXQsbm6s.d.mts → fetcher-D2vjr7jB.d.mts} +2 -2
  70. package/dist/{fetcher-cXQsbm6s.d.mts.map → fetcher-D2vjr7jB.d.mts.map} +1 -1
  71. package/dist/gateway-client-ip.d.mts +0 -2
  72. package/dist/gateway-client-ip.d.mts.map +1 -1
  73. package/dist/gateway-client-ip.d.ts +0 -2
  74. package/dist/gateway-client-ip.d.ts.map +1 -1
  75. package/dist/gateway-client-ip.mjs.map +1 -1
  76. package/dist/host-adapter/index.d.mts +1 -1
  77. package/dist/host-adapter/index.d.ts +1 -1
  78. package/dist/host-adapter/index.js +1 -1
  79. package/dist/host-adapter/index.mjs +1 -1
  80. package/dist/{host-adapter-DHyISsIf.mjs → host-adapter-BKdQHwbi.mjs} +2 -2
  81. package/dist/{host-adapter-DHyISsIf.mjs.map → host-adapter-BKdQHwbi.mjs.map} +1 -1
  82. package/dist/{host-adapter-0F8EpbD6.js → host-adapter-bWftXA9T.js} +1 -1
  83. package/dist/{index-CXbOY7gB.d.ts → index-DnFsmr_o.d.ts} +3 -3
  84. package/dist/{index-CXbOY7gB.d.ts.map → index-DnFsmr_o.d.ts.map} +1 -1
  85. package/dist/{index-B3cHxr3O.d.mts → index-rvw5Bz-r.d.mts} +3 -3
  86. package/dist/{index-B3cHxr3O.d.mts.map → index-rvw5Bz-r.d.mts.map} +1 -1
  87. package/dist/index.d.mts +94 -449
  88. package/dist/index.d.mts.map +1 -1
  89. package/dist/index.d.ts +94 -449
  90. package/dist/index.d.ts.map +1 -1
  91. package/dist/index.js +25 -455
  92. package/dist/index.mjs +17 -422
  93. package/dist/index.mjs.map +1 -1
  94. package/dist/{kya-http-error-codes-UYb1zpGM.js → kya-http-error-codes-B4rUmUEI.js} +2 -0
  95. package/dist/{kya-http-error-codes-7ewV5RuK.d.ts → kya-http-error-codes-C14E4gi3.d.mts} +2 -1
  96. package/dist/kya-http-error-codes-C14E4gi3.d.mts.map +1 -0
  97. package/dist/{kya-http-error-codes-7ewV5RuK.d.mts → kya-http-error-codes-C14E4gi3.d.ts} +2 -1
  98. package/dist/kya-http-error-codes-C14E4gi3.d.ts.map +1 -0
  99. package/dist/{kya-http-error-codes-C2JiWPsi.mjs → kya-http-error-codes-DSBrxNry.mjs} +3 -1
  100. package/dist/kya-http-error-codes-DSBrxNry.mjs.map +1 -0
  101. package/dist/kya-http.d.mts +1 -1
  102. package/dist/kya-http.d.ts +1 -1
  103. package/dist/kya-http.js +1 -1
  104. package/dist/kya-http.mjs +1 -1
  105. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
  106. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
  107. package/dist/mcpi/dashboard-config/index.mjs.map +1 -1
  108. package/dist/{patterns-B2r7M9wR.js → patterns-CiMpbdAF.js} +1 -1
  109. package/dist/{patterns-B7dQoeE3.mjs → patterns-D4OAsNQY.mjs} +2 -2
  110. package/dist/{patterns-B7dQoeE3.mjs.map → patterns-D4OAsNQY.mjs.map} +1 -1
  111. package/dist/patterns.js +1 -1
  112. package/dist/patterns.mjs +1 -1
  113. package/dist/policy/fetcher.d.mts +1 -1
  114. package/dist/policy/fetcher.d.ts +1 -1
  115. package/dist/policy/schemas.d.mts +1 -1
  116. package/dist/policy/schemas.d.ts +1 -1
  117. package/dist/{schemas-C_3C72SR.d.ts → schemas-CGKHzcMV.d.ts} +21 -21
  118. package/dist/{schemas-C_3C72SR.d.ts.map → schemas-CGKHzcMV.d.ts.map} +1 -1
  119. package/dist/{schemas-02CI7jgm.d.mts → schemas-m-GqyfyO.d.mts} +21 -21
  120. package/dist/{schemas-02CI7jgm.d.mts.map → schemas-m-GqyfyO.d.mts.map} +1 -1
  121. package/dist/tool-protection/index.d.mts +12 -0
  122. package/dist/tool-protection/index.d.mts.map +1 -1
  123. package/dist/tool-protection/index.d.ts +12 -0
  124. package/dist/tool-protection/index.d.ts.map +1 -1
  125. package/dist/tool-protection/index.js +46 -0
  126. package/dist/tool-protection/index.mjs +44 -1
  127. package/dist/tool-protection/index.mjs.map +1 -1
  128. package/fixtures/kya-http/error-codes.json +2 -1
  129. package/package.json +19 -3
  130. package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +0 -1
  131. package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +0 -1
  132. package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"browser-posture.mjs","names":["z.object","z.literal","z.string","z.guid","z.enum","z.number","z.array","z.boolean","z\n .object","z\n .string","z.object","z.string","z.guid","z.enum","z.number","z.array","z.literal","z\n .object","z\n .record","z.unknown","record","z.record","z.string","z.unknown"],"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"],"sourcesContent":["// 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","/**\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 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 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 /** Build item 6: mirrors `BeaconConfig.anonymizeIp` (default `false`) — see the beacon route's own doc comment. */\n anonymizeIp?: boolean;\n /** Nonce-bound ingest (build item 5): the value from the prior 202 response's `nonce`. */\n nonce?: string;\n /** Nonce-bound ingest (build item 5): declares this client echoes nonces — see checkpoint-beacon's `BeaconBatch`. */\n nonceEcho?: boolean;\n /** Holder-of-key posture binding (P37): the beacon's own DPoP public key,\n * sent once per browser session (first batch only) so the issuer can bind\n * every subsequent posture mint to it via `cnf.jkt`. */\n publicJwk?: EcPublicJwk;\n queueEvictions?: number;\n queueExpirations?: number;\n queueCorruptions?: number;\n}\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 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\nexport function beaconBodyIdentity(body: object): string {\n return JSON.stringify({\n ...body,\n nonce: undefined,\n nonceEcho: undefined,\n deviceId: undefined,\n anonymizeIp: undefined,\n publicJwk: undefined,\n handoffToken: undefined,\n queueEvictions: undefined,\n queueExpirations: undefined,\n queueCorruptions: undefined,\n });\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","import { z } from 'zod';\n\nexport const BrowserPostureSchema = z.object({\n v: z.literal(1),\n project_id: z.string().min(1).max(128),\n origin: z.string().url(),\n // Consolidated IDs include PostgreSQL MD5()::uuid values with arbitrary\n // version/variant bits. Keep their stored identity intact across Zod upgrades.\n session_id: z.guid(),\n binding: z.string().regex(/^[a-f0-9]{64}$/),\n verdict: z.enum(['agent-driven', 'human', 'insufficient']),\n score: z.number().min(0).max(1).nullable(),\n scorer_version: z.number().int().positive().max(2147483647),\n reasons: z.array(z.string().max(160)).max(8),\n // Defaulted, not required: a token minted by a not-yet-upgraded issuer\n // (rolling deploy) must still verify on an upgraded reader, matching the\n // Java `asBoolean(false)` / .NET `TryGetProperty` default-false handling\n // for the identical claims.\n automation_disclosed: z.boolean().default(false),\n automation_corroborated: z.boolean().default(false),\n detection: z\n .object({\n class: z.enum(['ai_agent', 'bot']),\n name: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[^\\p{Cc}]+$/u),\n confidence: z.number().int().min(0).max(100),\n })\n .optional(),\n // Holder-of-key posture binding (P37): the RFC 7638 thumbprint of the\n // public key a DPoP-shaped proof must be signed by to accompany this\n // token. Optional: absent for a session that hasn't sent its public JWK\n // yet, or for a token minted by a not-yet-upgraded issuer - the same\n // rolling-deploy tolerance `automation_disclosed`/`automation_corroborated`\n // already have. A verifier with no proof support simply never checks it,\n // so a cnf-bearing token still verifies today exactly as one without it.\n cnf: z\n .object({\n jkt: z.string().min(1).max(255),\n })\n .optional(),\n iat: z.number().int().nonnegative(),\n exp: z.number().int().positive(),\n});\n\n/** Authenticates a risk observation. This is never an agent credential. */\nexport type BrowserPosture = z.infer<typeof BrowserPostureSchema>;\n","import { z } from 'zod';\nimport type { BrowserPosture } from './browser-posture-schema';\n\nexport const POSTURE_VERIFICATION_STATUSES = ['verified', 'absent', 'rejected'] as const;\nexport type PostureVerificationStatus = (typeof POSTURE_VERIFICATION_STATUSES)[number];\n\n/** Audit projection: no token, cookie binding, raw counters, or credential fields. */\nexport const BrowserPostureReportSchema = z.object({\n projectId: z.string().min(1).max(128),\n // Match the signed posture's MD5-derived consolidated session IDs.\n sessionId: z.guid(),\n verdict: z.enum(['human', 'agent-driven', 'insufficient']),\n score: z.number().min(0).max(1).nullable(),\n scorerVersion: z.number().int().positive(),\n reasons: z.array(z.string().max(160)).max(8),\n issuedAt: z.number().int().nonnegative(),\n expiresAt: z.number().int().positive(),\n source: z.literal('verified-posture'),\n});\n\nexport const BROWSER_POSTURE_REJECTION_REASONS = [\n 'malformed',\n 'unknown-key',\n 'bad-signature',\n 'invalid-claims',\n 'project-mismatch',\n 'origin-mismatch',\n 'audience-mismatch',\n 'expired',\n 'not-yet-valid',\n 'binding-mismatch',\n 'session-missing',\n] as const;\nexport type BrowserPostureRejectionReason = (typeof BROWSER_POSTURE_REJECTION_REASONS)[number];\n\nexport const BrowserPostureOutcomeSchema = z\n .object({\n status: z.enum(POSTURE_VERIFICATION_STATUSES),\n reason: z.enum(BROWSER_POSTURE_REJECTION_REASONS).optional(),\n })\n .refine((outcome) => (outcome.status === 'rejected') === (outcome.reason !== undefined), {\n message: 'reason is required if and only if status is rejected',\n path: ['reason'],\n });\nexport type BrowserPostureOutcome = z.infer<typeof BrowserPostureOutcomeSchema>;\n\nexport const BROWSER_POSTURE_REASON_PATTERN = /^[a-z][a-z-]{0,31}$/;\nexport const BROWSER_POSTURE_REJECTIONS_MAX_ENTRIES = 50;\nexport const BROWSER_POSTURE_REJECTION_COUNT_MAX = 1_000_000;\n\nexport const BrowserPostureRejectionsSchema = z\n .record(z.string(), z.unknown())\n .transform((counts) =>\n Object.fromEntries(\n Object.entries(counts)\n .filter(\n (entry): entry is [string, number] =>\n BROWSER_POSTURE_REASON_PATTERN.test(entry[0]) &&\n typeof entry[1] === 'number' &&\n Number.isInteger(entry[1]) &&\n entry[1] > 0\n )\n .slice(0, BROWSER_POSTURE_REJECTIONS_MAX_ENTRIES)\n .map(([reason, count]): [string, number] => [\n reason,\n Math.min(count, BROWSER_POSTURE_REJECTION_COUNT_MAX),\n ])\n )\n );\nexport type BrowserPostureRejections = z.infer<typeof BrowserPostureRejectionsSchema>;\n\nexport const BrowserPostureReportIngestSchema = BrowserPostureReportSchema.extend({\n score: BrowserPostureReportSchema.shape.score.default(null),\n});\n\nexport function browserPostureReport(posture: BrowserPosture) {\n return {\n projectId: posture.project_id,\n sessionId: posture.session_id,\n verdict: posture.verdict,\n score: posture.score,\n scorerVersion: posture.scorer_version,\n reasons: posture.reasons,\n issuedAt: posture.iat,\n expiresAt: posture.exp,\n source: 'verified-posture' as const,\n };\n}\n","import {\n compactVerify,\n decodeProtectedHeader,\n importJWK,\n SignJWT,\n type CompactVerifyResult,\n type JWK,\n} from 'jose';\nimport { z } from 'zod';\nimport { projectVerificationKey } from './project-verification-key';\nimport { VALIDATION_PATTERNS } from './constants/patterns';\nimport { postureCookieName } from './browser-posture-cookie';\nimport { matchAllowedOrigin, MAX_POSTURE_ORIGINS, parseOriginPattern } from './posture-origins';\nimport { POSTURE_TTL_SECONDS } from './beacon-types';\nimport { BrowserPostureSchema, type BrowserPosture } from './browser-posture-schema';\nimport type {\n BrowserPostureOutcome,\n BrowserPostureRejectionReason,\n} from './browser-posture-report';\n\nexport { BrowserPostureSchema } from './browser-posture-schema';\nexport type { BrowserPosture } from './browser-posture-schema';\n\nexport { postureCookieName, POSTURE_TTL_SECONDS };\n\nexport const UNSIGNED_BROWSER_AGENT = {\n agentType: 'Browser agent (unsigned)',\n detectionClass: 'ai_agent',\n verificationMethod: 'behavioral',\n} as const;\nexport const behavioralConfidence = (score: number | null): number =>\n Math.min(85, Math.max(50, Math.round((score ?? 0.5) * 100)));\n\ninterface PostureUpgrade {\n detectionClass: 'ai_agent' | 'bot' | 'incomplete_data';\n isAgent: boolean;\n agentName?: string;\n confidence: number;\n verificationMethod: 'behavioral';\n reasons: string[];\n}\n\nexport function postureUpgrade(posture: BrowserPosture): PostureUpgrade | undefined {\n const { detection, reasons } = posture;\n const verificationMethod = 'behavioral';\n if (detection)\n return {\n detectionClass: detection.class,\n isAgent: true,\n agentName: detection.name,\n confidence: detection.confidence,\n verificationMethod,\n reasons,\n };\n if (posture.automation_disclosed)\n return {\n detectionClass: 'bot',\n isAgent: true,\n agentName: 'Automation Tools',\n confidence: 80,\n verificationMethod,\n reasons,\n };\n if (posture.verdict === 'agent-driven')\n return {\n detectionClass: UNSIGNED_BROWSER_AGENT.detectionClass,\n isAgent: true,\n agentName: UNSIGNED_BROWSER_AGENT.agentType,\n confidence: behavioralConfidence(posture.score),\n verificationMethod,\n reasons,\n };\n if (posture.automation_corroborated)\n return {\n detectionClass: 'incomplete_data',\n isAgent: false,\n confidence: 40,\n verificationMethod,\n reasons,\n };\n return undefined;\n}\n\nexport const POSTURE_ISSUER = 'checkpoint:browser-posture:v1';\n// A custom Nimbus JOSE+JWT type verifier is required to accept this typ; see\n// packages/checkpoint-java/README.md's \"Verifying with your own Nimbus-based stack\".\nexport const POSTURE_TYPE = 'checkpoint-posture+jwt';\n\nexport interface BrowserPostureConfig {\n /** Locally configured public project key; never taken from a cookie or header. */\n publicKey: JWK;\n keyId: string;\n /** Exact HTTPS origin of the protected resource, from operator configuration. */\n origin: string;\n origins?: string[];\n sessionCookieName?: string;\n /** Explicit path/scope designations for the default integrity step-up rule. */\n protectedRoutes?: Array<{ path: string; scopes: string[] }>;\n}\n\n/** Duplicate cookies are ambiguous, so none is trusted. */\nexport function readPostureCookie(\n header: string | null | undefined,\n name: string\n): string | undefined {\n const matches = (header ?? '')\n .split(';')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(`${name}=`));\n if (matches.length !== 1) return undefined;\n try {\n return decodeURIComponent(matches[0].slice(name.length + 1));\n } catch {\n return undefined;\n }\n}\n\nexport async function postureSessionBinding(sessionId: string): Promise<string> {\n const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(sessionId));\n return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction validOrigin(origin: string): boolean {\n try {\n const url = new URL(origin);\n return url.protocol === 'https:' && url.origin === origin && /^[^.*][^*]*$/.test(url.hostname);\n } catch {\n return false;\n }\n}\n\nexport async function signBrowserPosture(\n posture: BrowserPosture,\n privateKey: JWK,\n keyId: string\n): Promise<string> {\n const claims = BrowserPostureSchema.parse(posture);\n if (\n !validOrigin(claims.origin) ||\n claims.exp <= claims.iat ||\n claims.exp - claims.iat > POSTURE_TTL_SECONDS ||\n privateKey.kty !== 'EC' ||\n privateKey.crv !== 'P-256' ||\n !privateKey.d ||\n !keyId\n ) {\n throw new Error('Invalid posture signing configuration');\n }\n const key = await importJWK(privateKey, 'ES256');\n return new SignJWT(claims)\n .setProtectedHeader({ alg: 'ES256', typ: POSTURE_TYPE, kid: keyId })\n .setIssuer(POSTURE_ISSUER)\n .setAudience(claims.origin)\n .sign(key);\n}\n\nexport type PostureVerification =\n | { status: 'verified'; posture: BrowserPosture }\n | { status: 'absent' }\n | { status: 'rejected'; reason: BrowserPostureRejectionReason };\n\nconst BASE64URL = /^[A-Za-z0-9_-]+$/;\n\nconst rejected = (reason: BrowserPostureRejectionReason) =>\n ({ status: 'rejected', reason }) as const;\n\nexport const postureOutcomeReport = (outcome: PostureVerification): BrowserPostureOutcome =>\n outcome.status === 'verified' ? { status: 'verified' } : outcome;\n\nconst verifiedPosture = (outcome: PostureVerification): BrowserPosture | undefined =>\n outcome.status === 'verified' ? outcome.posture : undefined;\n\nexport async function inspectBrowserPosture(\n token: string | undefined,\n config: BrowserPostureConfig,\n projectId: string,\n browserSessionId: string | undefined,\n now = Math.floor(Date.now() / 1000)\n): Promise<PostureVerification> {\n if (!token) return { status: 'absent' };\n if (!browserSessionId || browserSessionId.length > 255) return rejected('session-missing');\n const parts = token.split('.');\n if (\n token.length > 3800 ||\n parts.length !== 3 ||\n !parts.every((part) => BASE64URL.test(part)) ||\n parts[0].length % 4 === 1\n )\n return rejected('malformed');\n let header: ReturnType<typeof decodeProtectedHeader>;\n try {\n header = decodeProtectedHeader(token);\n } catch {\n return rejected('malformed');\n }\n if (\n header.alg !== 'ES256' ||\n header.typ !== POSTURE_TYPE ||\n typeof header.kid !== 'string' ||\n 'crit' in header ||\n 'b64' in header\n )\n return rejected('malformed');\n const publicKey =\n validOrigin(config.origin) &&\n !config.publicKey.d &&\n config.publicKey.kty === 'EC' &&\n config.publicKey.crv === 'P-256'\n ? projectVerificationKey(token, config, now)\n : undefined;\n const key = publicKey && (await importJWK(publicKey, 'ES256').catch(() => undefined));\n if (!key) return rejected('unknown-key');\n let signed: CompactVerifyResult;\n try {\n signed = await compactVerify(token, key, { algorithms: ['ES256'] });\n } catch {\n return rejected('bad-signature');\n }\n let json: unknown;\n try {\n json = JSON.parse(new TextDecoder().decode(signed.payload));\n } catch {\n return rejected('malformed');\n }\n const record = z.record(z.string(), z.unknown()).safeParse(json);\n if (!record.success) return rejected('invalid-claims');\n const audiences = [record.data.aud].flat();\n if (audiences.some((audience) => typeof audience !== 'string')) return rejected('malformed');\n const notBefore = record.data.nbf;\n const parsed = BrowserPostureSchema.safeParse(record.data);\n if (\n !parsed.success ||\n record.data.iss !== POSTURE_ISSUER ||\n (notBefore !== undefined && typeof notBefore !== 'number') ||\n record.data.origin !== parsed.data.origin ||\n !validOrigin(parsed.data.origin)\n )\n return rejected('invalid-claims');\n const claims = parsed.data;\n if (claims.project_id !== projectId) return rejected('project-mismatch');\n if (claims.origin !== config.origin && !matchAllowedOrigin(claims.origin, config.origins ?? []))\n return rejected('origin-mismatch');\n if (!audiences.includes(claims.origin)) return rejected('audience-mismatch');\n if (claims.exp <= now) return rejected('expired');\n if (claims.iat > now + 5 || (notBefore !== undefined && notBefore > now))\n return rejected('not-yet-valid');\n if (claims.exp <= claims.iat || claims.exp - claims.iat > POSTURE_TTL_SECONDS)\n return rejected('invalid-claims');\n if (claims.binding !== (await postureSessionBinding(browserSessionId)))\n return rejected('binding-mismatch');\n return { status: 'verified', posture: claims };\n}\n\nexport async function verifyBrowserPosture(\n token: string | undefined,\n config: BrowserPostureConfig,\n projectId: string,\n browserSessionId: string | undefined,\n now = Math.floor(Date.now() / 1000)\n): Promise<BrowserPosture | undefined> {\n return verifiedPosture(\n await inspectBrowserPosture(token, config, projectId, browserSessionId, now)\n );\n}\n\n/**\n * Request headers a page sends when its posture cookies cannot reach the\n * server: a request to another host (the cookies are host-only) or a browser\n * that blocks cookies. The page reads both values from the beacon's\n * `onReceipt`.\n */\nexport const POSTURE_HEADER = 'kya-posture';\nexport const POSTURE_SESSION_HEADER = 'kya-posture-session';\n\n/** The request values posture is read from. A string array is a header sent more than once. */\nexport interface PostureRequest {\n cookie?: string | null;\n /** `KYA-Posture`: the posture token. */\n posture?: string | string[] | null;\n /** `KYA-Posture-Session`: the browser session id the token is bound to. */\n session?: string | string[] | null;\n}\n\n/** The `PostureRequest` of any header store, read through its own lowercase-name getter. */\nexport function postureRequestFromHeaders(\n get: (lowercaseName: string) => string | string[] | null | undefined\n): PostureRequest {\n const cookie = get('cookie');\n return {\n cookie: Array.isArray(cookie) ? cookie.join('; ') : cookie,\n posture: get(POSTURE_HEADER),\n session: get(POSTURE_SESSION_HEADER),\n };\n}\n\n/**\n * A header, when the request carries a non-empty one, wins over its cookie.\n * A header sent twice, or joined into one comma-separated value, is ambiguous,\n * so neither copy is trusted and the cookie is not consulted either: the page\n * chose the header. Every runtime applies the same rule\n * (`tests/browser-posture/vectors.json` `requests`).\n */\nfunction postureRequestValue(\n header: string | string[] | null | undefined,\n cookieHeader: string | null | undefined,\n cookieName: string\n): string | undefined {\n const values = (Array.isArray(header) ? header : [header])\n .map((value) => value?.trim())\n .filter((value): value is string => Boolean(value));\n if (values.length === 0) return readPostureCookie(cookieHeader, cookieName);\n return values.length === 1 && !values[0].includes(',') ? values[0] : undefined;\n}\n\n/** Read and verify posture from the `KYA-Posture` headers, falling back to the cookies. */\nexport async function postureOutcomeFromRequest(\n request: PostureRequest,\n config: BrowserPostureConfig,\n projectId: string,\n now?: number\n): Promise<PostureVerification> {\n return inspectBrowserPosture(\n postureRequestValue(request.posture, request.cookie, postureCookieName(projectId)),\n config,\n projectId,\n postureRequestValue(\n request.session,\n request.cookie,\n config.sessionCookieName ?? '_as_beacon_session'\n ),\n now\n );\n}\n\nexport async function postureFromRequest(\n request: PostureRequest,\n config: BrowserPostureConfig,\n projectId: string,\n now?: number\n): Promise<BrowserPosture | undefined> {\n return verifiedPosture(await postureOutcomeFromRequest(request, config, projectId, now));\n}\n\nexport async function postureFromCookies(\n header: string | null | undefined,\n config: BrowserPostureConfig,\n projectId: string\n): Promise<BrowserPosture | undefined> {\n return postureFromRequest({ cookie: header }, config, projectId);\n}\n\n/** Exact paths or an explicit subtree ending in /*. Longest designation wins. */\nexport function postureRequiredScopes(\n config: BrowserPostureConfig,\n path: string\n): string[] | undefined {\n const routes = config.protectedRoutes ?? [];\n const route = [...routes]\n .sort((a, b) => b.path.length - a.path.length)\n .find((r) => (r.path.endsWith('/*') ? path.startsWith(r.path.slice(0, -1)) : path === r.path));\n if (!route) return undefined;\n if (\n !route.scopes.length ||\n route.scopes.length > 50 ||\n route.scopes.some((s) => s.length > 200 || !/^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/.test(s)) ||\n new Set(route.scopes).size !== route.scopes.length\n ) {\n throw new Error('Integrity-protected routes require explicit, unique scopes');\n }\n return route.scopes;\n}\n\n/** Validate operator configuration at startup, before any request can depend on it. */\nexport function validateBrowserPostureConfig(\n config: BrowserPostureConfig,\n projectId: string | undefined\n): void {\n // The issuer signs `project_id` as the project UUID and the beacon names\n // the cookie after that claim, so a reader configured with the project's\n // friendly id could never match either: it would verify nothing, silently,\n // for the life of the deployment. Refuse it at startup instead.\n if (\n !projectId ||\n !VALIDATION_PATTERNS.UUID.test(projectId) ||\n projectId !== projectId.toLowerCase()\n ) {\n throw new Error(\n 'Browser posture requires projectId to be the lowercase project UUID (the friendly id is not accepted)'\n );\n }\n if (\n !validOrigin(config.origin) ||\n !config.keyId ||\n config.publicKey.kty !== 'EC' ||\n config.publicKey.crv !== 'P-256' ||\n !config.publicKey.x ||\n !config.publicKey.y ||\n config.publicKey.d\n ) {\n throw new Error(\n 'Browser posture requires projectId, an exact HTTPS origin, and a public ES256 key'\n );\n }\n const origins = config.origins ?? [];\n if (origins.length > MAX_POSTURE_ORIGINS)\n throw new Error(`Browser posture accepts at most ${MAX_POSTURE_ORIGINS} additional origins`);\n for (const entry of origins) {\n const parsed = parseOriginPattern(entry);\n if (!parsed.ok) throw new Error(`Invalid browser posture origin \"${entry}\": ${parsed.error}`);\n }\n const paths = new Set<string>();\n for (const route of config.protectedRoutes ?? []) {\n if (!/^\\/(?:[^?#*\\\\]*)(?:\\/\\*)?$/.test(route.path) && route.path !== '/*')\n throw new Error('Invalid integrity-protected path');\n if (paths.has(route.path)) throw new Error('Duplicate integrity-protected path');\n paths.add(route.path);\n postureRequiredScopes({ ...config, protectedRoutes: [route] }, route.path.replace(/\\*$/, ''));\n }\n}\n\nexport type { JWK } from 'jose';\n\nexport {\n BROWSER_POSTURE_REJECTION_REASONS,\n BrowserPostureOutcomeSchema,\n POSTURE_VERIFICATION_STATUSES,\n BrowserPostureReportIngestSchema,\n BrowserPostureReportSchema,\n browserPostureReport,\n} from './browser-posture-report';\nexport type {\n BrowserPostureOutcome,\n BrowserPostureRejectionReason,\n PostureVerificationStatus,\n} from './browser-posture-report';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgBA,SAAgB,kBAAkB,WAA2B;CAC3D,IAAI,CAAC,aAAa,KAAK,SAAS,KAAK,cAAc,UAAU,YAAY,GACvE,MAAM,IAAI,MAAM,4BAA4B;CAC9C,OAAO,6BAA6B;AACtC;;;;;;;;;AC+nDA,MAAa,sBAAsB;;;;ACjpDnC,MAAa,uBAAuBA,OAAS;CAC3C,GAAGC,QAAU,CAAC;CACd,YAAYC,OAAS,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;CACrC,QAAQA,OAAS,CAAC,CAAC,IAAI;CAGvB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KACjF,IAAI,IAAI,MAAM,MAAM,CAAC,CAAC,SAAS,MAAM,OAAO,QAE5C,MAAM,IAAI,MAAM,4DAA4D;CAE9E,OAAO,MAAM;AACf;;AAGA,SAAgB,6BACd,QACA,WACM;CAKN,IACE,CAAC,aACD,CAAC,oBAAoB,KAAK,KAAK,SAAS,KACxC,cAAc,UAAU,YAAY,GAEpC,MAAM,IAAI,MACR,uGACF;CAEF,IACE,CAAC,YAAY,OAAO,MAAM,KAC1B,CAAC,OAAO,SACR,OAAO,UAAU,QAAQ,QACzB,OAAO,UAAU,QAAQ,WACzB,CAAC,OAAO,UAAU,KAClB,CAAC,OAAO,UAAU,KAClB,OAAO,UAAU,GAEjB,MAAM,IAAI,MACR,mFACF;CAEF,MAAM,UAAU,OAAO,WAAW,CAAC;CACnC,IAAI,QAAQ,aACV,MAAM,IAAI,MAAM,sCAAuD,oBAAoB;CAC7F,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,SAAS,mBAAmB,KAAK;EACvC,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,MAAM,mCAAmC,MAAM,KAAK,OAAO,OAAO;CAC9F;CACA,MAAM,wBAAQ,IAAI,IAAY;CAC9B,KAAK,MAAM,SAAS,OAAO,mBAAmB,CAAC,GAAG;EAChD,IAAI,CAAC,6BAA6B,KAAK,MAAM,IAAI,KAAK,MAAM,SAAS,MACnE,MAAM,IAAI,MAAM,kCAAkC;EACpD,IAAI,MAAM,IAAI,MAAM,IAAI,GAAG,MAAM,IAAI,MAAM,oCAAoC;EAC/E,MAAM,IAAI,MAAM,IAAI;EACpB,sBAAsB;GAAE,GAAG;GAAQ,iBAAiB,CAAC,KAAK;EAAE,GAAG,MAAM,KAAK,QAAQ,OAAO,EAAE,CAAC;CAC9F;AACF"}
1
+ {"version":3,"file":"browser-posture.mjs","names":["z.object","z.literal","z.string","z.guid","z.enum","z.number","z.array","z.boolean","z\n .object","z\n .string","z.object","z.string","z.guid","z.enum","z.number","z.array","z.literal","z\n .object","z\n .record","z.unknown","record","z.record","z.string","z.unknown"],"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"],"sourcesContent":["// 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","/**\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","import { z } from 'zod';\n\nexport const BrowserPostureSchema = z.object({\n v: z.literal(1),\n project_id: z.string().min(1).max(128),\n origin: z.string().url(),\n // Consolidated IDs include PostgreSQL MD5()::uuid values with arbitrary\n // version/variant bits. Keep their stored identity intact across Zod upgrades.\n session_id: z.guid(),\n binding: z.string().regex(/^[a-f0-9]{64}$/),\n verdict: z.enum(['agent-driven', 'human', 'insufficient']),\n score: z.number().min(0).max(1).nullable(),\n scorer_version: z.number().int().positive().max(2147483647),\n reasons: z.array(z.string().max(160)).max(8),\n // Defaulted, not required: a token minted by a not-yet-upgraded issuer\n // (rolling deploy) must still verify on an upgraded reader, matching the\n // Java `asBoolean(false)` / .NET `TryGetProperty` default-false handling\n // for the identical claims.\n automation_disclosed: z.boolean().default(false),\n automation_corroborated: z.boolean().default(false),\n detection: z\n .object({\n class: z.enum(['ai_agent', 'bot']),\n name: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[^\\p{Cc}]+$/u),\n confidence: z.number().int().min(0).max(100),\n })\n .optional(),\n // Holder-of-key posture binding (P37): the RFC 7638 thumbprint of the\n // public key a DPoP-shaped proof must be signed by to accompany this\n // token. Optional: absent for a session that hasn't sent its public JWK\n // yet, or for a token minted by a not-yet-upgraded issuer - the same\n // rolling-deploy tolerance `automation_disclosed`/`automation_corroborated`\n // already have. A verifier with no proof support simply never checks it,\n // so a cnf-bearing token still verifies today exactly as one without it.\n cnf: z\n .object({\n jkt: z.string().min(1).max(255),\n })\n .optional(),\n iat: z.number().int().nonnegative(),\n exp: z.number().int().positive(),\n});\n\n/** Authenticates a risk observation. This is never an agent credential. */\nexport type BrowserPosture = z.infer<typeof BrowserPostureSchema>;\n","import { z } from 'zod';\nimport type { BrowserPosture } from './browser-posture-schema';\n\nexport const POSTURE_VERIFICATION_STATUSES = ['verified', 'absent', 'rejected'] as const;\nexport type PostureVerificationStatus = (typeof POSTURE_VERIFICATION_STATUSES)[number];\n\n/** Audit projection: no token, cookie binding, raw counters, or credential fields. */\nexport const BrowserPostureReportSchema = z.object({\n projectId: z.string().min(1).max(128),\n // Match the signed posture's MD5-derived consolidated session IDs.\n sessionId: z.guid(),\n verdict: z.enum(['human', 'agent-driven', 'insufficient']),\n score: z.number().min(0).max(1).nullable(),\n scorerVersion: z.number().int().positive(),\n reasons: z.array(z.string().max(160)).max(8),\n issuedAt: z.number().int().nonnegative(),\n expiresAt: z.number().int().positive(),\n source: z.literal('verified-posture'),\n});\n\nexport const BROWSER_POSTURE_REJECTION_REASONS = [\n 'malformed',\n 'unknown-key',\n 'bad-signature',\n 'invalid-claims',\n 'project-mismatch',\n 'origin-mismatch',\n 'audience-mismatch',\n 'expired',\n 'not-yet-valid',\n 'binding-mismatch',\n 'session-missing',\n] as const;\nexport type BrowserPostureRejectionReason = (typeof BROWSER_POSTURE_REJECTION_REASONS)[number];\n\nexport const BrowserPostureOutcomeSchema = z\n .object({\n status: z.enum(POSTURE_VERIFICATION_STATUSES),\n reason: z.enum(BROWSER_POSTURE_REJECTION_REASONS).optional(),\n })\n .refine((outcome) => (outcome.status === 'rejected') === (outcome.reason !== undefined), {\n message: 'reason is required if and only if status is rejected',\n path: ['reason'],\n });\nexport type BrowserPostureOutcome = z.infer<typeof BrowserPostureOutcomeSchema>;\n\nexport const BROWSER_POSTURE_REASON_PATTERN = /^[a-z][a-z-]{0,31}$/;\nexport const BROWSER_POSTURE_REJECTIONS_MAX_ENTRIES = 50;\nexport const BROWSER_POSTURE_REJECTION_COUNT_MAX = 1_000_000;\n\nexport const BrowserPostureRejectionsSchema = z\n .record(z.string(), z.unknown())\n .transform((counts) =>\n Object.fromEntries(\n Object.entries(counts)\n .filter(\n (entry): entry is [string, number] =>\n BROWSER_POSTURE_REASON_PATTERN.test(entry[0]) &&\n typeof entry[1] === 'number' &&\n Number.isInteger(entry[1]) &&\n entry[1] > 0\n )\n .slice(0, BROWSER_POSTURE_REJECTIONS_MAX_ENTRIES)\n .map(([reason, count]): [string, number] => [\n reason,\n Math.min(count, BROWSER_POSTURE_REJECTION_COUNT_MAX),\n ])\n )\n );\nexport type BrowserPostureRejections = z.infer<typeof BrowserPostureRejectionsSchema>;\n\nexport const BrowserPostureReportIngestSchema = BrowserPostureReportSchema.extend({\n score: BrowserPostureReportSchema.shape.score.default(null),\n});\n\nexport function browserPostureReport(posture: BrowserPosture) {\n return {\n projectId: posture.project_id,\n sessionId: posture.session_id,\n verdict: posture.verdict,\n score: posture.score,\n scorerVersion: posture.scorer_version,\n reasons: posture.reasons,\n issuedAt: posture.iat,\n expiresAt: posture.exp,\n source: 'verified-posture' as const,\n };\n}\n","import {\n compactVerify,\n decodeProtectedHeader,\n importJWK,\n SignJWT,\n type CompactVerifyResult,\n type JWK,\n} from 'jose';\nimport { z } from 'zod';\nimport { projectVerificationKey } from './project-verification-key';\nimport { VALIDATION_PATTERNS } from './constants/patterns';\nimport { postureCookieName } from './browser-posture-cookie';\nimport { matchAllowedOrigin, MAX_POSTURE_ORIGINS, parseOriginPattern } from './posture-origins';\nimport { POSTURE_TTL_SECONDS } from './beacon-types';\nimport { BrowserPostureSchema, type BrowserPosture } from './browser-posture-schema';\nimport type {\n BrowserPostureOutcome,\n BrowserPostureRejectionReason,\n} from './browser-posture-report';\n\nexport { BrowserPostureSchema } from './browser-posture-schema';\nexport type { BrowserPosture } from './browser-posture-schema';\n\nexport { postureCookieName, POSTURE_TTL_SECONDS };\n\nexport const UNSIGNED_BROWSER_AGENT = {\n agentType: 'Browser agent (unsigned)',\n detectionClass: 'ai_agent',\n verificationMethod: 'behavioral',\n} as const;\nexport const behavioralConfidence = (score: number | null): number =>\n Math.min(85, Math.max(50, Math.round((score ?? 0.5) * 100)));\n\ninterface PostureUpgrade {\n detectionClass: 'ai_agent' | 'bot' | 'incomplete_data';\n isAgent: boolean;\n agentName?: string;\n confidence: number;\n verificationMethod: 'behavioral';\n reasons: string[];\n}\n\nexport function postureUpgrade(posture: BrowserPosture): PostureUpgrade | undefined {\n const { detection, reasons } = posture;\n const verificationMethod = 'behavioral';\n if (detection)\n return {\n detectionClass: detection.class,\n isAgent: true,\n agentName: detection.name,\n confidence: detection.confidence,\n verificationMethod,\n reasons,\n };\n if (posture.automation_disclosed)\n return {\n detectionClass: 'bot',\n isAgent: true,\n agentName: 'Automation Tools',\n confidence: 80,\n verificationMethod,\n reasons,\n };\n if (posture.verdict === 'agent-driven')\n return {\n detectionClass: UNSIGNED_BROWSER_AGENT.detectionClass,\n isAgent: true,\n agentName: UNSIGNED_BROWSER_AGENT.agentType,\n confidence: behavioralConfidence(posture.score),\n verificationMethod,\n reasons,\n };\n if (posture.automation_corroborated)\n return {\n detectionClass: 'incomplete_data',\n isAgent: false,\n confidence: 40,\n verificationMethod,\n reasons,\n };\n return undefined;\n}\n\nexport const POSTURE_ISSUER = 'checkpoint:browser-posture:v1';\n// A custom Nimbus JOSE+JWT type verifier is required to accept this typ; see\n// packages/checkpoint-java/README.md's \"Verifying with your own Nimbus-based stack\".\nexport const POSTURE_TYPE = 'checkpoint-posture+jwt';\n\nexport interface BrowserPostureConfig {\n /** Locally configured public project key; never taken from a cookie or header. */\n publicKey: JWK;\n keyId: string;\n /** Exact HTTPS origin of the protected resource, from operator configuration. */\n origin: string;\n origins?: string[];\n sessionCookieName?: string;\n /** Explicit path/scope designations for the default integrity step-up rule. */\n protectedRoutes?: Array<{ path: string; scopes: string[] }>;\n}\n\n/** Duplicate cookies are ambiguous, so none is trusted. */\nexport function readPostureCookie(\n header: string | null | undefined,\n name: string\n): string | undefined {\n const matches = (header ?? '')\n .split(';')\n .map((s) => s.trim())\n .filter((s) => s.startsWith(`${name}=`));\n if (matches.length !== 1) return undefined;\n try {\n return decodeURIComponent(matches[0].slice(name.length + 1));\n } catch {\n return undefined;\n }\n}\n\nexport async function postureSessionBinding(sessionId: string): Promise<string> {\n const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(sessionId));\n return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nfunction validOrigin(origin: string): boolean {\n try {\n const url = new URL(origin);\n return url.protocol === 'https:' && url.origin === origin && /^[^.*][^*]*$/.test(url.hostname);\n } catch {\n return false;\n }\n}\n\nexport async function signBrowserPosture(\n posture: BrowserPosture,\n privateKey: JWK,\n keyId: string\n): Promise<string> {\n const claims = BrowserPostureSchema.parse(posture);\n if (\n !validOrigin(claims.origin) ||\n claims.exp <= claims.iat ||\n claims.exp - claims.iat > POSTURE_TTL_SECONDS ||\n privateKey.kty !== 'EC' ||\n privateKey.crv !== 'P-256' ||\n !privateKey.d ||\n !keyId\n ) {\n throw new Error('Invalid posture signing configuration');\n }\n const key = await importJWK(privateKey, 'ES256');\n return new SignJWT(claims)\n .setProtectedHeader({ alg: 'ES256', typ: POSTURE_TYPE, kid: keyId })\n .setIssuer(POSTURE_ISSUER)\n .setAudience(claims.origin)\n .sign(key);\n}\n\nexport type PostureVerification =\n | { status: 'verified'; posture: BrowserPosture }\n | { status: 'absent' }\n | { status: 'rejected'; reason: BrowserPostureRejectionReason };\n\nconst BASE64URL = /^[A-Za-z0-9_-]+$/;\n\nconst rejected = (reason: BrowserPostureRejectionReason) =>\n ({ status: 'rejected', reason }) as const;\n\nexport const postureOutcomeReport = (outcome: PostureVerification): BrowserPostureOutcome =>\n outcome.status === 'verified' ? { status: 'verified' } : outcome;\n\nconst verifiedPosture = (outcome: PostureVerification): BrowserPosture | undefined =>\n outcome.status === 'verified' ? outcome.posture : undefined;\n\nexport async function inspectBrowserPosture(\n token: string | undefined,\n config: BrowserPostureConfig,\n projectId: string,\n browserSessionId: string | undefined,\n now = Math.floor(Date.now() / 1000)\n): Promise<PostureVerification> {\n if (!token) return { status: 'absent' };\n if (!browserSessionId || browserSessionId.length > 255) return rejected('session-missing');\n const parts = token.split('.');\n if (\n token.length > 3800 ||\n parts.length !== 3 ||\n !parts.every((part) => BASE64URL.test(part)) ||\n parts[0].length % 4 === 1\n )\n return rejected('malformed');\n let header: ReturnType<typeof decodeProtectedHeader>;\n try {\n header = decodeProtectedHeader(token);\n } catch {\n return rejected('malformed');\n }\n if (\n header.alg !== 'ES256' ||\n header.typ !== POSTURE_TYPE ||\n typeof header.kid !== 'string' ||\n 'crit' in header ||\n 'b64' in header\n )\n return rejected('malformed');\n const publicKey =\n validOrigin(config.origin) &&\n !config.publicKey.d &&\n config.publicKey.kty === 'EC' &&\n config.publicKey.crv === 'P-256'\n ? projectVerificationKey(token, config, now)\n : undefined;\n const key = publicKey && (await importJWK(publicKey, 'ES256').catch(() => undefined));\n if (!key) return rejected('unknown-key');\n let signed: CompactVerifyResult;\n try {\n signed = await compactVerify(token, key, { algorithms: ['ES256'] });\n } catch {\n return rejected('bad-signature');\n }\n let json: unknown;\n try {\n json = JSON.parse(new TextDecoder().decode(signed.payload));\n } catch {\n return rejected('malformed');\n }\n const record = z.record(z.string(), z.unknown()).safeParse(json);\n if (!record.success) return rejected('invalid-claims');\n const audiences = [record.data.aud].flat();\n if (audiences.some((audience) => typeof audience !== 'string')) return rejected('malformed');\n const notBefore = record.data.nbf;\n const parsed = BrowserPostureSchema.safeParse(record.data);\n if (\n !parsed.success ||\n record.data.iss !== POSTURE_ISSUER ||\n (notBefore !== undefined && typeof notBefore !== 'number') ||\n record.data.origin !== parsed.data.origin ||\n !validOrigin(parsed.data.origin)\n )\n return rejected('invalid-claims');\n const claims = parsed.data;\n if (claims.project_id !== projectId) return rejected('project-mismatch');\n if (claims.origin !== config.origin && !matchAllowedOrigin(claims.origin, config.origins ?? []))\n return rejected('origin-mismatch');\n if (!audiences.includes(claims.origin)) return rejected('audience-mismatch');\n if (claims.exp <= now) return rejected('expired');\n if (claims.iat > now + 5 || (notBefore !== undefined && notBefore > now))\n return rejected('not-yet-valid');\n if (claims.exp <= claims.iat || claims.exp - claims.iat > POSTURE_TTL_SECONDS)\n return rejected('invalid-claims');\n if (claims.binding !== (await postureSessionBinding(browserSessionId)))\n return rejected('binding-mismatch');\n return { status: 'verified', posture: claims };\n}\n\nexport async function verifyBrowserPosture(\n token: string | undefined,\n config: BrowserPostureConfig,\n projectId: string,\n browserSessionId: string | undefined,\n now = Math.floor(Date.now() / 1000)\n): Promise<BrowserPosture | undefined> {\n return verifiedPosture(\n await inspectBrowserPosture(token, config, projectId, browserSessionId, now)\n );\n}\n\n/**\n * Request headers a page sends when its posture cookies cannot reach the\n * server: a request to another host (the cookies are host-only) or a browser\n * that blocks cookies. The page reads both values from the beacon's\n * `onReceipt`.\n */\nexport const POSTURE_HEADER = 'kya-posture';\nexport const POSTURE_SESSION_HEADER = 'kya-posture-session';\n\n/** The request values posture is read from. A string array is a header sent more than once. */\nexport interface PostureRequest {\n cookie?: string | null;\n /** `KYA-Posture`: the posture token. */\n posture?: string | string[] | null;\n /** `KYA-Posture-Session`: the browser session id the token is bound to. */\n session?: string | string[] | null;\n}\n\n/** The `PostureRequest` of any header store, read through its own lowercase-name getter. */\nexport function postureRequestFromHeaders(\n get: (lowercaseName: string) => string | string[] | null | undefined\n): PostureRequest {\n const cookie = get('cookie');\n return {\n cookie: Array.isArray(cookie) ? cookie.join('; ') : cookie,\n posture: get(POSTURE_HEADER),\n session: get(POSTURE_SESSION_HEADER),\n };\n}\n\n/**\n * A header, when the request carries a non-empty one, wins over its cookie.\n * A header sent twice, or joined into one comma-separated value, is ambiguous,\n * so neither copy is trusted and the cookie is not consulted either: the page\n * chose the header. Every runtime applies the same rule\n * (`tests/browser-posture/vectors.json` `requests`).\n */\nfunction postureRequestValue(\n header: string | string[] | null | undefined,\n cookieHeader: string | null | undefined,\n cookieName: string\n): string | undefined {\n const values = (Array.isArray(header) ? header : [header])\n .map((value) => value?.trim())\n .filter((value): value is string => Boolean(value));\n if (values.length === 0) return readPostureCookie(cookieHeader, cookieName);\n return values.length === 1 && !values[0].includes(',') ? values[0] : undefined;\n}\n\n/** Read and verify posture from the `KYA-Posture` headers, falling back to the cookies. */\nexport async function postureOutcomeFromRequest(\n request: PostureRequest,\n config: BrowserPostureConfig,\n projectId: string,\n now?: number\n): Promise<PostureVerification> {\n return inspectBrowserPosture(\n postureRequestValue(request.posture, request.cookie, postureCookieName(projectId)),\n config,\n projectId,\n postureRequestValue(\n request.session,\n request.cookie,\n config.sessionCookieName ?? '_as_beacon_session'\n ),\n now\n );\n}\n\nexport async function postureFromRequest(\n request: PostureRequest,\n config: BrowserPostureConfig,\n projectId: string,\n now?: number\n): Promise<BrowserPosture | undefined> {\n return verifiedPosture(await postureOutcomeFromRequest(request, config, projectId, now));\n}\n\nexport async function postureFromCookies(\n header: string | null | undefined,\n config: BrowserPostureConfig,\n projectId: string\n): Promise<BrowserPosture | undefined> {\n return postureFromRequest({ cookie: header }, config, projectId);\n}\n\n/** Exact paths or an explicit subtree ending in /*. Longest designation wins. */\nexport function postureRequiredScopes(\n config: BrowserPostureConfig,\n path: string\n): string[] | undefined {\n const routes = config.protectedRoutes ?? [];\n const route = [...routes]\n .sort((a, b) => b.path.length - a.path.length)\n .find((r) => (r.path.endsWith('/*') ? path.startsWith(r.path.slice(0, -1)) : path === r.path));\n if (!route) return undefined;\n if (\n !route.scopes.length ||\n route.scopes.length > 50 ||\n route.scopes.some((s) => s.length > 200 || !/^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/.test(s)) ||\n new Set(route.scopes).size !== route.scopes.length\n ) {\n throw new Error('Integrity-protected routes require explicit, unique scopes');\n }\n return route.scopes;\n}\n\n/** Validate operator configuration at startup, before any request can depend on it. */\nexport function validateBrowserPostureConfig(\n config: BrowserPostureConfig,\n projectId: string | undefined\n): void {\n // The issuer signs `project_id` as the project UUID and the beacon names\n // the cookie after that claim, so a reader configured with the project's\n // friendly id could never match either: it would verify nothing, silently,\n // for the life of the deployment. Refuse it at startup instead.\n if (\n !projectId ||\n !VALIDATION_PATTERNS.UUID.test(projectId) ||\n projectId !== projectId.toLowerCase()\n ) {\n throw new Error(\n 'Browser posture requires projectId to be the lowercase project UUID (the friendly id is not accepted)'\n );\n }\n if (\n !validOrigin(config.origin) ||\n !config.keyId ||\n config.publicKey.kty !== 'EC' ||\n config.publicKey.crv !== 'P-256' ||\n !config.publicKey.x ||\n !config.publicKey.y ||\n config.publicKey.d\n ) {\n throw new Error(\n 'Browser posture requires projectId, an exact HTTPS origin, and a public ES256 key'\n );\n }\n const origins = config.origins ?? [];\n if (origins.length > MAX_POSTURE_ORIGINS)\n throw new Error(`Browser posture accepts at most ${MAX_POSTURE_ORIGINS} additional origins`);\n for (const entry of origins) {\n const parsed = parseOriginPattern(entry);\n if (!parsed.ok) throw new Error(`Invalid browser posture origin \"${entry}\": ${parsed.error}`);\n }\n const paths = new Set<string>();\n for (const route of config.protectedRoutes ?? []) {\n if (!/^\\/(?:[^?#*\\\\]*)(?:\\/\\*)?$/.test(route.path) && route.path !== '/*')\n throw new Error('Invalid integrity-protected path');\n if (paths.has(route.path)) throw new Error('Duplicate integrity-protected path');\n paths.add(route.path);\n postureRequiredScopes({ ...config, protectedRoutes: [route] }, route.path.replace(/\\*$/, ''));\n }\n}\n\nexport type { JWK } from 'jose';\n\nexport {\n BROWSER_POSTURE_REJECTION_REASONS,\n BrowserPostureOutcomeSchema,\n POSTURE_VERIFICATION_STATUSES,\n BrowserPostureReportIngestSchema,\n BrowserPostureReportSchema,\n browserPostureReport,\n} from './browser-posture-report';\nexport type {\n BrowserPostureOutcome,\n BrowserPostureRejectionReason,\n PostureVerificationStatus,\n} from './browser-posture-report';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAgBA,SAAgB,kBAAkB,WAA2B;CAC3D,IAAI,CAAC,aAAa,KAAK,SAAS,KAAK,cAAc,UAAU,YAAY,GACvE,MAAM,IAAI,MAAM,4BAA4B;CAC9C,OAAO,6BAA6B;AACtC;;;;;;;;;AC2pDA,MAAa,sBAA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