@kya-os/checkpoint-shared 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/beacon-types/index.d.mts +441 -432
  3. package/dist/beacon-types/index.d.mts.map +1 -0
  4. package/dist/beacon-types/index.d.ts +441 -432
  5. package/dist/beacon-types/index.d.ts.map +1 -0
  6. package/dist/beacon-types/index.js +198 -182
  7. package/dist/beacon-types/index.mjs +197 -179
  8. package/dist/beacon-types/index.mjs.map +1 -0
  9. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +5 -0
  10. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +1 -0
  11. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +5 -0
  12. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +1 -0
  13. package/dist/browser-posture-cookie.d.mts +2 -0
  14. package/dist/browser-posture-cookie.d.ts +2 -0
  15. package/dist/browser-posture-cookie.js +1 -0
  16. package/dist/browser-posture-cookie.mjs +2 -0
  17. package/dist/browser-posture-cookie.mjs.map +1 -0
  18. package/dist/browser-posture-report.d.mts +48 -44
  19. package/dist/browser-posture-report.d.mts.map +1 -0
  20. package/dist/browser-posture-report.d.ts +48 -44
  21. package/dist/browser-posture-report.d.ts.map +1 -0
  22. package/dist/browser-posture-report.js +1 -1
  23. package/dist/browser-posture-report.mjs +2 -1
  24. package/dist/browser-posture-report.mjs.map +1 -0
  25. package/dist/browser-posture.d.mts +80 -75
  26. package/dist/browser-posture.d.mts.map +1 -0
  27. package/dist/browser-posture.d.ts +80 -75
  28. package/dist/browser-posture.d.ts.map +1 -0
  29. package/dist/browser-posture.js +159 -18993
  30. package/dist/browser-posture.mjs +158 -18990
  31. package/dist/browser-posture.mjs.map +1 -0
  32. package/dist/browser.d.mts +323 -316
  33. package/dist/browser.d.mts.map +1 -0
  34. package/dist/browser.d.ts +323 -316
  35. package/dist/browser.d.ts.map +1 -0
  36. package/dist/browser.js +1 -1
  37. package/dist/browser.mjs +2 -1
  38. package/dist/browser.mjs.map +1 -0
  39. package/dist/canonical-signer/index.d.mts +38 -33
  40. package/dist/canonical-signer/index.d.mts.map +1 -0
  41. package/dist/canonical-signer/index.d.ts +38 -33
  42. package/dist/canonical-signer/index.d.ts.map +1 -0
  43. package/dist/canonical-signer/index.js +411 -181
  44. package/dist/canonical-signer/index.mjs +383 -175
  45. package/dist/canonical-signer/index.mjs.map +1 -0
  46. package/dist/clearance.d.mts +30 -0
  47. package/dist/clearance.d.mts.map +1 -0
  48. package/dist/clearance.d.ts +30 -0
  49. package/dist/clearance.d.ts.map +1 -0
  50. package/dist/clearance.js +120 -0
  51. package/dist/clearance.mjs +112 -0
  52. package/dist/clearance.mjs.map +1 -0
  53. package/dist/client-ip-1y2iXAYW.js +237 -0
  54. package/dist/client-ip-HOfe6ucV.mjs +215 -0
  55. package/dist/client-ip-HOfe6ucV.mjs.map +1 -0
  56. package/dist/deploy/index.d.mts +339 -339
  57. package/dist/deploy/index.d.mts.map +1 -0
  58. package/dist/deploy/index.d.ts +339 -339
  59. package/dist/deploy/index.d.ts.map +1 -0
  60. package/dist/deploy/index.js +505 -413
  61. package/dist/deploy/index.mjs +504 -410
  62. package/dist/deploy/index.mjs.map +1 -0
  63. package/dist/errors/index.d.mts +101 -101
  64. package/dist/errors/index.d.mts.map +1 -0
  65. package/dist/errors/index.d.ts +101 -101
  66. package/dist/errors/index.d.ts.map +1 -0
  67. package/dist/errors/index.js +341 -314
  68. package/dist/errors/index.mjs +340 -311
  69. package/dist/errors/index.mjs.map +1 -0
  70. package/dist/external-jr_S4iSS.d.mts +4187 -0
  71. package/dist/external-jr_S4iSS.d.mts.map +1 -0
  72. package/dist/external-jr_S4iSS.d.ts +4187 -0
  73. package/dist/external-jr_S4iSS.d.ts.map +1 -0
  74. package/dist/gateway/index.d.mts +138 -132
  75. package/dist/gateway/index.d.mts.map +1 -0
  76. package/dist/gateway/index.d.ts +138 -132
  77. package/dist/gateway/index.d.ts.map +1 -0
  78. package/dist/gateway/index.js +117 -81
  79. package/dist/gateway/index.mjs +116 -78
  80. package/dist/gateway/index.mjs.map +1 -0
  81. package/dist/gateway-client-ip.d.mts +59 -0
  82. package/dist/gateway-client-ip.d.mts.map +1 -0
  83. package/dist/gateway-client-ip.d.ts +59 -0
  84. package/dist/gateway-client-ip.d.ts.map +1 -0
  85. package/dist/gateway-client-ip.js +149 -0
  86. package/dist/gateway-client-ip.mjs +139 -0
  87. package/dist/gateway-client-ip.mjs.map +1 -0
  88. package/dist/index.d.mts +14895 -14240
  89. package/dist/index.d.mts.map +1 -0
  90. package/dist/index.d.ts +14895 -14240
  91. package/dist/index.d.ts.map +1 -0
  92. package/dist/index.js +15180 -31025
  93. package/dist/index.mjs +15065 -30942
  94. package/dist/index.mjs.map +1 -0
  95. package/dist/mcpi/agentshield-api/index.d.mts +45 -44
  96. package/dist/mcpi/agentshield-api/index.d.mts.map +1 -0
  97. package/dist/mcpi/agentshield-api/index.d.ts +45 -44
  98. package/dist/mcpi/agentshield-api/index.d.ts.map +1 -0
  99. package/dist/mcpi/agentshield-api/index.js +0 -2
  100. package/dist/mcpi/agentshield-api/index.mjs +1 -1
  101. package/dist/mcpi/approval-grant/index.d.mts +63 -61
  102. package/dist/mcpi/approval-grant/index.d.mts.map +1 -0
  103. package/dist/mcpi/approval-grant/index.d.ts +63 -61
  104. package/dist/mcpi/approval-grant/index.d.ts.map +1 -0
  105. package/dist/mcpi/approval-grant/index.js +220 -140
  106. package/dist/mcpi/approval-grant/index.mjs +219 -137
  107. package/dist/mcpi/approval-grant/index.mjs.map +1 -0
  108. package/dist/mcpi/dashboard-config/index.d.mts +2323 -2318
  109. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -0
  110. package/dist/mcpi/dashboard-config/index.d.ts +2323 -2318
  111. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -0
  112. package/dist/mcpi/dashboard-config/index.js +605 -458
  113. package/dist/mcpi/dashboard-config/index.mjs +604 -455
  114. package/dist/mcpi/dashboard-config/index.mjs.map +1 -0
  115. package/dist/mcpi/multibase-ed25519.d.mts +10 -8
  116. package/dist/mcpi/multibase-ed25519.d.mts.map +1 -0
  117. package/dist/mcpi/multibase-ed25519.d.ts +10 -8
  118. package/dist/mcpi/multibase-ed25519.d.ts.map +1 -0
  119. package/dist/mcpi/multibase-ed25519.js +182 -106
  120. package/dist/mcpi/multibase-ed25519.mjs +181 -103
  121. package/dist/mcpi/multibase-ed25519.mjs.map +1 -0
  122. package/dist/patterns-CkRVOdtV.js +243 -0
  123. package/dist/patterns-DzkGy_qk.mjs +173 -0
  124. package/dist/patterns-DzkGy_qk.mjs.map +1 -0
  125. package/dist/project-verification-key-C3L5rd8a.js +41 -0
  126. package/dist/project-verification-key-CgSVX9_m.mjs +37 -0
  127. package/dist/project-verification-key-CgSVX9_m.mjs.map +1 -0
  128. package/dist/rolldown-runtime-iY2fYEqi.mjs +19 -0
  129. package/dist/schemas-BmjNLAE7.js +5677 -0
  130. package/dist/schemas-DxY-dk9y.mjs +5511 -0
  131. package/dist/schemas-DxY-dk9y.mjs.map +1 -0
  132. package/dist/signals/index.d.mts +125 -115
  133. package/dist/signals/index.d.mts.map +1 -0
  134. package/dist/signals/index.d.ts +125 -115
  135. package/dist/signals/index.d.ts.map +1 -0
  136. package/dist/signals/index.js +1693 -1536
  137. package/dist/signals/index.mjs +1692 -1533
  138. package/dist/signals/index.mjs.map +1 -0
  139. package/dist/test-fixtures/index.d.mts +124 -119
  140. package/dist/test-fixtures/index.d.mts.map +1 -0
  141. package/dist/test-fixtures/index.d.ts +124 -119
  142. package/dist/test-fixtures/index.d.ts.map +1 -0
  143. package/dist/test-fixtures/index.js +460 -228
  144. package/dist/test-fixtures/index.mjs +459 -225
  145. package/dist/test-fixtures/index.mjs.map +1 -0
  146. package/dist/tool-protection/index.d.mts +343 -343
  147. package/dist/tool-protection/index.d.mts.map +1 -0
  148. package/dist/tool-protection/index.d.ts +343 -343
  149. package/dist/tool-protection/index.d.ts.map +1 -0
  150. package/dist/tool-protection/index.js +366 -285
  151. package/dist/tool-protection/index.mjs +365 -282
  152. package/dist/tool-protection/index.mjs.map +1 -0
  153. package/fixtures/bot-signal-resolution.json +142 -0
  154. package/fixtures/browser-posture-claims.json +421 -0
  155. package/fixtures/browser-posture-headers.json +46 -0
  156. package/fixtures/detection/reason-codes.json +10 -1
  157. package/fixtures/kya-http/challenge.delegation.fetcher-200.json +9 -3
  158. package/fixtures/kya-http/challenge.delegation.full.json +9 -3
  159. package/fixtures/kya-http/challenge.delegation.minimal.json +9 -3
  160. package/fixtures/kya-http/error-codes.json +7 -2
  161. package/package.json +20 -6
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["core._coercedNumber","schemas.ZodNumber","core._coercedBoolean","schemas.ZodBoolean","core._coercedDate","schemas.ZodDate","z\n .enum","z.discriminatedUnion","z.object","z.literal","z.string","z.enum","z\n .enum","z.record","z.unknown","z.date","z\n .enum","z\n .number","z\n .string","z\n .record","z.number","z.array","z.boolean","z\n .object","z\n // Dual-accept (mcp-i → kya-os): accept the canonical engine value\n // `kyaos_handshake` alongside the legacy `mcp_i_handshake` so engine output\n // still validates once upstream flips its emitter.\n .enum","z.union","z.instanceof","z.enum","z.object","z.string","z.boolean","z.array","z.record","z.number","z\n .enum","z.enum","z.object","z.number","z.array","z.string","z.object","z.string","z.number","z.object","z.boolean","z.number","z.enum","z\n .array","z.string","z.array","z.record","z.union","z.ipv4","z.ipv6","z.custom","z.object","z.boolean","z.enum","z.number","z.string","z\n .object","z.record","z.any","z.array","z.enum","BotPatternSchema","z.object","z.string","z.array","z.number","z.object","z.number","z.enum","z.string","z\n .object","z.array","z.boolean","z.object","z.string","z.record","z\n .object","z.enum","z.boolean","z.number","z.array","z\n .array","z.object","z.boolean","z.any","z\n .object","z.string","z.number","z.array","z.enum","z\n .record","z.enum","z.object","z.string","z.boolean","z.array","z.number","z.union","z.date","z.record","z.unknown","z\n .object","z\n .object","z\n .record","z.object","z.string","z.enum","z.record","z.number","z.unknown","z.boolean","z\n .object","z.array","z\n .object","z.date","z.enum","z.object","z.string","z.number","z.record","z.boolean","z\n .object","z\n .object","z.date","z\n .enum","z.enum","z.object","z.boolean","z.number","z.unknown","z\n .object","z.string","z.array","z.discriminatedUnion","z.literal","z.enum","z.object","z.string","z.date","z.boolean","z.number","z.array","z.record","z.unknown","z.string","z.enum","z\n .enum","z\n .string","z.object","z.number","z.literal","z\n .object","z.array","z.boolean","z.record","z.union","z\n .object","z\n .string","z.discriminatedUnion","z\n .string","z\n .object","z\n .string","z.unknown","z\n .string","z.enum","z\n .object","z.boolean","z.string","z.array","z.object","z.number","z\n .object","z\n .string","z.ZodError","z.string","z.object","z.coerce.number","z.coerce\n .number","z.enum","z.array","z\n .object","z.boolean","z.number","z\n .string","z.record","z.unknown","AnalyticsQuerySchema","z\n .enum","z.coerce.boolean","z\n .array","z.literal","z.object","z.string","z.enum","z.number","z.boolean","z.array","z\n .object","z.any","z\n .object","z.object","z\n .array","z\n .boolean","ClientDetectionSchema","z.object","z.boolean","z.number","z.array","z.string","z\n .object","z\n .object","z.record","z.unknown","z.date","z.enum","z.object","z.string","z.literal","z.boolean","z.number","z.enum","z.array","z\n .object","z.object","z.string","z.number","z.enum","z.object","z.number","z.string","z.any","z.literal","DidStringSchema","z\n .string","z.enum","z\n .object","z.boolean","z.string","z.number","z.array","z\n .array","z\n .object","z.object","z.literal","z.discriminatedUnion","z\n .object","z.enum","z.object","z.string","z.number","z\n .object","z.literal","z.array","z.boolean","z\n .array","z.record","z.union","z.string","z.object","z.boolean","z.number","z.enum","z.object","z.string","z.date","z.boolean","z.number","z.record","z.unknown","z.object","z.number","z.boolean","z.string","z.any","z.enum","z.array","z.enum","z.object","z.string","z.any","z.number","z.boolean","z.record","z.literal","z.object","z.enum","z.array","z.record","z.string","z.unknown","z\n .object","z.boolean","z.number","z\n .array","z.date","z.object","z\n .object","z.string","z.number","z.record","z.unknown","z.enum","z.boolean","z.array","z.date","AnalyticsSummarySchema","z.object","z\n .object","z.string","z.enum","z.array","z.record","z.boolean","z.number","z.enum","z.object","z.string","z.date","z.record","z\n .object","z\n .object","z.boolean","z.number","z.array","z.any","z\n .array","z\n .object","z\n .partialRecord","z\n .array","FingerprintRecordSchema","z.partialRecord","z\n .array","z.enum","z.object","z.string","z.boolean","z.number","z.array","z.date","z.record","z.unknown","z.object","z.literal","z.boolean","z.string","z.enum","z.array","z.coerce.number","z.object","z.enum","z\n .string","z.coerce\n .number","z.object","z.string","z.number","z\n .object","z.boolean","ErrorResponseSchema","z.literal","z.any","z.array","z.string","z\n .string","z.object","z.string","z\n .object","z.object","z.enum","z.string","z\n .object","z.boolean","z.array","z.number","z.coerce.number","z\n .object","z.string","z.record","z.unknown","z.enum","z.number","z.array","z\n .string","z.object","z.string","z.enum","z.array","z.record","z.boolean","z.number","z\n .array","z\n .string","z\n .object","z\n .object","z\n .number","z\n .record","z.coerce.date","z.object","z.enum","z.string","z.coerce.number","z.coerce.boolean","z.number","z.literal","z.array","z.object","z.array","z.string","z.number","z.enum","z.record","z.any","z.boolean","z.union","z\n .object","z\n .array","z.ZodError","z.ZodError","z.enum","z.discriminatedUnion","z.object","z.literal","z.string","z.array","z.number","z\n .number","z.boolean","z.union","z\n .object","z.string","z.record","z.literal","z\n .object","z\n .object","z.number","z.discriminatedUnion","z\n .string","z.string","z\n .object","z.enum","z.array","z.number","ED25519_PUBKEY_LENGTH","ED25519_MULTIKEY_LENGTH","z\n .string","z.NEVER","z\n .object","z.string","z.array"],"sources":["../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/compat.js","../../../node_modules/.pnpm/zod@4.5.4/node_modules/zod/v4/classic/coerce.js","../src/core/detection-reason-codes.ts","../src/core/detection.ts","../src/core/agent.ts","../src/core/confidence.ts","../src/core/verdict-evidence.ts","../src/utils/verification.ts","../src/core/detection-reason-mapping.ts","../src/config/shield.ts","../src/utils/zod-helpers.ts","../src/config/middleware.ts","../src/constants/agents.ts","../src/constants/bots.ts","../src/constants/defaults.ts","../src/constants/delegation.ts","../src/constants/errors.ts","../src/constants/limits.ts","../src/constants/rules.ts","../src/events/behavioral.ts","../src/api/request.ts","../src/api/response.ts","../src/types/pixel.ts","../src/api/event.ts","../src/api/verification.ts","../src/api/bulk.ts","../src/constants/ai-traffic-taxonomy.ts","../src/types/entities.ts","../src/schemas/provider-registry.ts","../src/schemas/bouncer.ts","../src/types/organization.ts","../src/mcpi/authorization-host.ts","../src/api/internal.ts","../src/api/public.ts","../src/api/signal-exposure.ts","../src/api/fingerprint.ts","../src/types/shopify.ts","../src/events/agent-shield.ts","../src/events/realtime.ts","../src/deploy/index.ts","../src/events/deploy-progress.ts","../src/types/wasm.ts","../src/types/session.ts","../src/types/transport.ts","../src/types/worker.ts","../src/types/database.ts","../src/types/analytics.ts","../src/types/detection-metadata.ts","../src/types/auth.ts","../src/types/fingerprint.ts","../src/types/signing-vendors.generated.ts","../src/types/agent-classification.ts","../src/types/admin.ts","../src/types/admin-overview.ts","../src/types/api.ts","../src/types/responses.ts","../src/utils/detection-class.ts","../src/utils/agent-runtime-label.ts","../src/utils/bot-signals.ts","../src/utils/correlation-id.ts","../src/schemas/auth.ts","../src/schemas/admin.ts","../src/wire/gateway-internal-tools.ts","../src/schemas/gateway.ts","../src/schemas/index.ts","../src/schemas/analytics.ts","../src/schemas/rules.ts","../src/rules/rule-validator.ts","../src/rules/rule-parser.ts","../src/data/compiled/merged-rules.json","../src/rules/rule-loader.ts","../src/rules/vendor-range-freshness.ts","../src/policy/constants.ts","../src/policy/schemas.ts","../src/policy/evaluator.ts","../src/policy/cedar-string.ts","../src/policy/cedar-rule-match.ts","../src/policy/required-scopes.ts","../src/policy/decision-policy-id.ts","../src/policy/bespoke-policy.ts","../src/policy/policy-lint.ts","../src/policy/approval-quorum.ts","../src/policy/step-up.ts","../src/policy/fetcher.ts","../src/policy/index.ts","../src/host-adapter/verdict-cookie.ts","../src/host-adapter/content-negotiation.ts","../src/host-adapter/decision-mapping.ts","../src/host-adapter/fetcher-envelope.ts","../src/mcpi/kya-http-error-codes.ts","../src/host-adapter/challenge-wire.ts","../src/host-adapter/challenge-context.ts","../src/wire/vault.ts","../src/mcpi/org-did.ts","../src/mcpi/delegation-headers.ts","../src/mcpi/principal.ts","../src/mcpi/reported-identity.ts","../src/mcpi/did-key.ts","../src/mcpi/multibase-ed25519.ts","../src/mcpi/delegation-verdict.ts","../src/parsers/jafar.ts","../src/index.ts"],"sourcesContent":["// Zod 3 compat layer\nimport * as core from \"../core/index.js\";\n/** @deprecated Use the raw string literal codes instead, e.g. \"invalid_type\". */\nexport const ZodIssueCode = {\n invalid_type: \"invalid_type\",\n too_big: \"too_big\",\n too_small: \"too_small\",\n invalid_format: \"invalid_format\",\n not_multiple_of: \"not_multiple_of\",\n unrecognized_keys: \"unrecognized_keys\",\n invalid_union: \"invalid_union\",\n invalid_key: \"invalid_key\",\n invalid_element: \"invalid_element\",\n invalid_value: \"invalid_value\",\n custom: \"custom\",\n};\nexport { $brand, config } from \"../core/index.js\";\n/** @deprecated Use `z.config(params)` instead. */\nexport function setErrorMap(map) {\n core.config({\n customError: map,\n });\n}\n/** @deprecated Use `z.config()` instead. */\nexport function getErrorMap() {\n return core.config().customError;\n}\n/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport function string(params) {\n return core._coercedString(schemas.ZodString, params);\n}\nexport function number(params) {\n return core._coercedNumber(schemas.ZodNumber, params);\n}\nexport function boolean(params) {\n return core._coercedBoolean(schemas.ZodBoolean, params);\n}\nexport function bigint(params) {\n return core._coercedBigint(schemas.ZodBigInt, params);\n}\nexport function date(params) {\n return core._coercedDate(schemas.ZodDate, params);\n}\n","/**\n * Detection reason code registry — machine-readable \"why\" behind a\n * `kya-confidence` verdict (companion to the `kya-http-error-codes.ts` /\n * `bespoke-policy.ts` registries; same `as const satisfies` + namespaced\n * string-literal convention).\n *\n * The engine already emits everything needed to derive these in structured\n * form — `DetectionSignalDetail[]` (`signal_type` / `source`),\n * `detection_class`, `verification_method`, and the AI-crawler flag (see\n * `rust/crates/kya-os-engine/src/types.rs` + `api.rs`) — but until now the\n * only wire-level \"why\" was `reasons[]`, free English prose, and only ever\n * on a block/claim-rejection response. Downstream dashboards, alerts, and\n * customer integrations were left string-matching that prose (see\n * `apps/web/app/api/v1/pixel/route.ts` `validateDetectionResult`,\n * `detection-cache.service.ts`, and `agent-classification.service.ts` for\n * three live examples of exactly that pattern).\n *\n * `detection/*` codes are a PROJECTION of the engine's own fields: see\n * `mapDetectionToReasonCodes` in the sibling `detection-reason-mapping.ts`,\n * the single place that turns a detection's structured facts into an\n * ordered list of these codes (consumed by the gateway worker via\n * `apps/web/workers/gateway/src/detection/reason-codes.ts` and by the\n * `/api/v1/enforce` signal exposure, KYA-1107). This registry never\n * changes a verdict; it only labels one that already happened.\n *\n * The golden fixture `packages/checkpoint-shared/fixtures/detection/reason-codes.json`\n * is the source of truth; the parity test in\n * `__tests__/detection-reason-codes.test.ts` asserts this map is byte-exact\n * against it (no drift, no omissions) — same guard shape as\n * `kya-http-error-codes.test.ts`.\n *\n * `as const satisfies Record<string, \\`detection/${string}\\`>` keeps the\n * narrow literal value types (autocomplete + a compile error on a typo'd\n * code) while proving every value is a well-formed `detection/…` string.\n */\nimport { z } from 'zod';\n\nexport const DETECTION_REASON_CODES = {\n // ── Cryptographic / verified attribution (strongest evidence, first) ────\n /** `verificationMethod === 'kya-http'` — a kya-http/RFC 9421 signature verified. */\n SIGNATURE_VERIFIED: 'detection/signature-verified',\n /** `verificationMethod === 'kya-http-delegated'` — a verified delegation credential rode the request. */\n DELEGATION_VERIFIED: 'detection/delegation-verified',\n /** `verificationMethod === 'mcp-i' | 'kya-os'` (the wire values; `isKyaOsWireMethod`) — the MCP-I/KYA-OS handshake verified. */\n MCP_I_VERIFIED: 'detection/mcp-i-verified',\n /** `verificationMethod === 'did'` — the worker's DID-header scheme verified an Ed25519 signature against the agent's DID Document. */\n DID_SIGNATURE_VERIFIED: 'detection/did-signature-verified',\n /** `verificationMethod === 'signature'` — the worker's RFC 9421 signature verifier (ChatGPT et al.) verified against the DB-refreshed key directory. */\n RFC9421_SIGNATURE_VERIFIED: 'detection/rfc9421-signature-verified',\n /** `verificationMethod` starts with `tier1_` (e.g. `tier1_rfc9421`) — the engine's Tier-1 protocol attribution verified. */\n TIER1_ATTRIBUTION_VERIFIED: 'detection/tier1-attribution-verified',\n /** `verificationMethod === 'a2a'` — an A2A Agent Card's declared security scheme (RFC 9421 keyid, or a JWT bearer against resolved JWKS) cryptographically verified. */\n A2A_VERIFIED: 'detection/a2a-verified',\n /** `verificationMethod === 'error'` — a presented credential was demoted/rejected during verification; see the sibling `kyaErrorCode`. */\n VERIFICATION_ERROR: 'detection/verification-error',\n\n // ── Structured evidence signals (one per distinct `signals[].source`) ───\n /** A `signals[]` entry with `source === 'user_agent_pattern'` — the User-Agent matched a known pattern. */\n UA_PATTERN_MATCH: 'detection/ua-pattern-match',\n /** `source === 'header_heuristic'` — a header shape/combination heuristic matched. */\n HEADER_HEURISTIC: 'detection/header-heuristic',\n /** `source === 'ip_heuristic'` — an IP-based heuristic matched. */\n IP_HEURISTIC: 'detection/ip-heuristic',\n /** `source === 'vendor_ip_feed'` — the request IP matched a known vendor's published IP range. */\n VENDOR_IP_CORROBORATED: 'detection/vendor-ip-corroborated',\n /** `source === 'ip_intelligence'` — the host's IP-intelligence provider flagged the request's true IP as a proxy/VPN/Tor/anonymization exit. */\n IP_INTELLIGENCE_PROXY_SIGNAL: 'detection/ip-intelligence-proxy-signal',\n /** `source === 'transport.ja4'` — a TLS JA4 fingerprint was observed at the terminating proxy (emit-only observation marker; it matches no list). */\n JA4_FINGERPRINT_MATCH: 'detection/ja4-fingerprint-match',\n /** `source === 'client_integrity'` — the pixel/beacon ingest's own nonce-binding or pairwise-contradiction check flagged this request as not coming from the client it claims to. */\n CLIENT_INTEGRITY_FAILURE: 'detection/client-integrity-failure',\n /** `source === 'ua_tls_mismatch'` — the User-Agent claims a browser but the JA4 cipher-list hash (JA4_b) belongs to known non-browser tooling. */\n UA_TLS_MISMATCH: 'detection/ua-tls-mismatch',\n /** `source === 'client.attributes'` — a pixel/beacon-reported client attribute contributed. */\n CLIENT_ATTRIBUTE_SIGNAL: 'detection/client-attribute-signal',\n /** `source === 'behavioural.interaction'` — a behavioral/interaction signal contributed. */\n BEHAVIORAL_SIGNAL: 'detection/behavioral-signal',\n /** `source === 'mcp_i'` — an MCP-I header was present (evidence short of a completed handshake). */\n MCP_I_SIGNAL: 'detection/mcp-i-signal',\n /** `source === 'kya_http_binding'` — a kya-http binding was presented (evidence short of full verification). */\n KYA_HTTP_BINDING_SIGNAL: 'detection/kya-http-binding-signal',\n /** `source === 'kya_delegation_bearer'` — a delegation bearer credential was presented. */\n KYA_DELEGATION_BEARER_SIGNAL: 'detection/kya-delegation-bearer-signal',\n /** A `signals[]` entry with `source === 'a2a_agent_card'`: an A2A Agent Card was presented (evidence short of, or alongside, full verification). */\n A2A_CARD_SIGNAL: 'detection/a2a-card-signal',\n /** `source === 'scanner_misclassification_hint'`: Cloudflare's bot score contradicted a zero-evidence Human verdict, overriding it to Unknown. */\n SCANNER_MISCLASSIFICATION_HINT_SIGNAL: 'detection/scanner-misclassification-hint-signal',\n /** `source === 'client_headless_escalation'`: the beacon disclosed `navigator.webdriver`, or reported corroborating automation evidence (CDP/plugin/WebGL consistency, a distinctive property), escalating the classification. */\n CLIENT_HEADLESS_ESCALATION_SIGNAL: 'detection/client-headless-escalation-signal',\n /** `source === 'transport.cloudflare_bot_management'`: Cloudflare's bot-management score or verified-bot determination contributed. */\n CLOUDFLARE_BOT_MANAGEMENT_SIGNAL: 'detection/cloudflare-bot-management-signal',\n /** `source === 'session_velocity'`: the edge-computed request-velocity heuristic contributed (confidence/weight scale with request count, a first-pass ramp, not yet fitted to measured traffic). */\n SESSION_VELOCITY_SIGNAL: 'detection/session-velocity-signal',\n /** A `signals[]` entry whose `source` starts with `tier1_` — raw Tier-1 protocol evidence, short of (or alongside) full verification. */\n TIER1_ATTRIBUTION_SIGNAL: 'detection/tier1-attribution-signal',\n\n // ── Classification flags ─────────────────────────────────────────────────\n /** `isAiCrawler === true` — classified as an AI training crawler (GPTBot, ClaudeBot, etc.), not an interactive agent. */\n AI_CRAWLER_FLAG: 'detection/ai-crawler-flag',\n\n // ── Zero-evidence fallbacks — an assumed verdict deserves a code saying so\n // (in the spirit of #4800): these fire ONLY when nothing above matched,\n // so the mapping never returns an empty list. ───────────────────────────\n /** `detectionClass === 'human'` with no contributing signals and no verification — the baseline \"nothing matched\" human path. */\n ZERO_EVIDENCE_HUMAN: 'detection/zero-evidence-human',\n /** `detectionClass === 'incomplete_data' | 'unknown'` (or absent) — the engine could not classify confidently. */\n INCOMPLETE_DATA_OVERRIDE: 'detection/incomplete-data-override',\n /** A non-human, non-incomplete-data class (`ai_agent` / `bot` / `automation`) reached with zero contributing signals and no verification — classified on prior/heuristic grounds alone. */\n CLASSIFIED_WITHOUT_SIGNAL_EVIDENCE: 'detection/classified-without-signal-evidence',\n} as const satisfies Record<string, `detection/${string}`>;\n\n/** A `detection/*` registry code (the value side of {@link DETECTION_REASON_CODES}). */\nexport type DetectionReasonCode =\n (typeof DETECTION_REASON_CODES)[keyof typeof DETECTION_REASON_CODES];\n\n/** The registry's value tuple, for z.enum. */\nconst REASON_CODE_VALUES = Object.values(DETECTION_REASON_CODES) as [\n DetectionReasonCode,\n ...DetectionReasonCode[],\n];\n\n/** A single `detection/*` code from the DETECTION_REASON_CODES registry. */\nexport const DetectionReasonCodeSchema = z\n .enum(REASON_CODE_VALUES)\n .describe(\n 'A machine-readable detection/* reason code from the DETECTION_REASON_CODES registry (see docs/architecture/detection-reason-codes.generated.md).'\n );\n","/**\n * Core detection types for Checkpoint\n *\n * BREAKING CHANGE v1.40.0: Confidence scores now use 0-100 scale\n * ─────────────────────────────────────────────────────────────\n * Previously: confidence values were 0-1 decimal (e.g., 0.85)\n * Now: confidence values are 0-100 percentage (e.g., 85)\n *\n * Migration guide:\n * - Test fixtures: expectedConfidence: 0.5 → expectedConfidence: 50\n * - API responses: { confidence: 0.85 } → { confidence: 85 }\n * - Threshold configs: confidenceThreshold: 0.7 → confidenceThreshold: 70\n * - Display: Math.round(confidence * 100) → Math.round(confidence)\n */\n\nimport { z } from 'zod';\n\nimport { DetectionReasonCodeSchema } from './detection-reason-codes';\n\n/**\n * Detection class enum for clear hierarchy (updated in migration 0029)\n * - Human: Regular human user\n * - AiAgent: AI assistants (ChatGPT, Claude, etc.) - PRIMARY VALUE\n * - Bot: Bots, scrapers, crawlers (includes former 'automation' category)\n * - IncompleteData: Cannot determine due to insufficient data (replaces 'unknown')\n *\n * Legacy types (maintained for backwards compatibility):\n * - Automation: Deprecated - migrated to Bot in migration 0029\n * - Unknown: Deprecated - migrated to IncompleteData in migration 0029\n */\nexport const DetectionClassSchema = z.discriminatedUnion('type', [\n z.object({\n type: z.literal('Human'),\n }),\n z.object({\n type: z.literal('AiAgent'),\n agentType: z.string().optional(),\n vendor: z.string().optional(),\n model: z.string().optional(),\n }),\n z.object({\n type: z.literal('Automation'),\n toolType: z.enum(['Puppeteer', 'Selenium', 'Playwright', 'Custom']).optional(),\n purpose: z.enum(['Testing', 'Scraping', 'Monitoring', 'Analytics', 'Other']).optional(),\n }),\n z.object({\n type: z.literal('Bot'),\n botType: z\n .enum(['SearchEngine', 'SocialMedia', 'Monitoring', 'Scraper', 'Security', 'Analytics'])\n .optional(),\n legitimacy: z.enum(['Legitimate', 'Suspicious', 'Malicious']).optional(),\n }),\n z.object({\n type: z.literal('IncompleteData'),\n }),\n z.object({\n type: z.literal('Unknown'),\n }),\n]);\nexport type DetectionClass = z.infer<typeof DetectionClassSchema>;\n\n/**\n * Input data for agent detection\n */\nexport const DetectionInputSchema = z.object({\n userAgent: z.string().optional(),\n ip: z.string().optional(),\n ipAddress: z.string().optional(), // Alias for ip\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n body: z.unknown().optional(),\n timestamp: z.date().default(() => new Date()),\n});\nexport type DetectionInput = z.infer<typeof DetectionInputSchema>;\n\n/**\n * Request context for analysis\n */\nexport const RequestContextSchema = z.object({\n userAgent: z.string().optional(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n body: z.unknown().optional(),\n timestamp: z.date().default(() => new Date()),\n});\nexport type RequestContext = z.infer<typeof RequestContextSchema>;\n\n/**\n * Context passed through Checkpoint event listeners.\n *\n * Runtime integrations may add transport-specific metadata, but the common\n * request fields stay typed so consumers don't need to fall back to `any`.\n */\nexport interface CheckpointEventContext {\n userAgent?: string;\n ipAddress?: string;\n headers?: Record<string, string>;\n url?: string;\n method?: string;\n body?: unknown;\n timestamp?: Date;\n [key: string]: unknown;\n}\n\n/** @deprecated Renamed to {@link CheckpointEventContext}. Identical shape. */\nexport type AgentShieldEventContext = CheckpointEventContext;\n\n/**\n * Session payload emitted by Checkpoint session events.\n */\nexport interface CheckpointSession {\n sessionId: string;\n startedAt?: Date | string | number;\n lastSeenAt?: Date | string | number;\n requestCount?: number;\n metadata?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\n/** @deprecated Renamed to {@link CheckpointSession}. Identical shape. */\nexport type AgentShieldSession = CheckpointSession;\n\n/**\n * Detection signal from various analysis methods\n * Note: All confidence scores use 0-100 scale for consistency\n *\n * The per-field `.describe()` strings below are the SSOT for the generated\n * signal-exposure reference (`scripts/generate-signal-exposure-docs.ts`,\n * KYA-1107): the generator throws on any undescribed field, and CI fails\n * on a stale generated page, so schema and docs cannot drift.\n */\nexport const DetectionSignalSchema = z.object({\n signalType: z\n .enum(['signature', 'pattern', 'behavioral', 'network', 'fingerprint'])\n .describe(\n 'Evidence plane this signal was observed on: cryptographic signature, User-Agent/header pattern, behavioral interaction, network/IP, or transport fingerprint.'\n ),\n confidence: z\n .number()\n .min(0)\n .max(100)\n .describe(\"This signal's own confidence contribution on the 0-100 scale.\"),\n weight: z\n .number()\n .min(0)\n .max(1)\n .describe(\"This signal's relative weight (0-1) in the combined verdict.\"),\n source: z\n .string()\n .describe(\n \"Machine-readable evidence source (e.g. 'user_agent_pattern', 'vendor_ip_feed', 'transport.ja4', 'mcp_i'). New signal families (e.g. request-velocity, platform bot-management corroboration) appear as new source values: additive, never a breaking change.\"\n ),\n explanation: z\n .string()\n .describe('Human-readable explanation of what this signal observed. Prose, not a contract.'),\n metadata: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Optional source-specific structured details (e.g. the matched pattern, the vendor feed name).'\n ),\n});\nexport type DetectionSignal = z.infer<typeof DetectionSignalSchema>;\n\n/**\n * Reasoning step for transparent confidence calculation\n * Note: All confidence scores use 0-100 scale for consistency\n */\nexport const ReasoningStepSchema = z.object({\n signalType: z.string(),\n rawConfidence: z.number().min(0).max(100),\n weight: z.number().min(0).max(1),\n reliability: z.number().min(0).max(1),\n contribution: z.number(),\n explanation: z.string(),\n});\nexport type ReasoningStep = z.infer<typeof ReasoningStepSchema>;\n\n/**\n * Per-stage trace step emitted by the engine on every `verify()` call.\n * Wire keys are camelCase — mirrors `#[serde(rename_all = \"camelCase\")]`\n * on the Rust side (`rust/crates/kya-os-engine/src/types.rs`).\n */\nexport const TraceStepSchema = z.object({\n /**\n * Stable stage identifier. Canonical names: `\"detection\"` (PlainHttp) or\n * `\"identity\"` | `\"signature\"` | `\"revocation\"` | `\"expiration\"` |\n * `\"scope\"` | `\"reputation\"` | `\"policy\"` (MCP-I's 7-stage pipeline).\n * Not a union on the wire — new step names are non-breaking. Mirrors\n * `TraceStep::name` on the Rust side.\n */\n name: z.string(),\n /**\n * Per-step verdict. `\"pass\"` = step ran and succeeded, `\"fail\"` = step\n * ran and rejected, `\"skip\"` = step was skipped (e.g. no identity\n * material on PlainHttp). Mirrors `TraceVerdict` on the Rust side,\n * which serializes lowercase.\n */\n verdict: z.enum(['pass', 'fail', 'skip']),\n /**\n * Stage execution time in microseconds. Mirrors `latency_micros` on the\n * Rust side which carries the `#[serde(rename = \"latencyMicros\")]` wire\n * key.\n */\n latencyMicros: z.number(),\n /**\n * Optional human-readable reason. Always present when verdict is\n * `\"fail\"`.\n */\n reason: z.string().optional(),\n});\nexport type TraceStep = z.infer<typeof TraceStepSchema>;\n\n/**\n * Detailed reasoning for detection decisions\n * Note: All confidence scores use 0-100 scale for consistency\n */\nexport const DetectionReasoningSchema = z.object({\n primaryFactors: z.array(z.string()),\n supportingEvidence: z.array(z.string()),\n confidenceBreakdown: z.record(\n z.string(),\n z.object({\n confidence: z.number().min(0).max(100),\n weight: z.number().min(0).max(1),\n contribution: z.number(),\n })\n ),\n reasoningSteps: z.array(ReasoningStepSchema),\n explanation: z.string(),\n calculationMethod: z.string().default('weighted_aggregation'),\n});\nexport type DetectionReasoning = z.infer<typeof DetectionReasoningSchema>;\n\n/**\n * Engine self-identification — Phase 0.1 of the Checkpoint refactor.\n *\n * Stamped on every DetectionResult so the dashboard can attribute a\n * detection to the specific implementation + ruleset that produced\n * it. Distinguishes package drift (two surfaces on different SDK\n * versions) from implementation divergence (two engines disagreeing\n * on the same rules). Optional for backwards compatibility with\n * SDKs that predate Phase 0.1.\n *\n * Known engine `name` values (kept here so downstream code can rely\n * on string equality without a separate enum import — engine names\n * are forward-compatible additions, never breaking changes). All\n * names use the `checkpoint-` brand prefix; the npm packages still\n * carry the legacy `agentshield-*` names until they're migrated to\n * `checkpoint-*` shims in Phase 1, but the engine string is the\n * customer-visible attribution and must reflect the brand.\n *\n * - 'checkpoint-engine-wasm' post-refactor Rust→WASM (Phase 2)\n * - 'checkpoint-matcher-js' post-refactor pure JS matcher (Phase 2)\n * - 'checkpoint-remote' result came from a remote enforce call\n * - 'checkpoint-edge-pattern' Next.js edge regex tables (pre-Phase-1)\n * - 'checkpoint-edge-wasm' Next.js edge WASM loader (pre-Phase-1)\n * - 'checkpoint-worker-wasm' Cloudflare worker WASM (pre-Phase-1)\n * - 'checkpoint-core' core agent-detector default (pre-Phase-1)\n */\nexport const EngineInfoSchema = z.object({\n name: z.string(),\n version: z.string(),\n rulesetHash: z.string(),\n rulesetVersion: z.string(),\n buildSha: z.string().optional(),\n extras: z.record(z.string(), z.unknown()).optional(),\n});\nexport type EngineInfo = z.infer<typeof EngineInfoSchema>;\n\n/**\n * Coarse network-path classification for a request's `trueIp`. `'unknown'`\n * is the host's own \"no verdict\" value — distinct from the whole\n * {@link NetworkContextSchema} being absent (no lookup attempted at all).\n */\nexport const RoutingTypeSchema = z.enum([\n 'residential',\n 'mobile',\n 'datacenter',\n 'hosting',\n 'unknown',\n]);\nexport type RoutingType = z.infer<typeof RoutingTypeSchema>;\n\n/** Coarse proxy/anonymization category, when `ProxyInfo.isProxy` is true. */\nexport const ProxyTypeSchema = z.enum(['vpn', 'tor', 'datacenter', 'residential_proxy', 'unknown']);\nexport type ProxyType = z.infer<typeof ProxyTypeSchema>;\n\n/**\n * Host-supplied proxy/anonymization verdict for a request's `trueIp`.\n * Mirrors the Rust `ProxyInfo` (`rust/crates/kya-os-engine/src/types.rs`).\n */\nexport const ProxyInfoSchema = z.object({\n isProxy: z.boolean(),\n proxyIp: z.string().optional(),\n proxyType: ProxyTypeSchema,\n lastDetected: z.number().optional(),\n /** Provider confidence in the proxy verdict, 0-100. */\n confidence: z.number().int().min(0).max(100),\n});\nexport type ProxyInfo = z.infer<typeof ProxyInfoSchema>;\n\n/**\n * Host-supplied network / IP-intelligence context for a request's\n * `trueIp`. Mirrors the Rust `NetworkContext`; echoed verbatim on the\n * engine's `VerifyResult.network` (a sibling of `DetectionDetail`, like\n * `EngineInfo` above — there is no wrapping `VerifyResultSchema`) when the\n * host supplied one, and exposed to Cedar as `context.ip_routing_type` /\n * `context.is_proxy`. Absent-safe: a request with no network context is\n * the normal case, not an error.\n */\nexport const NetworkContextSchema = z.object({\n trueIp: z.string().optional(),\n asn: z.number().int().nonnegative().optional(),\n isp: z.string().optional(),\n routingType: RoutingTypeSchema,\n proxy: ProxyInfoSchema.optional(),\n});\nexport type NetworkContext = z.infer<typeof NetworkContextSchema>;\n\n/**\n * Descriptive detection detail from the engine.\n *\n * This is the signal layer: what was detected, why, and with what\n * attribution. Enforcement decisions live separately on `Decision`.\n * Enhanced with detailed reasoning, signals, and risk assessment\n */\nexport const DetectionDetailSchema = z.object({\n // Core fields\n /**\n * @deprecated Use detectionClass instead. Will be removed in v2.0.0\n * Migration guide:\n * - isAgent: false → detectionClass: { type: 'Human' }\n * - isAgent: true → check detectionClass for specific type\n */\n isAgent: z.boolean().describe('DEPRECATED: Use detectionClass instead'),\n isBot: z.boolean().optional(), // Backwards compatibility\n /** True when detected bot is an AI crawler (GPTBot, ClaudeBot, etc.) */\n isAiCrawler: z.boolean().optional(),\n\n /**\n * Confidence score (0-100 scale)\n * - 0-30: Low confidence\n * - 31-70: Medium confidence\n * - 71-90: High confidence\n * - 91-100: Very high confidence\n */\n confidence: z.number().min(0).max(100),\n\n // NEW: Clear classification hierarchy\n detectionClass: DetectionClassSchema,\n\n // Detection details with enhanced reasoning\n confidenceLevel: z.enum(['low', 'medium', 'high', 'very_high']).optional(),\n reasons: z.array(z.string()),\n detectedPatterns: z.array(z.string()).optional(),\n\n // NEW: Detection signals and reasoning\n signals: z.array(DetectionSignalSchema).default([]),\n reasoning: DetectionReasoningSchema.optional(),\n\n // Agent information\n detectedAgent: z\n .object({\n type: z.string(),\n name: z.string(),\n vendor: z.string().optional(),\n model: z.string().optional(),\n version: z.string().optional(),\n })\n .optional(),\n botType: z.string().optional(), // Backwards compatibility\n agentType: z.string().optional(),\n\n // Verification and enhanced risk assessment\n verificationMethod: z\n // Dual-accept (mcp-i → kya-os): accept the canonical engine value\n // `kyaos_handshake` alongside the legacy `mcp_i_handshake` so engine output\n // still validates once upstream flips its emitter.\n .enum([\n 'signature',\n 'pattern',\n 'behavioral',\n 'network',\n 'mcp_i_handshake',\n 'kyaos_handshake',\n 'kya-http',\n 'kya-http-delegated',\n // Tier-1 RFC 9421 (Web Bot Auth) verification. The engine emits this\n // on a verified HTTP Message Signature (api.rs Tier-1 path); without\n // it here, Zod-validating a Tier-1 verdict rejects a legitimately\n // signature-verified agent.\n 'tier1_rfc9421',\n // A2A Agent Card security scheme (RFC 9421 keyid, or a JWT bearer\n // against resolved JWKS) cryptographically verified — see\n // docs/architecture/a2a-verification.md.\n 'a2a',\n 'none',\n 'error',\n ])\n .optional(),\n riskLevel: z.string().optional(),\n forgeabilityRisk: z.enum(['low', 'medium', 'high']).optional(),\n // draft-kya-http-02 §1 assurance tier the engine established for this\n // verdict (`anonymous` | `attested-bearer` | `key-bound` | `registered` |\n // `delegated`). Stamped by the engine on every verdict; the canonical\n // ladder is `AssuranceTierSchema` in `../policy/schemas`. Kept a loose\n // string here (like `riskLevel`) to avoid a core→policy module dependency.\n assurance: z.string().optional(),\n\n // NEW: Enhanced risk assessment\n riskAssessment: z\n .object({\n level: z.enum(['low', 'medium', 'high', 'critical']),\n score: z.number().min(0).max(100),\n factors: z.array(z.string()),\n forgeabilityRisk: z.enum(['low', 'medium', 'high']),\n recommendations: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Metadata\n metadata: z.record(z.string(), z.unknown()).optional(),\n timestamp: z.union([z.date(), z.number()]).default(() => new Date()),\n requestId: z.string().optional(),\n\n /** Engine self-identification — see EngineInfoSchema. Optional for\n * pre-Phase-0.1 SDKs; dashboard treats absence as \"legacy SDK.\" */\n engine: EngineInfoSchema.optional(),\n\n /** Scopes granted by a verified single-hop delegation (the mcp-i path).\n * Surfaced by the engine so a host can FORWARD them into\n * `context.granted_scopes` (authorize()) without re-decoding the delegation\n * credential — the engine already verified them. Omitted/empty for L1\n * envelopes or any unverified/forged path. Mirrors the Rust\n * `DetectionDetail.granted_scopes` (additive, omitted when empty). */\n grantedScopes: z.array(z.string()).optional(),\n\n /**\n * GODPROMPTS/detection-reason-codes: namespaced detection/* codes, most-\n * significant-evidence first, derived via mapDetectionToReasonCodes.\n * Optional: only producers that opt into signal exposure (currently\n * /api/v1/detect via buildDetectionSignalExposure) populate this.\n */\n reasonCodes: z.array(DetectionReasonCodeSchema).optional(),\n});\nexport type DetectionDetail = z.infer<typeof DetectionDetailSchema>;\n\n/**\n * @deprecated Use DetectionDetailSchema. Kept for one minor release so\n * older host packages can migrate without a coordinated breaking cut.\n */\nexport const DetectionResultSchema = DetectionDetailSchema;\n\n/**\n * @deprecated Use DetectionDetail. Kept for one minor release so older\n * host packages can migrate without a coordinated breaking cut.\n */\nexport type DetectionResult = DetectionDetail;\n\n/**\n * Detection mode configuration\n */\nexport const DetectionModeSchema = z.enum(['strict', 'balanced', 'lenient']);\nexport type DetectionMode = z.infer<typeof DetectionModeSchema>;\n\n/**\n * Custom detection rule\n */\nexport const CustomRuleSchema = z.object({\n id: z.string(),\n name: z.string(),\n pattern: z.union([z.string(), z.instanceof(RegExp)]),\n weight: z.number().min(0).max(1),\n type: z.enum(['userAgent', 'header', 'behavior', 'ip']),\n enabled: z.boolean().default(true),\n});\nexport type CustomRule = z.infer<typeof CustomRuleSchema>;\n\n/**\n * Detection options\n */\nexport const DetectionOptionsSchema = z.object({\n mode: DetectionModeSchema.optional(),\n customRules: z.array(CustomRuleSchema).optional(),\n enablePatternMatching: z.boolean().default(true),\n enableBehaviorAnalysis: z.boolean().default(true),\n enableNetworkAnalysis: z.boolean().default(true),\n confidenceThreshold: z.number().min(0).max(100).default(70),\n});\nexport type DetectionOptions = z.infer<typeof DetectionOptionsSchema>;\n\n/**\n * Utility functions for confidence score conversion\n * All internal processing should use 0-100 scale\n */\nexport const ConfidenceUtils = {\n /**\n * Convert 0-1 scale to 0-100 scale\n */\n fromDecimal(score: number): number {\n return Math.round(Math.max(0, Math.min(1, score)) * 100);\n },\n\n /**\n * Convert 0-1000 scale to 0-100 scale\n */\n fromThousand(score: number): number {\n return Math.round(Math.max(0, Math.min(1000, score)) / 10);\n },\n\n /**\n * Convert 0-100 scale to 0-1 scale (for legacy compatibility)\n */\n toDecimal(score: number): number {\n return Math.max(0, Math.min(100, score)) / 100;\n },\n\n /**\n * Convert 0-100 scale to 0-1000 scale (for WASM compatibility)\n */\n toThousand(score: number): number {\n return Math.round(Math.max(0, Math.min(100, score)) * 10);\n },\n\n /**\n * Normalize any confidence score to 0-100 scale\n */\n normalize(score: number): number {\n if (score <= 1) {\n // Assume 0-1 scale\n return this.fromDecimal(score);\n } else if (score <= 100) {\n // Already 0-100 scale\n return Math.round(Math.max(0, Math.min(100, score)));\n } else {\n // Assume 0-1000 scale\n return this.fromThousand(score);\n }\n },\n\n /**\n * Get confidence level from score\n */\n getLevel(score: number): 'low' | 'medium' | 'high' | 'very_high' {\n const normalizedScore = this.normalize(score);\n if (normalizedScore >= 91) return 'very_high';\n if (normalizedScore >= 71) return 'high';\n if (normalizedScore >= 31) return 'medium';\n return 'low';\n },\n\n /**\n * Format score for display as percentage\n */\n toPercentage(score: number): string {\n return `${this.normalize(score)}%`;\n },\n};\n\n/**\n * Known AI crawler name patterns. Used as a fallback when isAiCrawler is not\n * explicitly set (e.g., pattern-detection paths that don't go through WASM).\n */\nconst AI_CRAWLER_NAMES = [\n 'gptbot',\n 'claudebot',\n 'perplexitybot',\n 'deepseekbot',\n 'bytespider',\n 'ccbot',\n 'google-extended',\n 'cohere',\n 'huggingface',\n 'amazon bedrock',\n 'vertex',\n];\n\n/**\n * Check if an agent name matches a known AI crawler.\n * Use this to set isAiCrawler on detection results from pattern-based paths.\n */\nexport function isKnownAiCrawler(agentName: string | undefined | null): boolean {\n if (!agentName) return false;\n const lower = agentName.toLowerCase();\n return AI_CRAWLER_NAMES.some((crawler) => lower.includes(crawler));\n}\n","/**\n * Agent-specific types and schemas\n */\n\nimport { z } from 'zod';\n\n/**\n * Known AI agent types (AI companies only, not traditional bots)\n */\nexport const AgentTypeSchema = z.enum([\n // OpenAI\n 'openai',\n 'chatgpt',\n // Anthropic\n 'claude',\n 'anthropic',\n // Search AI\n 'perplexity',\n 'phind',\n 'you',\n 'neeva',\n // Big Tech AI\n 'google',\n 'microsoft',\n 'meta',\n 'alibaba',\n // AI Model Providers\n 'mistral',\n 'cohere',\n 'huggingface',\n 'inflection',\n 'stability',\n 'replicate',\n 'together',\n '01ai',\n // Content/Writing AI\n 'writer',\n 'jasper',\n // Additional AI vendors — Engine-Pattern-Codegen-Retirement-1 backfilled\n // these after the SSOT migration surfaced legacy patterns_generated.rs\n // entries (xAI Grok, DeepSeek-User/DeepSeekBot, Amazon Q + NovaAct,\n // KYA Agent) that were never represented in TS. Their patterns lived\n // only in the retired YAML→Rust pipeline; without these types the\n // backfilled `KNOWN_AGENT_PATTERNS` entries would have to coerce to\n // `'unknown'` and lose per-vendor classification downstream.\n 'xai',\n 'deepseek',\n 'amazon',\n 'kya',\n // Unknown AI agent\n 'unknown',\n]);\nexport type AgentType = z.infer<typeof AgentTypeSchema>;\n\n/**\n * Agent information\n */\nexport const AgentInfoSchema = z.object({\n type: AgentTypeSchema,\n name: z.string(),\n version: z.string().optional(),\n provider: z.string().optional(),\n verified: z.boolean().default(false),\n});\nexport type AgentInfo = z.infer<typeof AgentInfoSchema>;\n\n/**\n * Agent pattern for matching\n *\n * F-08 PR-C: each pattern entry now carries its own `category` value.\n * Replaces the previous arrangement where agent-types-sync.service.ts\n * hardcoded `'ai_assistant'` for every KNOWN_AGENT_PATTERNS entry,\n * which conflated training crawlers with interactive AI assistants.\n * Targets the 9-value canonical taxonomy locked by F-03 (#2160) — see\n * AgentCategorySchema in `../types/agent-classification`.\n *\n * Optional for backward compatibility with any external callers; the\n * sync service falls back to `'ai_assistant'` if absent (pre-PR-C\n * behaviour). New entries should always declare a category explicitly.\n */\nexport const AgentPatternSchema = z.object({\n id: z.string(),\n type: AgentTypeSchema,\n name: z.string(),\n patterns: z.array(z.string()),\n headers: z.record(z.string(), z.string()).optional(),\n ipRanges: z.array(z.string()).optional(),\n confidence: z.number().min(0).max(1).default(0.8),\n category: z\n .enum([\n 'ai_assistant',\n 'search_engine',\n 'social_media',\n 'monitoring',\n 'scraper',\n 'automation',\n 'security',\n 'analytics',\n 'unknown',\n ])\n .optional(),\n /**\n * Whether this pattern represents a known, declared, well-behaved\n * crawler / agent. Optional — defaults to `true` for known AI\n * providers in KNOWN_AGENT_PATTERNS (Anthropic's ClaudeBot, OpenAI's\n * GPTBot, etc. all respect robots.txt and declare themselves).\n *\n * F-08 PR-C followup (cursor bot review): without this field,\n * `agent-types-sync.service.ts` derives isLegitimate from category\n * via a hardcoded `ai_assistant | search_engine | social_media` set.\n * That set excludes `scraper`, so well-behaved AI training crawlers\n * (which legitimately live in the `scraper` bucket per F-03's\n * locked taxonomy) would silently flip from isLegitimate=true to\n * false on the next sync. Per-entry isLegitimate prevents that.\n */\n isLegitimate: z.boolean().optional(),\n});\nexport type AgentPattern = z.infer<typeof AgentPatternSchema>;\n\n/**\n * Agent classification result\n */\nexport const AgentClassificationSchema = z.object({\n primary: AgentTypeSchema,\n secondary: z.array(AgentTypeSchema).optional(),\n confidence: z.number().min(0).max(1),\n matchedPatterns: z.array(z.string()),\n});\nexport type AgentClassification = z.infer<typeof AgentClassificationSchema>;\n","/**\n * Confidence and risk assessment types\n */\n\nimport { z } from 'zod';\nimport type { SignalMode, SignalPlane, StabilityTier } from '../signals/types';\n\n/**\n * Confidence levels for detection\n */\nexport const ConfidenceLevelSchema = z.enum(['low', 'medium', 'high', 'very_high']);\nexport type ConfidenceLevel = z.infer<typeof ConfidenceLevelSchema>;\n\n/**\n * Forgeability risk levels\n */\nexport const ForgeabilityRiskSchema = z.enum(['low', 'medium', 'high']);\nexport type ForgeabilityRisk = z.infer<typeof ForgeabilityRiskSchema>;\n\n/**\n * Risk assessment result\n */\nexport const RiskAssessmentSchema = z.object({\n level: z.enum(['low', 'medium', 'high', 'critical']),\n score: z.number().min(0).max(1),\n factors: z.array(z.string()),\n forgeabilityRisk: ForgeabilityRiskSchema,\n recommendations: z.array(z.string()).optional(),\n});\nexport type RiskAssessment = z.infer<typeof RiskAssessmentSchema>;\n\n/**\n * Confidence breakdown by detection method\n */\nexport const ConfidenceBreakdownSchema = z.object({\n patternMatching: z.number().min(0).max(1).optional(),\n behaviorAnalysis: z.number().min(0).max(1).optional(),\n networkAnalysis: z.number().min(0).max(1).optional(),\n signatureVerification: z.number().min(0).max(1).optional(),\n overall: z.number().min(0).max(1),\n});\nexport type ConfidenceBreakdown = z.infer<typeof ConfidenceBreakdownSchema>;\n\n/**\n * Confidence threshold configuration\n * Using 0-1 scale for internal consistency\n */\nexport const ConfidenceThresholdSchema = z.object({\n low: z.number().min(0).max(1).default(0.3),\n medium: z.number().min(0).max(1).default(0.6),\n high: z.number().min(0).max(1).default(0.8),\n veryHigh: z.number().min(0).max(1).default(0.95),\n});\nexport type ConfidenceThreshold = z.infer<typeof ConfidenceThresholdSchema>;\n\n/**\n * Helper function to get confidence level from score\n */\nexport function getConfidenceLevel(\n score: number,\n thresholds?: ConfidenceThreshold\n): ConfidenceLevel {\n const t = thresholds || {\n low: 0.3,\n medium: 0.6,\n high: 0.8,\n veryHigh: 0.95,\n };\n\n if (score >= t.veryHigh) return 'very_high';\n if (score >= t.high) return 'high';\n if (score >= t.medium) return 'medium';\n return 'low';\n}\n\n// ============================================================================\n// CONFIDENCE SCALE UTILITIES\n// ============================================================================\n//\n// IMPORTANT: All Checkpoint confidence scores use a 0.0-1.0 scale internally.\n// - WASM detect_agent() returns: 0.95 (not 95)\n// - Pattern definitions use: 0.70, 0.85, 0.95 (not 70, 85, 95)\n// - Thresholds should be: 0.3, 0.7, 0.9 (not 30, 70, 90)\n//\n// Use these utilities to convert for display or validate incoming values.\n// ============================================================================\n\n/**\n * Convert confidence (0.0-1.0) to percentage (0-100) for display\n *\n * @example\n * const result = detect_agent(metadata); // returns 0.95\n * toPercent(result.confidence) // returns 95\n */\nexport function toPercent(confidence: number): number {\n return Math.round(confidence * 100);\n}\n\n/**\n * Format confidence as percentage string\n *\n * @example\n * formatConfidence(0.95) // \"95%\"\n */\nexport function formatConfidence(confidence: number): string {\n return `${toPercent(confidence)}%`;\n}\n\n/**\n * Validate and normalize confidence to 0.0-1.0 scale.\n * If value > 1, assumes it's in 0-100 scale and converts.\n * Logs warning in development when conversion happens.\n *\n * @example\n * normalizeConfidence(0.95) // 0.95 (unchanged)\n * normalizeConfidence(95) // 0.95 (converted, logs warning)\n */\nexport function normalizeConfidence(value: number, context?: string): number {\n if (value > 1.0) {\n if (process.env.NODE_ENV !== 'production') {\n const location = context ? ` in ${context}` : '';\n console.warn(\n `[AgentShield] Confidence value ${value}${location} appears to be 0-100 scale. ` +\n `Expected 0.0-1.0. Auto-converting to ${value / 100}.`\n );\n }\n return Math.min(value / 100, 1.0);\n }\n return Math.max(0, Math.min(value, 1.0));\n}\n\n// ============================================================================\n// ENTROPY-DERIVED CONFIDENCE (P19)\n// ============================================================================\n//\n// This is a different axis from classification PROBABILITY (P17/P18's\n// calibrated \"how likely is this traffic automated\"). Confidence measures\n// how much evidence we collected, not what we concluded from it. A\n// high-confidence human and a high-confidence bot are both possible; a\n// low-confidence read of either can happen too. Never combine the two\n// into one number, and name them distinctly wherever both appear (see\n// P51 for the UI-facing convention, which this ticket does not set).\n//\n// THE FORMULA, RATIFIED\n// ----------------------\n// Every observed signal contributes information in bits: `-log2(u)` once\n// the P21 frequency table populates `u` (the coincidence probability —\n// how often two unrelated visitors would agree on this read), falling\n// back to a tier-based proxy (TIER_INFO_BITS) until then. A signal whose\n// `mode` is 'never' contributes nothing, matching the registry's own\n// contract that such signals never feed identity.\n//\n// Raw evidence bits are not simply summed, because signals sharing a\n// Merkle `group` (near-duplicate reads of the same underlying source,\n// e.g. a canvas signal and its v2 fork) or the same `plane` (broader\n// subsystem, e.g. two different rendering reads sharing GPU/driver\n// characteristics) co-vary — they are not independent evidence, so\n// summing them at face value would overstate what six correlated reads\n// from one plane tell you versus three genuinely independent ones.\n//\n// Instead, contributions are combined with a two-tier discount, geometric\n// by rank within each tier:\n//\n// groupBits(group) = Σ_i bits_i * GROUP_DISCOUNT^i (i-th largest bits in the group, 0-indexed)\n// planeBits(plane) = Σ_j groupBits_j * PLANE_DISCOUNT^j (j-th largest groupBits in the plane)\n// totalBits = Σ_planes planeBits(plane) (full weight — planes are independent by definition)\n//\n// This is deliberately the maximum weighted sum achievable by any\n// pairing of (sorted) values against (sorted) discount weights — by the\n// rearrangement inequality, sorting descending against descending\n// weights is that maximum. That characterization is what makes the\n// result PROVABLY monotonic: `Σ v_(i) w_i` equals `max over permutations\n// π of Σ v_i w_π(i)`, a pointwise max of functions each linear (hence\n// non-decreasing, since every w_i >= 0) in every v_i. A max of\n// non-decreasing functions is non-decreasing, so totalBits can only\n// rise or hold steady as evidence is added at any level — removing or\n// zeroing out a signal (mode 'never' is exactly a zero-bit signal) can\n// only lower it. That is \"falls when a high-entropy signal is absent\"\n// and \"rises with independent planes\" as a mathematical guarantee, not\n// a property that happens to hold on the test fixtures.\n//\n// Bits are then mapped onto a bounded, asymptotic confidence:\n//\n// confidence = FLOOR + (CEILING - FLOOR) * (1 - e^(-totalBits / SCALE_BITS))\n//\n// This is strictly increasing in totalBits, equals FLOOR exactly at\n// zero bits (no evidence still yields a floor, never a bare zero — a\n// bare zero would read as \"we know literally nothing,\" which is never\n// true; even a non-response carries some information), and approaches\n// but never reaches CEILING (< 1.0) for any finite evidence — certainty\n// is not on offer.\n//\n// GROUP_DISCOUNT (0.5) is steeper than PLANE_DISCOUNT (0.75): a fork of\n// the same read (same group) co-varies more tightly than two different\n// subsystems that merely share a broad plane, so it is discounted harder.\n// TIER_INFO_BITS is an illustrative proxy — every registry entry's\n// `measurement` is still provisional (no shipped agreement-rate data),\n// so these are placeholder bit-counts (a \"high\" tier signal is modeled\n// as roughly as informative as picking 1-of-64; \"medium\" 1-of-8; \"low\"\n// 1-of-2) that P21's real `u` values supersede per-signal the moment\n// they land — no code change required, since `u` is checked first.\n// ============================================================================\n\n/** One observed signal's evidence-relevant metadata, as needed to compute\n * entropy-derived confidence. A structural subset of the P8 signal\n * registry's `SignalDefinition` — any `SignalDefinition` already satisfies\n * this shape — kept narrow so confidence computation doesn't couple to\n * registry bookkeeping (versioning, description, review) it doesn't need.\n */\nexport interface EvidenceSignal {\n /** Where this signal's read sits for grouping correlated evidence. */\n plane: SignalPlane;\n /** Finer-grained grouping within a plane; near-duplicate/forked reads share a group. */\n group: string;\n /** Stability tier, used as the information-content proxy until `u` is populated (P21). */\n tier: StabilityTier;\n /** Governs identity contribution: 'never' signals carry zero evidence weight. */\n mode: SignalMode;\n /** Coincidence probability from the frequency table (P21). Null until populated. */\n u: number | null;\n}\n\n/** Confidence returned for zero observed evidence. Strictly positive: even total\n * silence isn't \"we know literally nothing,\" so it never reads as a bare zero. */\nexport const ENTROPY_CONFIDENCE_FLOOR = 0.02;\n\n/** Asymptotic upper bound. Never reached for any finite evidence — certainty\n * is not on offer, per the ticket's \"bounded, and never exactly 1.0\" requirement. */\nexport const ENTROPY_CONFIDENCE_CEILING = 0.98;\n\n/** Bits of accumulated evidence at which confidence has closed roughly\n * two-thirds of the gap between FLOOR and CEILING (1 - e^-1 ≈ 0.63). */\nconst CONFIDENCE_SCALE_BITS = 8;\n\n/** Decay applied to the 2nd, 3rd, ... signal within the SAME group (rank\n * 0-indexed): near-duplicate reads of one underlying source co-vary tightly. */\nconst GROUP_DISCOUNT = 0.5;\n\n/** Decay applied to the 2nd, 3rd, ... group's contribution within the SAME\n * plane: different subsystems in one broad plane co-vary more loosely than\n * same-group reads do, so the penalty is milder than GROUP_DISCOUNT. */\nconst PLANE_DISCOUNT = 0.75;\n\n/** Illustrative information-content proxy (bits) per stability tier, used\n * only until a signal's real coincidence probability `u` is populated. */\nconst TIER_INFO_BITS: Record<StabilityTier, number> = {\n high: 6,\n medium: 3,\n low: 1,\n};\n\n/** Floor on `u` before taking -log2, so a frequency-table entry of exactly\n * (or effectively) zero can't blow the formula up to +Infinity bits. */\nconst MIN_COINCIDENCE_PROBABILITY = 1e-6;\n\nfunction signalInfoBits(signal: EvidenceSignal): number {\n if (signal.mode === 'never') return 0;\n if (signal.u !== null && Number.isFinite(signal.u)) {\n const u = Math.min(Math.max(signal.u, MIN_COINCIDENCE_PROBABILITY), 1);\n return -Math.log2(u);\n }\n // Unknown tier (or a non-finite `u` with no valid tier to fall back to) —\n // e.g. a future registry tier this build doesn't know about yet, or a\n // malformed evidence object from a caller that bypassed the type system\n // — contributes no evidence rather than poisoning the whole sum to NaN.\n return TIER_INFO_BITS[signal.tier] ?? 0;\n}\n\n/** The rearrangement-inequality-maximal weighted sum: descending values\n * paired against descending powers of `discount`. See the module doc for\n * why this specific combination rule is what makes the formula monotonic. */\nfunction sortedGeometricSum(values: number[], discount: number): number {\n return [...values]\n .sort((a, b) => b - a)\n .reduce((sum, value, rank) => sum + value * discount ** rank, 0);\n}\n\n/**\n * Computes confidence (how much evidence we have) from the signals actually\n * observed for a detection event — never from a platform/OS lookup table.\n * See the module doc above for the ratified formula and its properties.\n *\n * This is NOT a probability that traffic is automated; see P17/P18 for\n * that calibrated, separately-computed number.\n */\nexport function computeEntropyConfidence(observed: readonly EvidenceSignal[]): number {\n const bitsByPlaneAndGroup = new Map<SignalPlane, Map<string, number[]>>();\n\n for (const signal of observed) {\n const bits = signalInfoBits(signal);\n if (bits <= 0) continue;\n\n let groups = bitsByPlaneAndGroup.get(signal.plane);\n if (!groups) {\n groups = new Map();\n bitsByPlaneAndGroup.set(signal.plane, groups);\n }\n const bitsInGroup = groups.get(signal.group);\n if (bitsInGroup) {\n bitsInGroup.push(bits);\n } else {\n groups.set(signal.group, [bits]);\n }\n }\n\n let totalBits = 0;\n for (const groups of bitsByPlaneAndGroup.values()) {\n const groupContributions = Array.from(groups.values(), (bitsInGroup) =>\n sortedGeometricSum(bitsInGroup, GROUP_DISCOUNT)\n );\n // Full weight across planes: planes are independent by definition.\n totalBits += sortedGeometricSum(groupContributions, PLANE_DISCOUNT);\n }\n\n return (\n ENTROPY_CONFIDENCE_FLOOR +\n (ENTROPY_CONFIDENCE_CEILING - ENTROPY_CONFIDENCE_FLOOR) *\n (1 - Math.exp(-totalBits / CONFIDENCE_SCALE_BITS))\n );\n}\n","/**\n * Verdict evidence (P20) — the contributing-signal list behind a detection\n * verdict, as structured output rather than a debug log.\n *\n * P16/P18 combine independent `DetectionSignal`s into one confidence number\n * via a Noisy-Or combiner (`rust/crates/kya-os-engine/src/stages/scoring.rs`):\n * each signal contributes `weight * probability` (`probability` being\n * `confidence / 100`), and the combiner folds those contributions together.\n * That per-signal contribution is exactly the number a reviewer needs to\n * answer \"why did this verdict land where it did\" — and today it is\n * recomputed and discarded inside the combiner, never persisted.\n *\n * `buildVerdictEvidence` re-derives the SAME `weight * probability` term for\n * each signal and returns it as a flat, typed, sorted list: the signal's\n * name, its weight, its probability contribution, and which detection\n * `plane` (`DetectionSignal.signalType`) it came from. This is deliberately\n * NOT the raw `DetectionSignal[]` passed straight through — that already\n * exists (`metadata.enforcement.signals`) as an opaque, unstructured\n * passthrough. Evidence is the derived, reviewable projection of it.\n *\n * SCOPE at the time this module was written: emit + persist only, with\n * dashboard rendering deferred to P51. P51 has since wired this into the\n * `/activity` Inspector and the agent detail sheet's recent-activity rows\n * (`EvidenceList` in `components/features/activity/verdict-evidence-list.tsx`).\n * Unifying this with the identity/fraud-signal \"explainable verdict\" object\n * `novelty.service.ts` (P25) forward-declares is still P38 — out of scope\n * here.\n */\nimport { z } from 'zod';\nimport { DetectionSignalSchema, type DetectionSignal } from './detection';\n\n/**\n * One contributing signal behind a verdict's confidence, as persisted\n * structured output.\n *\n * - `signal` — the signal's machine-readable source identifier\n * (`DetectionSignal.source`), e.g. `\"tier3_ua_pattern\"`.\n * - `plane` — which detection plane produced it (`DetectionSignal.signalType`\n * — signature / pattern / behavioral / network / fingerprint).\n * - `weight` — the signal family's relative trust weight, 0-1.\n * - `probabilityContribution` — `weight * (confidence / 100)`, the exact\n * term the Noisy-Or combiner multiplies together\n * (`1 - Π(1 - probabilityContribution_i)`). Storing this term (rather\n * than raw `weight` + `confidence` separately) is sufficient on its own to\n * reconstruct the combiner's confidence from stored evidence alone,\n * without replaying the original request.\n */\nexport const VerdictEvidenceSchema = z.object({\n signal: z.string(),\n plane: DetectionSignalSchema.shape.signalType,\n weight: z.number().min(0).max(1),\n probabilityContribution: z.number().min(0).max(1),\n});\nexport type VerdictEvidence = z.infer<typeof VerdictEvidenceSchema>;\n\n/** `weight_i * probability_i` — mirrors the Noisy-Or combiner's own inline\n * `contribution` term (`stages::scoring::noisy_or_combine`) so the two can\n * never silently diverge. `probability` is `confidence / 100`, already\n * validated into `[0, 100]` by `DetectionSignalSchema`, so the product is\n * guaranteed to land in `[0, 1]` with no extra clamping needed. */\nfunction signalContribution(signal: DetectionSignal): number {\n return signal.weight * (signal.confidence / 100);\n}\n\n/**\n * Builds the verdict's evidence list from the engine's raw detection\n * signals — allow or block, live or shadow, persisted or not: this is a\n * pure function of `signals` with no I/O of its own, so it emits the exact\n * same evidence regardless of what a caller does with the result\n * afterward (including a caller that never persists it at all).\n *\n * Entries that don't parse as a well-formed `DetectionSignal` (a malformed\n * wire payload, or a future signal-shaped-but-not-quite record) are\n * dropped rather than allowed to poison the list with `NaN`/garbage\n * contributions — mirrors `extractShadowMetadata`'s \"never throws, always\n * returns a safe-to-use value\" contract.\n *\n * Ordering is deterministic — sorted by `(plane, signal)` and never by\n * input/iteration order, since the upstream signal list is assembled\n * differently by different detection paths (PlainHttp classification vs.\n * SDK/gateway self-reports) and must still diff/hash identically for the\n * same logical evidence. `probabilityContribution` descending is the final\n * tiebreak for the (rare) case of two entries sharing both plane and name.\n */\nexport function buildVerdictEvidence(\n signals: readonly unknown[] | null | undefined\n): VerdictEvidence[] {\n if (!signals || signals.length === 0) return [];\n\n const entries: VerdictEvidence[] = [];\n for (const raw of signals) {\n const parsed = DetectionSignalSchema.safeParse(raw);\n if (!parsed.success) continue;\n const signal = parsed.data;\n entries.push({\n signal: signal.source,\n plane: signal.signalType,\n weight: signal.weight,\n probabilityContribution: signalContribution(signal),\n });\n }\n\n entries.sort((a, b) => {\n if (a.plane !== b.plane) return a.plane < b.plane ? -1 : 1;\n if (a.signal !== b.signal) return a.signal < b.signal ? -1 : 1;\n return b.probabilityContribution - a.probabilityContribution;\n });\n\n return entries;\n}\n\n/**\n * Mirrors `UNCALIBRATED_NOISY_OR_PRIOR` in\n * `rust/crates/kya-os-engine/src/stages/scoring.rs` — the Noisy-Or\n * combiner's \"leak\" node, the baseline probability of the outcome even with\n * zero observed evidence. The Rust engine folds this into every live\n * confidence it computes (`noisy_or_confidence_percent` calls\n * `noisy_or_combine(UNCALIBRATED_NOISY_OR_PRIOR, &inputs)`); reconstructing\n * confidence from stored evidence without it silently drops a fixed,\n * predictable amount from every verdict (bestbrian, PR #4747 review:\n * verified by hand against `TWO_SIGNAL_EVIDENCE_FIXTURE` — the un-primed\n * formula returns 94.2, the real engine returns 94.78).\n *\n * NOT auto-synced with the Rust constant — there is no cross-language\n * value-extraction mechanism for a single scalar like there is for the\n * Tier-3 pattern tables (`tests/tier3_pattern_drift.rs`). If\n * `UNCALIBRATED_NOISY_OR_PRIOR` ever changes on the Rust side (P17\n * calibration landing, most likely), this constant must change with it —\n * grep both for `UNCALIBRATED_NOISY_OR_PRIOR` in a sibling-sweep before\n * touching either one.\n */\nexport const UNCALIBRATED_NOISY_OR_PRIOR = 0.1;\n\n/**\n * Reconstructs the Noisy-Or confidence (0-100 scale) from a persisted\n * evidence list alone — no access to the original request or the raw\n * signals it was built from. `1 - (1 - prior) * Π(1 - probabilityContribution_i)`,\n * the SAME formula (with the SAME prior) `stages::scoring::noisy_or_combine`\n * computes for the live verdict — this must never diverge from the number\n * the engine actually returned, or \"explainable from stored data\" is a lie\n * by a fixed, predictable margin.\n *\n * Zero evidence reconstructs to the bare prior (10.0 on the 0-100 scale),\n * never a bare 0 — a claim of certainty (\"definitely not automated\") that\n * zero observed evidence never actually supports, exactly as\n * `noisy_or_combine`'s own doc comment argues.\n *\n * This is the acceptance test made concrete: an adverse decision must be\n * explainable from what was stored, without replaying the request.\n */\nexport function reconstructConfidenceFromEvidence(evidence: readonly VerdictEvidence[]): number {\n const probabilityAbsent = evidence.reduce(\n (acc, entry) => acc * (1 - entry.probabilityContribution),\n 1 - UNCALIBRATED_NOISY_OR_PRIOR\n );\n return (1 - probabilityAbsent) * 100;\n}\n","/**\n * Shared utilities for verification method mapping and handling\n */\n\nexport type VerificationMethod =\n | 'signature'\n | 'pattern'\n | 'behavioral'\n | 'network'\n | 'mcp_i_handshake'\n | 'kyaos_handshake'\n | 'none'\n | 'error';\n\n/**\n * KYA-OS verification-method vocabulary rename (`mcp-i` → `kya-os`), read side.\n *\n * Mirrors the Vocab-1 dual-accept shape in `policy/constants.ts`: a canonical\n * value plus a deprecated legacy alias kept for a read-side cutover window.\n * **This widens READERS only** — nothing emits the canonical value yet (the\n * Rust engine still emits `mcp_i_handshake`; the gateway worker still emits the\n * wire value `mcp-i`). The canonical spelling matches the `kyaos-jws` token\n * chosen for the `verified_protocol` axis in #2937.\n *\n * Two distinct value spaces — do not conflate:\n * - **ENGINE value** — emitted by the detection engine (`mcp_i_handshake`).\n * - **WIRE value** — the normalized form stored/exposed downstream (`mcp-i`).\n *\n * This module is the SINGLE source of the legacy↔canonical alias map for both\n * spaces. Every downstream \"accept both\" site routes through the predicates\n * (`isKyaOs*Method`) or normalizers (`normalize*Method`) below, so the literal\n * alias strings live in exactly one place; adding or retiring an alias is a\n * one-file change, and no consumer can drift into a single-alias bypass.\n */\nexport const KYA_OS_HANDSHAKE_METHODS = {\n /** New canonical engine value. Not emitted yet — accepted on read. */\n CANONICAL: 'kyaos_handshake',\n /** @deprecated Legacy engine value. Still emitted by the Rust engine. */\n LEGACY: 'mcp_i_handshake',\n} as const;\n\nexport const KYA_OS_WIRE_METHODS = {\n /** New canonical wire value. Not emitted yet — accepted on read. */\n CANONICAL: 'kya-os',\n /** @deprecated Legacy wire value. Still emitted by the gateway worker. */\n LEGACY: 'mcp-i',\n} as const;\n\n/** True for either the legacy or canonical KYA-OS handshake ENGINE value. */\nexport function isKyaOsHandshakeMethod(value: string | null | undefined): boolean {\n return value === KYA_OS_HANDSHAKE_METHODS.LEGACY || value === KYA_OS_HANDSHAKE_METHODS.CANONICAL;\n}\n\n/** True for either the legacy or canonical KYA-OS delegation WIRE value. */\nexport function isKyaOsWireMethod(value: string | null | undefined): boolean {\n return value === KYA_OS_WIRE_METHODS.LEGACY || value === KYA_OS_WIRE_METHODS.CANONICAL;\n}\n\n/**\n * Collapse a KYA-OS handshake ENGINE value to its canonical form for INTERNAL\n * comparison. Either alias (`mcp_i_handshake` | `kyaos_handshake`) maps to\n * `KYA_OS_HANDSHAKE_METHODS.CANONICAL`; every other value (including\n * null/undefined) passes through unchanged. The return type widens the caller's\n * type by the canonical alias (`T | 'kyaos_handshake'`), which is honest (no\n * `as` cast) and still drops cleanly into a typed `switch`.\n *\n * Use this to normalize ONCE at a boundary so downstream decisions compare a\n * single value instead of re-listing both aliases. It does NOT touch the wire\n * value space; a wire value like `mcp-i` passes straight through.\n *\n * SECURITY/DATA NOTE: this is for comparison/decisions only. Do NOT use it to\n * rewrite a value that gets PERSISTED or EMITTED. Historical DB rows, the Rust\n * engine, and the gateway worker all still use the legacy spelling, so changing\n * a stored/emitted value would be a data-format change. Sites that map to a\n * stored/wire value keep emitting the legacy value deliberately.\n */\nexport function normalizeHandshakeMethod<T extends string | null | undefined>(\n value: T\n): T | typeof KYA_OS_HANDSHAKE_METHODS.CANONICAL {\n return isKyaOsHandshakeMethod(value) ? KYA_OS_HANDSHAKE_METHODS.CANONICAL : value;\n}\n\n/**\n * Collapse a KYA-OS delegation WIRE value to its canonical form for INTERNAL\n * comparison. Either alias (`mcp-i` | `kya-os`) maps to\n * `KYA_OS_WIRE_METHODS.CANONICAL`; every other value (including null/undefined)\n * passes through unchanged. Does NOT touch the engine value space.\n *\n * Same comparison-only contract and honest `T | 'kya-os'` return type as\n * `normalizeHandshakeMethod`; never use it to change a persisted/emitted value.\n */\nexport function normalizeWireMethod<T extends string | null | undefined>(\n value: T\n): T | typeof KYA_OS_WIRE_METHODS.CANONICAL {\n return isKyaOsWireMethod(value) ? KYA_OS_WIRE_METHODS.CANONICAL : value;\n}\n\n/**\n * Gets a human-readable description for a verification method\n */\nexport function getVerificationMethodDescription(method: VerificationMethod): string {\n // Normalize the handshake alias pair to canonical FIRST, so only the\n // canonical case is listed here; the legacy-to-canonical map lives solely in\n // `normalizeHandshakeMethod`.\n switch (normalizeHandshakeMethod(method)) {\n case 'signature':\n return 'HTTP Signature Verification';\n case 'pattern':\n return 'User-Agent Pattern Matching';\n case 'behavioral':\n return 'Behavioral Analysis';\n case 'network':\n return 'Network-based Detection';\n case KYA_OS_HANDSHAKE_METHODS.CANONICAL:\n return 'MCP Handshake Detection';\n case 'error':\n return 'Detection Error';\n case 'none':\n default:\n return 'No Verification';\n }\n}\n\n/**\n * Gets the reliability/confidence modifier for a verification method\n * Higher values indicate more reliable verification methods\n */\nexport function getVerificationReliability(method: VerificationMethod): number {\n // Normalize the handshake alias pair to canonical FIRST (see above).\n switch (normalizeHandshakeMethod(method)) {\n case 'signature':\n return 1.0; // Highest reliability\n case KYA_OS_HANDSHAKE_METHODS.CANONICAL:\n return 0.95;\n case 'behavioral':\n return 0.8;\n case 'network':\n return 0.6;\n case 'pattern':\n return 0.5;\n case 'none':\n return 0.3;\n case 'error':\n default:\n return 0.1; // Lowest reliability\n }\n}\n\n/**\n * Determines if a verification method indicates high confidence detection\n */\nexport function isHighConfidenceVerification(method: VerificationMethod): boolean {\n // Dual-accept via the shared predicate (legacy + canonical handshake).\n return method === 'signature' || isKyaOsHandshakeMethod(method);\n}\n\n/**\n * Maps verification method to appropriate risk level\n */\nexport function getVerificationRiskLevel(\n method: VerificationMethod,\n confidence: number\n): 'low' | 'medium' | 'high' {\n if (method === 'signature') {\n return 'low'; // Signatures are hard to forge\n }\n\n // Dual-accept via the shared predicate (legacy + canonical handshake).\n if (isKyaOsHandshakeMethod(method)) {\n return 'low'; // MCP handshakes are reliable\n }\n\n if (confidence >= 0.9) {\n return method === 'behavioral' ? 'medium' : 'high';\n }\n\n if (confidence >= 0.7) {\n return 'medium';\n }\n\n return 'high'; // Low confidence = high risk of false positive\n}\n","/**\n * Detection reason-code mapping: the single pure projection of a\n * detection's structured facts onto the `DETECTION_REASON_CODES` registry\n * (GODPROMPTS/detection-reason-codes).\n *\n * The engine already emits structured evidence (`signals[]` with a typed\n * `source`, `verificationMethod`, `detectionClass`, `isAiCrawler`) but the\n * only wire-level \"why\" used to be `reasons[]`, free English prose. This\n * module turns that structured evidence into an ordered list of stable,\n * namespaced codes, most-significant-evidence first.\n *\n * Consumers (all invoke this SAME pure function, so their codes can never\n * diverge):\n * - the gateway worker's `addDetectionHeaders` (`KYA-Reason-Codes` on\n * EVERY proxied response, including allow) and `log-detection.ts`\n * (persisted alongside the detection row), both via the re-export in\n * `apps/web/workers/gateway/src/detection/reason-codes.ts`;\n * - the `/api/v1/enforce` response's signal exposure\n * (KYA-1107) via `apps/web/lib/detection/signal-exposure.ts`.\n *\n * This module NEVER changes a verdict; it only labels one that already\n * happened (same non-negotiable as the registry doc comment).\n */\nimport { DETECTION_REASON_CODES, type DetectionReasonCode } from './detection-reason-codes';\nimport { isKyaOsHandshakeMethod, isKyaOsWireMethod } from '../utils/verification';\n\n/**\n * The structural subset of a detection detail the mapping actually reads.\n * Both the gateway's `GatewayDetectionDetail` (wire value space) and the\n * enforce route's engine-refined detail (engine value space) are assignable\n * since the mapping dual-accepts both value spaces where they differ (see the\n * handshake branch below).\n */\nexport interface ReasonCodeDetectionFacts {\n /** Verification method: WIRE (`mcp-i`/`kya-os`, `kya-http`, …) or ENGINE (`mcp_i_handshake`, …) value space. */\n verificationMethod?: string | null;\n /** The engine's per-signal evidence breakdown; only each entry's `source` is read. */\n signals?: ReadonlyArray<{ source: string }> | null;\n /** The engine's AI-training-crawler classification flag. */\n isAiCrawler?: boolean | null;\n /** Flat wire-form detection class (`human` | `ai_agent` | `bot` | `automation` | `incomplete_data` | `unknown`). */\n detectionClass?: string | null;\n}\n\n/**\n * `verificationMethod` → the single strongest code it proves. Keys are the\n * WIRE value space; the KYA-OS handshake/delegation alias pairs are handled\n * as explicit branches in `mapDetectionToReasonCodes` via the shared\n * `isKyaOs*Method` predicates (the SSOT for those alias pairs; Bugbot on\n * PR #4874 caught this table keyed on engine values instead, silently\n * missing every verified MCP-I/KYA-OS handshake) rather than hardcoding the\n * alias strings a second time in this map.\n */\nconst VERIFICATION_METHOD_CODES: Readonly<Record<string, DetectionReasonCode>> = {\n 'kya-http-delegated': DETECTION_REASON_CODES.DELEGATION_VERIFIED,\n 'kya-http': DETECTION_REASON_CODES.SIGNATURE_VERIFIED,\n did: DETECTION_REASON_CODES.DID_SIGNATURE_VERIFIED,\n signature: DETECTION_REASON_CODES.RFC9421_SIGNATURE_VERIFIED,\n a2a: DETECTION_REASON_CODES.A2A_VERIFIED,\n error: DETECTION_REASON_CODES.VERIFICATION_ERROR,\n};\n\n/**\n * A `signals[].source` value → the code naming that raw evidence.\n *\n * Declaration order IS the consideration order `mapDetectionToReasonCodes`\n * iterates (object key insertion order is guaranteed for string keys), NOT\n * the raw `signals[]` array order, which the engine assembles differently\n * per detection path (mirrors `buildVerdictEvidence`'s own doc comment on\n * the same nondeterminism). Roughly the engine's own construction order in\n * `api.rs` (identity/delegation evidence before UA/IP heuristics). Keeping\n * one map (rather than a map plus a separate priority-order array) means a\n * new signal source is added in exactly one place.\n */\nconst SIGNAL_SOURCE_CODES: Readonly<Record<string, DetectionReasonCode>> = {\n mcp_i: DETECTION_REASON_CODES.MCP_I_SIGNAL,\n kya_http_binding: DETECTION_REASON_CODES.KYA_HTTP_BINDING_SIGNAL,\n kya_delegation_bearer: DETECTION_REASON_CODES.KYA_DELEGATION_BEARER_SIGNAL,\n a2a_agent_card: DETECTION_REASON_CODES.A2A_CARD_SIGNAL,\n user_agent_pattern: DETECTION_REASON_CODES.UA_PATTERN_MATCH,\n ua_tls_mismatch: DETECTION_REASON_CODES.UA_TLS_MISMATCH,\n header_heuristic: DETECTION_REASON_CODES.HEADER_HEURISTIC,\n ip_heuristic: DETECTION_REASON_CODES.IP_HEURISTIC,\n scanner_misclassification_hint: DETECTION_REASON_CODES.SCANNER_MISCLASSIFICATION_HINT_SIGNAL,\n client_headless_escalation: DETECTION_REASON_CODES.CLIENT_HEADLESS_ESCALATION_SIGNAL,\n vendor_ip_feed: DETECTION_REASON_CODES.VENDOR_IP_CORROBORATED,\n ip_intelligence: DETECTION_REASON_CODES.IP_INTELLIGENCE_PROXY_SIGNAL,\n 'transport.ja4': DETECTION_REASON_CODES.JA4_FINGERPRINT_MATCH,\n 'transport.cloudflare_bot_management': DETECTION_REASON_CODES.CLOUDFLARE_BOT_MANAGEMENT_SIGNAL,\n client_integrity: DETECTION_REASON_CODES.CLIENT_INTEGRITY_FAILURE,\n 'client.attributes': DETECTION_REASON_CODES.CLIENT_ATTRIBUTE_SIGNAL,\n 'behavioural.interaction': DETECTION_REASON_CODES.BEHAVIORAL_SIGNAL,\n session_velocity: DETECTION_REASON_CODES.SESSION_VELOCITY_SIGNAL,\n};\n\n/**\n * Maps a detection's structured facts to an ordered, deduplicated list of\n * `detection/*` reason codes, most-significant-evidence first:\n *\n * 1. Verification-method-derived (cryptographic proof, strongest).\n * 2. Signal-source-derived (raw structured evidence), one code per\n * distinct source actually present, deduplicated.\n * 3. The AI-crawler classification flag.\n * 4. A zero-evidence fallback, ONLY when nothing above matched, so this\n * function never returns an empty list. An assumed verdict (e.g. the\n * baseline \"no known agent indicators matched\" human path) deserves a\n * code saying so, in the spirit of #4800, rather than silence.\n *\n * Pure: no I/O, no mutation of `detail`.\n */\nexport function mapDetectionToReasonCodes(detail: ReasonCodeDetectionFacts): DetectionReasonCode[] {\n const codes: DetectionReasonCode[] = [];\n const seen = new Set<DetectionReasonCode>();\n const push = (code: DetectionReasonCode | undefined): void => {\n if (code && !seen.has(code)) {\n seen.add(code);\n codes.push(code);\n }\n };\n\n // 1. Verification method.\n const verificationMethod = detail.verificationMethod;\n if (verificationMethod) {\n if (verificationMethod.startsWith('tier1_')) {\n push(DETECTION_REASON_CODES.TIER1_ATTRIBUTION_VERIFIED);\n } else if (\n // Dual-accept BOTH value spaces for the KYA-OS handshake: the gateway\n // worker normalizes to the WIRE values (`mcp-i`/`kya-os`) before\n // calling in, while the enforce route's engine-refined detail carries\n // the ENGINE values (`mcp_i_handshake`/`kyaos_handshake`). Routing\n // both through the shared predicates keeps the alias pairs in exactly\n // one place and closes the exact single-value-space gap Bugbot\n // caught on PR #4874.\n isKyaOsWireMethod(verificationMethod) ||\n isKyaOsHandshakeMethod(verificationMethod)\n ) {\n push(DETECTION_REASON_CODES.MCP_I_VERIFIED);\n } else {\n push(VERIFICATION_METHOD_CODES[verificationMethod]);\n }\n }\n\n // 2. Signal sources: one pass over detail.signals builds the dedup Set\n // AND detects a tier1_* source, rather than a second scan/spread over the\n // Set afterward. Then a fixed-order pass over SIGNAL_SOURCE_CODES's own\n // declaration order (the consideration order) pushes each present source's\n // code.\n const presentSources = new Set<string>();\n let hasTier1Signal = false;\n for (const signal of detail.signals ?? []) {\n presentSources.add(signal.source);\n if (signal.source.startsWith('tier1_')) hasTier1Signal = true;\n }\n for (const source of Object.keys(SIGNAL_SOURCE_CODES)) {\n if (presentSources.has(source)) push(SIGNAL_SOURCE_CODES[source]);\n }\n if (hasTier1Signal) {\n push(DETECTION_REASON_CODES.TIER1_ATTRIBUTION_SIGNAL);\n }\n\n // 3. AI-crawler flag: additive, independent of the codes above.\n if (detail.isAiCrawler) {\n push(DETECTION_REASON_CODES.AI_CRAWLER_FLAG);\n }\n\n // 4. Zero-evidence fallback: only when nothing above fired.\n if (codes.length === 0) {\n if (detail.detectionClass === 'human') {\n push(DETECTION_REASON_CODES.ZERO_EVIDENCE_HUMAN);\n } else if (\n detail.detectionClass === 'incomplete_data' ||\n detail.detectionClass === 'unknown' ||\n !detail.detectionClass\n ) {\n push(DETECTION_REASON_CODES.INCOMPLETE_DATA_OVERRIDE);\n } else {\n push(DETECTION_REASON_CODES.CLASSIFIED_WITHOUT_SIGNAL_EVIDENCE);\n }\n }\n\n return codes;\n}\n\n/** Wire cap: at most this many codes on the `KYA-Reason-Codes` header. */\nexport const MAX_REASON_CODES_ON_WIRE = 5;\n/** Wire cap: the header's serialized UTF-8 byte budget. */\nexport const MAX_REASON_CODES_HEADER_BYTES = 256;\n\nconst HEADER_BYTES_ENCODER = new TextEncoder();\n\n/**\n * Formats an ordered reason-code list into the `KYA-Reason-Codes` header\n * value: comma-separated, capped at {@link MAX_REASON_CODES_ON_WIRE} codes,\n * then trimmed from the end (never mid-string) until the UTF-8 byte length\n * fits {@link MAX_REASON_CODES_HEADER_BYTES}. `codes` is assumed already\n * ordered most-significant-first (mapDetectionToReasonCodes's contract);\n * this function only truncates, it never reorders.\n */\nexport function formatReasonCodesHeader(codes: readonly DetectionReasonCode[]): string {\n const capped = codes.slice(0, MAX_REASON_CODES_ON_WIRE);\n while (capped.length > 0) {\n const joined = capped.join(',');\n if (HEADER_BYTES_ENCODER.encode(joined).byteLength <= MAX_REASON_CODES_HEADER_BYTES) {\n return joined;\n }\n capped.pop();\n }\n return '';\n}\n","/**\n * Checkpoint configuration types\n */\n\nimport { z } from 'zod';\nimport { DetectionModeSchema } from '../core/detection';\nimport { ConfidenceThresholdSchema } from '../core/confidence';\n\n/**\n * Cache configuration\n */\nexport const CacheConfigSchema = z.object({\n enabled: z.boolean().default(true),\n ttl: z.number().positive().default(300000), // 5 minutes\n maxSize: z.number().positive().default(1000),\n strategy: z.enum(['lru', 'fifo', 'lfu']).default('lru'),\n});\nexport type CacheConfig = z.infer<typeof CacheConfigSchema>;\n\n/**\n * Network analysis configuration\n */\nexport const NetworkConfigSchema = z.object({\n enabled: z.boolean().default(true),\n checkCloudProviders: z.boolean().default(true),\n checkDataCenters: z.boolean().default(true),\n checkVpn: z.boolean().default(false),\n checkProxy: z.boolean().default(false),\n customIpRanges: z\n .array(\n z.object({\n name: z.string(),\n ranges: z.array(z.string()),\n action: z.enum(['allow', 'block', 'flag']),\n })\n )\n .optional(),\n});\nexport type NetworkConfig = z.infer<typeof NetworkConfigSchema>;\n\n/**\n * Logging configuration\n */\nexport const LoggingConfigSchema = z.object({\n enabled: z.boolean().default(true),\n level: z.enum(['debug', 'info', 'warn', 'error']).default('info'),\n logDetections: z.boolean().default(true),\n logErrors: z.boolean().default(true),\n destination: z.enum(['console', 'file', 'remote']).default('console'),\n});\nexport type LoggingConfig = z.infer<typeof LoggingConfigSchema>;\n\n/**\n * WASM configuration\n */\nexport const WasmConfigSchema = z.object({\n enabled: z.boolean().default(true),\n path: z.string().optional(),\n fallbackToJs: z.boolean().default(true),\n preload: z.boolean().default(false),\n});\nexport type WasmConfig = z.infer<typeof WasmConfigSchema>;\n\n/**\n * Main Checkpoint configuration\n */\nexport const AgentShieldConfigSchema = z.object({\n // Detection settings\n mode: DetectionModeSchema.default('balanced'),\n enablePatternMatching: z.boolean().default(true),\n enableBehaviorAnalysis: z.boolean().default(true),\n enableNetworkAnalysis: z.boolean().default(true),\n enableSignatureVerification: z.boolean().default(false),\n\n // Thresholds - Using 0-1 scale for consistency\n confidenceThreshold: z.number().min(0).max(1).default(0.7),\n confidenceThresholds: ConfidenceThresholdSchema.optional(),\n\n // Sub-configurations\n cache: CacheConfigSchema.optional(),\n network: NetworkConfigSchema.optional(),\n logging: LoggingConfigSchema.optional(),\n wasm: WasmConfigSchema.optional(),\n\n // Custom rules and patterns\n customRules: z.array(z.string()).optional(),\n customPatterns: z.record(z.string(), z.string()).optional(),\n\n // Allowlists and blocklists\n allowedAgents: z.array(z.string()).optional(),\n blockedAgents: z.array(z.string()).optional(),\n allowedIps: z.array(z.string()).optional(),\n blockedIps: z.array(z.string()).optional(),\n});\nexport type AgentShieldConfig = z.infer<typeof AgentShieldConfigSchema>;\n\n/**\n * Default configuration\n */\nexport const defaultConfig: AgentShieldConfig = {\n mode: 'balanced',\n enablePatternMatching: true,\n enableBehaviorAnalysis: true,\n enableNetworkAnalysis: true,\n enableSignatureVerification: false,\n confidenceThreshold: 0.7, // Using 0-1 scale\n};\n","/**\n * Version-agnostic Zod helper schemas.\n *\n * Zod 4 removes `z.string().ip()` and stops treating `z.function()` as a\n * schema. Every site that needs \"an IP address\" or \"some callback\" goes\n * through these two helpers so the Zod 4 flip changed one body each,\n * not a dozen call sites. The bodies below are the Zod 4 forms.\n */\n\nimport { z } from 'zod';\n\n/** Accepts a bare IPv4 or IPv6 address. Rejects ports, brackets, and whitespace. */\nexport const ipAddressSchema = z.union([z.ipv4(), z.ipv6()], { error: 'Invalid IP address' });\n\n/** Accepts any function value. Type is the top function type so any callback is assignable. */\nexport const callbackSchema = z.custom<(...args: never[]) => unknown>(\n (value) => typeof value === 'function'\n);\n","/**\n * Middleware configuration types\n */\n\nimport { z } from 'zod';\nimport { AgentShieldConfigSchema } from './shield';\nimport { callbackSchema } from '../utils/zod-helpers';\n\n/**\n * Middleware session tracking configuration\n */\nexport const MiddlewareSessionConfigSchema = z.object({\n enabled: z.boolean().default(false),\n storage: z.enum(['memory', 'redis', 'custom']).default('memory'),\n ttl: z.number().positive().default(3600000), // 1 hour\n cookieName: z.string().default('agentshield-session'),\n cookieOptions: z\n .object({\n httpOnly: z.boolean().default(true),\n secure: z.boolean().default(true),\n sameSite: z.enum(['strict', 'lax', 'none']).default('lax'),\n maxAge: z.number().optional(),\n })\n .optional(),\n});\nexport type MiddlewareSessionConfig = z.infer<typeof MiddlewareSessionConfigSchema>;\n\n/**\n * Middleware action types\n */\nexport const MiddlewareActionSchema = z.enum(['block', 'redirect', 'rewrite', 'allow', 'log']);\nexport type MiddlewareAction = z.infer<typeof MiddlewareActionSchema>;\n\n/**\n * Response action configuration\n */\nexport const ResponseActionSchema = z.object({\n block: z.boolean().default(false),\n statusCode: z.number().default(403),\n message: z.string().default('Access denied'),\n redirect: z.string().optional(),\n addHeaders: z.record(z.string(), z.string()).optional(),\n customResponse: z.any().optional(),\n});\nexport type ResponseAction = z.infer<typeof ResponseActionSchema>;\n\n/**\n * Event handling configuration\n */\nexport const EventConfigSchema = z.object({\n onDetection: callbackSchema.optional(),\n onBlock: callbackSchema.optional(),\n onAllow: callbackSchema.optional(),\n onError: callbackSchema.optional(),\n emitEvents: z.boolean().default(true),\n});\nexport type EventConfig = z.infer<typeof EventConfigSchema>;\n\n/**\n * Express middleware options\n */\nexport const ExpressMiddlewareOptionsSchema = AgentShieldConfigSchema.extend({\n session: MiddlewareSessionConfigSchema.optional(),\n responseAction: ResponseActionSchema.optional(),\n events: EventConfigSchema.optional(),\n excludePaths: z.array(z.string()).optional(),\n includePaths: z.array(z.string()).optional(),\n});\nexport type ExpressMiddlewareOptions = z.infer<typeof ExpressMiddlewareOptionsSchema>;\n\n/**\n * Next.js middleware options\n */\nexport const NextMiddlewareOptionsSchema = AgentShieldConfigSchema.extend({\n session: MiddlewareSessionConfigSchema.optional(),\n responseAction: ResponseActionSchema.optional(),\n events: EventConfigSchema.optional(),\n excludePaths: z.array(z.string()).optional(),\n includePaths: z.array(z.string()).optional(),\n edgeRuntime: z.boolean().default(true),\n useWasm: z.boolean().default(true),\n});\nexport type NextMiddlewareOptions = z.infer<typeof NextMiddlewareOptionsSchema>;\n\n/**\n * Storage adapter interface\n */\nexport interface StorageAdapter {\n // Left as `Promise<any>` deliberately. Making this generic at all breaks\n // existing implementers: a `get(key): Promise<string | null>` no longer\n // satisfies `<T>(key) => Promise<T>`, since T could be instantiated with an\n // unrelated type. Verified against an external-consumer probe. This is a\n // published interface, so tightening it is a major.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(key: string): Promise<any>;\n set(key: string, value: unknown, ttl?: number): Promise<void>;\n delete(key: string): Promise<void>;\n clear(): Promise<void>;\n has(key: string): Promise<boolean>;\n}\n\n/**\n * Middleware session data structure\n */\nexport const MiddlewareSessionDataSchema = z.object({\n id: z.string(),\n agentDetected: z.boolean(),\n detectionResult: z.any().optional(),\n firstSeen: z.number(),\n lastSeen: z.number(),\n requestCount: z.number(),\n metadata: z.record(z.string(), z.any()).optional(),\n});\nexport type MiddlewareSessionData = z.infer<typeof MiddlewareSessionDataSchema>;\n\n/**\n * Generic middleware configuration\n */\nexport const MiddlewareConfigSchema = z.object({\n action: MiddlewareActionSchema.default('log'),\n session: MiddlewareSessionConfigSchema.optional(),\n responseAction: ResponseActionSchema.optional(),\n events: EventConfigSchema.optional(),\n excludePaths: z.array(z.string()).optional(),\n includePaths: z.array(z.string()).optional(),\n});\nexport type MiddlewareConfig = z.infer<typeof MiddlewareConfigSchema>;\n","/**\n * Known AI agent patterns and constants\n *\n * F-08 PR-C: each entry now declares its own `category` (per the 9-value\n * canonical taxonomy locked by F-03 #2160). Previously\n * agent-types-sync.service.ts hardcoded `'ai_assistant'` for every entry\n * here, which is what stamped GPTBot / ClaudeBot / etc. as ai_assistant\n * in the agent_types table and ultimately as `detection_class='ai_agent'`\n * in detections (the F-08 bug). With per-entry categories, the sync\n * service routes each entry to the correct bucket directly.\n *\n * Two bundled entries from the prior shape have been split here so a\n * single agent_types row no longer represents both an interactive AI\n * session and a training crawler:\n * - `openai-gptbot` (was: GPTBot + ChatGPT-User + gpt-* models)\n * → `openai-gptbot` (scraper, just GPTBot)\n * + `openai-chatgpt` (ai_assistant, ChatGPT-User + gpt-* models)\n * - `google-bard` (was: Google-Extended + Bard + Google-InspectionTool + gemini + palm)\n * → `google-extended` (scraper, just Google-Extended)\n * + `google-bard` (ai_assistant, Bard + gemini + palm + Google-InspectionTool)\n * — later renamed to `gemini` (migration 0201, id only; the entry\n * and its patterns are unchanged).\n *\n * Mirrors the equivalent split in apps/web/scripts/seed-agent-types-data.ts\n * (claude / claudebot, perplexity / perplexity-bot).\n */\n\nimport { AgentPattern } from '../core/agent';\n\n/**\n * Known AI agent patterns\n */\nexport const KNOWN_AGENT_PATTERNS: AgentPattern[] = [\n // OpenAI — split into crawler vs interactive (PR-C)\n {\n id: 'openai-gptbot',\n type: 'openai',\n name: 'GPTBot',\n patterns: ['GPTBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'openai-chatgpt',\n type: 'openai',\n name: 'ChatGPT',\n // `OAI-SearchBot` backfilled by Engine-Pattern-Codegen-Retirement-1\n // after the legacy YAML→Rust path was retired. Previously detected\n // only via the legacy generator; the new TS SSOT migration would\n // have silently lost it.\n patterns: ['ChatGPT-User', 'OAI-SearchBot', 'gpt-4', 'gpt-3.5', 'gpt-4-turbo', 'gpt-4o'],\n headers: {\n 'X-OpenAI-Assistant': '*',\n },\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n // GPT-Crawler — distinct from GPTBot (OpenAI's official training crawler);\n // tracked separately so the classifier can attribute hits to the\n // right entity. PDM-2 promoted from the INTERACTIVE_AGENT_PATTERNS\n // supplement.\n {\n id: 'openai-gpt-crawler',\n type: 'openai',\n name: 'GPT Crawler',\n patterns: ['GPT-Crawler'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n // OpenAI generic vendor fallback — catches UAs that mention OpenAI\n // but use an undocumented sub-token (e.g. `OpenAI-Foo/1.0`,\n // `OpenAI-Web/2.0`). Word-boundary anchored (post-#2599). Lower\n // confidence than the strict per-token entries above. PDM-2.\n {\n id: 'openai-generic',\n type: 'openai',\n name: 'OpenAI',\n patterns: ['OpenAI'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Anthropic — split into interactive assistant vs training crawler.\n // The 'anthropic-ai' UA token used to live in this entry's patterns\n // alongside 'Claude-Web', which made every anthropic-ai crawler hit\n // resolve as ai_assistant. Moved out into the dedicated\n // `anthropic-ai-crawler` entry below so the classifier produces\n // (scraper, bot) for those rows. Same shape as the openai-gptbot /\n // openai-chatgpt split.\n {\n id: 'anthropic-claude',\n type: 'anthropic',\n name: 'Claude',\n patterns: [\n 'Claude-Web',\n 'claude-web',\n // Claude-User is Anthropic's user-initiated fetcher (the assistant\n // pulls a URL on the user's behalf — equivalent to ChatGPT-User).\n // Distinct from ClaudeBot (training crawler, captured separately\n // by `anthropic-claudebot`). anthropic.yaml already lists\n // 'Claude-User' on `anthropic_claude`, so the Rust WASM engine\n // recognizes it; this entry was the only layer where the pattern\n // was missing, which left ~14 real Claude-User sessions on\n // production stamped (bot, …) instead of (ai_agent, ai_assistant).\n 'Claude-User',\n // `Claude-SearchBot` and `claude-code` backfilled by\n // Engine-Pattern-Codegen-Retirement-1 — both were in the retired\n // YAML→Rust pipeline but never represented in TS. Claude-Code is\n // Anthropic's CLI agent (this very tool); Claude-SearchBot is\n // their search-augmented fetcher (parallel to OAI-SearchBot).\n 'Claude-SearchBot',\n 'claude-code',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #e111d65f):\n // the retired YAML→Rust pipeline matched both `claude-code` AND\n // `claude code` (space-separated). Some host wrappers stamp the\n // tool name with a space; the hyphenated form alone misses them.\n 'claude code',\n 'claude-3',\n 'claude-2',\n 'claude-instant',\n 'claude-3-opus',\n 'claude-3-sonnet',\n 'claude-3-haiku',\n ],\n headers: {\n 'X-Anthropic-Client': '*',\n },\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'anthropic-claudebot',\n type: 'anthropic',\n name: 'ClaudeBot',\n patterns: ['ClaudeBot', 'claudebot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n id: 'anthropic-ai-crawler',\n type: 'anthropic',\n name: 'Anthropic-AI Crawler',\n patterns: ['anthropic-ai'],\n // 0.95, matching every other single-exact-token vendor crawler\n // (openai-gptbot, anthropic-claudebot, meta-externalagent,\n // gemini-deep-research, deepseek-bot). Previously 0.9, tied with\n // anthropic-generic below — classifyByUserAgent picks the first\n // match on a confidence tie (strict `>`, no stable order), so an\n // 'anthropic-ai' UA could resolve to either row depending on DB\n // iteration order, reopening the exact misclassification this\n // taxonomy split retires the token to fix. Caught by Bugbot on\n // #4172 once the migration landing this row made the tie live.\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n // Anthropic generic vendor fallback — catches UAs that mention\n // Anthropic but use an undocumented sub-token (e.g. `Anthropic-Web`,\n // future variants). Word-boundary anchored (post-#2599) — only\n // matches when `Anthropic` is a standalone token, not embedded in\n // e.g. `AnthropicAssistant`. Lower confidence than the per-token\n // entries above. PDM-2 promoted from the INTERACTIVE_AGENT_PATTERNS\n // supplement.\n {\n id: 'anthropic-generic',\n type: 'anthropic',\n name: 'Anthropic',\n patterns: ['Anthropic'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Perplexity (training crawler, distinct from the interactive Perplexity-User\n // session captured by perplexity-user below)\n {\n id: 'perplexity-bot',\n type: 'perplexity',\n name: 'PerplexityBot',\n patterns: ['PerplexityBot', 'Perplexica'],\n confidence: 0.9,\n category: 'scraper',\n isLegitimate: true,\n },\n // Interactive Perplexity fetcher — parallel to ChatGPT-User shape;\n // the assistant pulls a URL on a human's behalf. Distinct from\n // PerplexityBot (training crawler). PDM-2 promoted this from the\n // INTERACTIVE_AGENT_PATTERNS supplement that #2599 carved out.\n {\n id: 'perplexity-user',\n type: 'perplexity',\n name: 'Perplexity',\n // `Comet` is Perplexity's AI-powered browser; backfilled into the\n // TS canonical via Engine-Pattern-Codegen-Retirement-1 after the\n // SSOT consolidation surfaced the gap. Previously detected only by\n // the legacy YAML→Rust codegen path; `apps/web/scripts/seed-agent-\n // types-data.ts` listed it as a Perplexity AI detection while\n // `KNOWN_AGENT_PATTERNS` did not. Now structurally enforced.\n patterns: ['Perplexity-User', 'Perplexity-AI', 'Comet'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n // Perplexity generic vendor fallback — catches UAs that mention\n // Perplexity but use an undocumented sub-token (future variants).\n // Lower confidence than the strict per-token entries above; the\n // matcher picks the highest-confidence match, so this only wins on\n // truly unknown shapes. Word-boundary anchored (post-#2599) so\n // `perplexity` only matches as a standalone token, not embedded.\n {\n id: 'perplexity-generic',\n type: 'perplexity',\n name: 'Perplexity',\n patterns: ['Perplexity'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Google — split into crawler (Google-Extended) vs interactive (Bard, Gemini, etc.) (PR-C)\n {\n id: 'google-extended',\n type: 'google',\n name: 'Google-Extended',\n patterns: ['Google-Extended'],\n confidence: 0.9,\n category: 'scraper',\n isLegitimate: true,\n },\n {\n // ORDERING NOTE: `gemini-deep-research` MUST appear BEFORE\n // `gemini` (renamed from `google-bard`, migration 0201) so the\n // more-specific 'Gemini-Deep-Research'\n // pattern wins under the engine's first-match-wins iteration over\n // AI_AGENT_PATTERNS. The legacy YAML→Rust output collapsed all\n // Google patterns under a single \"Google AI\" name with identical\n // confidence (0.90), so shadowing was benign; the SSOT migration\n // surfaced different names + confidences (0.95 scraper vs 0.90\n // ai_assistant), making the order load-bearing.\n //\n // Google's user-directed deep-research agent — distinct UA from\n // Bard/Gemini interactive sessions. CT85 (pattern-gaps-and-taxonomy,\n // 2026-09-03): was category 'scraper', which the DB agent_types\n // catalog row (apps/web/scripts/seed-agent-types-data.ts, migration\n // 0231) copied — that mismatched the engine's own ai_agent/95 wire\n // verdict and Google's own docs (a user-directed agent, not a\n // training crawler). Realigned here too so this SSOT, the DB\n // catalog, and the wire all agree — this is the file\n // agent-types-sync.service.ts reads as canonical, so leaving it at\n // 'scraper' would let a future sync silently revert the DB fix.\n id: 'gemini-deep-research',\n type: 'google',\n name: 'Gemini-Deep-Research',\n patterns: ['Gemini-Deep-Research', 'gemini-deep-research'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n // Renamed from 'google-bard' (migration 0201, P4 follow-up). The prior\n // fix (Fix-Gemini-Mislabeled-As-Google-Bard-1) deliberately left the id\n // as `google-bard` and only renamed the human-facing `name` below,\n // because the id is the stable codegen/stored key (Rust pattern ids via\n // build.rs -> known-agent-patterns.json, the agent_types.name DB row,\n // `agent-classification.service.ts`'s directMappings). This PR does the\n // full id rename instead: verified zero live project/org policies\n // (cedar_policy_text, allowed/denied agent-type lists) reference the\n // 'google-bard' slug (checked against a Neon branch off prod main,\n // 2026-08-14), so the earlier narrower fix's risk no longer applies.\n // `agent_types.agent_did` already reads\n // `did:web:knowthat.ai:agents:gemini` — this id rename just catches the\n // codegen/DB slug up to what the DID already assumed.\n id: 'gemini',\n type: 'google',\n name: 'Google Gemini',\n // Engine-Pattern-Codegen-Retirement-1 corrections:\n // - REMOVED `Google-InspectionTool` from this entry. The legacy\n // YAML→Rust pipeline classified Google-InspectionTool as a\n // Googlebot-family search inspection tool (Search Console\n // verification, structured-data testing), not a Bard/Gemini AI\n // session. Moved to `NON_AI_PATTERNS` in\n // `rust/crates/kya-os-engine/src/stages/patterns.rs` under the\n // `Googlebot` family so classification stays SearchCrawler.\n // - ADDED `LaMDA` (Google's pre-Bard conversational AI; legacy\n // YAML had it under Google AI) and `GoogleAgent-Mariner`\n // (Google's browser-controlling agent product) — both were in\n // the retired pipeline, never in TS.\n //\n // Engine-Pattern-Codegen-Retirement-2 (this PR, Bugbot #ae22713a and\n // #6984df6d): bare 'gemini'/'palm' matched `GeminiiOS` (Google's own\n // Gemini app rendering a page in its in-app webview — a HUMAN, not an\n // agent) as a plain unanchored substring — `build.rs` emits every\n // pattern here into `format!(\"(?i){pattern}\")` with no escaping and no\n // boundary, so a literal `'gemini'` compiles to `Regex::new(\"(?i)gemini\")`,\n // which `.is_match()`-style scanning matches anywhere. That reopened,\n // one layer down, the exact hole migration 0208 closed on the\n // DB-side `classifyByUserAgent` path: this PR's own `lookupAgentDid`\n // fix matches the WASM engine's emitted `name` ('Google Gemini')\n // against `agent_types.displayName` for the enforce/pixel-track\n // routes, which run no TS classifier and never touch\n // `classifyByUserAgent` at all — so `GeminiiOS` could still reach the\n // live `gemini` DID via this second, engine-only path.\n //\n // First attempt was an outright removal, which closed the hole but\n // also dropped genuine coverage: a bare `Gemini/1.0` or\n // `Google-Gemini/1.0` UA carrying no specific model suffix no longer\n // matched anything (caught by Bugbot #6984df6d's follow-up review,\n // and independently by 4 apps/web unit tests asserting exactly that\n // coverage — see git history). Word-boundary anchors close the false\n // positive AND keep the coverage: `\\bgemini\\b` matches `Gemini/1.0`\n // and `Google-Gemini/1.0` (boundary before the leading `G`/after `-`,\n // and before the trailing `/`) but NOT `GeminiiOS` (no boundary\n // between the two `i`s — both are word characters). Same shape for\n // `\\bpalm\\b` vs `palm2` (own explicit token, digit is a word\n // character so no double-match) vs a hypothetical `PalmOS`-style\n // collision. TS string literals need `\\\\b` (double backslash) to\n // produce a literal `\\b` in the resulting string — `\\b` alone is the\n // JS backspace escape, not a regex boundary.\n patterns: [\n 'Bard',\n '\\\\bgemini\\\\b',\n 'gemini-pro',\n 'gemini-1.5',\n 'gemini-1.5-pro',\n 'gemini-ultra',\n '\\\\bpalm\\\\b',\n 'palm2',\n 'LaMDA',\n 'GoogleAgent-Mariner',\n ],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Microsoft Copilot\n {\n id: 'microsoft-copilot',\n type: 'microsoft',\n name: 'Microsoft Copilot',\n patterns: [\n 'copilot',\n 'github-copilot',\n 'microsoft-copilot',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #89cfb23d):\n // the retired YAML→Rust pipeline carried `BingPreview/.*ChatGPT`\n // for Bing Copilot UAs. Without this, BingPreview+ChatGPT UAs hit\n // the non-AI `BingPreview` Bingbot rule and resolve as SearchBot.\n // Note: this entry must order BEFORE the Bingbot regex in the\n // composed table — AI patterns lead, so the dispatch order in\n // patterns.rs::AI_AGENT_PATTERNS (AI_PATTERNS_FROM_TS then\n // NON_AI_PATTERNS) preserves the precedence the legacy table\n // gave Microsoft AI at confidence 0.9.\n 'BingPreview/.*ChatGPT',\n ],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Meta AI (LLaMA) — interactive assistant only.\n // Disambiguated from Meta's web crawler (Meta-ExternalAgent) in the\n // dedicated entry below. Pre-split, prod's `meta-ai` agent_types row\n // had 'Meta-ExternalAgent' in its patterns AND category='ai_assistant',\n // which silently classified ~10K Meta-ExternalAgent crawler hits as\n // AI-assistant traffic on Hardware-World alone. Same pattern as the\n // openai-gptbot / openai-chatgpt split.\n {\n id: 'meta-ai',\n type: 'meta',\n name: 'Meta AI',\n patterns: ['Meta-AI'],\n confidence: 0.9,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'meta-externalagent',\n type: 'meta',\n name: 'Meta-ExternalAgent',\n patterns: ['Meta-ExternalAgent', 'meta-externalagent'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Cohere — bot variant (training/research crawler)\n {\n id: 'cohere-bot',\n type: 'cohere',\n name: 'CohereBot',\n // Engine-Pattern-Codegen-Retirement-1 round 2 (Bugbot #8007b7a3):\n // the retired YAML→Rust pipeline matched the literal `CohereBot`\n // token; without it the UA falls through to the generic-bot\n // fallback (`bot` substring) and resolves as `Generic Bot` /\n // OtherBot, losing vendor attribution.\n patterns: ['cohere-ai', 'CohereBot'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // HuggingFace — bot variant\n {\n id: 'huggingface-bot',\n type: 'huggingface',\n name: 'HuggingFaceBot',\n patterns: ['HuggingFace', 'transformers'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Meta LLaMA\n {\n id: 'meta-llama',\n type: 'meta',\n name: 'LLaMA',\n patterns: ['llama', 'llama-2', 'llama-3', 'llama2', 'llama3', 'codellama', 'alpaca'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Mistral AI\n {\n id: 'mistral-ai',\n type: 'mistral',\n name: 'MistralBot',\n patterns: [\n 'mistral',\n 'mixtral',\n 'mistral-7b',\n 'mixtral-8x7b',\n 'mistral-medium',\n 'mistral-large',\n ],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Cohere Command\n {\n id: 'cohere-command',\n type: 'cohere',\n name: 'CommandBot',\n patterns: ['command', 'command-r', 'command-r-plus', 'commandr'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Microsoft Phi\n {\n id: 'microsoft-phi',\n type: 'microsoft',\n name: 'PhiBot',\n patterns: ['phi-2', 'phi-3', 'phi-3-mini', 'phi-3-medium'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Alibaba Qwen\n {\n id: 'alibaba-qwen',\n type: 'alibaba',\n name: 'QwenBot',\n patterns: ['qwen', 'qwen-7b', 'qwen-14b', 'qwen-72b', 'qwen1.5', 'qwen2'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // 01.AI Yi\n {\n id: '01ai-yi',\n type: '01ai',\n name: 'YiBot',\n patterns: ['yi-6b', 'yi-34b', 'yi-large'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Inflection AI\n {\n id: 'inflection-pi',\n type: 'inflection',\n name: 'PiBot',\n patterns: ['inflection', 'pi-bot', 'pi.ai'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Stability AI\n {\n id: 'stability-ai',\n type: 'stability',\n name: 'StabilityBot',\n patterns: ['stablelm', 'stable-lm', 'stability-ai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Writer AI\n {\n id: 'writer-ai',\n type: 'writer',\n name: 'WriterBot',\n patterns: ['writerai', 'palmyra'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Phind — bot variant\n {\n id: 'phind-bot',\n type: 'phind',\n name: 'PhindBot',\n patterns: ['phind', 'phind-codellama'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // You.com — bot variant (you.com / youbot are crawler patterns;\n // the interactive You.com session would be a separate entry if it\n // had a distinct UA, but currently doesn't)\n {\n id: 'you-bot',\n type: 'you',\n name: 'YouBot',\n patterns: ['you.com', 'youbot'],\n confidence: 0.85,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Neeva — bot variant\n {\n id: 'neeva-bot',\n type: 'neeva',\n name: 'NeevaBot',\n patterns: ['neeva', 'neevabot'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Jasper AI\n {\n id: 'jasper-ai',\n type: 'jasper',\n name: 'JasperBot',\n patterns: ['jasper', 'jasperai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // Replicate — bot variant\n {\n id: 'replicate-bot',\n type: 'replicate',\n name: 'ReplicateBot',\n patterns: ['replicate'],\n confidence: 0.8,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Together AI\n {\n id: 'together-ai',\n type: 'together',\n name: 'TogetherBot',\n patterns: ['together-ai', 'togetherai'],\n confidence: 0.8,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // ─────────────────────────────────────────────────────────────────────\n // Engine-Pattern-Codegen-Retirement-1 backfills.\n //\n // Each entry below was detected by the retired YAML→Rust codegen path\n // (`patterns_generated.rs`) but never represented in TS. The SSOT\n // migration would have silently dropped detection for these vendors.\n // Names + confidences mirror the legacy pipeline so classify_agent /\n // classify_vendor downstream consumers don't see a behavioral shift.\n // ─────────────────────────────────────────────────────────────────────\n\n // xAI Grok — Elon's AI; user-facing assistant + crawler share the\n // same vendor brand, all routed through this single entry. The\n // legacy pipeline emitted them under one \"xAI Grok\" name, so a split\n // would change downstream classification.\n {\n id: 'xai-grok',\n type: 'xai',\n name: 'xAI Grok',\n patterns: ['xAI-Grok', 'GrokBot', 'Grok-DeepSearch'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // DeepSeek — split into interactive (DeepSeek-User) and crawler\n // (DeepSeekBot), parallel to the openai-chatgpt / openai-gptbot\n // and anthropic-claude / anthropic-claudebot splits.\n {\n id: 'deepseek-user',\n type: 'deepseek',\n name: 'DeepSeek AI',\n patterns: ['DeepSeek-User'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n {\n id: 'deepseek-bot',\n type: 'deepseek',\n name: 'DeepSeekBot',\n patterns: ['DeepSeekBot'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Amazon Quick — AWS's rendering web crawler (formerly launched as part\n // of the \"Amazon Q\" family, since renamed; docs.aws.amazon.com/quick).\n // UA convention is `amazon-Quick-on-behalf-of-<id>` / AWS's own\n // documented `aws-quick-on-behalf-of-<UUID>`. Declared BEFORE\n // `amazon-q` below: the Rust engine's AI_AGENT_PATTERNS match is\n // first-match-wins in TS source order (see patterns.rs\n // `analyze_user_agent`), and 'Amazon-Quick' is a superstring of\n // 'Amazon-Q' below, so the more specific pattern must be tried first\n // there. `classifyByUserAgent` (TS/DB path) doesn't use source order —\n // it tie-breaks on confidence — so this row's confidence must also\n // stay strictly above `amazon-q`'s (mirrors the anthropic-ai-crawler /\n // anthropic-generic split: specific crawler token > broad label).\n // is_legitimate: AWS's docs describe it as a JS-rendering, non-\n // interactive crawler (no simulated user interaction) — the taxonomy's\n // `scraper` bucket, not `ai_assistant` (real-time human-driven use).\n {\n id: 'amazon-quick',\n type: 'amazon',\n name: 'Amazon Quick',\n patterns: ['Amazon-Quick', 'aws-quick'],\n confidence: 0.95,\n category: 'scraper',\n isLegitimate: true,\n },\n\n // Amazon Q + NovaAct — Amazon's AI assistant product family.\n // NovaAct is the AWS-branded browser-controlling agent (parallel to\n // Anthropic's Claude-Code, Google's GoogleAgent-Mariner).\n //\n // Confidence intentionally below `amazon-quick` above, by MORE than the\n // TS/DB path's max multi-pattern bonus (+5 for 2+ pattern matches — see\n // calculateConfidence in agent-classification.service.ts): 0.85 not 0.90.\n // A UA containing both of amazon-q's patterns ('Amazon-Q' — substring-\n // matched by 'Amazon-Quick' — and 'NovaAct', plausible on the same\n // product family's browser-driving traffic) would score 90 + 5 = 95,\n // tying amazon-quick's flat 95 and recreating the exact order-dependent\n // tie this split exists to eliminate (own regression test:\n // agent-classification-amazon-quick-crawler-tie.test.ts). At 0.85 the\n // bonus tops out at 85 + 5 = 90, still short of amazon-quick's 95.\n {\n id: 'amazon-q',\n type: 'amazon',\n name: 'Amazon Q',\n patterns: ['Amazon-Q', 'NovaAct'],\n confidence: 0.85,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n\n // KYA Agent — our own product family. KYA-Agent/<version> is the\n // canonical UA; KYA-OS is the umbrella protocol token; KYA-Compute/\n // is the signed-compute variant. All ai_assistant — none of these\n // are training crawlers.\n //\n // Display name is `'Kya Agent'` (sentence case), NOT `'KYA Agent'`\n // (brand all-caps). Matches every other consumer's expectation:\n // `did-verifier.ts` hardcodes `'Kya Agent'` as the display fallback\n // for did:key / unhumanizable did:web (3 sites), the gateway router\n // docstring refers to the \"Kya Agent\" pattern, and the signed-agent\n // e2e test asserts on `'Kya Agent'` for both the unsigned Tier-3 UA\n // path and the signed DID-verified path. The prior `'KYA Agent'`\n // value here was a codegen-source outlier that produced consistent\n // brand-case-vs-sentence-case drift between Tier 3 emissions (which\n // read this) and Tier 1 emissions (which use the did-verifier\n // hardcode). One source of truth, sentence case.\n {\n id: 'kya-agent',\n type: 'kya',\n name: 'Kya Agent',\n patterns: ['KYA-Agent/', 'KYA-OS', 'KYA-Compute/'],\n confidence: 0.95,\n category: 'ai_assistant',\n isLegitimate: true,\n },\n];\n\n/**\n * Known cloud provider IP ranges (partial list)\n */\nexport const CLOUD_PROVIDER_RANGES = {\n aws: ['52.0.0.0/8', '54.0.0.0/8', '18.0.0.0/8', '35.0.0.0/8'],\n gcp: ['35.190.0.0/16', '35.240.0.0/16', '34.0.0.0/8'],\n azure: ['40.0.0.0/8', '20.0.0.0/8', '13.0.0.0/8'],\n};\n\n/**\n * Common bot user agent patterns\n * Updated with comprehensive AI model detection\n */\nexport const BOT_USER_AGENT_PATTERNS = [\n /bot/i,\n /crawler/i,\n /spider/i,\n /scraper/i,\n /agent/i,\n /ai\\//i,\n // OpenAI models\n /gpt(-?[0-9])?/i,\n /chatgpt/i,\n /openai/i,\n // Anthropic models\n /claude(-?[0-9])?/i,\n /anthropic/i,\n // Google models\n /gemini(-?[0-9.]+)?/i,\n /bard/i,\n /palm[0-9]?/i,\n // Meta models\n /llama(-?[0-9])?/i,\n /codellama/i,\n /alpaca/i,\n // Mistral models\n /mistral/i,\n /mixtral/i,\n // Microsoft models\n /phi(-?[0-9])?/i,\n /copilot/i,\n // Other major models\n /perplexity/i,\n /command(-?r)?/i,\n /qwen[0-9.]?/i,\n /yi(-?[0-9]+b)?/i,\n /stablelm/i,\n /\\bphind\\b/i,\n // `you.com` is detected as a UA SUBSTRING — the pattern is consumed\n // only by `BOT_USER_AGENT_PATTERNS.some(p => p.test(userAgent))`\n // (UA context, not URL). CodeQL js/regex/missing-regexp-anchor\n // speculated about URL misuse on PR #2576; PR #2591's tightened\n // consuming-class form (`[\\s;()]`) introduced a real false-negative\n // for legit UA shapes containing `/`:\n // - `you.com/1.0` (You.com bot, version-suffixed)\n // - `Mozilla/5.0 you.com/bot` (token-with-version)\n // - `+https://you.com)` (token after URL inside parens)\n // Cursor caught the regression on PR #2591. Reverting to `\\b` —\n // word-boundary is the correct anchor for UA-substring matching;\n // the original CodeQL flag is a context-blind false positive (the\n // codebase does not apply BOT_USER_AGENT_PATTERNS to URL strings).\n // If CodeQL re-flags, dismiss in the UI as \"false positive\" with\n // pointer to this comment.\n /\\byou\\.com\\b/i,\n /\\bneeva\\b/i,\n /jasper/i,\n /replicate/i,\n /together(-?ai)?/i,\n /cohere/i,\n /huggingface/i,\n /transformers/i,\n];\n\n/**\n * Headers commonly used by AI agents\n */\nexport const AI_AGENT_HEADERS = [\n 'X-OpenAI-Assistant',\n 'X-Anthropic-Client',\n 'X-AI-Agent',\n 'X-Bot-Token',\n 'X-Agent-ID',\n 'X-LLM-Request',\n];\n\n/**\n * Suspicious header patterns\n */\nexport const SUSPICIOUS_HEADERS = {\n // Missing standard headers\n missingUserAgent: 'User-Agent header is missing',\n missingAccept: 'Accept header is missing',\n\n // Unusual values\n genericUserAgent: 'User-Agent appears to be generic or spoofed',\n mismatchedHeaders: 'Headers contain conflicting information',\n\n // Known spoofing attempts\n fakeChrome: 'Chrome user agent without expected Chrome headers',\n fakeSafari: 'Safari user agent without expected Safari headers',\n};\n","/**\n * Traditional Bot Constants and Types\n *\n * These are NON-AI bots like search engines, crawlers, and SEO tools.\n * AI agents (Claude, GPT, etc.) should be in agents.ts\n */\n\nimport { z } from 'zod';\n\n/**\n * Traditional bot types (not AI agents)\n */\nexport const BotTypeSchema = z.enum([\n 'search_engine', // googlebot, bingbot, yandexbot\n 'social_media', // facebookbot, twitterbot, linkedinbot\n 'seo_tool', // semrushbot, ahrefsbot, mj12bot\n 'crawler', // generic web crawlers\n 'scraper', // data scrapers\n 'monitoring', // uptime monitors, health checkers\n 'security_scanner', // security scanning tools\n 'unknown_bot',\n]);\n\nexport type BotType = z.infer<typeof BotTypeSchema>;\n\n/**\n * Trusted traditional bots that can be cached\n * These are well-known, legitimate bots with stable patterns\n * NOT for AI agents - those should never be cached\n */\nexport const TRUSTED_BOTS = [\n // Search engines\n 'googlebot', // Google Search\n 'bingbot', // Bing Search\n 'slurp', // Yahoo\n 'duckduckbot', // DuckDuckGo\n 'baiduspider', // Baidu\n 'yandexbot', // Yandex\n 'applebot', // Apple Search\n\n // Social media\n 'facebookexternalhit', // Facebook\n 'twitterbot', // Twitter/X\n 'linkedinbot', // LinkedIn\n 'whatsapp', // WhatsApp\n\n // SEO tools\n 'semrushbot', // SEMrush SEO\n 'ahrefsbot', // Ahrefs SEO\n 'mj12bot', // Majestic SEO\n 'dotbot', // Moz SEO\n];\n\n/**\n * Bot pattern for traditional bot matching\n */\nexport const BotPatternSchema = z.object({\n id: z.string(),\n type: BotTypeSchema,\n name: z.string(),\n patterns: z.array(z.string()),\n confidence: z.number().min(0).max(1).default(0.8),\n});\n\nexport type BotPattern = z.infer<typeof BotPatternSchema>;\n\n/**\n * Traditional bot patterns.\n *\n * NAME VOCABULARY: `name` MUST be the detection engine's pattern name — the\n * string `kya-os-engine` stamps as `agent_name` (see the `NON_AI_PATTERNS`\n * table in `rust/crates/kya-os-engine/src/stages/patterns.rs`). That string\n * becomes `agent_types.display_name` via the sync service, the Cedar\n * principal the policy picker emits, and the `principal.name` every\n * evaluator byte-compares. A name the engine never emits can't be policy-\n * matched. Drift is pinned by `bot-name-vocabulary.spec.ts`, which parses\n * the Rust table at test time; entries the engine has NO name for are\n * allow-listed there and tracked by the codegen-consolidation issue.\n */\nexport const TRADITIONAL_BOT_PATTERNS: BotPattern[] = [\n // Search engines\n {\n id: 'googlebot',\n type: 'search_engine',\n name: 'Googlebot',\n patterns: ['googlebot', 'google-structured-data-testing-tool'],\n confidence: 0.95,\n },\n {\n id: 'bingbot',\n type: 'search_engine',\n name: 'Bingbot',\n patterns: ['bingbot', 'bingpreview', 'msnbot'],\n confidence: 0.95,\n },\n {\n id: 'yandexbot',\n type: 'search_engine',\n name: 'Yandexbot',\n patterns: ['yandexbot', 'yandex'],\n confidence: 0.9,\n },\n\n // Social media\n {\n id: 'facebook',\n type: 'social_media',\n name: 'Meta Crawler',\n patterns: ['facebookexternalhit', 'facebookcatalog', 'Meta-ExternalAgent'],\n confidence: 0.9,\n },\n {\n id: 'twitter',\n type: 'social_media',\n name: 'Twitterbot',\n patterns: ['twitterbot'],\n confidence: 0.9,\n },\n\n // SEO tools\n {\n id: 'semrush',\n type: 'seo_tool',\n name: 'SEMrush',\n patterns: ['semrushbot'],\n confidence: 0.85,\n },\n {\n id: 'ahrefs',\n type: 'seo_tool',\n name: 'Ahrefsbot',\n patterns: ['ahrefsbot'],\n confidence: 0.85,\n },\n\n // Generic crawlers\n {\n id: 'generic-crawler',\n type: 'crawler',\n name: 'Generic Bot',\n patterns: ['crawler', 'spider', 'bot/'],\n confidence: 0.6,\n },\n {\n id: 'generic-scraper',\n type: 'scraper',\n name: 'Generic Scraper',\n patterns: ['scraper', 'python-requests', 'curl/', 'wget/'],\n confidence: 0.7,\n },\n];\n\n/**\n * Check if a user agent is a traditional bot (not AI agent)\n */\nexport function isTraditionalBot(userAgent: string): boolean {\n const lowerUA = userAgent.toLowerCase();\n return TRUSTED_BOTS.some((bot) => lowerUA.includes(bot));\n}\n\n/**\n * Get bot type from user agent\n */\nexport function getBotType(userAgent: string): BotType | null {\n const lowerUA = userAgent.toLowerCase();\n\n for (const pattern of TRADITIONAL_BOT_PATTERNS) {\n if (pattern.patterns.some((p) => lowerUA.includes(p.toLowerCase()))) {\n return pattern.type;\n }\n }\n\n return null;\n}\n","/**\n * Default Configuration Values\n *\n * Default values used across the Checkpoint platform\n */\n\nimport type {\n AgentShieldConfig,\n PixelConfiguration,\n ProjectSettings,\n SessionConfig,\n ApiKeyRateLimits,\n DetectionOptions,\n} from '../types';\n\n/**\n * Default Checkpoint Configuration\n */\nexport const DEFAULT_AGENTSHIELD_CONFIG: AgentShieldConfig = {\n mode: 'balanced',\n enablePatternMatching: true,\n enableBehaviorAnalysis: true,\n enableNetworkAnalysis: true,\n enableSignatureVerification: false,\n confidenceThreshold: 0.65,\n confidenceThresholds: undefined,\n cache: {\n enabled: true,\n ttl: 3600,\n maxSize: 1000,\n strategy: 'lru' as const,\n },\n network: undefined,\n logging: undefined,\n wasm: undefined,\n customRules: undefined,\n customPatterns: undefined,\n allowedAgents: undefined,\n blockedAgents: undefined,\n allowedIps: undefined,\n blockedIps: undefined,\n};\n\n/**\n * Default Detection Options\n */\nexport const DEFAULT_DETECTION_OPTIONS: DetectionOptions = {\n mode: 'balanced',\n customRules: [],\n enablePatternMatching: true,\n enableBehaviorAnalysis: true,\n enableNetworkAnalysis: true,\n confidenceThreshold: 0.65,\n};\n\n/**\n * Default Project Settings\n */\nexport const DEFAULT_PROJECT_SETTINGS: ProjectSettings = {\n blockOnHighConfidence: false,\n confidenceThreshold: 0.8,\n enableSessionTracking: true,\n enableWasm: true,\n customDomain: undefined,\n allowedOrigins: [],\n blockedAgents: [],\n webhookUrl: undefined,\n webhookSecret: undefined,\n};\n\n/**\n * Default Pixel Configuration\n */\nexport const DEFAULT_PIXEL_CONFIG: PixelConfiguration = {\n enabled: true,\n skipPaths: [],\n allowedDomains: [],\n blockedAgents: [],\n batchSize: 10,\n flushInterval: 5000,\n enableBehavioralTracking: true,\n enableSessionReplay: false,\n customHeaders: {},\n};\n\n/**\n * Default Session Configuration\n */\nexport const DEFAULT_SESSION_CONFIG: SessionConfig = {\n storage: 'memory',\n storageOptions: {},\n ttl: 3600,\n idleTimeout: 1800,\n absoluteTimeout: 86400,\n rollingSession: true,\n destroyOnLogout: true,\n regenerateOnLogin: true,\n secure: true,\n sameSite: 'lax',\n httpOnly: true,\n domain: undefined,\n path: '/',\n cookieName: '__agentshield_session',\n cookieSecret: undefined,\n redisPrefix: 'as:session:',\n redisUrl: undefined,\n tableName: 'sessions',\n trackBehavior: true,\n trackPageViews: true,\n cleanupInterval: 300000,\n maxSessions: undefined,\n};\n\n/**\n * Default API Key Rate Limits\n */\nexport const DEFAULT_API_KEY_RATE_LIMITS: ApiKeyRateLimits = {\n requestsPerSecond: 10,\n requestsPerMinute: 100,\n requestsPerHour: 1000,\n requestsPerDay: 10000,\n burstLimit: 20,\n};\n\n/**\n * Default Confidence Thresholds\n */\nexport const DEFAULT_CONFIDENCE_THRESHOLDS = Object.freeze({\n low: 0.3,\n medium: 0.6,\n high: 0.8,\n veryHigh: 0.95,\n} as const);\n\n/**\n * Default Timeout Values (in milliseconds)\n */\nexport const DEFAULT_TIMEOUTS = Object.freeze({\n apiRequest: 10000,\n wasmInit: 5000,\n detection: 1000,\n sessionRefresh: 30000,\n pixelFlush: 5000,\n webhookRequest: 10000,\n cacheCleanup: 60000,\n} as const);\n\n/**\n * Default Retry Configuration\n */\nexport const DEFAULT_RETRY_CONFIG = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 30000,\n backoffMultiplier: 2,\n jitter: true,\n} as const;\n\n/**\n * Default Cache Configuration\n */\nexport const DEFAULT_CACHE_CONFIG = {\n detection: {\n enabled: true,\n ttl: 3600,\n maxSize: 10000,\n },\n session: {\n enabled: true,\n ttl: 1800,\n maxSize: 1000,\n },\n apiResponse: {\n enabled: true,\n ttl: 300,\n maxSize: 100,\n },\n} as const;\n\n/**\n * Default Logging Configuration\n */\nexport const DEFAULT_LOG_CONFIG = {\n level: 'info' as const,\n format: 'json' as const,\n timestamps: true,\n colorize: false,\n maxFiles: 5,\n maxSize: '10m',\n} as const;\n\n/**\n * Default Behavioral Thresholds\n */\nexport const DEFAULT_BEHAVIORAL_THRESHOLDS = {\n minMouseMovements: 5,\n minScrollEvents: 2,\n minTimeOnPage: 3000,\n maxClickRate: 10,\n suspiciousPatternScore: 0.7,\n} as const;\n\n/**\n * Default API Response Headers\n */\nexport const DEFAULT_RESPONSE_HEADERS = {\n 'KYA-Version': '1.0.0',\n 'KYA-Detection': 'enabled',\n 'Cache-Control': 'no-cache, no-store, must-revalidate',\n 'X-Content-Type-Options': 'nosniff',\n 'X-Frame-Options': 'DENY',\n} as const;\n\n/**\n * Default CORS Configuration\n */\nexport const DEFAULT_CORS_CONFIG = {\n origin: '*',\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n allowedHeaders: ['Content-Type', 'Authorization', 'X-API-Key', 'X-Pixel-ID'],\n exposedHeaders: ['KYA-Detection', 'X-Rate-Limit-Remaining'],\n credentials: true,\n maxAge: 86400,\n} as const;\n\n/**\n * Default Webhook Event Types\n */\nexport const DEFAULT_WEBHOOK_EVENTS = Object.freeze([\n 'agent.detected',\n 'agent.blocked',\n 'threshold.exceeded',\n 'suspicious.activity',\n 'rate.limit.exceeded',\n] as const);\n\n/**\n * Default Environment Variables\n */\nexport const DEFAULT_ENV_VARS = {\n AGENTSHIELD_API_KEY: '',\n AGENTSHIELD_SECRET_KEY: '',\n AGENTSHIELD_PIXEL_ID: '',\n AGENTSHIELD_API_ENDPOINT: 'https://api.agentshield.ai',\n AGENTSHIELD_WASM_PATH: '/wasm/agentshield_wasm_bg.wasm',\n AGENTSHIELD_CACHE_TTL: '3600',\n AGENTSHIELD_DEBUG: 'false',\n AGENTSHIELD_LOG_LEVEL: 'info',\n} as const;\n\n/**\n * Helper function to merge configurations with defaults\n */\nexport function mergeWithDefaults<T extends object>(config: Partial<T>, defaults: T): T {\n return {\n ...defaults,\n ...config,\n };\n}\n\n/**\n * Helper function to get environment variable with default\n */\nexport function getEnvVar(key: keyof typeof DEFAULT_ENV_VARS): string {\n return process.env[key] || DEFAULT_ENV_VARS[key];\n}\n","/**\n * Delegation credential lifetime bounds.\n *\n * Shared because the mint and the dashboard MUST agree: the policy page once\n * advertised a project's configured `delegationExpirationDays` (\"good for 7\n * days\") while the credential that flow actually minted was 900 seconds.\n */\n\n/**\n * Maximum lifetime of an `attested-bearer` DelegationCredential, in seconds.\n *\n * A credential with no `cnf` (holder-key) claim is a bearer credential:\n * whoever holds the bytes can use them. The HTTP binding therefore bounds it\n * at 900s, and key-bound remains the default and conformance floor. Raising\n * this hands out longer-lived ambient authority — the exact failure the\n * key-bound design removes — so it is a spec change, not a config knob.\n */\nexport const ATTESTED_BEARER_MAX_TTL_SECONDS = 900;\n","/**\n * Error Codes and Messages\n *\n * Standardized error codes and messages used across all packages\n */\n\n/**\n * Error Code Categories\n */\nexport const ERROR_CATEGORIES = {\n AUTH: 'AUTH',\n VALIDATION: 'VALIDATION',\n DETECTION: 'DETECTION',\n RATE_LIMIT: 'RATE_LIMIT',\n PERMISSION: 'PERMISSION',\n NETWORK: 'NETWORK',\n INTERNAL: 'INTERNAL',\n CONFIGURATION: 'CONFIGURATION',\n WASM: 'WASM',\n SESSION: 'SESSION',\n PIXEL: 'PIXEL',\n API: 'API',\n} as const;\n\n/**\n * Authentication Error Codes\n */\nexport const AUTH_ERRORS = {\n INVALID_API_KEY: 'AUTH_INVALID_API_KEY',\n EXPIRED_API_KEY: 'AUTH_EXPIRED_API_KEY',\n INVALID_TOKEN: 'AUTH_INVALID_TOKEN',\n EXPIRED_TOKEN: 'AUTH_EXPIRED_TOKEN',\n MISSING_CREDENTIALS: 'AUTH_MISSING_CREDENTIALS',\n UNAUTHORIZED: 'AUTH_UNAUTHORIZED',\n INVALID_PIXEL_ID: 'AUTH_INVALID_PIXEL_ID',\n INVALID_SECRET_KEY: 'AUTH_INVALID_SECRET_KEY',\n} as const;\n\n/**\n * Validation Error Codes\n */\nexport const VALIDATION_ERRORS = {\n INVALID_REQUEST: 'VALIDATION_INVALID_REQUEST',\n MISSING_REQUIRED_FIELD: 'VALIDATION_MISSING_REQUIRED_FIELD',\n INVALID_FIELD_TYPE: 'VALIDATION_INVALID_FIELD_TYPE',\n INVALID_FIELD_VALUE: 'VALIDATION_INVALID_FIELD_VALUE',\n FIELD_TOO_LONG: 'VALIDATION_FIELD_TOO_LONG',\n FIELD_TOO_SHORT: 'VALIDATION_FIELD_TOO_SHORT',\n INVALID_EMAIL: 'VALIDATION_INVALID_EMAIL',\n INVALID_URL: 'VALIDATION_INVALID_URL',\n INVALID_UUID: 'VALIDATION_INVALID_UUID',\n INVALID_IP_ADDRESS: 'VALIDATION_INVALID_IP_ADDRESS',\n INVALID_USER_AGENT: 'VALIDATION_INVALID_USER_AGENT',\n BAD_REQUEST: 'VALIDATION_BAD_REQUEST',\n INVALID_START_DATE: 'VALIDATION_INVALID_START_DATE',\n INVALID_END_DATE: 'VALIDATION_INVALID_END_DATE',\n INVALID_DATE_RANGE: 'VALIDATION_INVALID_DATE_RANGE',\n} as const;\n\n/**\n * Detection Error Codes\n */\nexport const DETECTION_ERRORS = {\n DETECTION_FAILED: 'DETECTION_FAILED',\n INSUFFICIENT_DATA: 'DETECTION_INSUFFICIENT_DATA',\n PATTERN_MATCH_FAILED: 'DETECTION_PATTERN_MATCH_FAILED',\n WASM_NOT_LOADED: 'DETECTION_WASM_NOT_LOADED',\n WASM_EXECUTION_FAILED: 'DETECTION_WASM_EXECUTION_FAILED',\n CONFIDENCE_BELOW_THRESHOLD: 'DETECTION_CONFIDENCE_BELOW_THRESHOLD',\n SIGNATURE_VERIFICATION_FAILED: 'DETECTION_SIGNATURE_VERIFICATION_FAILED',\n} as const;\n\n/**\n * Rate Limit Error Codes\n */\nexport const RATE_LIMIT_ERRORS = {\n RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',\n BURST_LIMIT_EXCEEDED: 'RATE_LIMIT_BURST_EXCEEDED',\n DAILY_LIMIT_EXCEEDED: 'RATE_LIMIT_DAILY_EXCEEDED',\n MONTHLY_LIMIT_EXCEEDED: 'RATE_LIMIT_MONTHLY_EXCEEDED',\n CONCURRENT_LIMIT_EXCEEDED: 'RATE_LIMIT_CONCURRENT_EXCEEDED',\n QUOTA_EXCEEDED: 'RATE_LIMIT_QUOTA_EXCEEDED',\n} as const;\n\n/**\n * Permission Error Codes\n */\nexport const PERMISSION_ERRORS = {\n INSUFFICIENT_PERMISSIONS: 'PERMISSION_INSUFFICIENT',\n RESOURCE_NOT_FOUND: 'PERMISSION_RESOURCE_NOT_FOUND',\n RESOURCE_ACCESS_DENIED: 'PERMISSION_ACCESS_DENIED',\n OPERATION_NOT_ALLOWED: 'PERMISSION_OPERATION_NOT_ALLOWED',\n PROJECT_ACCESS_DENIED: 'PERMISSION_PROJECT_ACCESS_DENIED',\n PIXEL_ACCESS_DENIED: 'PERMISSION_PIXEL_ACCESS_DENIED',\n FORBIDDEN: 'PERMISSION_FORBIDDEN',\n} as const;\n\n/**\n * Network Error Codes\n */\nexport const NETWORK_ERRORS = {\n CONNECTION_FAILED: 'NETWORK_CONNECTION_FAILED',\n TIMEOUT: 'NETWORK_TIMEOUT',\n DNS_RESOLUTION_FAILED: 'NETWORK_DNS_FAILED',\n SSL_ERROR: 'NETWORK_SSL_ERROR',\n PROXY_ERROR: 'NETWORK_PROXY_ERROR',\n UPSTREAM_ERROR: 'NETWORK_UPSTREAM_ERROR',\n} as const;\n\n/**\n * Internal Error Codes\n */\nexport const INTERNAL_ERRORS = {\n INTERNAL_SERVER_ERROR: 'INTERNAL_SERVER_ERROR',\n DATABASE_ERROR: 'INTERNAL_DATABASE_ERROR',\n CACHE_ERROR: 'INTERNAL_CACHE_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_CONFIGURATION_ERROR',\n INITIALIZATION_ERROR: 'INTERNAL_INITIALIZATION_ERROR',\n PROCESSING_ERROR: 'INTERNAL_PROCESSING_ERROR',\n UNKNOWN_ERROR: 'INTERNAL_UNKNOWN_ERROR',\n SERVICE_UNAVAILABLE_TRANSIENT: 'SERVICE_UNAVAILABLE_TRANSIENT',\n} as const;\n\n/**\n * Session Error Codes\n */\nexport const SESSION_ERRORS = {\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_EXPIRED: 'SESSION_EXPIRED',\n SESSION_INVALID: 'SESSION_INVALID',\n SESSION_CREATION_FAILED: 'SESSION_CREATION_FAILED',\n SESSION_UPDATE_FAILED: 'SESSION_UPDATE_FAILED',\n SESSION_STORAGE_ERROR: 'SESSION_STORAGE_ERROR',\n MAX_SESSIONS_EXCEEDED: 'SESSION_MAX_EXCEEDED',\n} as const;\n\n/**\n * Pixel Error Codes\n */\nexport const PIXEL_ERRORS = {\n PIXEL_NOT_FOUND: 'PIXEL_NOT_FOUND',\n PIXEL_DISABLED: 'PIXEL_DISABLED',\n PIXEL_CONFIGURATION_ERROR: 'PIXEL_CONFIGURATION_ERROR',\n PIXEL_DOMAIN_NOT_ALLOWED: 'PIXEL_DOMAIN_NOT_ALLOWED',\n PIXEL_PATH_SKIPPED: 'PIXEL_PATH_SKIPPED',\n PIXEL_EVENT_INVALID: 'PIXEL_EVENT_INVALID',\n PIXEL_BATCH_TOO_LARGE: 'PIXEL_BATCH_TOO_LARGE',\n MISSING_PIXEL_ID: 'MISSING_PIXEL_ID',\n DETECTION_STORAGE_FAILED: 'DETECTION_STORAGE_FAILED',\n} as const;\n\n/**\n * API Error Codes\n */\nexport const API_ERRORS = {\n ENDPOINT_NOT_FOUND: 'API_ENDPOINT_NOT_FOUND',\n METHOD_NOT_ALLOWED: 'API_METHOD_NOT_ALLOWED',\n VERSION_NOT_SUPPORTED: 'API_VERSION_NOT_SUPPORTED',\n CONTENT_TYPE_NOT_SUPPORTED: 'API_CONTENT_TYPE_NOT_SUPPORTED',\n RESPONSE_TOO_LARGE: 'API_RESPONSE_TOO_LARGE',\n REQUEST_TOO_LARGE: 'API_REQUEST_TOO_LARGE',\n} as const;\n\n/**\n * Billing Error Codes\n */\nexport const BILLING_ERRORS = {\n LIMIT_EXCEEDED: 'LIMIT_EXCEEDED',\n BILLING_SUSPENDED: 'BILLING_SUSPENDED',\n BILLING_GRACE_PERIOD: 'BILLING_GRACE_PERIOD',\n} as const;\n\n/**\n * Resource Error Codes\n */\nexport const RESOURCE_ERRORS = {\n CONFLICT: 'CONFLICT',\n PROJECT_NOT_FOUND: 'PROJECT_NOT_FOUND',\n REVIEW_REQUIRED: 'REVIEW_REQUIRED',\n} as const;\n\n/**\n * Policy Error Codes\n */\nexport const POLICY_ERRORS = {\n POLICY_FETCH_FAILED: 'POLICY_FETCH_FAILED',\n} as const;\n\n/**\n * Bare Error Codes\n *\n * Un-prefixed upper-case wire strings shared by several surfaces (pixel,\n * pixel/track, openclaw, deploy, shopify, bouncer). Keyed by value with a\n * BARE_ prefix so the key cannot collide with the prefixed groups.\n */\nexport const BARE_ERRORS = {\n BARE_VALIDATION_ERROR: 'VALIDATION_ERROR',\n BARE_INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\n/**\n * Lowercase Error Codes\n *\n * Lowercase wire strings are the SPEC-EVENTS wire format used by\n * /api/v1/kya-os/events and reused by the bouncer family. Keyed by value\n * with a LOWERCASE_ prefix.\n */\nexport const LOWERCASE_ERRORS = {\n LOWERCASE_INVALID_JSON: 'invalid_json',\n LOWERCASE_VALIDATION_ERROR: 'validation_error',\n} as const;\n\n/**\n * All Error Codes\n */\nexport const ERROR_CODES = {\n ...AUTH_ERRORS,\n ...VALIDATION_ERRORS,\n ...DETECTION_ERRORS,\n ...RATE_LIMIT_ERRORS,\n ...PERMISSION_ERRORS,\n ...NETWORK_ERRORS,\n ...INTERNAL_ERRORS,\n ...SESSION_ERRORS,\n ...PIXEL_ERRORS,\n ...API_ERRORS,\n ...BILLING_ERRORS,\n ...RESOURCE_ERRORS,\n ...POLICY_ERRORS,\n ...BARE_ERRORS,\n ...LOWERCASE_ERRORS,\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * Error Messages\n */\nexport const ERROR_MESSAGES: Record<ErrorCode, string> = {\n // Authentication\n [AUTH_ERRORS.INVALID_API_KEY]: 'The provided API key is invalid',\n [AUTH_ERRORS.EXPIRED_API_KEY]: 'The API key has expired',\n [AUTH_ERRORS.INVALID_TOKEN]: 'The provided token is invalid',\n [AUTH_ERRORS.EXPIRED_TOKEN]: 'The token has expired',\n [AUTH_ERRORS.MISSING_CREDENTIALS]: 'Authentication credentials are required',\n [AUTH_ERRORS.UNAUTHORIZED]: 'You are not authorized to perform this action',\n [AUTH_ERRORS.INVALID_PIXEL_ID]: 'The provided pixel ID is invalid',\n [AUTH_ERRORS.INVALID_SECRET_KEY]: 'The provided secret key is invalid',\n\n // Validation\n [VALIDATION_ERRORS.INVALID_REQUEST]: 'The request is invalid',\n [VALIDATION_ERRORS.MISSING_REQUIRED_FIELD]: 'A required field is missing',\n [VALIDATION_ERRORS.INVALID_FIELD_TYPE]: 'Field type is invalid',\n [VALIDATION_ERRORS.INVALID_FIELD_VALUE]: 'Field value is invalid',\n [VALIDATION_ERRORS.FIELD_TOO_LONG]: 'Field value exceeds maximum length',\n [VALIDATION_ERRORS.FIELD_TOO_SHORT]: 'Field value is below minimum length',\n [VALIDATION_ERRORS.INVALID_EMAIL]: 'Invalid email address format',\n [VALIDATION_ERRORS.INVALID_URL]: 'Invalid URL format',\n [VALIDATION_ERRORS.INVALID_UUID]: 'Invalid UUID format',\n [VALIDATION_ERRORS.INVALID_IP_ADDRESS]: 'Invalid IP address format',\n [VALIDATION_ERRORS.INVALID_USER_AGENT]: 'Invalid or missing user agent',\n [VALIDATION_ERRORS.BAD_REQUEST]: 'Bad request',\n [VALIDATION_ERRORS.INVALID_START_DATE]: 'Invalid request data',\n [VALIDATION_ERRORS.INVALID_END_DATE]: 'Invalid request data',\n [VALIDATION_ERRORS.INVALID_DATE_RANGE]: 'Invalid request data',\n\n // Detection\n [DETECTION_ERRORS.DETECTION_FAILED]: 'Agent detection failed',\n [DETECTION_ERRORS.INSUFFICIENT_DATA]: 'Insufficient data for detection',\n [DETECTION_ERRORS.PATTERN_MATCH_FAILED]: 'Pattern matching failed',\n [DETECTION_ERRORS.WASM_NOT_LOADED]: 'WASM module is not loaded',\n [DETECTION_ERRORS.WASM_EXECUTION_FAILED]: 'WASM execution failed',\n [DETECTION_ERRORS.CONFIDENCE_BELOW_THRESHOLD]: 'Detection confidence below threshold',\n [DETECTION_ERRORS.SIGNATURE_VERIFICATION_FAILED]: 'Signature verification failed',\n\n // Rate Limiting\n [RATE_LIMIT_ERRORS.RATE_LIMIT_EXCEEDED]: 'Rate limit exceeded',\n [RATE_LIMIT_ERRORS.BURST_LIMIT_EXCEEDED]: 'Burst limit exceeded',\n [RATE_LIMIT_ERRORS.DAILY_LIMIT_EXCEEDED]: 'Daily request limit exceeded',\n [RATE_LIMIT_ERRORS.MONTHLY_LIMIT_EXCEEDED]: 'Monthly request limit exceeded',\n [RATE_LIMIT_ERRORS.CONCURRENT_LIMIT_EXCEEDED]: 'Concurrent request limit exceeded',\n [RATE_LIMIT_ERRORS.QUOTA_EXCEEDED]: 'Account quota exceeded',\n\n // Permissions\n [PERMISSION_ERRORS.INSUFFICIENT_PERMISSIONS]: 'Insufficient permissions',\n [PERMISSION_ERRORS.RESOURCE_NOT_FOUND]: 'Resource not found',\n [PERMISSION_ERRORS.RESOURCE_ACCESS_DENIED]: 'Access to resource denied',\n [PERMISSION_ERRORS.OPERATION_NOT_ALLOWED]: 'Operation not allowed',\n [PERMISSION_ERRORS.PROJECT_ACCESS_DENIED]: 'Project access denied',\n [PERMISSION_ERRORS.PIXEL_ACCESS_DENIED]: 'Pixel access denied',\n [PERMISSION_ERRORS.FORBIDDEN]: 'Access denied',\n\n // Network\n [NETWORK_ERRORS.CONNECTION_FAILED]: 'Connection failed',\n [NETWORK_ERRORS.TIMEOUT]: 'Request timeout',\n [NETWORK_ERRORS.DNS_RESOLUTION_FAILED]: 'DNS resolution failed',\n [NETWORK_ERRORS.SSL_ERROR]: 'SSL/TLS error',\n [NETWORK_ERRORS.PROXY_ERROR]: 'Proxy error',\n [NETWORK_ERRORS.UPSTREAM_ERROR]: 'Upstream service error',\n\n // Internal\n [INTERNAL_ERRORS.INTERNAL_SERVER_ERROR]: 'Internal server error',\n [INTERNAL_ERRORS.DATABASE_ERROR]: 'Database error',\n [INTERNAL_ERRORS.CACHE_ERROR]: 'Cache error',\n [INTERNAL_ERRORS.CONFIGURATION_ERROR]: 'Configuration error',\n [INTERNAL_ERRORS.INITIALIZATION_ERROR]: 'Initialization error',\n [INTERNAL_ERRORS.PROCESSING_ERROR]: 'Processing error',\n [INTERNAL_ERRORS.UNKNOWN_ERROR]: 'An unknown error occurred',\n [INTERNAL_ERRORS.SERVICE_UNAVAILABLE_TRANSIENT]:\n 'A dependency is temporarily unavailable. Retry shortly.',\n\n // Session\n [SESSION_ERRORS.SESSION_NOT_FOUND]: 'Session not found',\n [SESSION_ERRORS.SESSION_EXPIRED]: 'Session has expired',\n [SESSION_ERRORS.SESSION_INVALID]: 'Session is invalid',\n [SESSION_ERRORS.SESSION_CREATION_FAILED]: 'Failed to create session',\n [SESSION_ERRORS.SESSION_UPDATE_FAILED]: 'Failed to update session',\n [SESSION_ERRORS.SESSION_STORAGE_ERROR]: 'Session storage error',\n [SESSION_ERRORS.MAX_SESSIONS_EXCEEDED]: 'Maximum sessions exceeded',\n\n // Pixel\n [PIXEL_ERRORS.PIXEL_NOT_FOUND]: 'Pixel not found',\n [PIXEL_ERRORS.PIXEL_DISABLED]: 'Pixel is disabled',\n [PIXEL_ERRORS.PIXEL_CONFIGURATION_ERROR]: 'Pixel configuration error',\n [PIXEL_ERRORS.PIXEL_DOMAIN_NOT_ALLOWED]: 'Domain not allowed for this pixel',\n [PIXEL_ERRORS.PIXEL_PATH_SKIPPED]: 'Path is configured to be skipped',\n [PIXEL_ERRORS.PIXEL_EVENT_INVALID]: 'Invalid pixel event',\n [PIXEL_ERRORS.PIXEL_BATCH_TOO_LARGE]: 'Event batch exceeds maximum size',\n [PIXEL_ERRORS.MISSING_PIXEL_ID]: 'Project ID is required',\n [PIXEL_ERRORS.DETECTION_STORAGE_FAILED]: 'Failed to store detection data',\n\n // API\n [API_ERRORS.ENDPOINT_NOT_FOUND]: 'API endpoint not found',\n [API_ERRORS.METHOD_NOT_ALLOWED]: 'HTTP method not allowed',\n [API_ERRORS.VERSION_NOT_SUPPORTED]: 'API version not supported',\n [API_ERRORS.CONTENT_TYPE_NOT_SUPPORTED]: 'Content type not supported',\n [API_ERRORS.RESPONSE_TOO_LARGE]: 'Response exceeds maximum size',\n [API_ERRORS.REQUEST_TOO_LARGE]: 'Request exceeds maximum size',\n\n // Billing\n [BILLING_ERRORS.LIMIT_EXCEEDED]: 'Billing limit exceeded',\n [BILLING_ERRORS.BILLING_SUSPENDED]: 'Account billing suspended',\n [BILLING_ERRORS.BILLING_GRACE_PERIOD]: 'Account in billing grace period',\n\n // Resources\n [RESOURCE_ERRORS.CONFLICT]: 'Resource conflict',\n [RESOURCE_ERRORS.PROJECT_NOT_FOUND]: 'Project not found',\n [RESOURCE_ERRORS.REVIEW_REQUIRED]:\n 'Deploy requires explicit confirmation of the consequential writes it will perform.',\n\n // Policy\n [POLICY_ERRORS.POLICY_FETCH_FAILED]: 'Failed to fetch policy',\n\n // Bare (un-prefixed, shared across pixel/openclaw/deploy/shopify/bouncer)\n [BARE_ERRORS.BARE_VALIDATION_ERROR]: 'Invalid request data',\n [BARE_ERRORS.BARE_INTERNAL_ERROR]: 'Internal server error',\n\n // Lowercase (kya-os events wire format)\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_JSON]: 'Request body must be valid JSON',\n [LOWERCASE_ERRORS.LOWERCASE_VALIDATION_ERROR]: 'Invalid request body',\n};\n\n/**\n * HTTP Status Codes for Errors\n */\nexport const ERROR_STATUS_CODES: Partial<Record<ErrorCode, number>> = {\n // 200 OK (billing grace period is a soft warning, not a failure)\n [BILLING_ERRORS.BILLING_GRACE_PERIOD]: 200,\n\n // 400 Bad Request\n [VALIDATION_ERRORS.INVALID_REQUEST]: 400,\n [VALIDATION_ERRORS.MISSING_REQUIRED_FIELD]: 400,\n [VALIDATION_ERRORS.INVALID_FIELD_TYPE]: 400,\n [VALIDATION_ERRORS.INVALID_FIELD_VALUE]: 400,\n [VALIDATION_ERRORS.BAD_REQUEST]: 400,\n [VALIDATION_ERRORS.INVALID_START_DATE]: 400,\n [VALIDATION_ERRORS.INVALID_END_DATE]: 400,\n [VALIDATION_ERRORS.INVALID_DATE_RANGE]: 400,\n [PIXEL_ERRORS.MISSING_PIXEL_ID]: 400,\n [BARE_ERRORS.BARE_VALIDATION_ERROR]: 400,\n [LOWERCASE_ERRORS.LOWERCASE_INVALID_JSON]: 400,\n [LOWERCASE_ERRORS.LOWERCASE_VALIDATION_ERROR]: 400,\n\n // 401 Unauthorized\n [AUTH_ERRORS.INVALID_API_KEY]: 401,\n [AUTH_ERRORS.EXPIRED_API_KEY]: 401,\n [AUTH_ERRORS.INVALID_TOKEN]: 401,\n [AUTH_ERRORS.EXPIRED_TOKEN]: 401,\n [AUTH_ERRORS.MISSING_CREDENTIALS]: 401,\n [AUTH_ERRORS.UNAUTHORIZED]: 401,\n\n // 402 Payment Required\n [BILLING_ERRORS.LIMIT_EXCEEDED]: 402,\n [BILLING_ERRORS.BILLING_SUSPENDED]: 402,\n\n // 403 Forbidden\n [PERMISSION_ERRORS.INSUFFICIENT_PERMISSIONS]: 403,\n [PERMISSION_ERRORS.RESOURCE_ACCESS_DENIED]: 403,\n [PERMISSION_ERRORS.OPERATION_NOT_ALLOWED]: 403,\n [PERMISSION_ERRORS.FORBIDDEN]: 403,\n\n // 404 Not Found\n [PERMISSION_ERRORS.RESOURCE_NOT_FOUND]: 404,\n [API_ERRORS.ENDPOINT_NOT_FOUND]: 404,\n [PIXEL_ERRORS.PIXEL_NOT_FOUND]: 404,\n [SESSION_ERRORS.SESSION_NOT_FOUND]: 404,\n\n // 405 Method Not Allowed\n [API_ERRORS.METHOD_NOT_ALLOWED]: 405,\n\n // 409 Conflict\n [RESOURCE_ERRORS.CONFLICT]: 409,\n\n // NOTE: RESOURCE_ERRORS.PROJECT_NOT_FOUND deliberately has no entry here.\n // The pixel API emits it with 400, while enforce and the policy\n // middleware emit it with 404. There is no single correct status, so it\n // stays unpinned and callers set their own status per surface. Locked by\n // a test in __tests__/errors.test.ts.\n\n // 413 Payload Too Large\n [API_ERRORS.REQUEST_TOO_LARGE]: 413,\n [PIXEL_ERRORS.PIXEL_BATCH_TOO_LARGE]: 413,\n\n // 415 Unsupported Media Type\n [API_ERRORS.CONTENT_TYPE_NOT_SUPPORTED]: 415,\n\n // 422 Unprocessable Entity\n [RESOURCE_ERRORS.REVIEW_REQUIRED]: 422,\n\n // 429 Too Many Requests\n [RATE_LIMIT_ERRORS.RATE_LIMIT_EXCEEDED]: 429,\n [RATE_LIMIT_ERRORS.BURST_LIMIT_EXCEEDED]: 429,\n [RATE_LIMIT_ERRORS.DAILY_LIMIT_EXCEEDED]: 429,\n\n // 500 Internal Server Error\n [INTERNAL_ERRORS.INTERNAL_SERVER_ERROR]: 500,\n [INTERNAL_ERRORS.DATABASE_ERROR]: 500,\n [INTERNAL_ERRORS.PROCESSING_ERROR]: 500,\n [PIXEL_ERRORS.DETECTION_STORAGE_FAILED]: 500,\n [POLICY_ERRORS.POLICY_FETCH_FAILED]: 500,\n [BARE_ERRORS.BARE_INTERNAL_ERROR]: 500,\n\n // 502 Bad Gateway\n [NETWORK_ERRORS.UPSTREAM_ERROR]: 502,\n\n // 503 Service Unavailable\n [INTERNAL_ERRORS.INITIALIZATION_ERROR]: 503,\n [INTERNAL_ERRORS.SERVICE_UNAVAILABLE_TRANSIENT]: 503,\n\n // 504 Gateway Timeout\n [NETWORK_ERRORS.TIMEOUT]: 504,\n};\n\n/**\n * Create a standardized error object\n */\nexport function createError(\n code: ErrorCode,\n details?: Record<string, unknown>,\n customMessage?: string\n) {\n return {\n code,\n message: customMessage || ERROR_MESSAGES[code] || 'An error occurred',\n statusCode: ERROR_STATUS_CODES[code] || 500,\n details,\n timestamp: new Date().toISOString(),\n };\n}\n","/**\n * Rate Limits and Plan Limits\n *\n * Defines limits for different subscription plans and API usage\n */\n\nimport { UserPlan } from '../types/entities';\n\n/**\n * Plan-based Rate Limits\n */\nexport const PLAN_RATE_LIMITS: Record<\n UserPlan,\n {\n requestsPerSecond: number;\n requestsPerMinute: number;\n requestsPerHour: number;\n requestsPerDay: number;\n requestsPerMonth: number;\n burstLimit: number;\n concurrentRequests: number;\n }\n> = {\n free: {\n requestsPerSecond: 1,\n requestsPerMinute: 20,\n requestsPerHour: 500,\n requestsPerDay: 1_000,\n requestsPerMonth: 10_000,\n burstLimit: 5,\n concurrentRequests: 2,\n },\n pro: {\n requestsPerSecond: 10,\n requestsPerMinute: 200,\n requestsPerHour: 5_000,\n requestsPerDay: 50_000,\n requestsPerMonth: 1_000_000,\n burstLimit: 20,\n concurrentRequests: 10,\n },\n enterprise: {\n requestsPerSecond: 100,\n requestsPerMinute: 2_000,\n requestsPerHour: 50_000,\n requestsPerDay: -1, // Unlimited\n requestsPerMonth: -1, // Unlimited\n burstLimit: 200,\n concurrentRequests: 100,\n },\n};\n\n/**\n * Plan-based Feature Limits\n */\nexport const PLAN_FEATURE_LIMITS: Record<\n UserPlan,\n {\n projects: number;\n pixelsPerProject: number;\n apiKeys: number;\n teamMembers: number;\n dataRetentionDays: number;\n customDomains: number;\n webhooks: number;\n alertRules: number;\n sessionsTracked: number;\n exportSizeLimit: number; // In MB\n organizations: number;\n }\n> = {\n free: {\n projects: 2,\n pixelsPerProject: 3,\n apiKeys: 2,\n teamMembers: 1,\n dataRetentionDays: 7,\n customDomains: 0,\n webhooks: 0,\n alertRules: 1,\n sessionsTracked: 1_000,\n exportSizeLimit: 10,\n organizations: 1,\n },\n pro: {\n projects: 10,\n pixelsPerProject: 20,\n apiKeys: 20,\n teamMembers: 5,\n dataRetentionDays: 90,\n customDomains: 3,\n webhooks: 5,\n alertRules: 10,\n sessionsTracked: 100_000,\n exportSizeLimit: 100,\n organizations: 5,\n },\n enterprise: {\n projects: -1, // Unlimited\n pixelsPerProject: -1, // Unlimited\n apiKeys: -1, // Unlimited\n teamMembers: -1, // Unlimited\n dataRetentionDays: 365,\n customDomains: -1, // Unlimited\n webhooks: -1, // Unlimited\n alertRules: -1, // Unlimited\n sessionsTracked: -1, // Unlimited\n exportSizeLimit: -1, // Unlimited\n organizations: -1, // Unlimited\n },\n};\n\n/**\n * API Request Limits\n */\nexport const API_REQUEST_LIMITS = {\n maxRequestBodySize: 10 * 1024 * 1024, // 10 MB\n maxResponseBodySize: 50 * 1024 * 1024, // 50 MB\n maxHeadersSize: 8 * 1024, // 8 KB\n maxUrlLength: 2048,\n maxQueryParams: 50,\n maxBatchSize: 100,\n maxFileUploadSize: 100 * 1024 * 1024, // 100 MB\n} as const;\n\n/**\n * Pixel Event Limits\n */\nexport const PIXEL_EVENT_LIMITS = {\n maxEventsPerBatch: 100,\n maxEventSize: 64 * 1024, // 64 KB per event\n maxMetadataSize: 16 * 1024, // 16 KB for metadata\n maxCustomDataFields: 50,\n maxSessionDuration: 24 * 60 * 60 * 1000, // 24 hours in ms\n maxPageViewsPerSession: 1000,\n maxInteractionsPerSession: 10000,\n eventQueueSize: 500,\n flushIntervalMin: 1000, // 1 second\n flushIntervalMax: 60000, // 60 seconds\n} as const;\n\n/**\n * Session Limits\n */\nexport const SESSION_LIMITS = {\n maxSessionsPerUser: 10,\n maxSessionsPerIp: 100,\n sessionTimeoutMin: 60, // 1 minute\n sessionTimeoutMax: 86400, // 24 hours\n idleTimeoutMin: 60, // 1 minute\n idleTimeoutMax: 7200, // 2 hours\n maxSessionDataSize: 64 * 1024, // 64 KB\n maxMetadataFields: 20,\n} as const;\n\n/**\n * Detection Limits\n */\nexport const DETECTION_LIMITS = {\n maxUserAgentLength: 1024,\n maxHeadersCount: 100,\n maxHeaderValueLength: 4096,\n maxIpAddressesPerRequest: 10,\n maxCustomRules: 100,\n maxPatternLength: 500,\n cacheSize: 10000,\n cacheTTL: 3600, // 1 hour in seconds\n maxConcurrentDetections: 1000,\n} as const;\n\n/**\n * Database Limits\n */\nexport const DATABASE_LIMITS = {\n maxQueryResults: 10000,\n maxBulkInsertSize: 1000,\n maxBulkUpdateSize: 500,\n maxBulkDeleteSize: 500,\n maxTransactionDuration: 30000, // 30 seconds\n maxConnectionPoolSize: 20,\n queryTimeout: 10000, // 10 seconds\n} as const;\n\n/**\n * Cache Limits\n */\nexport const CACHE_LIMITS = {\n maxCacheSize: 100 * 1024 * 1024, // 100 MB\n maxCacheEntries: 50000,\n maxKeyLength: 250,\n maxValueSize: 1 * 1024 * 1024, // 1 MB\n defaultTTL: 3600, // 1 hour\n maxTTL: 86400, // 24 hours\n} as const;\n\n/**\n * Webhook Limits\n */\nexport const WEBHOOK_LIMITS = {\n maxRetries: 3,\n retryDelayMs: [1000, 5000, 15000], // Exponential backoff\n requestTimeout: 10000, // 10 seconds\n maxPayloadSize: 256 * 1024, // 256 KB\n maxHeadersCount: 20,\n maxUrlLength: 2048,\n} as const;\n\n/**\n * Export Limits\n */\nexport const EXPORT_LIMITS = {\n maxCsvRows: 1000000,\n maxJsonSize: 100 * 1024 * 1024, // 100 MB\n maxExportDuration: 300000, // 5 minutes\n maxConcurrentExports: 3,\n exportRetentionDays: 7,\n} as const;\n\n/**\n * Security Limits\n */\nexport const SECURITY_LIMITS = {\n maxLoginAttempts: 5,\n lockoutDuration: 900, // 15 minutes in seconds\n passwordMinLength: 8,\n passwordMaxLength: 128,\n tokenLength: 32,\n apiKeyLength: 32,\n secretKeyLength: 64,\n otpLength: 6,\n otpValiditySeconds: 300, // 5 minutes\n maxActiveTokens: 10,\n} as const;\n\n/**\n * Performance Thresholds\n */\nexport const PERFORMANCE_THRESHOLDS = {\n slowQueryMs: 1000,\n slowApiCallMs: 3000,\n slowDetectionMs: 100,\n highMemoryUsageMB: 512,\n highCpuUsagePercent: 80,\n highDiskUsagePercent: 90,\n} as const;\n\n/**\n * Default Pagination\n */\nexport const PAGINATION_DEFAULTS = {\n defaultPageSize: 20,\n maxPageSize: 100,\n defaultOffset: 0,\n maxOffset: 100000,\n} as const;\n\n/**\n * Time Windows\n */\nexport const TIME_WINDOWS = {\n realtime: 60, // 1 minute\n hourly: 3600, // 1 hour\n daily: 86400, // 24 hours\n weekly: 604800, // 7 days\n monthly: 2592000, // 30 days\n yearly: 31536000, // 365 days\n} as const;\n\n/**\n * Helper function to check if a limit is exceeded\n */\nexport function isLimitExceeded(current: number, limit: number): boolean {\n if (limit === -1) return false; // Unlimited\n return current >= limit;\n}\n\n/**\n * Helper function to get remaining quota\n */\nexport function getRemainingQuota(used: number, limit: number): number {\n if (limit === -1) return Number.MAX_SAFE_INTEGER; // Unlimited\n return Math.max(0, limit - used);\n}\n\n/**\n * Helper function to calculate rate limit window\n */\nexport function getRateLimitWindow(windowType: keyof typeof TIME_WINDOWS): {\n start: Date;\n end: Date;\n duration: number;\n} {\n const now = new Date();\n const duration = TIME_WINDOWS[windowType] * 1000; // Convert to milliseconds\n const start = new Date(now.getTime() - duration);\n\n return {\n start,\n end: now,\n duration,\n };\n}\n","/**\n * Rule System Constants\n *\n * Configuration constants for the unified rule system\n */\n\n/**\n * Rule system version\n */\nexport const RULE_VERSION = '1.0.0';\n\n/**\n * Cache configuration\n */\nexport const RULE_CACHE = {\n /** Default cache duration in milliseconds */\n DEFAULT_DURATION: 3600000, // 1 hour\n /** Maximum cache duration */\n MAX_DURATION: 86400000, // 24 hours\n /** Minimum cache duration */\n MIN_DURATION: 60000, // 1 minute\n /** LocalStorage key for cached rules */\n STORAGE_KEY: 'agentshield_rules',\n /** LocalStorage key for cache timestamp */\n TIMESTAMP_KEY: 'agentshield_rules_timestamp',\n} as const;\n\n/**\n * CDN configuration for future use\n */\nexport const RULE_CDN = {\n /** Primary CDN endpoint */\n PRIMARY_URL: 'https://kya.vouched.id/rules/latest.json',\n /** Fallback CDN endpoint */\n FALLBACK_URL: 'https://rules.agentshield.io/latest.json',\n /** CDN request timeout */\n TIMEOUT: 5000,\n /** Retry attempts for CDN fetch */\n RETRY_ATTEMPTS: 3,\n /** Retry delay in milliseconds */\n RETRY_DELAY: 1000,\n} as const;\n\n/**\n * Rule validation modes\n */\nexport const VALIDATION_MODES = {\n /** Strict validation - all fields required */\n STRICT: 'strict',\n /** Loose validation - allow extra fields */\n LOOSE: 'loose',\n /** No validation - use with caution */\n NONE: 'none',\n} as const;\n\n/**\n * Rule categories\n */\nexport const RULE_CATEGORIES = {\n USER_AGENT: 'userAgent',\n IP_RANGE: 'ipRange',\n SIGNATURE: 'signature',\n BEHAVIORAL: 'behavioral',\n HEADER: 'header',\n} as const;\n\n/**\n * Confidence thresholds\n */\nexport const CONFIDENCE_THRESHOLDS = {\n /** Very high confidence */\n VERY_HIGH: 0.95,\n /** High confidence */\n HIGH: 0.8,\n /** Medium confidence */\n MEDIUM: 0.6,\n /** Low confidence */\n LOW: 0.4,\n /** Very low confidence */\n VERY_LOW: 0.2,\n} as const;\n\n/**\n * Rule update frequencies\n */\nexport const UPDATE_FREQUENCIES = {\n HOURLY: 'hourly',\n DAILY: 'daily',\n WEEKLY: 'weekly',\n MONTHLY: 'monthly',\n} as const;\n\n/**\n * Rule match actions\n *\n * @deprecated Dead internally as of the gateway-enforcement-step-up branch\n * (zero remaining callers repo-wide) — the doc comment claiming\n * `MATCH_ACTIONS.CHALLENGE` backs the worker's CAPTCHA/challenge action was\n * already stale (see `detection/types.ts`'s own \"Future - CAPTCHA or\n * proof-of-work\" note; the real challenge mechanism is\n * `@challenge_type`/`human_step_up`, unrelated to this enum). Kept\n * `@deprecated` rather than removed (bestbrian P2, 2026-09-09): this is a\n * wildcard-re-exported member of `@kya-os/checkpoint-shared`'s public\n * surface at 1.4.0, so deleting it outright is a breaking change for any\n * external consumer without a major version bump. Remove in the next\n * major.\n */\nexport const MATCH_ACTIONS = {\n /** Block the request */\n BLOCK: 'block',\n /** Allow but log */\n LOG: 'log',\n /** Challenge with CAPTCHA */\n CHALLENGE: 'challenge',\n /** Rate limit the client */\n RATE_LIMIT: 'rate_limit',\n /** Allow the request */\n ALLOW: 'allow',\n} as const;\n\n/**\n * Error messages\n */\nexport const RULE_ERRORS = {\n INVALID_FORMAT: 'Invalid rule format',\n VALIDATION_FAILED: 'Rule validation failed',\n LOAD_FAILED: 'Failed to load rules',\n PARSE_FAILED: 'Failed to parse rules',\n VERSION_MISMATCH: 'Rule version mismatch',\n MISSING_REQUIRED: 'Missing required rule fields',\n CDN_UNAVAILABLE: 'CDN rules unavailable',\n CACHE_EXPIRED: 'Cached rules expired',\n} as const;\n\n/**\n * Rule file paths\n */\nexport const RULE_PATHS = {\n /** Source YAML file */\n YAML_SOURCE: 'src/data/default-rules.yaml',\n /** Generated JSON file */\n JSON_OUTPUT: 'dist/rules.json',\n /** Bundled rules path */\n BUNDLED: '@kya-os/checkpoint-shared/dist/rules.json',\n} as const;\n","/**\n * Behavioral event types for detection\n */\n\nimport { z } from 'zod';\n\n/**\n * Mouse movement event\n */\nexport const MouseEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n type: z.enum(['move', 'click', 'down', 'up']).optional(),\n});\nexport type MouseEvent = z.infer<typeof MouseEventSchema>;\n\n/**\n * Keyboard event\n */\nexport const KeyboardEventSchema = z.object({\n keyCode: z.number(),\n key: z.string().optional(),\n timestamp: z.number(),\n type: z.enum(['keydown', 'keyup', 'keypress']).optional(),\n});\nexport type KeyboardEvent = z.infer<typeof KeyboardEventSchema>;\n\n/**\n * Scroll event\n */\nexport const ScrollEventSchema = z.object({\n deltaX: z.number().optional(),\n deltaY: z.number(),\n timestamp: z.number(),\n position: z\n .object({\n x: z.number(),\n y: z.number(),\n })\n .optional(),\n});\nexport type ScrollEvent = z.infer<typeof ScrollEventSchema>;\n\n/**\n * Click event with position\n */\nexport const ClickEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n button: z.enum(['left', 'right', 'middle']).optional(),\n target: z.string().optional(),\n});\nexport type ClickEvent = z.infer<typeof ClickEventSchema>;\n\n/**\n * Touch event for mobile devices\n */\nexport const TouchEventSchema = z.object({\n x: z.number(),\n y: z.number(),\n timestamp: z.number(),\n type: z.enum(['start', 'move', 'end', 'cancel']),\n identifier: z.number().optional(),\n});\nexport type TouchEvent = z.infer<typeof TouchEventSchema>;\n\n/**\n * Aggregated behavioral data\n */\nexport const BehavioralDataSchema = z.object({\n mouseMovements: z.array(MouseEventSchema).default([]),\n keyboardEvents: z.array(KeyboardEventSchema).default([]),\n scrollEvents: z.array(ScrollEventSchema).default([]),\n clickEvents: z.array(ClickEventSchema).default([]),\n touchEvents: z.array(TouchEventSchema).default([]),\n sessionDuration: z.number().optional(),\n pageViews: z.number().optional(),\n interactionRate: z.number().optional(),\n});\nexport type BehavioralData = z.infer<typeof BehavioralDataSchema>;\n\n/**\n * Behavioral analysis result\n */\nexport const BehavioralAnalysisSchema = z.object({\n isHumanLike: z.boolean(),\n confidence: z.number().min(0).max(1),\n patterns: z.array(z.string()),\n anomalies: z.array(z.string()).optional(),\n metrics: z\n .object({\n mouseEntropy: z.number().optional(),\n typingSpeed: z.number().optional(),\n scrollPattern: z.string().optional(),\n interactionComplexity: z.number().optional(),\n })\n .optional(),\n});\nexport type BehavioralAnalysis = z.infer<typeof BehavioralAnalysisSchema>;\n","/**\n * API request schemas\n */\n\nimport { z } from 'zod';\nimport { BehavioralDataSchema } from '../events/behavioral';\n\n/**\n * Detection API request\n */\nexport const DetectionRequestSchema = z.object({\n // Required fields\n userAgent: z.string(),\n\n // Optional fields\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n url: z.string().optional(),\n method: z.string().optional(),\n\n // Behavioral data\n behavioralData: BehavioralDataSchema.optional(),\n\n // Options\n options: z\n .object({\n mode: z.enum(['strict', 'balanced', 'lenient']).optional(),\n includeMetadata: z.boolean().optional(),\n includeBreakdown: z.boolean().optional(),\n })\n .optional(),\n\n // Request metadata\n requestId: z.string().optional(),\n timestamp: z.number().optional(),\n});\nexport type DetectionRequest = z.infer<typeof DetectionRequestSchema>;\n\n/**\n * Batch detection request\n */\nexport const BatchDetectionRequestSchema = z.object({\n requests: z.array(DetectionRequestSchema).min(1),\n options: z\n .object({\n parallel: z.boolean().default(true),\n continueOnError: z.boolean().default(true),\n })\n .default({\n parallel: true,\n continueOnError: true,\n }),\n});\nexport type BatchDetectionRequest = z.infer<typeof BatchDetectionRequestSchema>;\n\n/**\n * Verification request\n */\nexport const VerificationRequestSchema = z.object({\n signature: z.string(),\n payload: z.string(),\n timestamp: z.number(),\n publicKey: z.string().optional(),\n});\nexport type VerificationRequest = z.infer<typeof VerificationRequestSchema>;\n\n/**\n * Pattern update request\n */\nexport const PatternUpdateRequestSchema = z.object({\n patterns: z\n .array(\n z.object({\n id: z.string(),\n name: z.string(),\n pattern: z.string(),\n type: z.string(),\n enabled: z.boolean(),\n })\n )\n .min(1),\n action: z.enum(['add', 'update', 'remove', 'replace']),\n});\nexport type PatternUpdateRequest = z.infer<typeof PatternUpdateRequestSchema>;\n","/**\n * API response schemas\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\nimport { ConfidenceBreakdownSchema } from '../core/confidence';\nimport { BehavioralAnalysisSchema } from '../events/behavioral';\n\n/**\n * Standard API response wrapper\n */\nexport const ApiResponseSchema = z.object({\n success: z.boolean(),\n data: z.any().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n details: z.any().optional(),\n })\n .optional(),\n metadata: z\n .object({\n timestamp: z.number(),\n requestId: z.string().optional(),\n /**\n * Canonical 32-hex correlation id (`deriveCorrelationId`), for\n * cross-surface correlation independent of the per-call `requestId`\n * above. Also echoed as the `X-KYA-Correlation-Id` response header on\n * routes that derive one.\n */\n correlationId: z.string().optional(),\n version: z.string().optional(),\n })\n .optional(),\n});\nexport type ApiResponse<T = unknown> = Omit<z.infer<typeof ApiResponseSchema>, 'data'> & {\n data?: T;\n};\n\n/**\n * Detection API response\n */\nexport const DetectionResponseSchema = z.object({\n result: DetectionResultSchema,\n breakdown: ConfidenceBreakdownSchema.optional(),\n behavioralAnalysis: BehavioralAnalysisSchema.optional(),\n metadata: z\n .object({\n processingTime: z.number(),\n wasmUsed: z.boolean().optional(),\n cacheHit: z.boolean().optional(),\n })\n .optional(),\n});\nexport type DetectionResponse = z.infer<typeof DetectionResponseSchema>;\n\n/**\n * Batch detection response\n */\nexport const BatchDetectionResponseSchema = z.object({\n results: z.array(\n z.object({\n index: z.number(),\n success: z.boolean(),\n result: DetectionResultSchema.optional(),\n error: z.string().optional(),\n })\n ),\n summary: z.object({\n total: z.number(),\n successful: z.number(),\n failed: z.number(),\n agentsDetected: z.number(),\n }),\n});\nexport type BatchDetectionResponse = z.infer<typeof BatchDetectionResponseSchema>;\n\n/**\n * Verification response\n */\nexport const VerificationResponseSchema = z.object({\n valid: z.boolean(),\n algorithm: z.string().optional(),\n timestamp: z.number(),\n message: z.string().optional(),\n});\nexport type VerificationResponse = z.infer<typeof VerificationResponseSchema>;\n\n/**\n * Health check response\n */\nexport const HealthResponseSchema = z.object({\n status: z.enum(['healthy', 'degraded', 'unhealthy']),\n version: z.string(),\n uptime: z.number().min(0),\n checks: z\n .record(\n z.string(),\n z.object({\n status: z.enum(['pass', 'fail']),\n message: z.string().optional(),\n })\n )\n .optional(),\n});\nexport type HealthResponse = z.infer<typeof HealthResponseSchema>;\n\n/**\n * Statistics response\n */\nexport const StatsResponseSchema = z.object({\n totalRequests: z.number().min(0),\n agentsDetected: z.number().min(0),\n detectionRate: z.number().min(0).max(1),\n averageConfidence: z.number().min(0).max(1),\n topAgents: z.array(\n z.object({\n type: z.string(),\n count: z.number().min(0),\n percentage: z.number().min(0).max(100),\n })\n ),\n timeRange: z.object({\n start: z.number(),\n end: z.number(),\n }),\n});\nexport type StatsResponse = z.infer<typeof StatsResponseSchema>;\n","/**\n * Pixel Tracking Types\n *\n * Types for pixel-based agent detection and event tracking\n * Used by the pixel script, API endpoints, and dashboard\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\nimport { callbackSchema } from '../utils/zod-helpers';\n\n/**\n * Pixel Event Types\n */\nexport const PixelEventTypeSchema = z.enum([\n 'pageview',\n 'detection',\n 'interaction',\n 'error',\n 'session_start',\n 'session_end',\n 'custom',\n]);\nexport type PixelEventType = z.infer<typeof PixelEventTypeSchema>;\n\n/**\n * Browser Information\n */\nexport const BrowserInfoSchema = z.object({\n name: z.string().optional(),\n version: z.string().optional(),\n platform: z.string().optional(),\n mobile: z.boolean().default(false),\n language: z.string().optional(),\n cookiesEnabled: z.boolean().optional(),\n doNotTrack: z.boolean().optional(),\n plugins: z.array(z.string()).optional(),\n});\nexport type BrowserInfo = z.infer<typeof BrowserInfoSchema>;\n\n/**\n * Page Context\n */\nexport const PageContextSchema = z.object({\n url: z.string().url(),\n title: z.string().optional(),\n referrer: z.string().optional(),\n path: z.string(),\n hostname: z.string(),\n protocol: z.string(),\n search: z.string().optional(),\n hash: z.string().optional(),\n});\nexport type PageContext = z.infer<typeof PageContextSchema>;\n\n/**\n * Behavioral Signals\n */\nexport const BehavioralSignalsSchema = z.object({\n mouseMovements: z.number().int().min(0).default(0),\n clicks: z.number().int().min(0).default(0),\n scrollEvents: z.number().int().min(0).default(0),\n keyPresses: z.number().int().min(0).default(0),\n touchEvents: z.number().int().min(0).default(0),\n timeOnPage: z.number().min(0).default(0),\n interactionRate: z.number().min(0).max(1).default(0),\n scrollDepth: z.number().min(0).max(100).default(0),\n isAutomated: z.boolean().optional(),\n});\nexport type BehavioralSignals = z.infer<typeof BehavioralSignalsSchema>;\n\n/**\n * Core Pixel Event\n */\nexport const PixelEventSchema = z.object({\n // Event Identification\n id: z.string().uuid(),\n pixelId: z.string(),\n sessionId: z.string(),\n eventType: PixelEventTypeSchema,\n\n // Timing\n timestamp: z.union([z.string(), z.date()]),\n clientTimestamp: z.union([z.string(), z.date()]).optional(),\n\n // Context\n page: PageContextSchema,\n browser: BrowserInfoSchema.optional(),\n\n // Request Information\n userAgent: z.string(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n\n // Detection Results\n detection: DetectionResultSchema.optional(),\n\n // Behavioral Data\n behavioral: BehavioralSignalsSchema.optional(),\n\n // Custom Data\n metadata: z.record(z.string(), z.unknown()).optional(),\n customEventName: z.string().optional(),\n});\nexport type PixelEvent = z.infer<typeof PixelEventSchema>;\n\n/**\n * Batch Event Request\n */\nexport const BatchPixelEventRequestSchema = z.object({\n pixelId: z.string(),\n secretKey: z.string().optional(),\n events: z.array(PixelEventSchema).min(1).max(100),\n compressed: z.boolean().default(false),\n});\nexport type BatchPixelEventRequest = z.infer<typeof BatchPixelEventRequestSchema>;\n\n/**\n * Pixel Installation Config\n */\nexport const PixelInstallConfigSchema = z.object({\n pixelId: z.string(),\n endpoint: z.string().url().default('https://api.agentshield.ai/v1/pixel'),\n\n // Tracking Options\n autoTrack: z.boolean().default(true),\n trackPageviews: z.boolean().default(true),\n trackDetections: z.boolean().default(true),\n trackBehavior: z.boolean().default(false),\n\n // Performance Options\n batchEvents: z.boolean().default(true),\n batchSize: z.number().min(1).max(100).default(10),\n flushInterval: z.number().min(1000).max(60000).default(5000),\n\n // Privacy Options\n respectDoNotTrack: z.boolean().default(true),\n anonymizeIp: z.boolean().default(false),\n\n // Session Options\n sessionTimeout: z.number().min(60000).default(1800000), // 30 minutes\n sessionCookieName: z.string().default('_as_session'),\n\n // Debug Options\n debug: z.boolean().default(false),\n logLevel: z.enum(['error', 'warn', 'info', 'debug']).default('error'),\n});\nexport type PixelInstallConfig = z.infer<typeof PixelInstallConfigSchema>;\n\n/**\n * Pixel Script Initialization\n */\nexport const PixelInitSchema = z.object({\n config: PixelInstallConfigSchema,\n onReady: callbackSchema.optional(),\n onError: callbackSchema.optional(),\n onDetection: callbackSchema.optional(),\n});\nexport type PixelInit = z.infer<typeof PixelInitSchema>;\n\n/**\n * Client Detection Data Schema\n * Data collected by the checkpoint-detector.js module\n */\nexport const ClientDetectionSchema = z.object({\n // Critical Perplexity detection signals\n headless: z.boolean().optional(),\n canvas: z.string().optional(),\n webrtc: z.string().optional(),\n plugins: z.number().optional(),\n automation: z.string().nullable().optional(),\n\n // Browser characteristics\n chrome: z.boolean().optional(),\n languages: z.array(z.string()).optional(),\n hardwareConcurrency: z.number().nullable().optional(),\n deviceMemory: z.number().nullable().optional(),\n maxTouchPoints: z.number().optional(),\n platform: z.string().optional(),\n vendor: z.string().optional(),\n screenResolution: z.string().optional(),\n colorDepth: z.number().optional(),\n pixelRatio: z.number().optional(),\n timezone: z.string().optional(),\n timezoneOffset: z.number().optional(),\n cookieEnabled: z.boolean().optional(),\n localStorage: z.boolean().optional(),\n sessionStorage: z.boolean().optional(),\n doNotTrack: z.string().nullable().optional(),\n hasTouch: z.boolean().optional(),\n\n // Interaction metrics\n mouseMovements: z.number().optional(),\n keyboardEvents: z.number().optional(),\n scrollEvents: z.number().optional(),\n clickEvents: z.number().optional(),\n touchEvents: z.number().optional(),\n // Input events dispatched with isTrusted:false (synthetic script/extension\n // input, never real hardware). Provenance signal for content-script agent\n // drivers — see human-promotion-audit.untrustedInputShare.\n untrustedEvents: z.number().optional(),\n // Timing physics, counters only (checkpoint-detector.js). Bucket edges sit\n // below the floor a hand showed on the lab gauntlet; the server derives\n // shares and means (lib/detection/timing-physics.ts). No timestamps,\n // coordinates, or key identity ever ride here. `timingVersion` names the\n // detector's guard set (IME, modifier, multi-touch skips) so rows from\n // different sets can be told apart at calibration.\n timingVersion: z.number().optional(),\n keyDwellCount: z.number().optional(),\n keyDwellUnder5: z.number().optional(),\n keyDwellSumMs: z.number().optional(),\n keyGapCount: z.number().optional(),\n keyGapUnder5: z.number().optional(),\n pressCount: z.number().optional(),\n pressAdjacencyCount: z.number().int().nonnegative().optional(),\n pressAdjacentUnder5: z.number().int().nonnegative().optional(),\n pressUnder10: z.number().optional(),\n pressSumMs: z.number().optional(),\n mouseClicks: z.number().optional(),\n zeroTrailClicks: z.number().optional(),\n // Path kinematics, counters only (checkpoint-detector.js), for the driver\n // that manufactures a hand's timing: coalesced samples per pointermove,\n // and whether consecutive steps repeat their length or their heading.\n // Mouse pointer only; no coordinate rides here. `kinematicsVersion` names\n // the rule set (tolerances, pointer filter) the way `timingVersion` does.\n kinematicsVersion: z.number().optional(),\n pointerMoves: z.number().optional(),\n coalescedMoves: z.number().optional(),\n stepPairs: z.number().optional(),\n equalSteps: z.number().optional(),\n straightSteps: z.number().optional(),\n hasInteraction: z.boolean().optional(),\n\n // Connection info\n connection: z\n .object({\n effectiveType: z.string().optional(),\n rtt: z.number().optional(),\n downlink: z.number().optional(),\n saveData: z.boolean().optional(),\n })\n .nullable()\n .optional(),\n\n // Performance metrics\n performance: z\n .object({\n navigation: z.number().nullable().optional(),\n memory: z\n .object({\n usedJSHeapSize: z.number().optional(),\n totalJSHeapSize: z.number().optional(),\n jsHeapSizeLimit: z.number().optional(),\n })\n .optional(),\n })\n .nullable()\n .optional(),\n\n // Collection metadata\n collectionTime: z.number().optional(),\n timestamp: z.string().optional(),\n error: z.string().optional(),\n});\nexport type ClientDetection = z.infer<typeof ClientDetectionSchema>;\n\n/**\n * Pixel Tracking Request - Simplified request from pixel beacon\n * Used by the POST /api/v1/pixel endpoint\n */\nexport const PixelTrackingRequestSchema = z.object({\n // Pixel identification\n pixelId: z.string(), // UUID of the pixel\n sessionId: z.string(), // Session identifier\n\n // User identification\n userId: z.string().nullable().optional(), // Identified user ID\n // Prior (typically anonymous) user id for an `identify` alias. When present\n // and different from `userId`, the server COPIES older properties from this\n // profile onto the newly-identified one (properties are never merged across\n // profiles automatically). Mirrors the analytics-SDK `identify(previousId)` arg.\n previousId: z.string().optional(),\n userTraits: z\n .record(z.string(), z.unknown())\n .optional() // User properties/traits\n .refine((traits) => !traits || JSON.stringify(traits).length < 10000, {\n message: 'User traits too large (max 10KB)',\n })\n .refine((traits) => !traits || Object.keys(traits).length < 50, {\n message: 'Too many user trait properties (max 50)',\n })\n .refine(\n (traits) => {\n // Validate trait value types - prevent nested objects that are too deep\n if (!traits) return true;\n const validateDepth = (obj: unknown, depth = 0): boolean => {\n if (depth > 3) return false; // Max nesting depth of 3\n if (typeof obj !== 'object' || obj === null) return true;\n return Object.values(obj as Record<string, unknown>).every((val) =>\n validateDepth(val, depth + 1)\n );\n };\n return validateDepth(traits);\n },\n {\n message: 'User traits contain overly nested objects (max depth 3)',\n }\n ),\n\n // Page context\n url: z.string().url(), // Current page URL\n referrer: z.string().optional(), // Referrer URL\n title: z.string().optional(), // Page title\n\n // Detection data\n userAgent: z.string(), // Browser user agent\n headers: z.record(z.string(), z.string()).optional(), // Any additional headers\n\n // Client info\n screenResolution: z.string().optional(), // \"1920x1080\"\n viewport: z.string().optional(), // \"1200x800\"\n timezone: z.string().optional(), // \"America/New_York\"\n language: z.string().optional(), // \"en-US\"\n platform: z.string().optional(), // navigator.platform\n cookiesEnabled: z.boolean().optional(), // navigator.cookieEnabled\n onLine: z.boolean().optional(), // navigator.onLine\n timezoneOffset: z.number().optional(), // Date.getTimezoneOffset()\n connectionType: z.string().optional(), // navigator.connection.effectiveType\n connectionSpeed: z.number().optional(), // navigator.connection.downlink\n\n // Device identity — cross-subdomain cookie set by pixel.js\n deviceId: z.string().optional(),\n\n // Behavioral (if available)\n timeOnPage: z.number().optional(), // Milliseconds\n mouseMovements: z.number().optional(), // Count of mouse events\n clickCount: z.number().optional(), // Number of clicks\n scrollDepth: z.number().optional(), // Percentage 0-100\n pageLoadTime: z.number().optional(), // performance.timing load duration, ms\n domContentLoadedTime: z.number().optional(), // performance.timing DCL duration, ms\n\n // Client-side detection data (NEW)\n clientDetection: ClientDetectionSchema.optional(),\n\n // Request tracking (client-provided, will be validated server-side)\n requestId: z.string().optional(), // Unique request ID for deduplication\n correlationId: z.string().optional(), // Cross-surface correlation id (validated/normalized server-side)\n\n // Event type for special events\n eventType: z.string().optional(), // 'pageview', 'identify', 'logout', etc.\n\n // Metadata\n timestamp: z.string(), // ISO 8601\n version: z.string().optional(), // Pixel version\n\n // Nonce-bound ingest: the value from the PRIOR 202 response's `nonce`\n // field (see `lib/services/nonce.service.ts` in apps/web). Absent on the\n // first pixel hit of a session; absent, stale, or mismatched on any\n // later hit is a forgery signal, never a 400 — a forged hit is accepted\n // for storage but tagged, not rejected.\n nonce: z.string().max(64).optional(),\n // Declares this client stores and echoes the nonce it's handed (the\n // pixel script always sends `true`; absent means a cached pre-upgrade\n // copy of pixel.js, never something a client turns off) — see\n // `nonce.service.ts`'s missing-nonce rule for why the distinction matters.\n nonceEcho: z.boolean().optional(),\n binding: z.string().max(128).optional(),\n\n // IP anonymization (build item 6). Default false, unlike beacon: Tier 2\n // vendor-IP corroboration needs the full address for pixel traffic — see\n // the pixel route's own doc comment.\n anonymizeIp: z.boolean().optional(),\n});\nexport type PixelTrackingRequest = z.infer<typeof PixelTrackingRequestSchema>;\n\n/**\n * Internal Processing Flags (server-side only, not exposed to client)\n */\nexport const InternalProcessingFlagsSchema = z.object({\n edgeProcessed: z.boolean().optional(), // Request was handled by Edge endpoint\n skipDatabaseWrite: z.boolean().optional(), // Skip DB write for low-value detections\n serverRequestId: z.string().optional(), // Server-generated request ID\n});\nexport type InternalProcessingFlags = z.infer<typeof InternalProcessingFlagsSchema>;\n\n/**\n * Pixel Tracking Response\n */\nexport const PixelTrackingResponseSchema = z.object({\n success: z.boolean(),\n eventId: z.string().uuid().optional(),\n sessionId: z.string().optional(),\n detection: DetectionResultSchema.optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n // Nonce-bound ingest: echo this back as `nonce` on the NEXT pixel hit —\n // see `PixelTrackingRequestSchema`'s `nonce` field doc comment.\n nonce: z.string().max(64).optional(),\n});\nexport type PixelTrackingResponse = z.infer<typeof PixelTrackingResponseSchema>;\n\n/**\n * Pixel Analytics Data\n */\nexport const PixelAnalyticsSchema = z.object({\n pixelId: z.string(),\n period: z.object({\n start: z.date(),\n end: z.date(),\n }),\n metrics: z.object({\n totalEvents: z.number().int().min(0),\n uniqueSessions: z.number().int().min(0),\n agentsDetected: z.number().int().min(0),\n humanVisitors: z.number().int().min(0),\n detectionRate: z.number().min(0).max(1),\n averageConfidence: z.number().min(0).max(1),\n averageSessionDuration: z.number().min(0),\n bounceRate: z.number().min(0).max(1),\n }),\n topAgents: z.array(\n z.object({\n type: z.string(),\n count: z.number().int().min(0),\n percentage: z.number().min(0).max(1),\n })\n ),\n topPages: z.array(\n z.object({\n path: z.string(),\n views: z.number().int().min(0),\n agentViews: z.number().int().min(0),\n })\n ),\n hourlyDistribution: z.array(\n z.object({\n hour: z.number().int().min(0).max(23),\n events: z.number().int().min(0),\n })\n ),\n});\nexport type PixelAnalytics = z.infer<typeof PixelAnalyticsSchema>;\n\n/**\n * Pixel Session Data\n */\nexport const PixelSessionSchema = z.object({\n id: z.string(),\n pixelId: z.string(),\n startTime: z.date(),\n endTime: z.date().optional(),\n duration: z.number().min(0),\n pageViews: z.number().int().min(0),\n events: z.number().int().min(0),\n isAgent: z.boolean(),\n confidence: z.number().min(0).max(1).optional(),\n agentType: z.string().optional(),\n ipAddress: z.string().optional(),\n userAgent: z.string().optional(),\n referrer: z.string().optional(),\n entryPage: z.string().optional(),\n exitPage: z.string().optional(),\n behavioral: BehavioralSignalsSchema.optional(),\n});\nexport type PixelSession = z.infer<typeof PixelSessionSchema>;\n\n/**\n * Pixel Verification Status\n */\nexport const PixelVerificationStatusSchema = z.object({\n status: z.enum(['verified', 'partial', 'pending', 'failed']),\n message: z.string(),\n verified: z.boolean(),\n lastDetection: z.date().nullable(),\n detectionCount: z.number().int().min(0),\n metadata: z\n .object({\n recentDetections: z.number().int().min(0),\n failedDetections: z.number().int().min(0),\n timeWindow: z.string(),\n })\n .optional(),\n});\nexport type PixelVerificationStatus = z.infer<typeof PixelVerificationStatusSchema>;\n\n/**\n * User Identification Event\n */\nexport const PixelUserIdentificationSchema = z.object({\n userId: z.string(),\n traits: z\n .record(z.string(), z.unknown())\n .optional()\n .refine((traits) => !traits || JSON.stringify(traits).length < 10000, {\n message: 'User traits too large (max 10KB)',\n })\n .refine((traits) => !traits || Object.keys(traits).length < 50, {\n message: 'Too many user trait properties (max 50)',\n }),\n email: z.string().email().optional(),\n name: z.string().optional(),\n plan: z.string().optional(),\n company: z.string().optional(),\n timestamp: z.string(),\n});\nexport type PixelUserIdentification = z.infer<typeof PixelUserIdentificationSchema>;\n\n/**\n * Detection View Type\n */\nexport const DetectionViewTypeSchema = z.enum(['verification', 'list']);\nexport type DetectionViewType = z.infer<typeof DetectionViewTypeSchema>;\n\n/**\n * Detection Status\n */\nexport const DetectionStatusSchema = z.enum(['success', 'partial', 'failed', 'error']);\nexport type DetectionStatus = z.infer<typeof DetectionStatusSchema>;\n\n/**\n * Detection Error Details\n */\nexport const DetectionErrorDetailsSchema = z.object({\n type: z.enum(['wasm_failed', 'fallback_failed', 'both_failed']),\n message: z.string(),\n retryable: z.boolean(),\n});\nexport type DetectionErrorDetails = z.infer<typeof DetectionErrorDetailsSchema>;\n","/**\n * Event API schemas for tracking and batch processing\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\nimport { BehavioralDataSchema } from '../events/behavioral';\nimport { ClientDetectionSchema } from '../types/pixel';\nimport { ipAddressSchema } from '../utils/zod-helpers';\n\n/**\n * Single Event Tracking Request\n */\nexport const EventTrackingRequestSchema = z.object({\n // Required fields\n pixelId: z.string().uuid(),\n sessionId: z.string().min(1).max(255),\n url: z.string().url(),\n userAgent: z.string().min(1).max(1024),\n\n // Optional fields\n ip: ipAddressSchema.optional(),\n timestamp: z.string().datetime().optional(),\n referrer: z.string().url().optional(),\n method: z.enum(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']).optional(),\n\n // Headers for additional context\n headers: z.record(z.string(), z.string()).optional(),\n\n // Behavioral tracking data\n behavioralData: BehavioralDataSchema.optional(),\n\n // Client-side browser fingerprint (headless/automation tells, interaction).\n // Optional + additive: legacy clients that omit it are unaffected.\n clientDetection: ClientDetectionSchema.optional(),\n\n // Page metrics\n timeOnPage: z.number().min(0).optional(),\n scrollDepth: z.number().min(0).max(100).optional(),\n clickCount: z.number().min(0).optional(),\n mouseMovements: z.number().min(0).optional(),\n keystrokes: z.number().min(0).optional(),\n\n // Device/viewport info\n screenResolution: z.string().optional(),\n viewport: z.string().optional(),\n\n // Custom metadata\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type EventTrackingRequest = z.infer<typeof EventTrackingRequestSchema>;\n\n/**\n * Single Event Tracking Response\n */\nexport const EventTrackingResponseSchema = z.object({\n success: z.boolean(),\n eventId: z.string().uuid(),\n sessionId: z.string(),\n detection: DetectionResultSchema,\n\n // Rate limit info\n rateLimit: z\n .object({\n limit: z.number(),\n remaining: z.number(),\n reset: z.number(),\n })\n .optional(),\n\n // Debug info (only in development)\n debug: z\n .object({\n processingTime: z.number(),\n rulesVersion: z.string(),\n serverRegion: z.string().optional(),\n cacheHit: z.boolean().optional(),\n })\n .optional(),\n});\nexport type EventTrackingResponse = z.infer<typeof EventTrackingResponseSchema>;\n\n/**\n * Batch Event Request\n */\nexport const BatchEventRequestSchema = z.object({\n // API key for authentication (required for batch)\n apiKey: z.string().min(32).optional(), // Can be in header instead\n\n // Array of events (max 100)\n events: z.array(EventTrackingRequestSchema).min(1).max(100),\n\n // Processing options\n options: z\n .object({\n parallel: z.boolean().default(true),\n continueOnError: z.boolean().default(true),\n includeDetailed: z.boolean().default(false),\n })\n .optional(),\n});\nexport type BatchEventRequest = z.infer<typeof BatchEventRequestSchema>;\n\n/**\n * Batch Event Response\n */\nexport const BatchEventResponseSchema = z.object({\n success: z.boolean(),\n batchId: z.string().uuid(),\n\n // Processing results\n results: z.array(\n z.object({\n index: z.number(),\n eventId: z.string().uuid().optional(),\n success: z.boolean(),\n detection: DetectionResultSchema.optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n })\n ),\n\n // Summary statistics\n summary: z.object({\n total: z.number(),\n successful: z.number(),\n failed: z.number(),\n agentsDetected: z.number(),\n averageConfidence: z.number().min(0).max(1),\n processingTime: z.number(),\n }),\n\n // Rate limit info\n rateLimit: z\n .object({\n limit: z.number(),\n remaining: z.number(),\n reset: z.number(),\n })\n .optional(),\n});\nexport type BatchEventResponse = z.infer<typeof BatchEventResponseSchema>;\n\n/**\n * Event Storage Record (for database)\n */\nexport const EventStorageRecordSchema = z.object({\n id: z.string().uuid(),\n pixelId: z.string().uuid(),\n projectId: z.string().uuid(),\n sessionId: z.string(),\n\n // Request data\n url: z.string(),\n userAgent: z.string(),\n ipAddress: z.string().optional(),\n referrer: z.string().optional(),\n\n // Detection results\n isAgent: z.boolean(),\n confidence: z.number().min(0).max(1),\n agentType: z.string().optional(),\n detectionMethod: z.array(z.string()).optional(),\n\n // Behavioral metrics\n timeOnPage: z.number().optional(),\n scrollDepth: z.number().optional(),\n clickCount: z.number().optional(),\n\n // Metadata\n metadata: z.record(z.string(), z.unknown()).optional(),\n\n // Timestamps\n createdAt: z.date(),\n processedAt: z.date(),\n});\nexport type EventStorageRecord = z.infer<typeof EventStorageRecordSchema>;\n","/**\n * Signature Verification API schemas\n *\n * Used for verifying signatures from AI agents like ChatGPT\n */\n\nimport { z } from 'zod';\n\n/**\n * Supported signature algorithms\n */\nexport const SignatureAlgorithmSchema = z.enum([\n 'RS256',\n 'RS384',\n 'RS512',\n 'ES256',\n 'ES384',\n 'ES512',\n 'HS256',\n 'HS384',\n 'HS512',\n]);\nexport type SignatureAlgorithm = z.infer<typeof SignatureAlgorithmSchema>;\n\n/**\n * Agent verification provider\n */\nexport const VerificationProviderSchema = z.enum([\n 'chatgpt',\n 'claude',\n 'gemini',\n 'perplexity',\n 'custom',\n]);\nexport type VerificationProvider = z.infer<typeof VerificationProviderSchema>;\n\n/**\n * Signature Verification Request\n */\nexport const SignatureVerificationRequestSchema = z.object({\n // Signature to verify (from header)\n signature: z.string().min(1),\n\n // Payload that was signed\n payload: z.string().optional(),\n\n // Timestamp of signature\n timestamp: z.number().optional(),\n\n // Provider-specific fields\n provider: VerificationProviderSchema.default('chatgpt'),\n\n // Public key (if custom provider)\n publicKey: z.string().optional(),\n\n // Algorithm hint\n algorithm: SignatureAlgorithmSchema.optional(),\n\n // Additional headers for context\n headers: z.record(z.string(), z.string()).optional(),\n});\nexport type SignatureVerificationRequest = z.infer<typeof SignatureVerificationRequestSchema>;\n\n/**\n * Signature Verification Response\n */\nexport const SignatureVerificationResponseSchema = z.object({\n success: z.boolean(),\n\n // Verification result\n verified: z.boolean(),\n\n // Verification details\n details: z\n .object({\n provider: VerificationProviderSchema,\n algorithm: SignatureAlgorithmSchema.optional(),\n timestamp: z.number().optional(),\n expiresAt: z.number().optional(),\n\n // Agent information if verified\n agent: z\n .object({\n type: z.string(),\n name: z.string(),\n version: z.string().optional(),\n verified: z.boolean(),\n })\n .optional(),\n\n // Certificate info if available\n certificate: z\n .object({\n subject: z.string(),\n issuer: z.string(),\n validFrom: z.date(),\n validTo: z.date(),\n fingerprint: z.string(),\n })\n .optional(),\n })\n .optional(),\n\n // Error information if verification failed\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n reason: z\n .enum([\n 'invalid_signature',\n 'expired_signature',\n 'invalid_timestamp',\n 'unknown_provider',\n 'missing_public_key',\n 'invalid_algorithm',\n 'payload_mismatch',\n ])\n .optional(),\n })\n .optional(),\n\n // Metadata\n metadata: z\n .object({\n requestId: z.string().uuid(),\n verifiedAt: z.date(),\n cached: z.boolean().optional(),\n })\n .optional(),\n});\nexport type SignatureVerificationResponse = z.infer<typeof SignatureVerificationResponseSchema>;\n\n/**\n * Public Key Configuration\n */\nexport const PublicKeyConfigSchema = z.object({\n provider: VerificationProviderSchema,\n keyId: z.string(),\n publicKey: z.string(),\n algorithm: SignatureAlgorithmSchema,\n validFrom: z.date(),\n validTo: z.date().optional(),\n active: z.boolean().default(true),\n});\nexport type PublicKeyConfig = z.infer<typeof PublicKeyConfigSchema>;\n\n/**\n * Verification cache entry\n */\nexport const VerificationCacheEntrySchema = z.object({\n signature: z.string(),\n verified: z.boolean(),\n provider: VerificationProviderSchema,\n timestamp: z.number(),\n expiresAt: z.number(),\n});\nexport type VerificationCacheEntry = z.infer<typeof VerificationCacheEntrySchema>;\n","/**\n * Bulk Operations API schemas\n *\n * Standard schemas for bulk CRUD operations across all resources\n */\n\nimport { z } from 'zod';\n\n/**\n * Bulk operation types\n */\nexport const BulkOperationTypeSchema = z.enum(['create', 'update', 'delete']);\nexport type BulkOperationType = z.infer<typeof BulkOperationTypeSchema>;\n\n/**\n * Bulk operation options\n */\nexport const BulkOperationOptionsSchema = z.object({\n /** Continue processing remaining items on failure */\n continueOnError: z.boolean().default(true).optional(),\n /** Execute all operations in a single transaction (all-or-nothing) */\n transactional: z.boolean().default(false).optional(),\n /** Validate only without executing (dry run) */\n validateOnly: z.boolean().default(false).optional(),\n /** Preview what would be deleted without executing (alias for validateOnly on delete) */\n dryRun: z.boolean().default(false).optional(),\n});\nexport type BulkOperationOptions = z.infer<typeof BulkOperationOptionsSchema>;\n\n/**\n * Base bulk request schema\n */\nexport const BaseBulkRequestSchema = z.object({\n operation: BulkOperationTypeSchema,\n options: BulkOperationOptionsSchema.optional(),\n});\n\n/**\n * Bulk result item\n */\nexport const BulkResultItemSchema = z.object({\n index: z.number(),\n success: z.boolean(),\n data: z.unknown().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n })\n .optional(),\n});\nexport type BulkResultItem = z.infer<typeof BulkResultItemSchema>;\n\n/**\n * Bulk response\n */\nexport const BulkResponseSchema = z.object({\n success: z.boolean(),\n batchId: z.string().uuid(),\n summary: z.object({\n total: z.number(),\n succeeded: z.number(),\n failed: z.number(),\n skipped: z.number(),\n }),\n results: z.array(BulkResultItemSchema),\n metadata: z\n .object({\n processingTime: z.number(),\n transactional: z.boolean(),\n dryRun: z.boolean().optional(),\n })\n .optional(),\n});\nexport type BulkResponse = z.infer<typeof BulkResponseSchema>;\n\n/**\n * Bulk delete preview stats for a single project\n */\nexport const BulkDeletePreviewStatsSchema = z.object({\n projectId: z.string().uuid(),\n friendlyId: z.string().nullable(),\n name: z.string(),\n counts: z.object({\n detections: z.number(),\n pixels: z.number(),\n apiKeys: z.number(),\n members: z.number(),\n bouncerConfigs: z.number(),\n delegations: z.number(),\n bouncerProofs: z.number(),\n bouncerSessions: z.number(),\n userAccounts: z.number(),\n userProfiles: z.number(),\n }),\n totalRecords: z.number(),\n});\nexport type BulkDeletePreviewStats = z.infer<typeof BulkDeletePreviewStatsSchema>;\n\n/**\n * Bulk delete response with optional preview\n */\nexport const BulkDeleteResponseSchema = BulkResponseSchema.extend({\n preview: z.array(BulkDeletePreviewStatsSchema).optional(),\n});\nexport type BulkDeleteResponse = z.infer<typeof BulkDeleteResponseSchema>;\n\n/**\n * Projects Bulk Request\n */\nexport const ProjectsBulkCreateItemSchema = z.object({\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n })\n .optional(),\n});\n\nexport const ProjectsBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).optional(),\n blockedAgents: z.array(z.string()).optional(),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n })\n .optional(),\n});\n\nexport const ProjectsBulkDeleteItemSchema = z.object({\n /** Project UUID to delete */\n id: z.string().uuid(),\n /** Skip confirmation for automated cleanup (admin only) */\n force: z.boolean().optional(),\n});\n\nexport const ProjectsBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(ProjectsBulkCreateItemSchema).min(1).max(100),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(ProjectsBulkUpdateItemSchema).min(1).max(100),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(ProjectsBulkDeleteItemSchema).min(1).max(100),\n }),\n ])\n);\nexport type ProjectsBulkRequest = z.infer<typeof ProjectsBulkRequestSchema>;\n\n/**\n * Pixels Bulk Request\n */\nexport const PixelsBulkCreateItemSchema = z.object({\n projectId: z.string().uuid(),\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n isActive: z.boolean().default(true),\n configuration: z\n .object({\n allowedDomains: z.array(z.string()).default([]),\n collectBehavioral: z.boolean().default(true),\n enableFingerprinting: z.boolean().default(true),\n enableSessionTracking: z.boolean().default(true),\n sampleRate: z.number().min(0).max(1).default(1),\n })\n .optional(),\n});\n\nexport const PixelsBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n isActive: z.boolean().optional(),\n configuration: z\n .object({\n allowedDomains: z.array(z.string()).optional(),\n collectBehavioral: z.boolean().optional(),\n enableFingerprinting: z.boolean().optional(),\n enableSessionTracking: z.boolean().optional(),\n sampleRate: z.number().min(0).max(1).optional(),\n })\n .optional(),\n});\n\nexport const PixelsBulkDeleteItemSchema = z.object({\n id: z.string().uuid(),\n});\n\nexport const PixelsBulkRegenerateItemSchema = z.object({\n id: z.string().uuid(),\n});\n\nexport const PixelsBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(PixelsBulkCreateItemSchema).min(1).max(100),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(PixelsBulkUpdateItemSchema).min(1).max(100),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(PixelsBulkDeleteItemSchema).min(1).max(100),\n }),\n ])\n);\nexport type PixelsBulkRequest = z.infer<typeof PixelsBulkRequestSchema>;\n\n/**\n * API Keys Bulk Request\n */\nexport const ApiKeysBulkCreateItemSchema = z.object({\n name: z.string().min(1).max(255),\n projectId: z.string().uuid().optional(),\n permissions: z.array(z.enum(['read', 'write', 'admin'])).default(['read']),\n rateLimits: z\n .object({\n requestsPerSecond: z.number().min(1).optional(),\n requestsPerMinute: z.number().min(1).optional(),\n requestsPerHour: z.number().min(1).optional(),\n requestsPerDay: z.number().min(1).optional(),\n })\n .optional(),\n expiresAt: z.string().datetime().optional(),\n});\n\nexport const ApiKeysBulkRevokeItemSchema = z.object({\n id: z.string().uuid(),\n});\n\nexport const ApiKeysBulkUpdateItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255).optional(),\n permissions: z.array(z.enum(['read', 'write', 'admin'])).optional(),\n rateLimits: z\n .object({\n requestsPerSecond: z.number().min(1).optional(),\n requestsPerMinute: z.number().min(1).optional(),\n requestsPerHour: z.number().min(1).optional(),\n requestsPerDay: z.number().min(1).optional(),\n })\n .optional(),\n expiresAt: z.string().datetime().optional().nullable(),\n});\n\nexport const ApiKeysBulkRequestSchema = BaseBulkRequestSchema.and(\n z.discriminatedUnion('operation', [\n z.object({\n operation: z.literal('create'),\n items: z.array(ApiKeysBulkCreateItemSchema).min(1).max(100),\n }),\n z.object({\n operation: z.literal('update'),\n items: z.array(ApiKeysBulkUpdateItemSchema).min(1).max(100),\n }),\n z.object({\n operation: z.literal('delete'),\n items: z.array(ApiKeysBulkRevokeItemSchema).min(1).max(100),\n }),\n ])\n);\nexport type ApiKeysBulkRequest = z.infer<typeof ApiKeysBulkRequestSchema>;\n\n/**\n * Maximum batch size for bulk operations\n */\nexport const MAX_BULK_BATCH_SIZE = 100;\n\n/**\n * Bulk operation error codes\n */\nexport const BULK_ERROR_CODES = {\n BATCH_TOO_LARGE: 'BATCH_TOO_LARGE',\n INVALID_OPERATION: 'INVALID_OPERATION',\n TRANSACTION_FAILED: 'TRANSACTION_FAILED',\n TRANSACTION_ABORTED: 'TRANSACTION_ABORTED',\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n PARTIAL_FAILURE: 'PARTIAL_FAILURE',\n LIMIT_EXCEEDED: 'LIMIT_EXCEEDED',\n OWNERSHIP_ERROR: 'OWNERSHIP_ERROR',\n PERMISSION_DENIED: 'PERMISSION_DENIED',\n DELETE_FAILED: 'DELETE_FAILED',\n SKIPPED: 'SKIPPED',\n NOT_FOUND: 'NOT_FOUND',\n} as const;\nexport type BulkErrorCode = (typeof BULK_ERROR_CODES)[keyof typeof BULK_ERROR_CODES];\n","/**\n * Buckets an `agent_daily_rollup` row `(agent_type, detection_class)` into\n * the admin overview's four-bucket AI traffic taxonomy, reproducing the\n * internal \"Customers & Installations\" report's overlay.\n *\n * Name wins over class: historical rows stamped training crawlers\n * (ClaudeBot, GPTBot) as `ai_agent`, so the overlay name lists below take\n * precedence over the stored `detection_class` before either falls back to\n * `KNOWN_AGENT_PATTERNS` and then to the class itself.\n */\n\nimport { KNOWN_AGENT_PATTERNS } from './agents';\nimport type { AgentPattern } from '../core/agent';\nimport type { TrafficTaxonomyBucket } from '../types/admin-overview';\nimport type { DetectionClassEnum } from '../utils/detection-class';\n\n/**\n * Training / indexing crawlers run by AI vendors. Values are the exact names\n * stored in detections.agent_type: KNOWN_AGENT_PATTERNS `name`s for the TS\n * classifier path and the engine's emitted names (which keep their spaces,\n * e.g. 'Bytedance Crawler') for the WASM path.\n *\n * 'Meta AI' is listed here on purpose, matching the report: stored 'Meta AI'\n * rows are overwhelmingly pre-split Meta-ExternalAgent crawler hits (the\n * `meta-ai` agent type carried that UA before the split, see agents.ts), so\n * the report regroups them as crawlers. Genuine Meta-AI assistant sessions\n * are rare and accepted as a known trade-off of reproducing the report.\n */\nexport const REPORT_AI_CRAWLER_NAMES: readonly string[] = [\n 'GPTBot',\n 'ClaudeBot',\n 'Anthropic-AI Crawler',\n 'PerplexityBot',\n 'Google-Extended',\n 'Gemini-Deep-Research',\n 'Meta-ExternalAgent',\n 'Meta AI',\n 'CohereBot',\n 'DeepSeekBot',\n 'MistralBot',\n 'Amazonbot',\n 'Amazon Bedrock',\n 'Common Crawl',\n 'Bytedance Crawler',\n];\n/** Interactive assistants / agents acting for a person. */\nexport const REPORT_AI_AGENT_NAMES: readonly string[] = [\n 'ChatGPT',\n 'ChatGPT-User',\n 'OpenAI',\n 'Claude',\n 'Claude-User',\n 'Anthropic',\n 'Perplexity',\n 'Perplexity-User',\n 'Google Gemini',\n 'Microsoft Copilot',\n 'DeepSeek AI',\n 'xAI Grok',\n 'Amazon Q',\n 'Kya Agent',\n];\n\n// Built once at module scope: lowercase membership sets for the overlay\n// lists, and a lowercase name-or-id lookup into KNOWN_AGENT_PATTERNS.\nconst CRAWLER_NAME_SET = new Set(REPORT_AI_CRAWLER_NAMES.map((name) => name.toLowerCase()));\nconst AGENT_NAME_SET = new Set(REPORT_AI_AGENT_NAMES.map((name) => name.toLowerCase()));\n\n/**\n * Build a lowercase name-or-id lookup over `patterns`, first-wins: the first\n * match in source order wins so a later entry that reuses a name cannot\n * silently change a bucket. Exported so the rule is testable on synthetic\n * input.\n */\nexport function buildKnownPatternLookup(\n patterns: readonly AgentPattern[]\n): ReadonlyMap<string, AgentPattern> {\n const map = new Map<string, AgentPattern>();\n for (const entry of patterns) {\n const nameKey = entry.name.toLowerCase();\n const idKey = entry.id.toLowerCase();\n if (!map.has(nameKey)) map.set(nameKey, entry);\n if (!map.has(idKey)) map.set(idKey, entry);\n }\n return map;\n}\n\nconst KNOWN_PATTERN_BY_NAME_OR_ID = buildKnownPatternLookup(KNOWN_AGENT_PATTERNS);\n\n/**\n * Classify a rollup row's `(agent_type, detection_class)` pair into a\n * {@link TrafficTaxonomyBucket}. An unidentified agent (`agent_type` null,\n * stored as 'Unknown' by the rollup) falls to the class fallback, so an\n * `ai_agent`-classed unidentified row counts as an AI agent and a\n * `bot`-classed one as other automation.\n */\nexport function classifyAgentTaxonomy(\n agentType: string | null | undefined,\n detectionClass: DetectionClassEnum | string | null | undefined\n): TrafficTaxonomyBucket {\n if (detectionClass === 'human') return 'human';\n\n const normalized = agentType?.trim().toLowerCase();\n if (normalized) {\n if (CRAWLER_NAME_SET.has(normalized)) return 'ai_crawler';\n if (AGENT_NAME_SET.has(normalized)) return 'ai_agent';\n\n const known = KNOWN_PATTERN_BY_NAME_OR_ID.get(normalized);\n if (known) {\n return (known.category ?? 'ai_assistant') === 'ai_assistant' ? 'ai_agent' : 'ai_crawler';\n }\n }\n\n return detectionClass === 'ai_agent' ? 'ai_agent' : 'other_automation';\n}\n","/**\n * Database Entity Types\n *\n * Shared types for database entities used across the dashboard,\n * API, and other packages in the monorepo.\n */\n\nimport { z } from 'zod';\nimport { ipAddressSchema } from '../utils/zod-helpers';\n\n/**\n * User Plan Levels\n */\nexport const UserPlanSchema = z.enum(['free', 'pro', 'enterprise']);\nexport type UserPlan = z.infer<typeof UserPlanSchema>;\n\n/**\n * API Key Permissions\n */\nexport const ApiKeyPermissionSchema = z.enum(['read', 'write', 'admin']);\nexport type ApiKeyPermission = z.infer<typeof ApiKeyPermissionSchema>;\n\n/**\n * User Entity\n */\nexport const UserSchema = z.object({\n id: z.string().uuid(),\n email: z.string().email(),\n name: z.string().nullish(),\n image: z.string().url().nullish(),\n emailVerified: z.date().nullish(),\n plan: UserPlanSchema.default('free'),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type User = z.infer<typeof UserSchema>;\nexport type NewUser = Omit<User, 'id' | 'createdAt' | 'updatedAt'>;\n\n/**\n * Project Settings\n */\nexport const ProjectSettingsSchema = z.object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n // A caller-controlled configuration value, not a feature flag: raises a\n // project's beacon-ingest rate-limit ceiling above its plan's fixed\n // per-minute default (`PLAN_RATE_LIMITS[plan].requestsPerMinute`), for a\n // high-traffic tenant whose real visitor volume concentrates behind one\n // shared IP (e.g. a corporate NAT).\n beaconRateLimitPerMinute: z.number().int().positive().optional(),\n});\nexport type ProjectSettings = z.infer<typeof ProjectSettingsSchema>;\n\n/**\n * Project Entity\n */\nexport const ProjectSchema = z.object({\n id: z.string().uuid(),\n friendlyId: z.string().nullable().optional(), // Human-readable project ID for URLs\n userId: z.string().uuid(),\n name: z.string().min(1).max(255),\n domain: z.string().optional(),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside ProjectSettingsSchema. prefault parses it, as Zod 3 did.\n settings: ProjectSettingsSchema.prefault({}),\n // Setup Flow v2 step 1 (\"What brings you here?\") selections, if this\n // project was created via that flow — see CreateProjectSchema's own\n // doc comment. Null/absent for every other creation path.\n setupGoals: z.array(z.string()).nullable().optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type Project = z.infer<typeof ProjectSchema>;\nexport type NewProject = Omit<Project, 'id' | 'friendlyId' | 'createdAt' | 'updatedAt'>;\n\n/**\n * Pixel Configuration\n */\nexport const PixelConfigurationSchema = z.object({\n enabled: z.boolean().default(true),\n skipPaths: z.array(z.string()).default([]),\n allowedDomains: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n batchSize: z.number().min(1).max(100).default(10),\n flushInterval: z.number().min(100).max(60000).default(5000),\n enableBehavioralTracking: z.boolean().default(true),\n enableSessionReplay: z.boolean().default(false),\n customHeaders: z.record(z.string(), z.string()).default({}),\n});\nexport type PixelConfiguration = z.infer<typeof PixelConfigurationSchema>;\n\n/**\n * Pixel Entity\n */\nexport const PixelSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n name: z.string().min(1).max(255),\n secretKey: z.string().min(32),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside PixelConfigurationSchema. prefault parses it, as Zod 3 did.\n configuration: PixelConfigurationSchema.prefault({}),\n isActive: z.boolean().default(true),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type Pixel = z.infer<typeof PixelSchema>;\nexport type NewPixel = Omit<Pixel, 'id' | 'createdAt' | 'updatedAt'>;\n\n/**\n * Pixel Statistics\n */\nexport const PixelStatsSchema = z.object({\n totalEvents: z.number().int().min(0),\n agentsDetected: z.number().int().min(0),\n uniqueSessions: z.number().int().min(0),\n averageConfidence: z.number().min(0).max(1),\n lastEventAt: z.date().optional(),\n periodStart: z.date(),\n periodEnd: z.date(),\n});\nexport type PixelStats = z.infer<typeof PixelStatsSchema>;\n\n/**\n * API Key Rate Limits\n */\nexport const ApiKeyRateLimitsSchema = z.object({\n requestsPerSecond: z.number().min(1).default(10),\n requestsPerMinute: z.number().min(1).default(100),\n requestsPerHour: z.number().min(1).default(1000),\n requestsPerDay: z.number().min(1).default(10000),\n burstLimit: z.number().min(1).default(20),\n});\nexport type ApiKeyRateLimits = z.infer<typeof ApiKeyRateLimitsSchema>;\n\n/**\n * API Key Entity\n */\nexport const ApiKeySchema = z.object({\n id: z.string().uuid(),\n userId: z.string().uuid(),\n projectId: z.string().uuid().optional(),\n name: z.string().min(1).max(255),\n key: z.string().min(32),\n permissions: z.array(ApiKeyPermissionSchema).default(['read']),\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside ApiKeyRateLimitsSchema. prefault parses it, as Zod 3 did.\n rateLimits: ApiKeyRateLimitsSchema.prefault({}),\n lastUsedAt: z.date().optional(),\n expiresAt: z.date().optional(),\n createdAt: z.date(),\n revokedAt: z.date().optional(),\n});\nexport type ApiKey = z.infer<typeof ApiKeySchema>;\nexport type NewApiKey = Omit<ApiKey, 'id' | 'createdAt'>;\n\n/**\n * Detection Log Entity\n */\nexport const DetectionLogSchema = z.object({\n id: z.string().uuid(),\n pixelId: z.string().uuid(),\n projectId: z.string().uuid(),\n isAgent: z.boolean(),\n confidence: z.number().min(0).max(100), // Stored as 0-100 in DB\n agentType: z.string().optional(),\n userAgent: z.string().optional(),\n ipAddress: ipAddressSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n sessionId: z.string().optional(),\n createdAt: z.date(),\n});\nexport type DetectionLog = z.infer<typeof DetectionLogSchema>;\nexport type NewDetectionLog = Omit<DetectionLog, 'id' | 'createdAt'>;\n\n/**\n * Session Entity (for NextAuth)\n */\nexport const SessionSchema = z.object({\n sessionToken: z.string(),\n userId: z.string().uuid(),\n expires: z.date(),\n});\nexport type Session = z.infer<typeof SessionSchema>;\n\n/**\n * Account Entity (for OAuth providers)\n */\nexport const AccountSchema = z.object({\n userId: z.string().uuid(),\n type: z.string(),\n provider: z.string(),\n providerAccountId: z.string(),\n refresh_token: z.string().optional(),\n access_token: z.string().optional(),\n expires_at: z.number().optional(),\n token_type: z.string().optional(),\n scope: z.string().optional(),\n id_token: z.string().optional(),\n session_state: z.string().optional(),\n});\nexport type Account = z.infer<typeof AccountSchema>;\n\n/**\n * Verification Token Entity\n */\nexport const VerificationTokenSchema = z.object({\n identifier: z.string(),\n token: z.string(),\n expires: z.date(),\n});\nexport type VerificationToken = z.infer<typeof VerificationTokenSchema>;\n","/**\n * Provider Registry Re-exports\n *\n * This file re-exports types and schemas from @kya-os/provider-registry,\n * providing Checkpoint with a single source of truth for provider definitions\n * and eliminating type fragmentation bugs.\n *\n * ## Why This File Exists\n *\n * Prior to this integration, Checkpoint defined its own provider types that\n * diverged from the canonical types in provider-registry:\n * - Checkpoint used 'credential' while provider-registry uses 'password'\n * - Field names differed: 'authorizationUrl' vs 'authorizationEndpoint'\n * - Schemas were duplicated rather than shared\n *\n * ## Migration Notes\n *\n * For backward compatibility, we provide aliases:\n * - `AuthProviderType` = `ProviderAuthType` (with 'credential' mapped to 'password')\n *\n * @module provider-registry\n */\n\n// ==============================================================================\n// RE-EXPORT FROM @kya-os/provider-registry\n// ==============================================================================\n\n// Core types\nexport {\n type ProviderAuthType,\n type ConsentProviderType,\n type ProviderDefinition as ProviderRegistryDefinition,\n type ProviderConfig,\n type OAuthProviderConfig,\n type CredentialProviderConfig,\n AUTH_MODES,\n PROVIDER_AUTH_TYPES,\n type AuthMode,\n} from '@kya-os/provider-registry';\n\n// Zod schemas\nexport {\n ProviderDefinitionSchema as ProviderRegistryDefinitionSchema,\n OAuthProviderConfigSchema,\n CredentialProviderConfigSchema,\n ProviderConfigSchema,\n validateProviderDefinition,\n validateProviderConfig,\n} from '@kya-os/provider-registry';\n\n// Registry types (runtime registry should be imported directly from @kya-os/provider-registry)\nexport { type IProviderRegistry, type RegistryLogger } from '@kya-os/provider-registry';\n\n// ==============================================================================\n// BACKWARD COMPATIBILITY ALIASES\n// ==============================================================================\n\n/**\n * Backward compatibility alias for AuthProviderType.\n *\n * Checkpoint previously used 'credential' instead of 'password'.\n * This type alias allows existing code to continue working.\n *\n * @deprecated Use `ProviderAuthType` from provider-registry directly.\n * This alias maps:\n * - 'credential' → 'password' (canonical name)\n * - 'oauth2' → 'oauth2' (unchanged)\n */\nexport type LegacyAuthProviderType = 'oauth2' | 'credential';\n\n/**\n * Maps legacy auth type values to canonical provider-registry values.\n *\n * @example\n * ```typescript\n * import { mapLegacyAuthType } from '@kya-os/checkpoint-shared';\n *\n * const canonicalType = mapLegacyAuthType('credential'); // 'password'\n * ```\n */\nexport function mapLegacyAuthType(\n legacyType: LegacyAuthProviderType | string\n): 'oauth2' | 'password' | string {\n switch (legacyType) {\n case 'credential':\n case 'credentials':\n return 'password';\n case 'oauth2':\n return 'oauth2';\n default:\n return legacyType;\n }\n}\n\n/**\n * Maps canonical provider-registry auth types to legacy Checkpoint types.\n *\n * Useful when maintaining backward compatibility with existing API responses.\n *\n * @example\n * ```typescript\n * import { mapToLegacyAuthType } from '@kya-os/checkpoint-shared';\n *\n * const legacyType = mapToLegacyAuthType('password'); // 'credential'\n * ```\n */\nexport function mapToLegacyAuthType(canonicalType: string): 'oauth2' | 'credential' | string {\n switch (canonicalType) {\n case 'password':\n return 'credential';\n case 'oauth2':\n return 'oauth2';\n default:\n return canonicalType;\n }\n}\n\n// ==============================================================================\n// AUTHORIZATION MODE CONSTANTS (from provider-registry)\n// ==============================================================================\n\n/**\n * Authorization modes supported by Checkpoint Bouncer.\n *\n * These are aligned with consent UI auth modes and provider capabilities.\n *\n * Note: This is re-exported from @kya-os/provider-registry for consistency.\n * The canonical source is AUTH_MODES from provider-registry.\n */\nexport const AUTHORIZATION_MODES = {\n /** OAuth2 authentication flow */\n OAUTH: 'oauth',\n /** Username/password credential authentication */\n CREDENTIAL: 'credential',\n /** Consent-only - no authentication required */\n CONSENT_ONLY: 'consent-only',\n // Future modes (aligned with provider-registry):\n // PASSKEY: 'passkey',\n // MAGIC_LINK: 'magic-link',\n // OTP: 'otp',\n // IDV: 'idv',\n} as const;\n\nexport type AuthorizationMode = (typeof AUTHORIZATION_MODES)[keyof typeof AUTHORIZATION_MODES];\n","/**\n * Bouncer Schemas\n *\n * Zod schemas for Agent Bouncer KYA-OS protocol validation.\n *\n * ## Provider Registry Integration\n *\n * As of v0.3.0, this module imports core provider types from @kya-os/provider-registry\n * to eliminate type fragmentation between Checkpoint and KYA-OS.\n *\n * Key types imported:\n * - `ProviderAuthType` (canonical: 'oauth2' | 'password' | 'passkey' | etc.)\n * - `ProviderDefinition` (canonical provider metadata structure)\n * - `OAuthProviderConfig`, `CredentialProviderConfig` (canonical configs)\n *\n * For backward compatibility, we alias:\n * - `AuthProviderType` → maps 'credential' to 'password' internally\n */\n\nimport { z } from 'zod';\n\n// Import canonical types from provider-registry\nimport {\n type ProviderAuthType,\n type ConsentProviderType,\n mapLegacyAuthType,\n mapToLegacyAuthType,\n} from './provider-registry';\n\n// Re-export for consumers\nexport { mapLegacyAuthType, mapToLegacyAuthType };\n\n/**\n * Hex color validation regex - accepts #RRGGBB format only (6 hex digits)\n * Used for consent branding colors where we append alpha values like \"20\" or \"40\"\n * Note: 3-char hex (#RGB) is NOT allowed because appending alpha creates invalid 5-char CSS (#RGB20)\n * Note: 8-char hex (#RRGGBBAA) is NOT allowed because appending alpha would create invalid 10-char CSS\n */\nconst hexColorRegex = /^#[0-9A-Fa-f]{6}$/;\n\n/**\n * HTTP(S)-only URL validator.\n *\n * `z.string().url()` alone accepts dangerous pseudo-protocols like\n * `javascript:`, `data:`, `vbscript:`, and `file:` because the underlying\n * URL constructor parses them as valid URLs. When these values are later\n * rendered into `<a href>` or `<img src>` on a public page, they become\n * stored-XSS vectors.\n *\n * This validator parses the URL and explicitly requires the protocol to\n * be `http:` or `https:`. Used for every customer-editable URL field that\n * eventually gets rendered to a browser (logoUrl, termsUrl, mcpServerUrl,\n * etc.).\n *\n * Defense in depth — the render layer (`sanitizeDisplayUrl` in\n * apps/web/lib/utils/url-security.ts) also sanitizes at render time, so\n * legacy/direct-DB values don't bypass this.\n *\n * IMPORTANT: `maxLength` is opt-in with NO DEFAULT on purpose. Earlier\n * versions of this helper defaulted to 500 characters, which silently\n * capped fields that previously had no length cap — notably `authUrl` in\n * `DelegationPollingStatusSchema` and `mcpServerUrl` / `mcpWorkerUrl` in\n * `BouncerConfigSchema`. OAuth authorization URLs with scopes + PKCE +\n * state + redirect_uri routinely exceed 500 characters, so those fields\n * must NOT be capped. Always pass `maxLength` explicitly at the call site\n * and match the field's original constraint.\n *\n * @param maxLength - Optional maximum URL length. Pass only if the field\n * had a length cap before; pass nothing to preserve \"no length limit\".\n * @returns A zod schema that accepts only http(s) URLs\n */\nexport function httpUrlSchema(maxLength?: number) {\n const base = maxLength !== undefined ? z.string().url().max(maxLength) : z.string().url();\n return base.refine(\n (value) => {\n try {\n const parsed = new URL(value);\n return parsed.protocol === 'http:' || parsed.protocol === 'https:';\n } catch {\n return false;\n }\n },\n { message: 'URL must use http:// or https:// protocol' }\n );\n}\n\n/**\n * OAuth Provider Types\n */\nexport const OAuthProviderTypeSchema = z.enum(['oauth2', 'oidc', 'custom']);\nexport type OAuthProviderType = z.infer<typeof OAuthProviderTypeSchema>;\n\n/**\n * OAuth Connection Status\n */\nexport const OAuthConnectionStatusSchema = z.enum(['connected', 'disconnected', 'error']);\nexport type OAuthConnectionStatus = z.infer<typeof OAuthConnectionStatusSchema>;\n\n// ==============================================================================\n// MULTI-PROVIDER OAUTH TYPES (CRED-001)\n// Provider Registry Integration: Types aligned with @kya-os/provider-registry\n// ==============================================================================\n\n/**\n * Auth Provider Type - determines the authentication method.\n *\n * **Provider Registry Integration:**\n * - Canonical types: 'oauth2' | 'password' (from provider-registry)\n * - Legacy alias: 'credential' maps to 'password' internally\n *\n * For new code, prefer using 'password' for credential-based auth.\n * The 'credential' value is accepted for backward compatibility.\n *\n * @see PROVIDER_AUTH_TYPES from @kya-os/provider-registry for canonical values\n */\nexport const AuthProviderTypeSchema = z\n .enum(['oauth2', 'credential', 'password'])\n .transform((val) => {\n // Map legacy 'credential' to canonical 'password'\n if (val === 'credential') return 'password';\n return val;\n });\n\n/**\n * Auth Provider Type (input) - what clients can send\n * Accepts both canonical ('password') and legacy ('credential') values\n */\nexport type AuthProviderTypeInput = 'oauth2' | 'credential' | 'password';\n\n/**\n * Auth Provider Type (canonical) - normalized output type\n * Always 'oauth2' or 'password' after schema transformation\n */\nexport type AuthProviderType = 'oauth2' | 'password';\n\n/**\n * Legacy type alias for backward compatibility\n * @deprecated Use AuthProviderType directly\n */\nexport type LegacyAuthProviderType = 'oauth2' | 'credential';\n\n// Re-export the canonical type from provider-registry\nexport type { ProviderAuthType, ConsentProviderType };\n\n// ==============================================================================\n// PROVIDER SECRET METADATA (Provider Registry Alignment)\n// ==============================================================================\n\n/**\n * Secret name constraints: alphanumeric, underscores, max 128 chars\n * Pattern: KYA_{env}_{projectSlug}_{providerId}_{secretType}\n */\nexport const SecretNameSchema = z\n .string()\n .regex(/^[A-Z][A-Z0-9_]{2,127}$/, 'Secret name must be uppercase alphanumeric with underscores')\n .max(128);\nexport type SecretName = z.infer<typeof SecretNameSchema>;\n\n/**\n * Provider Secret Metadata - references to secrets stored in secure storage\n *\n * SECURITY: This schema stores ONLY metadata and secret names, NEVER actual secret values.\n * Secret values are resolved at runtime from Cloudflare Worker Secrets.\n */\nexport const ProviderSecretMetadataSchema = z.object({\n // Secret references (use consistent naming: *SecretName)\n clientIdSecretName: SecretNameSchema.optional(),\n clientSecretName: SecretNameSchema.optional(),\n apiKeySecretName: SecretNameSchema.optional(),\n // Rotation tracking\n clientSecretVersion: z.number().int().positive().optional(),\n lastRotatedAt: z.string().datetime().optional(),\n});\nexport type ProviderSecretMetadata = z.infer<typeof ProviderSecretMetadataSchema>;\n\n/**\n * Base Auth Provider - common fields for all provider types\n */\nexport const BaseAuthProviderSchema = z.object({\n displayName: z.string().max(100).optional(),\n status: OAuthConnectionStatusSchema.default('disconnected'),\n});\nexport type BaseAuthProvider = z.infer<typeof BaseAuthProviderSchema>;\n\n/**\n * OAuth2 Provider Configuration\n * Stores all configuration for an OAuth2 provider\n */\nexport const OAuth2ProviderSchema = BaseAuthProviderSchema.extend({\n type: z.literal('oauth2'),\n clientId: z.string().max(255),\n clientSecret: z.string().optional(), // Encrypted, never returned in GET - TO BE DEPRECATED\n authEndpoint: z.string().max(500),\n tokenEndpoint: z.string().max(500),\n userInfoUrl: httpUrlSchema(500).optional(), // User info endpoint for identity resolution\n /**\n * Optional dot-path field mapping into the `userInfoUrl` response for\n * merchant identity extraction (native consent merchant-oauth leg).\n * When absent, extraction defaults to: userId ← first present of\n * `sub`/`id`/`customerId`; userEmail ← `email`.\n */\n userInfoFields: z\n .object({\n userId: z.string().max(255).optional(), // JSON dot-path to the customer id\n userEmail: z.string().max(255).optional(), // JSON dot-path to the customer email\n })\n .optional(),\n redirectUri: z.string().max(500),\n scopes: z.array(z.string()).optional(),\n supportsPKCE: z.boolean().optional(),\n // Phase 3 fields\n customParams: z.record(z.string(), z.string()).optional(),\n tokenEndpointAuthMethod: z.enum(['client_secret_post', 'client_secret_basic']).optional(),\n responseType: z.string().optional(),\n grantType: z.string().optional(),\n // Provider Registry Alignment: Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\nexport type OAuth2Provider = z.infer<typeof OAuth2ProviderSchema>;\n\n/**\n * Credential Provider Configuration\n * Stores configuration for username/password, email/password, or cookie-based authentication\n *\n * Supports:\n * - JSON token responses (JWT, Bearer tokens)\n * - Cookie-based sessions (like HardwareWorld)\n * - Custom response validation\n */\nexport const CredentialProviderSchema = BaseAuthProviderSchema.extend({\n type: z.literal('credential'),\n authEndpoint: z.string().max(500),\n\n // Request configuration\n requestBodyTemplate: z.record(z.string(), z.string()).optional(), // Field mapping for request body\n\n // Response field mapping\n responseFields: z.object({\n // Session/auth token - can be JWT, session cookie, or any auth identifier\n sessionToken: z.string(), // JSON path to auth token (renamed from accessToken for clarity)\n userId: z.string().optional(), // JSON path to user ID\n userEmail: z.string().optional(), // JSON path to user email (for delegation records)\n userDisplayName: z.string().optional(), // JSON path to display name (for consent screens)\n expiresIn: z.string().optional(), // JSON path to token expiry (optional for cookie-based)\n }),\n\n // Success validation - verify the login actually succeeded\n successCheck: z\n .object({\n path: z.string(), // JSON path to check (e.g., \"success\", \"status\")\n expectedValue: z.union([z.string(), z.boolean(), z.number()]), // Expected value (e.g., true, \"ok\", 200)\n })\n .optional(),\n\n // Custom headers for API requests\n headers: z.record(z.string(), z.string()).optional(),\n\n // Token usage configuration (CRED-002)\n // Tells xmcp-i how to use the session token for subsequent API calls\n tokenUsage: z.enum(['cookie', 'bearer', 'header']).optional().default('cookie'),\n tokenHeader: z.string().max(100).optional(), // Custom header name if tokenUsage === 'header'\n cookieFormat: z.string().max(500).optional(), // Cookie format template, e.g., \"CIX={{token}}; customerCookie={{token}}\"\n apiHeaders: z.record(z.string(), z.string()).optional(), // Additional headers for API calls\n\n // Consent overrides for credential forms (CRED-002)\n consentOverrides: z\n .object({\n branding: z\n .object({\n primaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #2563EB)')\n .optional(),\n secondaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #DBEAFE)')\n .optional(),\n logoUrl: httpUrlSchema(500).optional(),\n companyName: z.string().max(255).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n })\n .partial()\n .optional(),\n terms: z\n .object({\n url: httpUrlSchema(500).optional(),\n text: z.string().max(500).optional(),\n required: z.boolean().optional(),\n version: z.string().max(50).optional(),\n })\n .partial()\n .optional(),\n formTitle: z.string().max(255).optional(),\n formDescription: z.string().max(1000).optional(),\n identityFieldLabel: z.string().max(255).optional(),\n passwordFieldLabel: z.string().max(255).optional(),\n submitButtonText: z.string().max(100).optional(),\n })\n .optional(),\n // Provider Registry Alignment: Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\nexport type CredentialProvider = z.infer<typeof CredentialProviderSchema>;\n\n/**\n * Configured Provider Union - can be OAuth2 or Credential\n * Named to avoid conflict with AuthProvider in types/auth.ts\n */\nexport const ConfiguredProviderSchema = z.discriminatedUnion('type', [\n OAuth2ProviderSchema,\n CredentialProviderSchema,\n]);\nexport type ConfiguredProvider = z.infer<typeof ConfiguredProviderSchema>;\n\n/**\n * OAuth Providers Map - keyed by provider ID (github, google, custom, etc.)\n */\nexport const OAuthProvidersMapSchema = z.record(z.string(), ConfiguredProviderSchema);\nexport type OAuthProvidersMap = z.infer<typeof OAuthProvidersMapSchema>;\n\n/**\n * Add/Update Provider Request Schema\n * Used for PUT /api/internal/bouncer/config/[projectId]/providers/[providerId]\n */\nexport const AddUpdateProviderRequestSchema = ConfiguredProviderSchema;\nexport type AddUpdateProviderRequest = z.infer<typeof AddUpdateProviderRequestSchema>;\n\n/**\n * Scope Definition\n */\nexport const ScopeSchema = z.object({\n name: z.string().min(1).max(100),\n description: z.string().max(500).optional(),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n category: z.string().max(50).optional(),\n});\nexport type Scope = z.infer<typeof ScopeSchema>;\n\n/**\n * CRISP Budget Configuration\n */\nexport const CRISPBudgetSchema = z.object({\n requestsPerHour: z.number().int().positive().optional(),\n requestsPerDay: z.number().int().positive().optional(),\n tokensPerHour: z.number().int().positive().optional(),\n tokensPerDay: z.number().int().positive().optional(),\n computeUnitsPerHour: z.number().int().positive().optional(),\n computeUnitsPerDay: z.number().int().positive().optional(),\n});\nexport type CRISPBudget = z.infer<typeof CRISPBudgetSchema>;\n\n/**\n * Consent Branding Configuration\n */\nexport const ConsentBrandingSchema = z.object({\n primaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #2563EB)')\n .optional(),\n secondaryColor: z\n .string()\n .regex(hexColorRegex, 'Color must be a valid hex color (e.g., #DBEAFE)')\n .optional(),\n logoUrl: httpUrlSchema(500).optional(),\n companyName: z.string().max(255).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n});\nexport type ConsentBranding = z.infer<typeof ConsentBrandingSchema>;\n\n/**\n * Consent Terms Configuration\n */\nexport const ConsentTermsSchema = z.object({\n url: httpUrlSchema(500).optional(),\n text: z.string().max(500).optional(),\n required: z.boolean().optional(),\n version: z.string().max(50).optional(),\n privacyUrl: httpUrlSchema(500).optional(),\n});\nexport type ConsentTerms = z.infer<typeof ConsentTermsSchema>;\n\n/**\n * Consent UI Configuration\n */\nexport const ConsentUISchema = z.object({\n title: z.string().max(255).optional(),\n description: z.string().max(1000).optional(),\n expirationText: z.string().max(500).optional(),\n cancelButtonText: z.string().max(100).optional(),\n submitButtonText: z.string().max(100).optional(),\n theme: z.enum(['light', 'dark', 'auto']).optional(),\n popupEnabled: z.boolean().optional(),\n autoClose: z.boolean().optional(),\n});\nexport type ConsentUI = z.infer<typeof ConsentUISchema>;\n\n/**\n * Consent Custom Field Configuration\n */\nexport const ConsentCustomFieldSchema = z.object({\n name: z.string().max(100),\n label: z.string().max(255),\n type: z.enum(['text', 'textarea', 'checkbox']),\n required: z.boolean(),\n});\nexport type ConsentCustomField = z.infer<typeof ConsentCustomFieldSchema>;\n\n/**\n * Consent metadata used for cache busting + UX hints\n */\nexport const ConsentConfigMetadataSchema = z.object({\n version: z.number().int().min(1).default(1),\n updatedAt: z.string().datetime().nullable().optional(),\n bumpedAt: z.string().datetime().nullable().optional(),\n});\nexport type ConsentConfigMetadata = z.infer<typeof ConsentConfigMetadataSchema>;\n\n/**\n * First-Contact Scope Cap section 3: the two risk tiers that require a\n * minimum Sensitive/Critical trust tier before a capability can be offered.\n * Shared by the Rule 1 refine below (`ConsentCapabilitySchema`) and the\n * Rule 2/3 refine on `ConsentConfigSchema`, so the tier boundary is defined\n * once instead of repeated as an inline check at each site.\n */\nfunction requiresSensitiveTier(riskLevel: 'low' | 'medium' | 'high' | 'critical'): boolean {\n return riskLevel === 'high' || riskLevel === 'critical';\n}\n\n/**\n * Capability — operator-authored capability row shown to the user during\n * consent. The `cedar` field holds the policy fragment (with `{{agent_did}}`,\n * `{{user_did}}`, `{{org}}`, `{{deployment}}` placeholders) that the runtime\n * binds and attaches to the issued delegation VC.\n */\nexport const ConsentCapabilitySchema = z\n .object({\n id: z\n .string()\n .min(1)\n .max(64)\n .regex(\n /^[a-z][a-z0-9._-]*$/,\n 'Capability id must be lowercase alphanumeric with `.`, `_`, or `-`'\n ),\n label: z.string().min(1).max(80),\n description: z.string().min(1).max(280),\n icon: z.enum([\n 'search',\n 'cart',\n 'card',\n 'pin',\n 'pin-new',\n 'shield',\n 'key',\n 'tools',\n 'user',\n 'calendar',\n 'lock',\n 'eye',\n 'send',\n 'package',\n 'neutral',\n ]),\n riskLevel: z.enum(['low', 'medium', 'high', 'critical']),\n defaultOn: z.boolean(),\n cedar: z\n .string()\n .min(1)\n .max(8000)\n .refine(\n (value) => /^\\s*(permit|forbid)\\s*\\(/.test(value),\n 'Cedar fragment must begin with `permit (` or `forbid (`'\n ),\n scopes: z.array(z.string().min(1).max(120)).min(1).max(20),\n category: z.string().max(80).optional(),\n })\n // First-Contact Scope Cap section 3, Rule 1: a high/critical capability can\n // never default on. Operators may still author one (probe-only, opt-in),\n // they just cannot pre-check the box for a grant that requires a\n // Sensitive/Critical tier. Reject at parse so this can never reach storage.\n //\n // Blast radius beyond direct capability edits: the write path\n // (UpdateBouncerConfigSchema) validates the WHOLE consentConfig on every\n // PUT/PATCH, so a stored row that already violates this rule (one exists\n // in prod today, pre-dating this floor) rejects ANY save that round-trips\n // it unchanged too -- including the dashboard editor's Cache Refresh\n // (ConsentScreenEditor.tsx's handleCacheRefresh, which merges + resubmits\n // the full stored config just to bump a cache-busting timestamp). That is\n // the intended fail-closed behavior, not a bug, but it is a wider surface\n // than \"editing capabilities\" -- an operator on an already-violating\n // project cannot even refresh the cache until the violating row is fixed.\n .superRefine((capability, ctx) => {\n if (requiresSensitiveTier(capability.riskLevel) && capability.defaultOn) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['defaultOn'],\n message: `Capability \"${capability.id}\" has riskLevel \"${capability.riskLevel}\" and cannot default on. High/critical capabilities must be structurally unmintable at first contact (First-Contact Scope Cap section 3, Rule 1).`,\n });\n }\n });\nexport type ConsentCapability = z.infer<typeof ConsentCapabilitySchema>;\n\n/**\n * Group of capabilities. Renders as a section in the consent screen.\n */\nexport const ConsentCapabilityGroupSchema = z.object({\n id: z\n .string()\n .min(1)\n .max(64)\n .regex(/^[a-z][a-z0-9._-]*$/),\n label: z.string().min(1).max(80),\n capabilities: z.array(ConsentCapabilitySchema).min(1).max(20),\n});\nexport type ConsentCapabilityGroup = z.infer<typeof ConsentCapabilityGroupSchema>;\n\n/**\n * Agent identity tile data shared between consent + gateway screens.\n */\nexport const ConsentAgentMetadataSchema = z.object({\n name: z.string().min(1).max(80),\n did: z.string().min(1).max(500),\n vendor: z.string().max(80).optional(),\n surfaceLabel: z.string().max(40).optional(),\n // Display-only. NOT authoritative for grant decisions: First-Contact\n // Scope Cap Rules 2 and 3 read first contact and verification from\n // server state (see FirstContactScopeCap resolver in\n // apps/web/lib/bouncer/services), never from this field, because it\n // sits inside the same config object an operator writes. Kept here only\n // so already-stored configs (and any future display use) keep parsing.\n verified: z.boolean(),\n logoUrl: httpUrlSchema(500).optional(),\n // Display-only, same as `verified` above: not consulted for grant\n // decisions.\n connectedAt: z.string().datetime().optional(),\n});\nexport type ConsentAgentMetadata = z.infer<typeof ConsentAgentMetadataSchema>;\n\n/**\n * Full Consent Configuration\n */\nexport const ConsentConfigSchema = z.object({\n branding: ConsentBrandingSchema.optional(),\n terms: ConsentTermsSchema.optional(),\n ui: ConsentUISchema.optional(),\n customFields: z.array(ConsentCustomFieldSchema).optional(),\n metadata: ConsentConfigMetadataSchema.optional(),\n expirationDays: z.number().int().min(1).max(365).optional(),\n // Humanized capability layout (Peter's mockup). When present the deployed\n // server renders the new design-language consent screen; when absent the\n // legacy raw-scope checkboxes are shown.\n capabilities: z.array(ConsentCapabilityGroupSchema).max(20).optional(),\n // Populated server-side only: `UpdateBouncerConfigSchema` (the one\n // write path) unconditionally rejects a write that sets this, so an\n // operator can never self-attest an agent's identity or verification\n // status. Display-only; see `ConsentAgentMetadataSchema` above. NOT\n // consulted by First-Contact Scope Cap Rules 2/3, which read server\n // state instead (apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts).\n agentMetadata: ConsentAgentMetadataSchema.optional(),\n // First-Contact Scope Cap section 3, Rules 2 and 3 opt-in. Per-project,\n // defaults to off/absent so every existing config, and every config that\n // hasn't explicitly opted in, renders byte-identically to before this\n // field existed. Flip to `true` on one project's consentConfig (a\n // normal PUT/PATCH) to turn the probe gate on for that project.\n //\n // This flag is read at RENDER time, not enforced by this schema: Rules 2\n // and 3 are not write-time properties of a config, they depend on who is\n // in front of the screen right now, which this schema has no way to\n // know. See `applyFirstContactScopeCap` in\n // apps/web/lib/bouncer/services/first-contact-scope-cap.service.ts for\n // the actual enforcement, which resolves first contact and verification\n // from server state (delegations, and a verification seam that returns\n // `indeterminate` until a real agent-verification source exists).\n firstContactScopeCapEnabled: z.boolean().optional(),\n consentTheme: z.enum(['light', 'dark']).optional(),\n headlineVerb: z.string().min(1).max(40).optional(),\n revocationPath: z.string().min(1).max(120).optional(),\n inactivityDays: z.number().int().min(1).max(3650).optional(),\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The RESOLVED bare\n // host where this project's consent screen + delegation pickup live (null\n // column → platform default). Surfaced so the consent PEP and the gateway\n // challenge emitter build consent_uri / pickup_uri from config, never a\n // hardcoded host. Populated server-side by `loadConsentConfig`.\n authorizationHost: z.string().min(1).max(255).optional(),\n});\nexport type ConsentConfig = z.infer<typeof ConsentConfigSchema>;\n\n/**\n * Tool Consent Overrides (CRED-002)\n * Per-tool customization for consent pages\n */\nexport const ToolConsentOverridesSchema = z\n .object({\n branding: ConsentBrandingSchema.partial().optional(),\n terms: ConsentTermsSchema.partial().optional(),\n headerText: z.string().max(255).optional(),\n description: z.string().max(1000).optional(),\n })\n .optional();\nexport type ToolConsentOverrides = z.infer<typeof ToolConsentOverridesSchema>;\n\n/**\n * Bouncer Config (for GET response)\n */\nexport const BouncerConfigSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n\n // Authorization settings\n reputationThreshold: z.number().int().min(0).max(100).default(76),\n allowedScopes: z.array(z.string()).default([]),\n deniedAgents: z.array(z.string()).default([]),\n\n // CRISP budget settings\n crispEnabled: z.boolean().default(false),\n crispBudget: CRISPBudgetSchema.nullable().optional(),\n\n // Multi-provider OAuth configuration (CRED-001)\n oauthProviders: OAuthProvidersMapSchema.default({}),\n defaultProvider: z.string().max(50).nullable().optional(),\n\n // Legacy OAuth configuration (deprecated - use oauthProviders)\n oauthClientId: z.string().max(255).nullable().optional(),\n oauthClientSecret: z.string().nullable().optional(), // Encrypted\n oauthRedirectUri: httpUrlSchema(500).nullable().optional(),\n oauthAuthEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthTokenEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthProviderType: OAuthProviderTypeSchema.default('oauth2'),\n oauthScopes: z.array(ScopeSchema).default([]),\n oauthConnectionStatus: OAuthConnectionStatusSchema.default('disconnected'),\n lastScopesSync: z.string().datetime().nullable().optional(),\n\n // Delegation configuration\n delegationExpirationDays: z.number().int().positive().default(7),\n\n // Consent page configuration\n consentConfig: ConsentConfigSchema.optional(),\n\n // Tool discovery\n discoveredTools: z.record(z.string(), z.unknown()).default({}),\n mcpServerUrl: httpUrlSchema().nullable().optional(),\n mcpWorkerUrl: httpUrlSchema().nullable().optional(),\n\n // Organization settings\n isEnabled: z.boolean().default(false),\n updatedAt: z.string().datetime(),\n createdAt: z.string().datetime(),\n});\nexport type BouncerConfig = z.infer<typeof BouncerConfigSchema>;\n\n/**\n * Update Bouncer Config (for PUT request body)\n */\nexport const UpdateBouncerConfigSchema = z\n .object({\n // Authorization settings\n reputationThreshold: z.number().int().min(0).max(100).optional(),\n allowedScopes: z.array(z.string()).optional(),\n deniedAgents: z.array(z.string()).optional(),\n\n // CRISP budget settings\n crispEnabled: z.boolean().optional(),\n crispBudget: CRISPBudgetSchema.nullable().optional(),\n\n // Multi-provider OAuth configuration (CRED-001)\n defaultProvider: z.string().max(50).nullable().optional(),\n\n // Legacy OAuth configuration (deprecated - use providers endpoint)\n oauthClientId: z.string().max(255).nullable().optional(),\n oauthClientSecret: z.string().nullable().optional(), // Will be encrypted by API\n oauthRedirectUri: httpUrlSchema(500).nullable().optional(),\n oauthAuthEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthTokenEndpoint: httpUrlSchema(500).nullable().optional(),\n oauthProviderType: OAuthProviderTypeSchema.optional(),\n oauthConnectionStatus: OAuthConnectionStatusSchema.optional(),\n\n // Delegation configuration\n delegationExpirationDays: z.number().int().positive().optional(),\n\n // Consent page configuration\n consentConfig: ConsentConfigSchema.optional(),\n\n // MCP Server URL (for manual configuration)\n mcpServerUrl: httpUrlSchema().nullable().optional(),\n\n // Organization settings\n isEnabled: z.boolean().optional(),\n })\n .strict()\n // First-Contact Scope Cap section 3: `agentMetadata` represents facts\n // about a specific requesting agent (identity, verification, connection\n // age), not an operator preference. It has no legitimate writer today (no\n // admin UI, no other backend job sets it), so this is the only place it\n // could ever reach storage. If an operator could submit it here, they\n // could self-attest `verified: true` and any `connectedAt` in the same\n // write that defines their capabilities, defeating Rules 2/3 entirely\n // since nothing else re-checks that claim against a real agent. Reject it\n // unconditionally so a stored `agentMetadata`, if one ever exists, can\n // only have come from a future render-assembly step, never the operator.\n .superRefine((data, ctx) => {\n if (data.consentConfig?.agentMetadata !== undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['consentConfig', 'agentMetadata'],\n message:\n 'consentConfig.agentMetadata cannot be set through this endpoint. It represents verified facts about a specific requesting agent, not an operator preference, and this is not the write path that populates it.',\n });\n }\n });\nexport type UpdateBouncerConfig = z.infer<typeof UpdateBouncerConfigSchema>;\n\n/**\n * Refresh Scopes Request\n */\nexport const RefreshScopesRequestSchema = z\n .object({\n mcpServerUrl: httpUrlSchema().optional(),\n })\n .strict();\nexport type RefreshScopesRequest = z.infer<typeof RefreshScopesRequestSchema>;\n\n/**\n * Delegation Status\n */\nexport const DelegationStatusSchema = z.enum(['active', 'expired', 'revoked']);\nexport type DelegationStatus = z.infer<typeof DelegationStatusSchema>;\n\n/**\n * Delegation (for GET response)\n */\nexport const DelegationSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n agentDid: z.string().max(500),\n agentName: z.string().max(255).nullable().optional(),\n // User identification - userDid is primary for KYA-OS, others for backward compatibility\n userDid: z.string().max(500).nullable().optional(), // DID of authorizing user (did:key or did:web)\n userId: z.string().max(500).nullable().optional(), // Internal application user ID\n userIdentifier: z.string().max(500).nullable().optional(), // Human-readable (email)\n scopes: z.array(z.string()),\n constraints: z.record(z.string(), z.unknown()).nullable().optional(),\n status: DelegationStatusSchema.default('active'),\n issuedAt: z.string().datetime(),\n expiresAt: z.string().datetime().nullable().optional(),\n revokedAt: z.string().datetime().nullable().optional(),\n revocationReason: z.string().max(500).nullable().optional(),\n credentialJwt: z.string().nullable().optional(),\n metadata: z.record(z.string(), z.unknown()).default({}),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n});\nexport type Delegation = z.infer<typeof DelegationSchema>;\n\n/**\n * Bouncer Proof Outcome\n */\nexport const BouncerOutcomeSchema = z.enum(['success', 'failed', 'blocked', 'error']);\nexport type BouncerOutcome = z.infer<typeof BouncerOutcomeSchema>;\n\n/**\n * Bouncer Proof (for GET response)\n */\nexport const BouncerProofSchema = z.object({\n id: z.string().uuid(),\n projectId: z.string().uuid(),\n delegationId: z.string().uuid().nullable().optional(),\n sessionId: z.string().max(100),\n agentDid: z.string().max(500),\n userIdentifier: z.string().max(500).nullable().optional(),\n toolName: z.string().max(255),\n toolArgs: z.record(z.string(), z.unknown()).nullable().optional(),\n toolResult: z.record(z.string(), z.unknown()).nullable().optional(),\n scopes: z.array(z.string()).nullable().optional(),\n signature: z.string(),\n publicKey: z.string(),\n timestamp: z.number().int(), // Unix timestamp\n nonce: z.string().max(100),\n crispDelta: z.record(z.string(), z.unknown()).nullable().optional(),\n outcome: BouncerOutcomeSchema.default('success'),\n errorMessage: z.string().nullable().optional(),\n createdAt: z.string().datetime(),\n});\nexport type BouncerProof = z.infer<typeof BouncerProofSchema>;\n\n/**\n * Delegation Polling Status\n */\nexport const DelegationPollingStatusSchema = z.object({\n status: z.enum(['pending', 'completed', 'expired', 'error']),\n delegationJwt: z.string().optional(), // Only present when status is 'completed'\n authUrl: httpUrlSchema().optional(), // Only present when status is 'pending'\n errorMessage: z.string().optional(), // Only present when status is 'error'\n expiresAt: z.string().datetime().optional(),\n});\nexport type DelegationPollingStatus = z.infer<typeof DelegationPollingStatusSchema>;\n\n/**\n * Custom URL validator that allows:\n * - Valid URLs (standard URL format)\n * - Empty strings (for optional endpoints)\n * - Placeholder URLs (URLs with {placeholder} patterns like {shop}, {domain})\n */\nconst urlOrPlaceholderSchema = z.string().refine(\n (val) => {\n if (val === '') return true; // Empty string is allowed\n // Check if it's a valid URL\n try {\n new URL(val);\n return true;\n } catch {\n // If not a valid URL, check if it's a placeholder URL (contains {placeholder})\n // Placeholder URLs follow URL structure but have {placeholder} segments\n // Example: https://{shop}.myshopify.com/admin/oauth/authorize\n const placeholderUrlPattern = /^https?:\\/\\/[^\\s]+$/;\n return placeholderUrlPattern.test(val) && val.includes('{') && val.includes('}');\n }\n },\n {\n message:\n 'Must be a valid URL, empty string, or placeholder URL (e.g., https://{shop}.example.com)',\n }\n);\n\n/**\n * OAuth Mode - determines how the OAuth flow is handled\n * - 'direct': KYA-OS handles OAuth directly with IDP (PKCE support, no secret needed)\n * - 'proxy': KYA-OS routes through Checkpoint (keeps client_secret secure server-side)\n */\nexport const OAuthModeSchema = z.enum(['direct', 'proxy']);\nexport type OAuthMode = z.infer<typeof OAuthModeSchema>;\n\n/**\n * OAuth Provider Metadata Schema\n * Used for /api/v1/bouncer/projects/{projectId}/providers endpoint\n */\nexport const OAuthProviderMetadataSchema = z.object({\n clientId: z.string().nullable(),\n // SECURITY: clientSecret is intentionally NOT returned in API responses\n // Agents receive only hasClientSecret flag and metadata.clientSecretName for runtime resolution\n hasClientSecret: z.boolean(), // Boolean for quick detection\n authorizationUrl: urlOrPlaceholderSchema, // Allow valid URLs, empty strings, or placeholder URLs\n tokenUrl: urlOrPlaceholderSchema, // Allow valid URLs, empty strings, or placeholder URLs\n userInfoUrl: urlOrPlaceholderSchema.optional(), // Optional per contracts interface\n supportsPKCE: z.boolean(),\n requiresClientSecret: z.boolean(),\n proxyMode: z.boolean().optional(), // Optional per contracts interface (deprecated - use mode)\n scopes: z.array(z.string()).optional(), // Optional per contracts interface\n defaultScopes: z.array(z.string()).optional(), // Optional per contracts interface\n // Phase 3 fields (all optional for backward compatibility)\n customParams: z.record(z.string(), z.string()).optional(),\n tokenEndpointAuthMethod: z.enum(['client_secret_post', 'client_secret_basic']).optional(),\n responseType: z.string().optional(),\n grantType: z.string().optional(),\n // KYA-OS coordination fields (added per OAUTH_FLOW_COORDINATION_PLAN.md)\n configured: z.boolean().optional(), // Whether this provider is configured for the project\n mode: OAuthModeSchema.optional(), // OAuth flow mode: 'direct' (PKCE) or 'proxy' (Checkpoint)\n // KYA-OS Provider Registry: Secret resolution metadata\n metadata: z\n .object({\n clientSecretName: z.string().optional(),\n clientIdSecretName: z.string().optional(),\n apiKeySecretName: z.string().optional(),\n clientSecretVersion: z.number().optional(),\n lastRotatedAt: z.string().optional(),\n })\n .optional(),\n});\nexport type OAuthProviderMetadata = z.infer<typeof OAuthProviderMetadataSchema>;\n\n/**\n * Providers API Response Schema\n * Used for /api/v1/bouncer/projects/{projectId}/providers endpoint\n */\nexport const ProvidersResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n providers: z.record(z.string(), OAuthProviderMetadataSchema),\n configuredProvider: z.string().nullable(),\n }),\n metadata: z.object({\n requestId: z.string(),\n timestamp: z.string().datetime(),\n }),\n});\nexport type ProvidersResponse = z.infer<typeof ProvidersResponseSchema>;\n\n/**\n * OAuth Tokens Response Schema\n * Used for GET /api/v1/bouncer/delegations/{delegationId}/tokens endpoint\n */\nexport const OAuthTokensResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n oauth_access_token: z.string(),\n oauth_refresh_token: z.string().nullable(),\n oauth_expires_at: z.string().datetime().nullable(), // ISO 8601\n oauth_expires_in: z.number().nullable(), // Seconds\n oauth_token_type: z.string(), // Token type (e.g., \"Bearer\")\n oauth_scope: z.string().nullable(), // Granted scopes (space-separated string)\n }),\n metadata: z.object({\n requestId: z.string(),\n timestamp: z.string().datetime(),\n }),\n});\nexport type OAuthTokensResponse = z.infer<typeof OAuthTokensResponseSchema>;\n\n// ==============================================================================\n// PROVIDERS CONFIG ENVELOPE (Provider Registry Alignment)\n// ==============================================================================\n\n/**\n * Checkpoint Provider Definition Schema\n *\n * This is the Checkpoint-specific provider definition used in API responses\n * and configuration. It has field naming differences from the canonical\n * @kya-os/provider-registry ProviderDefinition:\n *\n * | Checkpoint Field | Provider Registry Field | Notes |\n * |---------------------|----------------------------|--------------------------|\n * | type | authType | Both accept 'password' |\n * | authorizationUrl | oauthConfig.authorizationEndpoint | Nested in registry |\n * | tokenUrl | oauthConfig.tokenEndpoint | Nested in registry |\n * | userInfoUrl | oauthConfig.userInfoEndpoint | Nested in registry |\n *\n * For mapping between formats, use `toProviderRegistryFormat()` and\n * `fromProviderRegistryFormat()` helper functions.\n *\n * SECURITY: This schema NEVER contains actual secret values.\n * Only metadata.clientSecretName (reference to secure storage) is included.\n *\n * @see ProviderRegistryDefinition from @kya-os/provider-registry for canonical format\n */\nexport const ProviderDefinitionSchema = z.object({\n id: z.string().min(1),\n type: AuthProviderTypeSchema,\n displayName: z.string().optional(),\n configured: z.boolean().default(false),\n // OAuth2 specific fields (flat structure for API compat)\n authorizationUrl: z.string().optional(),\n tokenUrl: z.string().optional(),\n userInfoUrl: z.string().optional(),\n supportsPKCE: z.boolean().optional(),\n requiresClientSecret: z.boolean().optional(),\n // Credentials (only clientId is safe - NEVER clientSecret)\n clientId: z.string().nullable().optional(),\n hasClientSecret: z.boolean().default(false),\n // Scopes\n scopes: z.array(z.string()).optional(),\n defaultScopes: z.array(z.string()).optional(),\n // Mode\n mode: z.enum(['direct', 'proxy']).optional(),\n // Secret metadata (references to secure storage)\n metadata: ProviderSecretMetadataSchema.optional(),\n});\nexport type ProviderDefinition = z.infer<typeof ProviderDefinitionSchema>;\n\n/**\n * Canonical provider definition from @kya-os/provider-registry\n *\n * Re-exported for consumers who need the canonical format.\n * Use `toProviderRegistryFormat()` to convert Checkpoint format.\n */\nexport type { ProviderRegistryDefinition } from './provider-registry';\n\n/**\n * Providers Config Source Metadata\n * Tracks where the config came from for debugging and auditing\n */\nexport const ProvidersConfigSourceSchema = z.object({\n projectId: z.string().uuid(),\n projectFriendlyId: z.string(),\n deployId: z.string().uuid().optional(),\n generatedAt: z.string().datetime(),\n agentShieldVersion: z.string(),\n});\nexport type ProvidersConfigSource = z.infer<typeof ProvidersConfigSourceSchema>;\n\n/**\n * Providers Config Envelope\n *\n * The full signed configuration document served to KYA-OS agents.\n * Includes HMAC signature for tamper detection.\n *\n * SECURITY:\n * - NEVER contains actual secret values (clientSecret, apiKey, etc.)\n * - Agents MUST verify HMAC signature before loading\n * - Agents resolve secrets from secure storage at runtime using metadata.clientSecretName\n */\nexport const ProvidersConfigEnvelopeSchema = z.object({\n // Version for atomic updates (incrementing integer)\n version: z.number().int().positive(),\n // Source metadata for debugging and auditing\n source: ProvidersConfigSourceSchema,\n // Provider definitions (keyed by provider ID)\n providers: z.record(z.string(), ProviderDefinitionSchema),\n // HMAC signature for tamper detection (SHA-256 hex)\n signature: z\n .string()\n .regex(/^[a-f0-9]{64}$/)\n .optional(),\n // Which fields are included in the signature\n signedFields: z.array(z.string()).optional(),\n});\nexport type ProvidersConfigEnvelope = z.infer<typeof ProvidersConfigEnvelopeSchema>;\n\n// ==============================================================================\n// FORMAT CONVERSION HELPERS (Provider Registry <-> Checkpoint)\n// ==============================================================================\n\nimport type { ProviderRegistryDefinition } from './provider-registry';\n\n/**\n * Convert Checkpoint ProviderDefinition to canonical @kya-os/provider-registry format.\n *\n * Use this when sending provider config to KYA-OS agents that expect the canonical format.\n *\n * @example\n * ```typescript\n * const agentShieldProvider: ProviderDefinition = { ... };\n * const canonicalProvider = toProviderRegistryFormat(agentShieldProvider);\n * // Now canonicalProvider has nested oauthConfig structure\n * ```\n */\nexport function toProviderRegistryFormat(provider: ProviderDefinition): ProviderRegistryDefinition {\n const { type, authorizationUrl, tokenUrl, userInfoUrl, ...rest } = provider;\n\n // type is already 'oauth2' | 'password' after schema transformation\n // (legacy 'credential' is transformed to 'password' by AuthProviderTypeSchema)\n const authType: 'oauth2' | 'password' = type;\n\n // Base definition\n const result: ProviderRegistryDefinition = {\n id: rest.id,\n authType,\n displayName: rest.displayName,\n defaultScopes: rest.defaultScopes || rest.scopes,\n metadata: rest.metadata as Record<string, unknown>,\n };\n\n // Add OAuth config if OAuth provider\n if (authType === 'oauth2' && (authorizationUrl || tokenUrl)) {\n result.oauthConfig = {\n authorizationEndpoint: authorizationUrl || '',\n tokenEndpoint: tokenUrl || '',\n userInfoEndpoint: userInfoUrl,\n supportsPKCE: rest.supportsPKCE,\n requiresClientSecret: rest.requiresClientSecret,\n defaultScopes: rest.defaultScopes || rest.scopes,\n };\n }\n\n return result;\n}\n\n/**\n * Supported auth types that can be converted to Checkpoint ProviderDefinition.\n * Other types (passkey, magic_link, otp, etc.) are not yet supported.\n */\nexport type SupportedProviderAuthType = 'oauth2' | 'password';\n\n/**\n * Check if a provider auth type is supported by Checkpoint.\n */\nexport function isSupportedAuthType(\n authType: ProviderAuthType\n): authType is SupportedProviderAuthType {\n return authType === 'oauth2' || authType === 'password';\n}\n\n/**\n * Convert canonical @kya-os/provider-registry format to Checkpoint ProviderDefinition.\n *\n * Use this when receiving provider config from external sources in canonical format.\n *\n * **Note:** Only 'oauth2' and 'password' auth types are currently supported.\n * Providers with other auth types (passkey, magic_link, otp, etc.) will throw an error.\n * Use `isSupportedAuthType()` to check before calling this function.\n *\n * @throws {Error} If the provider's auth type is not supported\n *\n * @example\n * ```typescript\n * import { defaultProviderRegistry } from '@kya-os/provider-registry';\n *\n * const canonicalProvider = defaultProviderRegistry.getProvider('github');\n * if (canonicalProvider && isSupportedAuthType(canonicalProvider.authType)) {\n * const agentShieldProvider = fromProviderRegistryFormat(canonicalProvider);\n * // Now agentShieldProvider has flat structure for Checkpoint APIs\n * }\n * ```\n */\nexport function fromProviderRegistryFormat(\n provider: ProviderRegistryDefinition\n): ProviderDefinition {\n // Validate auth type is supported\n if (!isSupportedAuthType(provider.authType)) {\n throw new Error(\n `Auth type '${provider.authType}' is not yet supported in AgentShield. ` +\n `Provider '${provider.id}' cannot be converted. ` +\n `Supported types: 'oauth2', 'password'.`\n );\n }\n\n return {\n id: provider.id,\n type: provider.authType, // Now type-safe: only 'oauth2' | 'password'\n displayName: provider.displayName,\n configured: false, // External providers need configuration\n authorizationUrl: provider.oauthConfig?.authorizationEndpoint,\n tokenUrl: provider.oauthConfig?.tokenEndpoint,\n userInfoUrl: provider.oauthConfig?.userInfoEndpoint,\n supportsPKCE: provider.oauthConfig?.supportsPKCE,\n requiresClientSecret: provider.oauthConfig?.requiresClientSecret,\n clientId: null,\n hasClientSecret: false,\n scopes: provider.defaultScopes,\n defaultScopes: provider.defaultScopes,\n metadata: provider.metadata as ProviderSecretMetadata,\n };\n}\n\n/**\n * Safely convert canonical format to Checkpoint format, returning null for unsupported types.\n *\n * Use this when you want to gracefully skip unsupported providers instead of throwing.\n */\nexport function fromProviderRegistryFormatSafe(\n provider: ProviderRegistryDefinition\n): ProviderDefinition | null {\n if (!isSupportedAuthType(provider.authType)) {\n return null;\n }\n return fromProviderRegistryFormat(provider);\n}\n","/**\n * Organization Types and Interfaces\n *\n * Types related to organization management, validation, and errors\n */\n\nimport { z } from 'zod';\nimport { httpUrlSchema } from '../schemas/bouncer';\n\nconst organizationDomainSchema = z\n .string()\n .trim()\n .toLowerCase()\n .min(1, 'Domain is required')\n .max(255, 'Domain must be less than 255 characters')\n .regex(\n /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/,\n 'Domain must be a valid hostname'\n );\n\nconst clearableOptionalString = <TSchema extends z.ZodTypeAny>(schema: TSchema) =>\n schema.nullable().optional();\n\n/** Hostname rule shared with `organizationDomainSchema` (kept in sync). */\nconst HOSTNAME_REGEX = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+$/;\n\n/**\n * Accepted org logo values:\n * - an http(s) image URL (manually pasted), OR\n * - a `d:<domain>` token, which the app resolves to a logo.dev CDN URL at\n * read time (the auto-fetch-from-domain path), OR\n * - '' (and, at the field level, null) to clear.\n *\n * Implemented as a single refined string (not a `z.union`) to avoid Zod\n * union-inference pitfalls (TS2345). The `d:` form is validated against the\n * same hostname rule as claimed domains so a junk value can't be persisted.\n */\nconst organizationLogoSchema = z\n .string()\n .max(500)\n .refine(\n (v) => {\n if (v === '') return true; // explicit clear\n if (v.startsWith('d:')) return HOSTNAME_REGEX.test(v.slice(2));\n return httpUrlSchema(500).safeParse(v).success;\n },\n { message: 'Logo must be an http(s) URL or a d:domain token' }\n );\n\n/**\n * Organization-level SSO provider and policy settings.\n */\nexport const OrganizationSsoProviderSchema = z.enum(['rippling', 'saml']);\nexport type OrganizationSsoProvider = z.infer<typeof OrganizationSsoProviderSchema>;\n\nexport const OrganizationSsoModeSchema = z.enum(['optional', 'required']);\nexport type OrganizationSsoMode = z.infer<typeof OrganizationSsoModeSchema>;\n\nexport const OrganizationSsoSettingsSchema = z\n .object({\n enabled: z.boolean().optional(),\n mode: OrganizationSsoModeSchema.optional(),\n provider: OrganizationSsoProviderSchema.optional(),\n loginUrl: clearableOptionalString(z.string().url('SSO login URL must be a valid URL').max(500)),\n metadataUrl: clearableOptionalString(\n z.string().url('Metadata URL must be a valid URL').max(1000)\n ),\n metadataXml: clearableOptionalString(\n z.string().min(1, 'Metadata XML cannot be empty').max(500000)\n ),\n idpEntityId: clearableOptionalString(z.string().max(1000)),\n idpSsoUrl: clearableOptionalString(z.string().url('IdP SSO URL must be a valid URL').max(1000)),\n domains: z.array(organizationDomainSchema).max(50).optional(),\n allowPasswordFallback: z.boolean().optional(),\n autoProvisionMembers: z.boolean().optional(),\n /**\n * ISO-8601 timestamp of the last successful \"Test connection\". Lets the\n * verified state survive navigation (it's persisted JSON, re-parsed on\n * read — must stay a string, not z.date()). Cleared (null) when a\n * connection-affecting field changes, so a stale verification can't show\n * as current.\n */\n lastVerifiedAt: clearableOptionalString(z.string().datetime()),\n })\n .superRefine((value, ctx) => {\n // Validate strict login URL requirements only when callers explicitly submit\n // a full \"required SSO with no fallback\" configuration in this payload.\n // Partial updates are merged server-side with existing settings.\n const explicitlyRequiresSso =\n value.enabled === true && value.mode === 'required' && value.allowPasswordFallback === false;\n\n if (explicitlyRequiresSso && !value.loginUrl && !value.idpSsoUrl) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['loginUrl'],\n message:\n 'SSO login URL is required when mode is required and password fallback is disabled',\n });\n }\n });\n\nexport type OrganizationSsoSettings = z.infer<typeof OrganizationSsoSettingsSchema>;\n\n/**\n * Organization settings schema\n */\nexport const OrganizationSettingsSchema = z.object({\n maxProjects: z.number().optional(),\n maxMembers: z.number().optional(),\n /** Whether this is a personal/default organization created for a user */\n isPersonalOrg: z.boolean().optional(),\n sso: OrganizationSsoSettingsSchema.optional(),\n features: z\n .object({\n advancedAnalytics: z.boolean().optional(),\n customBranding: z.boolean().optional(),\n ssoEnabled: z.boolean().optional(),\n })\n .optional(),\n});\n\nexport type OrganizationSettings = z.infer<typeof OrganizationSettingsSchema>;\n\n/**\n * Organization role schema and type\n * Single source of truth for runtime validation and TypeScript types.\n * Adding a role here will update both; used when parsing DB role values.\n */\nexport const OrganizationRoleSchema = z.enum(['owner', 'admin', 'member']);\nexport type OrganizationRole = z.infer<typeof OrganizationRoleSchema>;\n\n/**\n * Base organization interface\n */\nexport interface Organization {\n id: string;\n name: string;\n slug: string;\n logoUrl?: string | null;\n settings: OrganizationSettings;\n /**\n * The org's designated primary project — the deterministic default anchor for\n * navigation (land on a chosen project) and the gateway merchant-consent flow.\n * Nullable: unset, or the referenced project was hard-deleted (FK ON DELETE\n * SET NULL). It may still point at a SOFT-deleted project, so resolve through\n * `resolveOrgPrimaryProject` before relying on it rather than reading raw.\n */\n primaryProjectId?: string | null;\n deletedAt?: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Organization with member information\n */\nexport interface OrganizationWithMembers extends Organization {\n members: OrganizationMember[];\n memberCount: number;\n projectCount: number;\n}\n\n/**\n * Organization member interface\n */\nexport interface OrganizationMember {\n organizationId: string;\n userId: string;\n role: OrganizationRole;\n joinedAt: Date;\n user?: {\n id: string;\n email: string;\n name?: string;\n image?: string;\n };\n}\n\n/**\n * User organizations response\n */\nexport interface UserOrganizations {\n organizations: (Organization & { role: OrganizationRole })[];\n defaultOrganizationId?: string;\n}\n\n/**\n * Create organization input with enhanced validation\n */\nexport const CreateOrganizationInputSchema = z.object({\n name: z\n .string()\n .min(2, 'Organization name must be at least 2 characters')\n .max(100, 'Organization name must be less than 100 characters')\n .trim()\n .regex(\n /^[a-zA-Z0-9\\s\\-&.,]+$/,\n 'Organization name can only contain letters, numbers, spaces, hyphens, ampersands, periods, and commas'\n )\n .transform((val) => val.trim()),\n slug: z\n .string()\n .min(1)\n .max(100)\n .regex(/^[a-z0-9-]+$/, 'Slug can only contain lowercase letters, numbers, and hyphens')\n .optional(),\n settings: OrganizationSettingsSchema.optional(),\n});\n\nexport type CreateOrganizationInput = z.infer<typeof CreateOrganizationInputSchema>;\n\n/**\n * Update organization input\n */\nexport const UpdateOrganizationInputSchema = z.object({\n name: z\n .string()\n .min(2, 'Organization name must be at least 2 characters')\n .max(100, 'Organization name must be less than 100 characters')\n .trim()\n .regex(\n /^[a-zA-Z0-9\\s\\-&.,]+$/,\n 'Organization name can only contain letters, numbers, spaces, hyphens, ampersands, periods, and commas'\n )\n .transform((val) => val.trim())\n .optional(),\n logoUrl: organizationLogoSchema.nullable().optional(),\n // REASON: single refined string (max 500) — http(s) URL, d:<hostname>, or '' to clear.\n settings: OrganizationSettingsSchema.optional(),\n});\n\nexport type UpdateOrganizationInput = z.infer<typeof UpdateOrganizationInputSchema>;\n\n/**\n * Organization error codes\n */\nexport enum OrganizationErrorCode {\n NAME_DUPLICATE = 'ORG_NAME_DUPLICATE',\n SLUG_DUPLICATE = 'ORG_SLUG_DUPLICATE',\n NOT_FOUND = 'ORG_NOT_FOUND',\n ACCESS_DENIED = 'ORG_ACCESS_DENIED',\n LIMIT_EXCEEDED = 'ORG_LIMIT_EXCEEDED',\n INVALID_NAME = 'ORG_INVALID_NAME',\n OPERATION_FAILED = 'ORG_OPERATION_FAILED',\n}\n\n/**\n * Organization suggestion for similar names\n */\nexport interface OrganizationSuggestion {\n id: string;\n name: string;\n slug: string;\n similarity: number; // 0-100 percentage\n}\n\n/**\n * Organization duplicate error response\n */\nexport interface OrganizationDuplicateError {\n code: OrganizationErrorCode.NAME_DUPLICATE;\n message: string;\n field: 'name';\n suggestions?: OrganizationSuggestion[];\n existingOrganization?: {\n id: string;\n name: string;\n slug: string;\n };\n}\n\n/**\n * Validation helpers\n */\nexport function normalizeOrganizationName(name: string): string {\n return name.trim().toLowerCase();\n}\n\nexport function validateOrganizationName(name: string): { valid: boolean; error?: string } {\n try {\n CreateOrganizationInputSchema.shape.name.parse(name);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return { valid: false, error: error.issues[0]?.message || 'Invalid organization name' };\n }\n return { valid: false, error: 'Invalid organization name' };\n }\n}\n","/**\n * Authorization Host resolution — draft-kya-http-02 §7 (H1.1 #3244).\n *\n * The **Authorization Host** is the per-project host that renders the\n * delegation consent screen and serves delegation pickup. Every PEP\n * (Policy Enforcement Point) config payload — routing entry, gateway\n * config, policy config, bouncer config — carries the RESOLVED host so a\n * PEP can build a challenge's `consent_uri` / `pickup_uri` against it.\n * Per spec §7, PEPs MUST read it from config and never hardcode it.\n *\n * Representation: a **bare host** (no scheme, no trailing slash), matching\n * the spec's `authorization_host` field (e.g. `auth.merchant.com`). The\n * challenge emitter (H2.1-WF) prepends `https://` and the path, exactly as\n * the golden fixtures show: `authorization_host=\"auth.merchant.com\"` →\n * `consent_uri=\"https://auth.merchant.com/consent?sid=…\"`.\n *\n * Resolution rule:\n * - project value set → org-branded host (e.g. `authenticate.acme.com`)\n * - project value null → the platform default host\n *\n * This module is intentionally pure (no env access): each caller supplies\n * its own `platformDefaultHost` so the Next.js web app (NEXT_PUBLIC_APP_URL)\n * and the Fly gateway can each resolve against the host they front. The\n * `DEFAULT_AUTHORIZATION_HOST` constant is the last-resort fallback when a\n * caller has no configured origin.\n */\n\n/**\n * Last-resort platform Authorization Host (bare host) when a caller passes no\n * `platformDefaultHost`. Mirrors the web app's production origin\n * (`https://kya.vouched.id`) reduced to its host.\n *\n * NOTE for non-web callers (Fly gateway, edge worker): you MUST pass your own\n * `platformDefaultHost` to {@link resolveAuthorizationHost}. This constant is a\n * web-origin fallback only — relying on it from another deployment silently\n * brands every unset project as the web app instead of the host you front.\n */\nexport const DEFAULT_AUTHORIZATION_HOST = 'kya.vouched.id';\n\n/**\n * Reduce an origin or host string to a normalized bare host: strips any\n * `http(s)://` scheme and trailing slashes, then lower-cases it. Hosts are\n * case-insensitive, so lower-casing keeps two equivalent configs byte-identical\n * on the wire (the golden fixtures are lower-case). Idempotent on values that\n * are already bare + lower-case.\n *\n * `https://Kya.Vouched.id/` → `kya.vouched.id`\n * `authenticate.acme.com` → `authenticate.acme.com`\n *\n * Normalization only — it does NOT validate. Use {@link isValidAuthorizationHost}\n * at the write boundary to reject paths, userinfo, whitespace, and bad labels.\n */\nexport function toBareHost(value: string): string {\n const withoutScheme = value.trim().replace(/^https?:\\/\\//i, '');\n // Strip trailing slashes with a linear scan rather than `/\\/+$/` — that\n // anchored, unbounded-repetition regex is a polynomial-ReDoS vector on\n // host strings with many trailing slashes (CodeQL js/polynomial-redos).\n let end = withoutScheme.length;\n while (end > 0 && withoutScheme.charCodeAt(end - 1) === 47 /* '/' */) {\n end--;\n }\n return withoutScheme.slice(0, end).toLowerCase();\n}\n\n/**\n * Validate that a value is a usable Authorization Host: it becomes the\n * authority of an `https://<host>/…` challenge URI, so anything that smuggles\n * a path, query, fragment, userinfo (`@`), or whitespace would silently produce\n * a broken or misdirected consent URL. After scheme/slash normalization the\n * value must be a bare `host[:port]` of RFC 1123 labels (`:port` allowed for\n * dev). Reject everything else at the write boundary.\n *\n * `authenticate.acme.com` → true\n * `localhost:3000` → true\n * `authenticate.acme.com/evil` → false (path)\n * `legit.com@evil.com` → false (userinfo)\n * `bad host.com` / `-acme.com` → false (whitespace / bad label)\n */\nexport function isValidAuthorizationHost(value: string): boolean {\n const bare = toBareHost(value);\n if (!bare || bare.length > 255) return false;\n // No path / query / fragment / userinfo / backslash / whitespace.\n if (/[/\\\\?#@\\s]/.test(bare)) return false;\n\n const parts = bare.split(':');\n if (parts.length > 2) return false; // at most one `:port`\n const [host, port] = parts;\n if (port !== undefined) {\n // A port must be 1-65535. The `1*5DIGIT` shape alone let \"99999\" through;\n // range-check it so an out-of-range port can't become a URL authority.\n if (!/^\\d{1,5}$/.test(port)) return false;\n const portNum = Number(port);\n if (portNum < 1 || portNum > 65535) return false;\n }\n if (host.length === 0 || host.length > 253) return false;\n\n // RFC 1123 labels: 1-63 of [a-z0-9-], no leading/trailing hyphen. The bounded\n // {0,61} keeps this linear (no catastrophic backtracking).\n const label = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n return host.split('.').every((l) => label.test(l));\n}\n\n/**\n * Resolve a project's effective Authorization Host as a bare host.\n *\n * @param authorizationHost - the `projects.authorization_host` column value\n * (null/blank → use the platform default).\n * @param platformDefaultHost - the caller's platform origin or host, used\n * when the project has no override. Defaults to\n * {@link DEFAULT_AUTHORIZATION_HOST}.\n */\nexport function resolveAuthorizationHost(\n authorizationHost: string | null | undefined,\n platformDefaultHost: string = DEFAULT_AUTHORIZATION_HOST\n): string {\n const override = authorizationHost?.trim();\n return toBareHost(override && override.length > 0 ? override : platformDefaultHost);\n}\n","/**\n * Internal API Schemas\n *\n * Schemas for internal dashboard API endpoints\n * Used for validation and type safety in internal routes\n */\n\nimport { z } from 'zod';\nimport { PAGINATION_DEFAULTS } from '../constants';\nimport {\n ApiKeyPermissionSchema,\n ApiKeyRateLimitsSchema,\n PixelConfigurationSchema,\n} from '../types/entities';\nimport {\n CreateOrganizationInputSchema,\n UpdateOrganizationInputSchema,\n} from '../types/organization';\nimport { isValidAuthorizationHost } from '../mcpi/authorization-host';\n\n/**\n * Flexible Project ID Schema\n * Accepts UUID format, kta- format, and friendly ID format\n *\n * \"Friendly ID format\" covers two shapes: a slug-suffix pair (e.g.\n * \"my-project-a1b2c3\") minted only to disambiguate a name collision, and a\n * bare slug with no suffix (e.g. \"my-project\"): the common case, minted by\n * apps/web's resolveUniqueFriendlyProjectId whenever a project's name is\n * unique. The bare-slug branch is capped at 20 characters to match\n * slugify()'s own truncation (apps/web/lib/utils/project-id.ts), so this\n * doesn't also swallow unrelated garbage (e.g. a truncated UUID) that\n * happens to be lowercase-alnum-and-hyphens shaped.\n */\nexport const ProjectIdSchema = z.string().refine(\n (val) => {\n // UUID v4 format\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n // Legacy kta- format (kta-XXXXXX where X is alphanumeric)\n const ktaIdRegex = /^kta-[a-z0-9]{6}$/;\n // Friendly ID format (slug-suffix, e.g., \"my-project-a1b2c3\")\n const friendlyIdRegex = /^[a-z0-9-]+-[a-z0-9]{6}$/;\n // Bare slug, no suffix (e.g. \"my-project\")\n const bareSlugRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;\n return (\n uuidRegex.test(val) ||\n ktaIdRegex.test(val) ||\n friendlyIdRegex.test(val) ||\n (val.length <= 20 && bareSlugRegex.test(val))\n );\n },\n {\n message:\n 'Invalid project ID format. Must be a UUID, kta-XXXXXX, or friendly ID (e.g., \"my-project-a1b2c3\" or \"my-project\")',\n }\n);\n\n/**\n * Flexible Organization ID Schema\n * Accepts UUID format and slug format (e.g., \"kya-os-kerjid\")\n * Mirrors ProjectIdSchema pattern for consistency\n */\nexport const OrganizationIdSchema = z.string().refine(\n (val) => {\n // UUID v4 format (all versions, not just v4)\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n // Organization slug format (lowercase alphanumeric with hyphens, e.g., \"kya-os-kerjid\")\n const slugRegex = /^[a-z0-9-]+$/i;\n return uuidRegex.test(val) || slugRegex.test(val);\n },\n {\n message: 'Invalid organization ID format. Must be a UUID or slug (e.g., \"kya-os-kerjid\")',\n }\n);\n\n/**\n * Common Query Parameters Schema\n * Used across multiple internal endpoints for pagination and filtering\n */\nexport const QuerySchema = z.object({\n page: z.coerce.number().min(1).default(1).optional(),\n limit: z.coerce\n .number()\n .min(1)\n .max(PAGINATION_DEFAULTS.maxPageSize)\n .default(PAGINATION_DEFAULTS.defaultPageSize)\n .optional(),\n sortBy: z.string().optional(),\n order: z.enum(['asc', 'desc']).default('desc').optional(),\n search: z.string().optional(),\n});\nexport type QueryParams = z.infer<typeof QuerySchema>;\n\n/**\n * Non-sensitive KYA-OS configuration projection returned by organization-wide\n * deployment inventory endpoints. Values are deliberately empty; consumers\n * use only the keys to count configured providers and discovered tools.\n */\nexport interface KyaosDeploymentInventoryConfig {\n oauthProviders: Record<string, Record<string, never>>;\n discoveredTools: Record<string, Record<string, never>>;\n}\n\n/**\n * Projects Schemas\n */\nexport const CreateProjectSchema = z.object({\n name: z.string().min(1).max(255),\n domain: z.string().optional(), // Changed: removed .url() validation to be more lenient\n organizationId: z.string().uuid().optional(), // Optional - backend uses auth session as fallback\n // Setup Flow v2 step 1 (\"What brings you here?\") — the stable\n // SetupV2NeedDef.id keys the user selected (apps/web's\n // lib/setup-v2/flow-types.ts owns the id -> label/product mapping; this\n // shared package only validates shape, not membership, matching\n // settings.allowedOrigins/blockedAgents below). Optional: only the\n // setup-v2 flow ever sends it.\n setupGoals: z.array(z.string().min(1).max(100)).max(50).optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().default(false),\n confidenceThreshold: z.number().min(0).max(1).default(0.8),\n enableSessionTracking: z.boolean().default(true),\n enableWasm: z.boolean().default(true),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).default([]),\n blockedAgents: z.array(z.string()).default([]),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n })\n .optional(),\n});\nexport type CreateProjectRequest = z.infer<typeof CreateProjectSchema>;\n\nexport const UpdateProjectSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n domain: z.string().optional(), // Changed: removed .url() validation to be more lenient\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The org-branded\n // bare host (e.g. `authenticate.acme.com`) that renders consent + serves\n // delegation pickup for this project. Empty string clears it → the web-app\n // platform default. This value becomes a challenge URI authority, so it's\n // validated strictly (no path / userinfo / whitespace / bad labels) rather\n // than left lenient like `domain` — see `isValidAuthorizationHost`.\n authorizationHost: z\n .string()\n .max(255)\n .refine((v) => v === '' || isValidAuthorizationHost(v), {\n message:\n 'Authorization host must be a bare hostname (e.g. authenticate.acme.com), optionally with a :port — no scheme path, \"@\", or spaces',\n })\n .optional(),\n // Detection retention window (project settings page). Min 7 enforced\n // here (application layer), not a DB CHECK — see schema.ts's column\n // comment. Default lives on the column (365), not here, so an update\n // that omits this field never resets an existing project's window.\n detectionRetentionDays: z.number().int().min(7).max(3650).optional(),\n // Per-project consent for publishing this project's agent site-visit\n // interactions to Know That AI's PUBLIC activity feed (project settings\n // page). Omitted on update leaves the column's own default/current value\n // untouched, same convention as detectionRetentionDays above.\n publishSiteVisitToKnowThatAi: z.boolean().optional(),\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n customDomain: z.string().optional(),\n allowedOrigins: z.array(z.string()).optional(),\n blockedAgents: z.array(z.string()).optional(),\n webhookUrl: z.string().url().optional(),\n webhookSecret: z.string().optional(),\n beaconRateLimitPerMinute: z.number().int().positive().optional(),\n })\n .optional(),\n});\nexport type UpdateProjectRequest = z.infer<typeof UpdateProjectSchema>;\n\n/**\n * Pixels Schemas\n */\nexport const CreatePixelSchema = z.object({\n projectId: ProjectIdSchema,\n name: z.string().min(1).max(255),\n domain: z.string().url().optional(),\n isActive: z.boolean().default(true),\n configuration: PixelConfigurationSchema.optional(),\n});\nexport type CreatePixelRequest = z.infer<typeof CreatePixelSchema>;\n\nexport const UpdatePixelSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n domain: z.string().url().optional(),\n isActive: z.boolean().optional(),\n configuration: PixelConfigurationSchema.optional(),\n});\nexport type UpdatePixelRequest = z.infer<typeof UpdatePixelSchema>;\n\n/**\n * API Keys Schemas\n */\n\nexport const CreateApiKeySchema = z.object({\n name: z.string().min(1).max(255),\n projectId: ProjectIdSchema.optional(),\n permissions: z.array(ApiKeyPermissionSchema).default(['read']),\n rateLimits: ApiKeyRateLimitsSchema.optional(),\n expiresAt: z.string().datetime().optional(),\n});\nexport type CreateApiKeyRequest = z.infer<typeof CreateApiKeySchema>;\n\nexport const UpdateApiKeySchema = z.object({\n name: z.string().min(1).max(255).optional(),\n permissions: z.array(ApiKeyPermissionSchema).optional(),\n rateLimits: ApiKeyRateLimitsSchema.optional(),\n expiresAt: z.string().datetime().optional().nullable(),\n});\nexport type UpdateApiKeyRequest = z.infer<typeof UpdateApiKeySchema>;\n\n/**\n * Marketplace Provisioning Schemas\n *\n * Contract for the internal `POST/DELETE /api/provisioning/keys` endpoint that the\n * KYA-OS Integrations Platform (Vercel/Netlify/… adapters) calls to mint and revoke a\n * per-resource KYA-OS project + API key. Idempotent on (source, externalId, resourceId).\n */\n\n/** Provider kinds that can drive provisioning. Grows as adapters are added. */\nexport const MarketplaceSourceSchema = z.enum([\n 'vercel',\n 'shopify',\n 'netlify',\n 'railway',\n 'shopware',\n 'mixer',\n]);\nexport type MarketplaceSource = z.infer<typeof MarketplaceSourceSchema>;\n\n/** Enforcement posture — mirrors the SDK's `enforcementMode` ('observe' = detect-only). */\nexport const ProvisioningModeSchema = z.enum(['observe', 'enforce']);\nexport type ProvisioningMode = z.infer<typeof ProvisioningModeSchema>;\n\nexport const ProvisionKeyRequestSchema = z.object({\n source: MarketplaceSourceSchema,\n /** Provider installation/configuration id (e.g. Vercel configurationId). */\n externalId: z.string().min(1).max(255),\n /**\n * Provider resource id (e.g. one Vercel project); idempotency key with (source, externalId).\n * Single-resource providers repeat `externalId` here rather than inventing a sentinel — a\n * Shopware shop, for instance, has no sub-resource comparable to a Vercel project, so its\n * triple is ('shopware', shopId, shopId). Intentional, not a caller bug.\n */\n resourceId: z.string().min(1).max(255),\n /** Human-readable label for the dashboard (e.g. \"Vercel / team_xxx / my-project\"). */\n label: z.string().min(1).max(200),\n /**\n * Owner of the provisioned project. `email` is the account-linking key: we find-or-create\n * the KYA-OS user + personal org from it (Shopify-parity), so an address matching an\n * existing account provisions INTO that account — including the org it lands in.\n *\n * The caller MUST send an address it has verified belongs to the installer. Nothing here\n * enforces that: there is no verification flag and no per-provider gate, so a wrong address\n * silently mints a project inside a stranger's org. Adapters carrying a verified identity\n * (Vercel's OIDC `user_email`, Railway's OIDC userinfo `email`) satisfy this directly;\n * Shopware satisfies it by convention only, since its app handshake carries no user identity\n * and the address is merchant-confirmed in the shop admin.\n *\n * Rationale, per-provider trust, and the accepted exposure:\n * `docs/integrations/provisioning-owner-email-trust.md`.\n */\n owner: z.object({\n email: z.string().email(),\n name: z.string().min(1).max(255).optional(),\n }),\n /** Recorded on the provision for the dashboard; the SDK's enforcementMode is code-level today. */\n mode: ProvisioningModeSchema.default('observe'),\n /**\n * Org the installer chose in the adapter UI. Treated as a HINT: the backend binds the\n * installation to it and mints there only when the resolved user OWNS or ADMINISTERS it\n * (matching the orgs the list endpoint surfaces) — otherwise it falls back to the personal\n * org (owner/admin backstop in `mintWithinTx`). Omitted = legacy behavior (personal/default\n * org).\n */\n organizationId: z.string().uuid().optional(),\n /** Optional non-secret provider context (teamId, userId, resource name). */\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type ProvisionKeyRequest = z.infer<typeof ProvisionKeyRequestSchema>;\n\nexport const ProvisionKeyResponseSchema = z.object({\n /**\n * Plaintext API key — injected by the adapter as CHECKPOINT_API_KEY. Returned once on mint;\n * on idempotent re-provision the same key is returned (decrypted from storage).\n */\n apiKey: z.string().min(1),\n /** The KYA-OS project the key is scoped to. */\n projectId: z.string().uuid(),\n /** The API key row id (revoke is keyed by source/externalId/resourceId, not this). */\n apiKeyId: z.string().uuid(),\n organizationId: z.string().uuid(),\n /** True when an existing provision was returned rather than a new one created. */\n idempotent: z.boolean(),\n});\nexport type ProvisionKeyResponse = z.infer<typeof ProvisionKeyResponseSchema>;\n\n/**\n * Request for `POST /api/provisioning/sso-link` — the \"Open in Provider\" handoff.\n * The adapter has already verified `ownerEmail` via the provider's OIDC token.\n */\nexport const SsoLinkRequestSchema = z.object({\n source: MarketplaceSourceSchema,\n /** Provider installation/configuration id (e.g. Vercel configurationId). */\n externalId: z.string().min(1).max(255),\n /** Optional provider resource id — present → deep-link to that project; absent → org landing. */\n resourceId: z.string().min(1).max(255).optional(),\n /** Verified installer email (the OIDC `user_email` claim). */\n ownerEmail: z.string().email(),\n});\nexport type SsoLinkRequest = z.infer<typeof SsoLinkRequestSchema>;\n\nexport const SsoLinkResponseSchema = z.object({\n /** Ready-to-redirect URL: the integration 302s the browser here. Establishes the session and lands on the friendly-id dashboard route. */\n url: z.string().min(1),\n});\nexport type SsoLinkResponse = z.infer<typeof SsoLinkResponseSchema>;\n\n/**\n * DELETE query for `/api/provisioning/keys`. Omitting `resourceId` revokes ALL keys for the\n * installation (the uninstall path); supplying it revokes a single resource.\n */\nexport const RevokeProvisionQuerySchema = z.object({\n source: MarketplaceSourceSchema,\n externalId: z.string().min(1).max(255),\n resourceId: z.string().min(1).max(255).optional(),\n});\nexport type RevokeProvisionQuery = z.infer<typeof RevokeProvisionQuerySchema>;\n\nexport const RevokeProvisionResponseSchema = z.object({\n /** Number of provisions revoked (0 if nothing matched — DELETE is idempotent). */\n revoked: z.number().int().nonnegative(),\n});\nexport type RevokeProvisionResponse = z.infer<typeof RevokeProvisionResponseSchema>;\n\n/**\n * Provisioning Organization-Selection Schemas\n *\n * Contract for the service-authenticated org chooser the KYA-OS Integrations adapter\n * (Vercel/…) drives so an installer can pick which Checkpoint org to link — or create a\n * new one — instead of always landing in their default/personal org. The end user is\n * identified ONLY by the verified `email` (the account-linking key); never a session.\n * - `POST /api/provisioning/organizations/list` → { organizations }\n * - `POST /api/provisioning/organizations` → { organization }\n * Both authenticate with the `sk_service_provisioning_` service key and wrap the payloads\n * below in the standard `{ success, data }` envelope at the route.\n */\n\n/** Roles the adapter may bind an installation to — an installer can only choose an org they administer. */\nexport const ProvisioningOrganizationRoleSchema = z.enum(['owner', 'admin']);\nexport type ProvisioningOrganizationRole = z.infer<typeof ProvisioningOrganizationRoleSchema>;\n\n/** One org the resolved user owns or administers (the adapter's `OrganizationSummary`). */\nexport const ProvisioningOrganizationSummarySchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n slug: z.string(),\n role: ProvisioningOrganizationRoleSchema,\n});\nexport type ProvisioningOrganizationSummary = z.infer<typeof ProvisioningOrganizationSummarySchema>;\n\n/** List a user's administrable orgs by verified email. No user match ⇒ `{ organizations: [] }`. */\nexport const ListProvisioningOrganizationsRequestSchema = z.object({\n email: z.string().email(),\n});\nexport type ListProvisioningOrganizationsRequest = z.infer<\n typeof ListProvisioningOrganizationsRequestSchema\n>;\n\nexport const ListProvisioningOrganizationsResponseSchema = z.object({\n organizations: z.array(ProvisioningOrganizationSummarySchema),\n});\nexport type ListProvisioningOrganizationsResponse = z.infer<\n typeof ListProvisioningOrganizationsResponseSchema\n>;\n\n/**\n * Create an org for a (found-or-created) user by verified email. `name`/`slug` reuse the\n * dashboard's `CreateOrganizationInputSchema` validators so the service + session paths\n * accept exactly the same input.\n */\nexport const CreateProvisioningOrganizationRequestSchema = z.object({\n email: z.string().email(),\n name: CreateOrganizationInputSchema.shape.name,\n slug: CreateOrganizationInputSchema.shape.slug,\n});\nexport type CreateProvisioningOrganizationRequest = z.infer<\n typeof CreateProvisioningOrganizationRequestSchema\n>;\n\nexport const CreateProvisioningOrganizationResponseSchema = z.object({\n /** The just-created org; `role` is always `owner` (the creator is inserted as owner). */\n organization: ProvisioningOrganizationSummarySchema,\n});\nexport type CreateProvisioningOrganizationResponse = z.infer<\n typeof CreateProvisioningOrganizationResponseSchema\n>;\n\n/**\n * Organizations Schemas\n * Using enhanced schemas from organization types\n */\nexport const CreateOrganizationSchema = CreateOrganizationInputSchema;\nexport type CreateOrganizationRequest = z.infer<typeof CreateOrganizationSchema>;\n\nexport const UpdateOrganizationSchema = UpdateOrganizationInputSchema;\nexport type UpdateOrganizationRequest = z.infer<typeof UpdateOrganizationSchema>;\n\n/**\n * Analytics Schemas\n */\nexport const AnalyticsQuerySchema = z.object({\n projectId: ProjectIdSchema.optional(),\n pixelId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n timeWindow: z\n .enum(['realtime', 'hourly', 'daily', 'weekly', 'monthly'])\n .default('daily')\n .optional(),\n groupBy: z.enum(['hour', 'day', 'week', 'month']).optional(),\n aiAgentsOnly: z.coerce.boolean().optional(),\n});\nexport type AnalyticsQueryRequest = z.infer<typeof AnalyticsQuerySchema>;\n\nexport const ExportAnalyticsSchema = z.object({\n projectId: ProjectIdSchema.optional(),\n organizationId: z.string().uuid().optional(),\n pixelId: z.string().uuid().optional(),\n startDate: z.string().datetime(),\n endDate: z.string().datetime(),\n format: z.enum(['csv', 'json']).default('csv'),\n sections: z\n .array(z.enum(['overview', 'traffic', 'agents', 'confidence', 'sessions']))\n .optional()\n .default(['overview', 'traffic', 'agents']),\n includeRawData: z.boolean().optional().default(false),\n showAIAgentsOnly: z.boolean().optional().default(false),\n});\nexport type ExportAnalyticsRequest = z.infer<typeof ExportAnalyticsSchema>;\n\n/**\n * Settings Schemas\n */\nexport const UpdateSettingsSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n email: z.string().email().optional(),\n // Note: Plan updates would typically be handled through billing/subscription endpoints\n});\nexport type UpdateSettingsRequest = z.infer<typeof UpdateSettingsSchema>;\n\nexport const DeleteAccountSchema = z.object({\n confirmation: z.literal('DELETE_MY_ACCOUNT'),\n});\nexport type DeleteAccountRequest = z.infer<typeof DeleteAccountSchema>;\n\n/**\n * Specialized Query Schemas\n */\nexport const ProjectsQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'updatedAt', 'name']).default('createdAt').optional(),\n // Accept both UUID and slug format for organization ID\n organizationId: OrganizationIdSchema.optional(),\n});\nexport type ProjectsQueryParams = z.infer<typeof ProjectsQuerySchema>;\n\nexport const PixelsQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'updatedAt', 'name']).default('createdAt').optional(),\n projectId: ProjectIdSchema.optional(),\n isActive: z.coerce.boolean().optional(),\n});\nexport type PixelsQueryParams = z.infer<typeof PixelsQuerySchema>;\n\nexport const ApiKeysQuerySchema = QuerySchema.extend({\n sortBy: z.enum(['createdAt', 'lastUsedAt', 'name']).default('createdAt').optional(),\n projectId: ProjectIdSchema.optional(),\n organizationId: z.string().uuid().optional(),\n includeRevoked: z.coerce.boolean().default(false).optional(),\n});\nexport type ApiKeysQueryParams = z.infer<typeof ApiKeysQuerySchema>;\n\n/**\n * Response Schemas\n */\nexport const PaginatedResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.boolean(),\n data: z.array(itemSchema),\n pagination: z.object({\n page: z.number(),\n limit: z.number(),\n total: z.number(),\n totalPages: z.number(),\n hasMore: z.boolean(),\n }),\n });\n\nexport const SingleItemResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.boolean(),\n data: itemSchema,\n });\n\nexport const ErrorResponseSchema = z.object({\n success: z.literal(false),\n error: z.object({\n code: z.string(),\n message: z.string(),\n details: z.unknown().optional(),\n }),\n});\nexport type ErrorResponse = z.infer<typeof ErrorResponseSchema>;\n\n/**\n * Generic Response Types\n */\nexport type SuccessResponse<T> = {\n success: true;\n data: T;\n};\n\nexport type PaginatedData<T> = {\n items: T[];\n pagination: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n hasMore: boolean;\n };\n};\n\nexport type PaginatedResponse<T> = {\n success: true;\n data: T[];\n pagination: {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n hasMore: boolean;\n // Optional field for client-side filtered results\n filteredCount?: number;\n };\n};\n\n/**\n * Analytics Response Types\n */\nexport type TimeSeriesPoint = {\n timestamp: string | Date;\n total: number;\n agents: number;\n humans: number;\n avgConfidence: number;\n // Session-based metrics\n totalSessions: number;\n agentSessions: number;\n humanSessions: number;\n // Separated bot and AI agent sessions\n botSessions: number;\n aiAgentSessions: number;\n};\n\nexport type AgentTypeDistribution = {\n agentType: string;\n count: number;\n uniqueSessions: number;\n avgConfidence: number;\n // Surfaced from the agent_types leftJoin so callers can filter on the\n // canonical category (e.g. 'ai_assistant') without re-running the JS\n // string heuristic in `lib/utils/agent-category.ts`. Optional because\n // a leftJoin miss returns null at runtime; consumers treat falsy as\n // \"unknown\" (#2275). Other join columns the route emits\n // (agentTypeId, displayName, isLegitimate, lastSeen) are intentionally\n // omitted — downstream consumers model those locally with stricter\n // shapes that conflict with the leftJoin nullability.\n category?: string;\n};\n\nexport type PixelStatsData = {\n pixel: {\n id: string;\n name: string;\n };\n detectionCount: number;\n agentCount: number;\n};\n\nexport type ConfidenceRange = {\n range: string;\n count: number;\n};\n\nexport type AnalyticsOverview = {\n totalDetections: number;\n totalAgents: number;\n averageConfidence: number;\n uniqueSessions: number;\n // Add unique session breakdowns to avoid double-counting\n uniqueAgentSessions?: number;\n uniqueHumanSessions?: number;\n uniqueBotSessions?: number;\n uniqueAIAgentSessions?: number;\n mostActiveHour?: {\n hour: number;\n detections: number;\n label: string;\n };\n detectionChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n sessionChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n aiAgentChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n botChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n humanChange?: {\n percentage: number;\n trend: 'up' | 'down' | 'neutral';\n previousPeriodCount: number;\n };\n};\n\nexport type AnalyticsData = {\n overview: AnalyticsOverview;\n timeSeries: TimeSeriesPoint[];\n agentTypes: AgentTypeDistribution[];\n topPixels: PixelStatsData[];\n confidenceDistribution: ConfidenceRange[];\n dateRange: {\n start: string;\n end: string;\n };\n};\n\n/**\n * Project Response Types\n */\nexport type ProjectWithStats = {\n id: string;\n friendlyId?: string | null;\n userId: string;\n organizationId?: string | null;\n name: string;\n domain?: string | null;\n /** Detection retention window in days (project settings page). Default 365, minimum 7. */\n detectionRetentionDays?: number;\n /** Whether this project's site-visit interactions publish to Know That AI's public activity feed. Default true. */\n publishSiteVisitToKnowThatAi?: boolean;\n /** Set once \"Browser posture\" is enabled for this project — never the private key itself. */\n postureKeyId?: string | null;\n /** Cloudflare Turnstile site key (gateway-enforcement-step-up, build item\n * 6) — public, safe to send to the dashboard. Presence is the\n * \"configured\" flag; the secret key never leaves the server. */\n turnstileSiteKey?: string | null;\n settings: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n userAccessLevel?: 'owner' | 'admin' | 'editor' | 'viewer' | null;\n stats: {\n pixelCount: number;\n detectionCount: number;\n sessionCount: number;\n weeklySessionCount: number;\n weeklyAgentSessionCount: number;\n lastDetection: Date | null;\n recentDetections?: number;\n recentAgents?: number;\n /**\n * Per-day session counts over the trailing 7 days (oldest first).\n * Always length 7 — days with no rollup row fill as 0 so the\n * sparkline renders a continuous timeline rather than a gappy\n * one. Drives the project card's sparkline.\n */\n dailySessions?: number[];\n /**\n * Total sessions in the **previous** 7-day window (days 8-14 ago).\n * Used to derive the week-over-week trend % on the project card.\n *\n * Note: this is the value used as the DENOMINATOR of the\n * trend calculation. When zero, no honest % can be computed\n * (division undefined) — the renderer drops the trend pill.\n */\n prevWeekSessionCount?: number;\n };\n};\n\n/**\n * Pixel Response Types\n */\nexport type PixelWithStats = {\n id: string;\n projectId: string;\n name: string;\n secretKey: string;\n configuration: Record<string, unknown>;\n isActive: boolean;\n createdAt: Date;\n updatedAt: Date;\n // Matches the actual shape returned by GET /api/internal/pixels:\n // `detectionCount` is the trigger-maintained ALL-TIME total and\n // `lastDetection` the trigger-maintained last-detection timestamp (both\n // denormalized pixels columns, no detections scan); `recentDetections` is\n // a live 24h rolling count. There is no per-agent/per-session breakdown\n // at this endpoint (see `/api/internal/pixels/[pixelId]` for the richer\n // single-pixel shape, which this type does not describe).\n stats?: {\n detectionCount: number;\n recentDetections: number;\n lastDetection: Date | null;\n };\n};\n\n/**\n * Settings Response Types\n */\nexport type UserUsage = {\n projects: {\n used: number;\n limit: number;\n percentage: number;\n };\n pixels: {\n used: number;\n limit: number;\n percentage: number;\n };\n apiKeys: {\n used: number;\n limit: number;\n percentage: number;\n };\n};\n\nexport type PlanLimits = {\n projects: number;\n pixelsPerProject: number;\n apiKeys: number;\n teamMembers: number;\n dataRetentionDays: number;\n customDomains: number;\n webhooks: number;\n alertRules: number;\n sessionsTracked: number;\n exportSizeLimit: number;\n};\n\nexport type PlanFeatures = {\n customDomains: boolean;\n webhooks: boolean;\n alertRules: boolean;\n teamMembers: boolean;\n unlimitedProjects: boolean;\n unlimitedPixels: boolean;\n unlimitedApiKeys: boolean;\n};\n\n/**\n * Dashboard Stats Types\n */\nexport type DashboardStatItem = {\n current: number;\n previous?: number;\n percentageChange?: number;\n};\n\nexport type DashboardStatsResponse = {\n domains: {\n current: number;\n activeProjects: number;\n inactiveProjects: number;\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n totalSessions: DashboardStatItem & {\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n agentSessions: DashboardStatItem & {\n weeklyTrend?: Array<{ day: string; value: number }>;\n };\n /**\n * Distinct agent types seen in the last 7 days across the org's\n * projects. Computed from a 14-day detections scan with PG `FILTER`\n * clauses so `current` and `previous` are produced in a single pass.\n * Optional fields preserve backwards compatibility with older\n * response payloads that emitted `current` only.\n */\n uniqueAgents?: DashboardStatItem;\n /**\n * Distinct users seen in the last 7 days across the org's AI-agent\n * detections. Same 14-day single-scan strategy as uniqueAgents.\n * Tier-coalesced identity (email > userId > ipAddress > 'unattributed').\n */\n uniqueUsers?: DashboardStatItem;\n};\n\nexport const DashboardStatsRequestSchema = z.object({\n organizationId: z.string().uuid().optional(),\n});\nexport type DashboardStatsRequest = z.infer<typeof DashboardStatsRequestSchema>;\n\n/* ─────────────────────────────────────────────────────────────────────\n Home-rail rollups — single payload for the four rollup-backed v2\n home-rail widgets (NOW, AGENT MIX, ACTIVE HOURS, CONFIDENCE).\n Service: apps/web/lib/services/analytics/home-rail-rollups.service.ts\n Route: GET /api/internal/home-rail/rollups\n ────────────────────────────────────────────────────────────────── */\n\n/** YYYY-MM-DD slot inside the 7-day sparkline / heatmap window. */\nexport interface HomeRailDailyPoint {\n /** UTC date as YYYY-MM-DD — same shape as the rollup column. */\n date: string;\n totalSessions: number;\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n /** 24-element histogram of distinct sessions per hour-of-day (UTC). */\n hourDistribution: number[];\n}\n\n/** Aggregated metrics over a 7-day window. */\nexport interface HomeRailWindowAggregate {\n totalSessions: number;\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n totalDetections: number;\n highConfidenceDetections: number;\n /**\n * Detection-weighted avg confidence — sum of (per-day avg × per-day\n * detections) / sum of detections. Reads honest even when one day\n * has 10x the traffic of the others.\n *\n * Cross-class — includes both ai_agent and bot detections, matching\n * how `organization_rollups.avg_confidence` is computed. For an\n * AI-only confidence number, use `HomeRailRollupsResponse.aiAgent7d`.\n */\n avgConfidence: number;\n}\n\n/**\n * AI-agent-only aggregate over the same 7-day window as `current7d`.\n *\n * Sourced from `agent_daily_rollup` filtered to `detection_class =\n * 'ai_agent'`, summed across all of the org's projects in the window.\n * Uses `totalConfidenceSum / detections` for the detection-weighted\n * average — same shape as `agent_daily_rollup.avg_confidence` math in\n * top-agents.service.ts.\n *\n * Why a separate aggregate (not a field on `current7d`)?\n * - `current7d` reads from `organization_rollups`, whose confidence\n * column is cross-class by design (and the schema comment warns\n * against narrowing only the numerator).\n * - `agent_daily_rollup` has the per-class breakdown we need, but\n * it's keyed per (project, agent_type, class, date) instead of\n * (org, date) — different scan, different aggregate.\n *\n * `high_confidence_detections` is *not* available per-class in the\n * rollups today, so the AI-only response only carries the avg and\n * the total. Surfacing a ratio bar honestly would require a new\n * column + backfill (F-05 follow-up).\n */\nexport interface HomeRailAiAgentAggregate {\n totalDetections: number;\n avgConfidence: number;\n}\n\nexport interface HomeRailRollupsResponse {\n today: HomeRailDailyPoint;\n current7d: HomeRailWindowAggregate;\n previous7d: HomeRailWindowAggregate;\n /** 7 daily points covering the current 7d window, ordered oldest → newest. */\n trend7d: HomeRailDailyPoint[];\n /**\n * AI-agent-only aggregate over the current 7d window. Powers\n * `ConfidenceWidget`, which deliberately scopes to AI agents (the\n * cross-class number in `current7d.avgConfidence` reads as\n * \"AI + bot confidence\" and was confusing operators).\n */\n aiAgent7d: HomeRailAiAgentAggregate;\n /** Newest `refreshedAt` across the read rows; null when no rows exist. */\n refreshedAt: string | null;\n /** Current 7d window bounds, UTC dates as YYYY-MM-DD. */\n windowStart: string;\n windowEnd: string;\n}\n\n// Accepts slug or UUID — matches the route's\n// `PermissionService.resolveOrganizationAccess` resolver and the\n// dashboard's URL pattern (orgs are navigated via slugs). The previous\n// `z.string().uuid()` constraint would have rejected every dashboard\n// call at runtime had any consumer validated input against this shared\n// schema (cursor-bot flagged the divergence on 6ceea5f24).\nexport const HomeRailRollupsRequestSchema = z.object({\n organizationId: OrganizationIdSchema,\n});\nexport type HomeRailRollupsRequest = z.infer<typeof HomeRailRollupsRequestSchema>;\n\nexport type SettingsData = {\n user: {\n id: string;\n email: string;\n name?: string | null;\n image?: string | null;\n plan?: string | null;\n emailVerified?: Date | null;\n createdAt: Date;\n updatedAt: Date;\n };\n usage: UserUsage;\n planLimits: PlanLimits;\n features: PlanFeatures;\n};\n\n/**\n * API Key Response Types\n */\nexport type ApiKeyWithProject = {\n id: string;\n userId: string;\n projectId?: string | null;\n name: string;\n key: string;\n permissions: string[];\n rateLimits: Record<string, unknown>;\n lastUsedAt?: Date | null;\n expiresAt?: Date | null;\n createdAt: Date;\n revokedAt?: Date | null;\n project?: {\n id: string;\n name: string;\n } | null;\n};\n","/**\n * Public API Types for v1 Endpoints\n *\n * Types and schemas for public-facing API endpoints\n * Provides clean, stable interfaces for external consumers\n */\n\nimport { z } from 'zod';\n\n/**\n * Public Project Interface\n * Simplified project representation for public API\n */\nexport interface PublicProject {\n id: string;\n name: string;\n createdAt: string; // ISO date string\n status: 'active' | 'inactive';\n detectionCount: number;\n}\n\n/**\n * Public Detection Interface\n * Detection data exposed through public API\n */\nexport interface PublicDetection {\n id: string;\n timestamp: string; // ISO date string\n isBot: boolean;\n confidence: number;\n botType: string;\n userAgent: string;\n url: string;\n}\n\n/**\n * Public Analytics Summary\n * High-level analytics data\n */\nexport interface PublicAnalyticsSummary {\n totalDetections: number;\n botDetections: number;\n humanDetections: number;\n averageConfidence: number;\n topBotTypes: Array<{\n type: string;\n count: number;\n percentage: number;\n }>;\n}\n\n/**\n * Public Analytics Time Series Data Point\n */\nexport interface PublicAnalyticsTimeSeriesPoint {\n timestamp: string; // ISO date string\n detections: number;\n bots: number;\n humans: number;\n}\n\n/**\n * Public Analytics Bot Types Distribution\n */\nexport interface PublicAnalyticsBotType {\n type: string;\n count: number;\n percentage: number;\n averageConfidence: number;\n}\n\n/**\n * Public Analytics Interface\n * Comprehensive analytics data for public consumption\n */\nexport interface PublicAnalytics {\n summary: PublicAnalyticsSummary;\n timeSeries: PublicAnalyticsTimeSeriesPoint[];\n botTypes: PublicAnalyticsBotType[];\n}\n\n/**\n * Pagination Response\n * Standard pagination metadata\n */\nexport interface PaginationResponse {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n hasMore: boolean;\n hasPrevious: boolean;\n}\n\n/**\n * Public API Response Wrapper\n * Consistent response format for all public endpoints\n */\nexport interface PublicApiResponse<T = unknown> {\n success: boolean;\n data?: T;\n error?: {\n code: string;\n message: string;\n details?: unknown;\n };\n pagination?: PaginationResponse;\n meta?: {\n timestamp: string;\n requestId?: string;\n version: string;\n rateLimit?: {\n remaining: number;\n resetTime: number;\n limit: number;\n };\n };\n}\n\n/**\n * Zod Schemas for Runtime Validation\n */\n\nexport const PublicProjectSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(255),\n createdAt: z.string().datetime(),\n status: z.enum(['active', 'inactive']),\n detectionCount: z.number().nonnegative(),\n});\n\nexport const PublicDetectionSchema = z.object({\n id: z.string().uuid(),\n timestamp: z.string().datetime(),\n isBot: z.boolean(),\n confidence: z.number().min(0).max(100),\n botType: z.string().min(1),\n userAgent: z.string(),\n url: z.string().url(),\n});\n\nexport const PublicAnalyticsSummarySchema = z.object({\n totalDetections: z.number().nonnegative(),\n botDetections: z.number().nonnegative(),\n humanDetections: z.number().nonnegative(),\n averageConfidence: z.number().min(0).max(100),\n topBotTypes: z.array(\n z.object({\n type: z.string(),\n count: z.number().nonnegative(),\n percentage: z.number().min(0).max(100),\n })\n ),\n});\n\nexport const PublicAnalyticsTimeSeriesPointSchema = z.object({\n timestamp: z.string().datetime(),\n detections: z.number().nonnegative(),\n bots: z.number().nonnegative(),\n humans: z.number().nonnegative(),\n});\n\nexport const PublicAnalyticsBotTypeSchema = z.object({\n type: z.string(),\n count: z.number().nonnegative(),\n percentage: z.number().min(0).max(100),\n averageConfidence: z.number().min(0).max(100),\n});\n\nexport const PublicAnalyticsSchema = z.object({\n summary: PublicAnalyticsSummarySchema,\n timeSeries: z.array(PublicAnalyticsTimeSeriesPointSchema),\n botTypes: z.array(PublicAnalyticsBotTypeSchema),\n});\n\nexport const PaginationResponseSchema = z.object({\n page: z.number().positive(),\n limit: z.number().positive(),\n total: z.number().nonnegative(),\n totalPages: z.number().nonnegative(),\n hasMore: z.boolean(),\n hasPrevious: z.boolean(),\n});\n\nexport const PublicApiResponseSchema = <T extends z.ZodType>(dataSchema: T) =>\n z.object({\n success: z.boolean(),\n data: dataSchema.optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n details: z.any().optional(),\n })\n .optional(),\n pagination: PaginationResponseSchema.optional(),\n meta: z\n .object({\n timestamp: z.string().datetime(),\n requestId: z.string().optional(),\n version: z.string(),\n rateLimit: z\n .object({\n remaining: z.number().nonnegative(),\n resetTime: z.number().positive(),\n limit: z.number().positive(),\n })\n .optional(),\n })\n .optional(),\n });\n\n/**\n * Public API Query Parameters\n */\nexport interface PublicApiQueryParams {\n // Pagination\n page?: number;\n limit?: number;\n\n // Sorting\n sortBy?: string;\n order?: 'asc' | 'desc';\n\n // Date filtering\n startDate?: string;\n endDate?: string;\n\n // Detection filtering\n isBot?: boolean;\n minConfidence?: number;\n maxConfidence?: number;\n botType?: string;\n}\n\nexport const PublicApiQueryParamsSchema = z.object({\n page: z.number().positive().default(1),\n limit: z.number().positive().max(1000).default(100),\n sortBy: z.string().optional(),\n order: z.enum(['asc', 'desc']).default('desc'),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n isBot: z.boolean().optional(),\n minConfidence: z.number().min(0).max(100).optional(),\n maxConfidence: z.number().min(0).max(100).optional(),\n botType: z.string().optional(),\n});\n\n/**\n * Public API Request Headers\n */\nexport interface PublicApiHeaders {\n authorization?: string;\n 'x-api-key'?: string;\n 'content-type'?: string;\n 'user-agent'?: string;\n 'x-request-id'?: string;\n}\n\nexport const PublicApiHeadersSchema = z.object({\n authorization: z.string().optional(),\n 'x-api-key': z.string().optional(),\n 'content-type': z.string().optional(),\n 'user-agent': z.string().optional(),\n 'x-request-id': z.string().optional(),\n});\n\n// Types are already exported above, no need to re-export them here\n","/**\n * Detection signal exposure: the wire shape of the \"full signal set\"\n * block on the `/api/v1/enforce` detection response (KYA-1107, \"Adobe\n * Golden Snapshot\").\n *\n * Every enforce detection payload carries these fields in addition to the\n * condensed summary fields. Additive only: consumers must ignore keys they\n * do not know (every current consumer was verified lenient to unknown keys\n * before this became unconditional).\n *\n * This schema is the SSOT for the exposed shape:\n * - the generated reference (`docs/architecture/detection-signal-exposure.generated.md`)\n * is derived from the `.describe()` strings here by\n * `scripts/generate-signal-exposure-docs.ts`, CI-gated so docs and wire\n * cannot drift (`detection-signal-exposure-check.yml`, same pattern as\n * the error-code and reason-code registries);\n * - the golden example `fixtures/detection/signal-exposure-example.json`\n * is parsed against it in `__tests__/signal-exposure.test.ts`.\n *\n * Extension point: `signals[]` is deliberately the ONLY place new detection\n * capabilities surface. A future signal family (request-velocity, platform\n * bot-management corroboration, …) ships as new `signals[].source` values\n * plus new `detection/*` reason codes (both additive), so this shape never\n * needs a breaking change to absorb them.\n */\nimport { z } from 'zod';\n\nimport { ConfidenceLevelSchema } from '../core/confidence';\nimport { DetectionSignalSchema } from '../core/detection';\nimport { DetectionReasonCodeSchema } from '../core/detection-reason-codes';\n\nexport { DetectionReasonCodeSchema };\n\n/**\n * The exposure block, spread flat onto the enforce response's\n * `detection` object (NOT nested) so it stays symmetric with the gateway\n * plane's detection detail, where `signals` already rides inline.\n */\nexport const DetectionSignalExposureSchema = z.object({\n signals: z\n .array(DetectionSignalSchema)\n .describe(\n \"The engine's full per-signal evidence breakdown, verbatim (not the condensed single-entry summary). Empty when the engine did not run (skipDetection) or faulted. THE extension point: future signal families arrive as new entries/sources here, additively.\"\n ),\n reasonCodes: z\n .array(DetectionReasonCodeSchema)\n .min(1)\n .describe(\n 'Ordered detection/* reason codes, most-significant-evidence first, derived by the same mapDetectionToReasonCodes projection that feeds the gateway KYA-Reason-Codes header. Never empty: an assumed verdict carries a zero-evidence fallback code.'\n ),\n confidenceLevel: ConfidenceLevelSchema.optional().describe(\n \"The engine's banded confidence level (low | medium | high | very_high). Omitted when the engine did not produce one (engine fault, skipDetection, or a demoted forged-credential verdict).\"\n ),\n isAiCrawler: z\n .boolean()\n .optional()\n .describe(\n 'True when the engine classified the client as an AI training crawler (GPTBot, ClaudeBot, …) rather than an interactive agent. Omitted when the engine did not run.'\n ),\n});\nexport type DetectionSignalExposure = z.infer<typeof DetectionSignalExposureSchema>;\n","/**\n * Fingerprint API Types and Schemas\n *\n * Comprehensive type definitions for the fingerprinting system\n * used to detect and analyze bot/AI agent characteristics\n */\n\nimport { z } from 'zod';\n\n/**\n * Client-side JavaScript detection data\n */\nexport const ClientDetectionSchema = z.object({\n // Core detection\n webdriver: z.boolean().optional(),\n plugins: z.number().optional(),\n languages: z.array(z.string()).optional(),\n platform: z.string().optional(),\n vendor: z.string().optional(),\n chrome: z.boolean().optional(),\n permissions: z.string().optional(),\n webrtc: z.string().optional(),\n automation: z.string().nullable().optional(),\n puppeteer: z.boolean().optional(),\n headless: z.boolean().optional(),\n\n // Device & Screen\n hasTouch: z.boolean().optional(),\n screenResolution: z.string().optional(),\n colorDepth: z.number().optional(),\n pixelRatio: z.number().optional(),\n\n // Advanced fingerprinting\n timezone: z.string().optional(),\n timezoneOffset: z.number().optional(),\n canvas: z.string().optional(),\n webgl: z.string().optional(),\n audioContext: z.string().optional(),\n fonts: z.array(z.string()).optional(),\n\n // Hardware\n hardwareConcurrency: z.number().optional(),\n deviceMemory: z.number().optional(),\n maxTouchPoints: z.number().optional(),\n\n // Browser features\n cookieEnabled: z.boolean().optional(),\n doNotTrack: z.string().nullable().optional(),\n localStorage: z.boolean().optional(),\n sessionStorage: z.boolean().optional(),\n indexedDB: z.boolean().optional(),\n openDatabase: z.boolean().optional(),\n\n // Network\n connection: z\n .object({\n effectiveType: z.string().optional(),\n rtt: z.number().optional(),\n downlink: z.number().optional(),\n saveData: z.boolean().optional(),\n })\n .optional(),\n\n // Performance metrics\n performance: z\n .object({\n navigation: z.number().optional(),\n memory: z\n .object({\n usedJSHeapSize: z.number().optional(),\n totalJSHeapSize: z.number().optional(),\n jsHeapSizeLimit: z.number().optional(),\n })\n .optional(),\n })\n .optional(),\n});\n\nexport type ClientDetection = z.infer<typeof ClientDetectionSchema>;\n\n/**\n * Fingerprint analysis result\n */\nexport const FingerprintAnalysisSchema = z.object({\n // Detection results\n hasChromiumHeaders: z.boolean(),\n hasBrowserHeaders: z.boolean(),\n hasSecFetchHeaders: z.boolean(),\n isAutomated: z.boolean(),\n suspiciousPatterns: z.array(z.string()),\n confidence: z.number().min(0).max(1),\n detectedAgent: z.string(),\n\n // Additional detection flags\n isLikelyBot: z.boolean().optional(),\n isLikelyAI: z.boolean().optional(),\n isLikelyClaude: z.boolean().optional(),\n\n // Detailed detection\n detection: z\n .object({\n isAutomatedBrowser: z.boolean().optional(),\n isPuppeteer: z.boolean().optional(),\n isPlaywright: z.boolean().optional(),\n isHeadless: z.boolean().optional(),\n hasWebDriverApi: z.boolean().optional(),\n isLikelyMCPTool: z.boolean().optional(),\n })\n .optional(),\n});\n\nexport type FingerprintAnalysis = z.infer<typeof FingerprintAnalysisSchema>;\n\n/**\n * Request body for POST /api/v1/fingerprint/detect\n */\nexport const FingerprintDetectRequestSchema = z.object({\n clientDetection: ClientDetectionSchema,\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\n\nexport type FingerprintDetectRequest = z.infer<typeof FingerprintDetectRequestSchema>;\n\n/**\n * Comprehensive fingerprint response\n */\nexport const FingerprintResponseSchema = z.object({\n timestamp: z.string(),\n method: z.string(),\n url: z.string(),\n path: z.string(),\n queryParams: z.record(z.string(), z.string()),\n headers: z.record(z.string(), z.string()),\n headerCount: z.number(),\n ip: z.string(),\n httpVersion: z.string(),\n\n // Analysis results\n fingerprint: FingerprintAnalysisSchema,\n\n // Detailed analysis\n analysis: z.object({\n userAgent: z.string(),\n acceptHeader: z.string(),\n acceptLanguage: z.string(),\n acceptEncoding: z.string(),\n hasReferer: z.boolean(),\n hasCookies: z.boolean(),\n hasAuthorization: z.boolean(),\n secChUa: z.string(),\n secChUaMobile: z.string(),\n secChUaPlatform: z.string(),\n secFetchSite: z.string(),\n secFetchMode: z.string(),\n secFetchDest: z.string(),\n }),\n\n // Detection summary\n detection: z.object({\n isLikelyBot: z.boolean(),\n isLikelyAI: z.boolean(),\n agentType: z.string(),\n confidence: z.string(),\n }),\n\n // For POST requests\n body: z.unknown().optional(),\n bodyType: z.string().optional(),\n contentType: z.string().optional(),\n});\n\nexport type FingerprintResponse = z.infer<typeof FingerprintResponseSchema>;\n\n/**\n * Enhanced detection response (from /detect endpoint)\n */\nexport const EnhancedFingerprintResponseSchema = z.object({\n timestamp: z.string(),\n\n // HTTP fingerprint\n http: z.object({\n method: z.string(),\n url: z.string(),\n headers: z.record(z.string(), z.string()),\n headerCount: z.number(),\n ip: z.string(),\n userAgent: z.string(),\n }),\n\n // JavaScript fingerprint\n javascript: ClientDetectionSchema,\n\n // Combined analysis\n analysis: z.object({\n signals: z.array(z.string()),\n confidence: z.number(),\n detectedTool: z.string(),\n isLikelyClaude: z.boolean(),\n detection: z.object({\n isAutomatedBrowser: z.boolean(),\n isPuppeteer: z.boolean(),\n isHeadless: z.boolean(),\n hasWebDriverApi: z.boolean(),\n isLikelyMCPTool: z.boolean(),\n }),\n }),\n\n // Summary\n summary: z.object({\n tool: z.string(),\n confidence: z.string(),\n isLikelyClaude: z.boolean(),\n signals: z.array(z.string()),\n recommendation: z.string(),\n }),\n});\n\nexport type EnhancedFingerprintResponse = z.infer<typeof EnhancedFingerprintResponseSchema>;\n\n/**\n * Fingerprint storage schema for database\n */\nexport const FingerprintRecordSchema = z.object({\n id: z.string(),\n timestamp: z.date(),\n\n // Request info\n method: z.string(),\n url: z.string(),\n path: z.string(),\n ip: z.string(),\n\n // Headers\n userAgent: z.string().nullable(),\n headers: z.record(z.string(), z.string()),\n\n // Detection results\n isBot: z.boolean(),\n botType: z.string().nullable(),\n confidence: z.number(),\n\n // Client detection\n clientData: ClientDetectionSchema.nullable(),\n\n // Analysis\n patterns: z.array(z.string()),\n signals: z.array(z.string()),\n\n // Metadata\n sessionId: z.string().nullable(),\n projectId: z.string().nullable(),\n metadata: z.record(z.string(), z.unknown()).nullable(),\n});\n\nexport type FingerprintRecord = z.infer<typeof FingerprintRecordSchema>;\n\n/**\n * Known bot patterns for matching\n */\nexport const BotPatternSchema = z.object({\n name: z.string(),\n pattern: z.string(),\n confidence: z.number(),\n category: z.enum(['ai_agent', 'crawler', 'automation', 'scraper', 'monitor']),\n});\n\nexport type BotPattern = z.infer<typeof BotPatternSchema>;\n\n/**\n * TLS fingerprint data\n */\nexport const TLSFingerprintSchema = z.object({\n version: z.string().optional(),\n cipherSuites: z.array(z.string()).optional(),\n extensions: z.array(z.string()).optional(),\n supportedGroups: z.array(z.string()).optional(),\n signatureAlgorithms: z.array(z.string()).optional(),\n ja3: z.string().optional(),\n ja3s: z.string().optional(),\n});\n\nexport type TLSFingerprint = z.infer<typeof TLSFingerprintSchema>;\n\n/**\n * Network timing data\n */\nexport const NetworkTimingSchema = z.object({\n dns: z.number().optional(),\n tcp: z.number().optional(),\n tls: z.number().optional(),\n ttfb: z.number().optional(),\n download: z.number().optional(),\n total: z.number().optional(),\n});\n\nexport type NetworkTiming = z.infer<typeof NetworkTimingSchema>;\n\n/**\n * Validation helpers\n */\nexport function validateFingerprintRequest(data: unknown): FingerprintDetectRequest {\n return FingerprintDetectRequestSchema.parse(data);\n}\n\nexport function validateClientDetection(data: unknown): ClientDetection {\n return ClientDetectionSchema.parse(data);\n}\n\nexport function isValidFingerprintResponse(data: unknown): data is FingerprintResponse {\n return FingerprintResponseSchema.safeParse(data).success;\n}\n","/**\n * Shopify Integration Types\n *\n * Type definitions for Shopify app integration endpoints and data structures\n */\n\nimport { z } from 'zod';\n\n/**\n * Shopify Project Provision Request\n */\nexport const ShopifyProjectProvisionRequestSchema = z.object({\n domain: z.string().min(1).max(255),\n email: z.string().email(),\n name: z.string().min(1).max(255),\n source: z.string().optional().default('shopify_app'),\n});\n\nexport type ShopifyProjectProvisionRequest = z.infer<typeof ShopifyProjectProvisionRequestSchema>;\n\n/**\n * Shopify Project Provision Result\n */\nexport const ShopifyProjectProvisionResultSchema = z.object({\n projectId: z.string().uuid(),\n friendlyId: z.string(),\n pixelId: z.string().uuid(),\n apiKey: z.string(),\n domain: z.string(),\n status: z.literal('active'),\n createdAt: z.string().datetime(),\n // User account information (for Shopify merchants)\n user: z.object({\n email: z.string().email(),\n userId: z.string().uuid(),\n accountCreated: z.boolean(), // true = new account, false = existing\n welcomeEmailSent: z.boolean(),\n setupTokenExpiry: z.string().datetime().nullable(),\n }),\n});\n\nexport type ShopifyProjectProvisionResult = z.infer<typeof ShopifyProjectProvisionResultSchema>;\n\n/**\n * Shopify Threat Information\n * Now represents a session (grouped by consolidated_session_id) rather than individual detections\n */\nexport const ShopifyThreatSchema = z.object({\n sessionId: z.string(), // consolidated_session_id for session grouping\n timestamp: z.string().datetime(), // lastSeen timestamp for the session\n type: z.string(), // agent type (e.g., \"ChatGPT\", \"Claude\")\n ip: z.string(),\n userAgent: z.string(),\n action: z.string(),\n pagesVisited: z.number().int().nonnegative(), // Count of unique pages visited in session\n});\n\nexport type ShopifyThreat = z.infer<typeof ShopifyThreatSchema>;\n\n/**\n * Pagination Information\n */\nexport const PaginationInfoSchema = z.object({\n page: z.number().int().positive(),\n limit: z.number().int().positive(),\n total: z.number().int().nonnegative(),\n hasMore: z.boolean(),\n});\n\nexport type PaginationInfo = z.infer<typeof PaginationInfoSchema>;\n\n/**\n * Shopify Stats Response\n */\nexport const ShopifyStatsResponseSchema = z.object({\n totalRequests: z.number().int().nonnegative(),\n blockedBots: z.number().int().nonnegative(),\n allowedRequests: z.number().int().nonnegative(),\n threatLevel: z.enum(['low', 'medium', 'high']),\n recentThreats: z.array(ShopifyThreatSchema),\n pagination: PaginationInfoSchema,\n});\n\nexport type ShopifyStatsResponse = z.infer<typeof ShopifyStatsResponseSchema>;\n\n/**\n * Shopify Project Settings Update Request\n */\nexport const ShopifyProjectSettingsUpdateSchema = z.object({\n settings: z\n .object({\n blockOnHighConfidence: z.boolean().optional(),\n confidenceThreshold: z.number().min(0).max(1).optional(),\n enableSessionTracking: z.boolean().optional(),\n enableWasm: z.boolean().optional(),\n })\n .optional(),\n});\n\nexport type ShopifyProjectSettingsUpdate = z.infer<typeof ShopifyProjectSettingsUpdateSchema>;\n","/**\n * Shared SDK event contracts.\n */\n\nimport { z } from 'zod';\nimport type { RequestContext } from '../core/detection';\n\n/**\n * Context attached to SDK lifecycle events.\n */\nexport type SdkEventContext = RequestContext;\n\n/**\n * Cookie/header-backed session data emitted when an AI agent session continues.\n */\nexport const SdkSessionDataSchema = z.object({\n id: z.string(),\n agent: z.string(),\n confidence: z.number(),\n detectedAt: z.number(),\n expires: z.number(),\n});\nexport type SdkSessionData = z.infer<typeof SdkSessionDataSchema>;\n\nexport type SdkMetricValue = string | number | boolean | null | undefined;\nexport type SdkMetricTags = Record<string, SdkMetricValue>;\n","/**\n * Real-time event types\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\n\n/**\n * Real-time event types\n */\nexport const RealtimeEventTypeSchema = z.enum([\n 'detection',\n 'blocked',\n 'allowed',\n 'error',\n 'pattern_update',\n 'config_change',\n 'stats_update',\n]);\nexport type RealtimeEventType = z.infer<typeof RealtimeEventTypeSchema>;\n\n/**\n * Base real-time event\n */\nexport const RealtimeEventSchema = z.object({\n type: RealtimeEventTypeSchema,\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.any(),\n});\nexport type RealtimeEvent = z.infer<typeof RealtimeEventSchema>;\n\n/**\n * Detection event\n */\nexport const DetectionEventSchema = z.object({\n type: z.literal('detection'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n result: DetectionResultSchema,\n request: z.object({\n userAgent: z.string(),\n ipAddress: z.string().optional(),\n url: z.string().optional(),\n }),\n }),\n});\nexport type DetectionEvent = z.infer<typeof DetectionEventSchema>;\n\n/**\n * Block event\n */\nexport const BlockEventSchema = z.object({\n type: z.literal('blocked'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n reason: z.string(),\n agentType: z.string(),\n confidence: z.number(),\n ipAddress: z.string().optional(),\n url: z.string().optional(),\n }),\n});\nexport type BlockEvent = z.infer<typeof BlockEventSchema>;\n\n/**\n * Stats update event\n */\nexport const StatsUpdateEventSchema = z.object({\n type: z.literal('stats_update'),\n timestamp: z.number(),\n projectId: z.string().optional(),\n data: z.object({\n period: z.enum(['minute', 'hour', 'day']),\n totalRequests: z.number(),\n agentsDetected: z.number(),\n averageConfidence: z.number(),\n }),\n});\nexport type StatsUpdateEvent = z.infer<typeof StatsUpdateEventSchema>;\n\n/**\n * Event emitter interface\n */\nexport interface EventEmitter {\n emit(event: RealtimeEvent): void;\n on(type: RealtimeEventType, handler: (event: RealtimeEvent) => void): void;\n off(type: RealtimeEventType, handler: (event: RealtimeEvent) => void): void;\n}\n","/**\n * Managed Agent Deployment + Compute Process Contracts (checkpoint-owned subset)\n *\n * Schemas for the managed hosting tier (agents on Fly.io) and the\n * `@kya-os/compute` ⇄ Checkpoint heartbeat/config/control protocol.\n *\n * Ported into checkpoint-shared from `@kya-os/contracts/agent-deployment` +\n * `@kya-os/contracts/compute` as part of the E6 / C-series decommission\n * (#2914 / #2917). Only the symbols re-exported by\n * `apps/web/lib/types/molti-deploy-contracts.ts` (plus their transitive deps —\n * `DidStringSchema`, the compute command sub-schemas) are ported.\n *\n * @module @kya-os/checkpoint-shared/deploy\n */\n\nimport { z } from 'zod';\n\n// ============================================================================\n// Cross-repo endpoint contract\n// ============================================================================\n\n/**\n * The KYA-OS activity-events ingest path (SPEC-EVENTS v0.1 batch endpoint).\n *\n * This is a CROSS-REPO CONTRACT. The Tier 2 worker runtime\n * (`@kya-os/mcp-i-cloudflare`) POSTs `tool.invoked` (and the other SPEC-EVENTS\n * types) to `${AGENTSHIELD_API_URL}${KYA_OS_EVENTS_PATH}`, authenticated by the\n * project API key. Checkpoint serves the batch ingest at this exact path\n * (`apps/web/app${KYA_OS_EVENTS_PATH}/route.ts`) and fans events out into the\n * `detections` table behind `/activity`.\n *\n * Managed deploy deliberately injects NO `KYA_OS_EVENTS_*` secret and relies on\n * this derivation instead, so the two sides agree only by matching this literal.\n * Changing it on either side silently drops all managed activity — it is pinned\n * by a contract test. Keep this value and the worker's derivation in sync.\n */\nexport const KYA_OS_EVENTS_PATH = '/api/v1/kya-os/events';\n\n// ============================================================================\n// Shared Schemas\n// ============================================================================\n\n/**\n * Validated DID string schema.\n * Reusable across all contract files that reference agent DIDs.\n *\n * Format: `did:<method>:<method-specific-id>`\n * - method: 1+ lowercase alphanumeric chars\n * - method-specific-id: 1+ non-whitespace chars\n *\n * Examples: `did:key:z6Mk...`, `did:web:example.com`\n */\nexport const DidStringSchema = z\n .string()\n .min(8, 'DID must be at least 8 characters')\n .regex(/^did:[a-z0-9]+:\\S+$/, 'DID must match format did:<method>:<method-specific-id>');\n\n/**\n * Fly.io deployment regions.\n * Enumerated to prevent arbitrary strings from being accepted.\n * @see https://fly.io/docs/reference/regions/\n */\nexport const FlyRegionSchema = z.enum([\n 'ams', // Amsterdam, Netherlands\n 'arn', // Stockholm, Sweden\n 'atl', // Atlanta, Georgia (US)\n 'bog', // Bogotá, Colombia\n 'bos', // Boston, Massachusetts (US)\n 'cdg', // Paris, France\n 'den', // Denver, Colorado (US)\n 'dfw', // Dallas, Texas (US)\n 'ewr', // Secaucus, NJ (US)\n 'eze', // Ezeiza, Argentina\n 'fra', // Frankfurt, Germany\n 'gdl', // Guadalajara, Mexico\n 'gig', // Rio de Janeiro, Brazil\n 'gru', // São Paulo, Brazil\n 'hkg', // Hong Kong\n 'iad', // Ashburn, Virginia (US)\n 'jnb', // Johannesburg, South Africa\n 'lax', // Los Angeles, California (US)\n 'lhr', // London, United Kingdom\n 'mad', // Madrid, Spain\n 'mia', // Miami, Florida (US)\n 'nrt', // Tokyo, Japan\n 'ord', // Chicago, Illinois (US)\n 'otp', // Bucharest, Romania\n 'phx', // Phoenix, Arizona (US)\n 'qro', // Querétaro, Mexico\n 'scl', // Santiago, Chile\n 'sea', // Seattle, Washington (US)\n 'sin', // Singapore\n 'sjc', // San Jose, California (US)\n 'syd', // Sydney, Australia\n 'waw', // Warsaw, Poland\n 'yul', // Montreal, Canada\n 'yyz', // Toronto, Canada\n]);\n\nexport type FlyRegion = z.infer<typeof FlyRegionSchema>;\n\n/**\n * Hosting mode discriminator — differentiates between deploy backends:\n * - `byok`: self-managed deploy in the customer's own Cloudflare account\n * (customer runs the deploy themselves).\n * - `managed`: platform-managed deploy in our Cloudflare account via Workers\n * for Platforms (dispatch namespace).\n * - `managed-byoa`: platform-managed deploy that lands in the customer's own\n * (\"bring your own account\") Cloudflare account via the standard Workers API,\n * after the org connects Cloudflare over OAuth/token (KYA-906-C).\n */\nexport const HostingModeSchema = z.enum(['byok', 'managed', 'managed-byoa']);\n\nexport type HostingMode = z.infer<typeof HostingModeSchema>;\n\n// ============================================================================\n// Protocol audit deployment contract\n// ============================================================================\n\nexport const AuditAssuranceProfileSchema = z.enum(['AAP-0', 'AAP-1', 'AAP-2', 'AAP-3', 'AAP-4']);\nexport const AuditDeliveryModeSchema = z.enum(['best-effort', 'buffered', 'required']);\n\n/**\n * Serializable request contract shared by the wizard and every deploy lane.\n * `requestedProfile` is intent, never an assurance claim. Only readiness\n * evaluation against observed runtime capabilities yields `effectiveProfile`.\n */\nexport const AuditDeploymentConfigSchema = z\n .object({\n enabled: z.boolean(),\n requestedProfile: AuditAssuranceProfileSchema,\n delivery: AuditDeliveryModeSchema,\n evidenceMode: z.enum(['none', 'encrypted-separate', 'encrypted-inline']),\n retentionClass: z.string().min(1).max(128),\n retentionDays: z.number().int().min(0).max(3650),\n residency: z.enum(['inherit-project', 'us', 'eu', 'global']),\n keyCustody: z.enum(['none', 'checkpoint-managed', 'customer-managed-kms']),\n recorderTopology: z.enum(['none', 'self-hosted', 'managed', 'verified-mirror']),\n })\n .strict()\n .superRefine((value, context) => {\n if (!value.enabled && value.requestedProfile !== 'AAP-0') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['requestedProfile'],\n message: 'Disabled audit configuration must request AAP-0',\n });\n }\n if (value.enabled && value.requestedProfile === 'AAP-0') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['requestedProfile'],\n message: 'Enabled audit configuration must request AAP-1 or higher',\n });\n }\n if (Number(value.requestedProfile.slice(-1)) >= 2 && value.delivery === 'best-effort') {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['delivery'],\n message: 'AAP-2 or higher cannot use best-effort delivery',\n });\n }\n if (!value.enabled && (value.keyCustody !== 'none' || value.recorderTopology !== 'none')) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'Disabled audit configuration cannot claim key custody or recorder topology',\n });\n }\n });\n\nexport type AuditDeploymentConfig = z.infer<typeof AuditDeploymentConfigSchema>;\nexport type AuditAssuranceProfile = z.infer<typeof AuditAssuranceProfileSchema>;\n\n/** Applied only when a user starts a new platform-managed deployment. */\nexport const NEW_MANAGED_AUDIT_DEPLOYMENT_DEFAULT: Readonly<AuditDeploymentConfig> = Object.freeze({\n enabled: true,\n requestedProfile: 'AAP-2',\n delivery: 'buffered',\n evidenceMode: 'encrypted-separate',\n retentionClass: 'integrity-ledger',\n retentionDays: 365,\n residency: 'inherit-project',\n keyCustody: 'checkpoint-managed',\n recorderTopology: 'managed',\n});\n\n/**\n * Missing audit config in an already persisted manifest is always AAP-0.\n * This prevents a dashboard or redeploy from silently upgrading old workers.\n */\nexport const ABSENT_AUDIT_DEPLOYMENT_CONFIG: Readonly<AuditDeploymentConfig> = Object.freeze({\n enabled: false,\n requestedProfile: 'AAP-0',\n delivery: 'best-effort',\n evidenceMode: 'none',\n retentionClass: 'none',\n retentionDays: 0,\n residency: 'inherit-project',\n keyCustody: 'none',\n recorderTopology: 'none',\n});\n\nexport const AuditRuntimeCapabilitiesSchema = z\n .object({\n recorderTopology: z.enum(['none', 'self-hosted', 'managed', 'verified-mirror']),\n delivery: AuditDeliveryModeSchema,\n journalDurability: z.enum(['none', 'ephemeral', 'durable']),\n atomicAppend: z.boolean(),\n sourceHighWater: z.boolean(),\n merkleCheckpoints: z.boolean(),\n independentObservation: z.boolean(),\n supportingAnchors: z.array(z.enum(['worm', 'rfc3161', 'scitt'])),\n evidenceRetention: z.enum(['none', 'inline', 'separate']),\n })\n .strict();\n\nexport type AuditRuntimeCapabilities = z.infer<typeof AuditRuntimeCapabilitiesSchema>;\n\nexport const AuditRuntimeCanaryResultSchema = z\n .object({\n passed: z.boolean(),\n observedAt: z.number().int().nonnegative(),\n capabilities: AuditRuntimeCapabilitiesSchema,\n checks: z\n .array(\n z\n .object({\n id: z.string().min(1).max(128),\n passed: z.boolean(),\n })\n .strict()\n )\n .min(1),\n bundleHash: z.string().min(1).max(256).optional(),\n })\n .strict()\n .superRefine((value, context) => {\n if (value.passed !== value.checks.every((check) => check.passed)) {\n context.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['passed'],\n message: 'Canary result must equal the aggregate of its mechanical checks',\n });\n }\n });\n\nexport type AuditRuntimeCanaryResult = z.infer<typeof AuditRuntimeCanaryResultSchema>;\n\nexport function requiredAuditRuntimeCanaryChecks(capabilities: AuditRuntimeCapabilities): string[] {\n const checks = [\n 'recorder_round_trip',\n 'verified_receipt',\n 'idempotent_retry',\n 'event_identity_conflict',\n 'source_state',\n ];\n if (capabilities.delivery === 'buffered') checks.push('buffered_outbox');\n if (capabilities.evidenceRetention !== 'none') checks.push('evidence_write_verified');\n return checks;\n}\n\nexport const AuditDeploymentReadinessSchema = z\n .object({\n requestedProfile: AuditAssuranceProfileSchema,\n effectiveProfile: AuditAssuranceProfileSchema,\n status: z.enum(['disabled', 'ready', 'degraded']),\n capabilities: AuditRuntimeCapabilitiesSchema.nullable(),\n canary: AuditRuntimeCanaryResultSchema.nullable(),\n reasonCodes: z.array(z.string().min(1).max(128)),\n })\n .strict();\n\nexport type AuditDeploymentReadiness = z.infer<typeof AuditDeploymentReadinessSchema>;\n\nconst PROFILE_BY_LEVEL = ['AAP-0', 'AAP-1', 'AAP-2', 'AAP-3', 'AAP-4'] as const;\n\nexport function resolveAuditDeploymentReadiness(\n config: AuditDeploymentConfig | undefined,\n capabilities: AuditRuntimeCapabilities | undefined,\n canary?: AuditRuntimeCanaryResult\n): AuditDeploymentReadiness {\n const requested = AuditDeploymentConfigSchema.parse(config ?? ABSENT_AUDIT_DEPLOYMENT_CONFIG);\n const observedCanary = canary ? AuditRuntimeCanaryResultSchema.parse(canary) : null;\n if (!requested.enabled) {\n return {\n requestedProfile: 'AAP-0',\n effectiveProfile: 'AAP-0',\n status: 'disabled',\n capabilities: capabilities ?? null,\n canary: observedCanary,\n reasonCodes: ['audit_not_configured'],\n };\n }\n const observedCapabilities = capabilities ?? observedCanary?.capabilities;\n if (!observedCapabilities) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: null,\n canary: observedCanary,\n reasonCodes: ['runtime_capabilities_unavailable'],\n };\n }\n const observed = AuditRuntimeCapabilitiesSchema.parse(observedCapabilities);\n if (!observedCanary) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: null,\n reasonCodes: ['runtime_canary_required'],\n };\n }\n if (\n !observedCanary.passed ||\n JSON.stringify(observedCanary.capabilities) !== JSON.stringify(observed)\n ) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: [\n observedCanary.passed ? 'runtime_canary_capability_mismatch' : 'runtime_canary_failed',\n ],\n };\n }\n const passedChecks = new Set(\n observedCanary.checks.filter((check) => check.passed).map((check) => check.id)\n );\n if (requiredAuditRuntimeCanaryChecks(observed).some((check) => !passedChecks.has(check))) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: ['runtime_canary_incomplete'],\n };\n }\n let maximum = 0;\n const reasons: string[] = [];\n if (observed.recorderTopology !== requested.recorderTopology) {\n reasons.push('recorder_topology_mismatch');\n }\n const deliveryRank = { 'best-effort': 0, buffered: 1, required: 2 } as const;\n if (deliveryRank[observed.delivery] < deliveryRank[requested.delivery]) {\n reasons.push('delivery_mode_mismatch');\n }\n const expectedEvidence =\n requested.evidenceMode === 'none'\n ? 'none'\n : requested.evidenceMode === 'encrypted-inline'\n ? 'inline'\n : 'separate';\n if (expectedEvidence !== observed.evidenceRetention) {\n reasons.push('evidence_retention_mismatch');\n }\n // These are explicit deployment-contract mismatches, not merely unavailable\n // higher-assurance services. Never activate a recorder against mechanics\n // weaker than (or topologically different from) the binding it was given.\n if (reasons.length > 0) {\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: 'AAP-0',\n status: 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: reasons,\n };\n }\n if (observed.recorderTopology !== 'none' && observed.journalDurability !== 'none') maximum = 1;\n else reasons.push('recorder_or_journal_unavailable');\n if (\n maximum >= 1 &&\n observed.journalDurability === 'durable' &&\n observed.atomicAppend &&\n observed.delivery !== 'best-effort'\n ) {\n maximum = 2;\n } else if (Number(requested.requestedProfile.slice(-1)) >= 2) {\n reasons.push('durable_atomic_buffered_append_unavailable');\n }\n if (maximum >= 2 && observed.merkleCheckpoints && observed.sourceHighWater) maximum = 3;\n else if (Number(requested.requestedProfile.slice(-1)) >= 3) {\n reasons.push('checkpoint_or_source_high_water_unavailable');\n }\n if (maximum >= 3 && observed.independentObservation && observed.supportingAnchors.length > 0) {\n maximum = 4;\n } else if (Number(requested.requestedProfile.slice(-1)) >= 4) {\n reasons.push('independent_observation_or_anchor_unavailable');\n }\n const requestedLevel = Number(requested.requestedProfile.slice(-1));\n const effectiveLevel = Math.min(requestedLevel, maximum);\n return {\n requestedProfile: requested.requestedProfile,\n effectiveProfile: PROFILE_BY_LEVEL[effectiveLevel]!,\n status: effectiveLevel === requestedLevel && reasons.length === 0 ? 'ready' : 'degraded',\n capabilities: observed,\n canary: observedCanary,\n reasonCodes: reasons,\n };\n}\n\n/**\n * Deploy step status — reuses same status enum as BYOK.\n */\nexport const ManagedDeployStepStatusSchema = z.enum([\n 'pending',\n 'in_progress',\n 'completed',\n 'failed',\n 'skipped',\n]);\n\nexport type ManagedDeployStepStatus = z.infer<typeof ManagedDeployStepStatusSchema>;\n\n// ============================================================================\n// Heartbeat Protocol (@kya-os/compute ⇄ AgentShield)\n// ============================================================================\n\n/**\n * Heartbeat request body.\n * Sent by compute process: POST /api/v1/molti/agents/{did}/heartbeat\n * Auth: X-Heartbeat-Token header\n */\nexport const HeartbeatRequestSchema = z.object({\n /** Agent DID this heartbeat is for */\n agentDid: DidStringSchema,\n /** Current compute process status */\n status: z.enum(['starting', 'running', 'error', 'stopping']),\n /** @kya-os/compute package version (from package.json) */\n computeVersion: z.string().min(1).max(50),\n /** Installed OpenClaw version (from npm ls) */\n openclawVersion: z.string().max(50).optional(),\n /** Fly machine ID (from FLY_MACHINE_ID env var) */\n machineId: z.string().max(255).optional(),\n /** Seconds since compute process started */\n uptimeSeconds: z.number().nonnegative().optional(),\n /** Current RSS memory in MB */\n memoryMb: z.number().nonnegative().optional(),\n});\n\nexport type HeartbeatRequest = z.infer<typeof HeartbeatRequestSchema>;\n\n// ============================================================================\n// Compute Commands (Discriminated Union)\n// ============================================================================\n\n/**\n * Stop command — graceful shutdown, no payload accepted.\n */\nexport const StopCommandSchema = z\n .object({\n type: z.literal('stop'),\n })\n .strict();\n\n/**\n * Restart command — restart the compute process, no payload accepted.\n */\nexport const RestartCommandSchema = z\n .object({\n type: z.literal('restart'),\n })\n .strict();\n\n/**\n * Update config command — triggers config re-fetch, no payload accepted.\n */\nexport const UpdateConfigCommandSchema = z\n .object({\n type: z.literal('update_config'),\n })\n .strict();\n\n/**\n * Update version command — requires target version in payload.\n */\nexport const UpdateVersionCommandSchema = z\n .object({\n type: z.literal('update_version'),\n payload: z.object({\n /** Target OpenClaw version to install */\n version: z.string().min(1).max(50),\n }),\n })\n .strict();\n\n/**\n * Command that Agent Shield can send to the compute process\n * via the heartbeat response.\n *\n * Discriminated union by `type` field:\n * - `stop` / `restart` / `update_config` — no payload\n * - `update_version` — requires `{ version: string }` payload\n */\nexport const ComputeCommandSchema = z.discriminatedUnion('type', [\n StopCommandSchema,\n RestartCommandSchema,\n UpdateConfigCommandSchema,\n UpdateVersionCommandSchema,\n]);\n\nexport type ComputeCommand = z.infer<typeof ComputeCommandSchema>;\n\n/**\n * Heartbeat response from Agent Shield.\n * Returned by: POST /api/v1/molti/agents/{did}/heartbeat\n */\nexport const HeartbeatResponseSchema = z.object({\n /** Always true for successful heartbeats */\n ack: z.literal(true),\n /** Pending commands for the compute process to execute */\n commands: z.array(ComputeCommandSchema).default([]),\n /** ISO timestamp of last config change (compute compares to detect updates) */\n configUpdatedAt: z.string().datetime().optional(),\n});\n\nexport type HeartbeatResponse = z.infer<typeof HeartbeatResponseSchema>;\n\n// ============================================================================\n// Config Bundle\n// ============================================================================\n\n/**\n * Config bundle returned by Agent Shield to the compute process.\n * Fetched on boot: GET /api/v1/molti/deployments/{did}/config-bundle\n * Auth: X-Heartbeat-Token header (for managed) or X-API-Key (for BYOK)\n *\n * **Private Key Delivery**: The agent's private key is NOT included in the config bundle.\n * It is delivered as the `AGENT_PRIVATE_KEY` environment variable at Fly machine creation\n * time and persists in the machine's env. This avoids transmitting the key on every\n * config fetch and keeps it out of the config-bundle response surface.\n */\nexport const ConfigBundleSchema = z.object({\n /** Schema version — 2 for managed bundles */\n version: z.number().int().positive(),\n /** Kill switch — if true, compute must exit immediately */\n killed: z.boolean(),\n /** Target OpenClaw version to install */\n openclawVersion: z.string().min(1).max(50),\n /** Agent personality/system prompt file contents (max 100KB) */\n soulFile: z.string().max(100_000).nullable(),\n /** Gateway auth token for OpenClaw */\n gatewayToken: z.string().min(1).max(500),\n /** Channel configurations */\n channels: z.object({\n telegram: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n })\n .optional(),\n discord: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n })\n .optional(),\n slack: z\n .object({\n enabled: z.boolean(),\n token: z.string().optional(),\n appToken: z.string().optional(),\n })\n .optional(),\n whatsapp: z\n .object({\n enabled: z.boolean(),\n })\n .strict()\n .optional(),\n }),\n /** AI provider configuration — key is decrypted, sent over TLS */\n aiProvider: z.object({\n type: z.enum(['anthropic', 'openai']),\n apiKey: z.string().min(1).max(500),\n /**\n * Optional base URL override. When set, OpenClaw routes all provider\n * traffic through this URL instead of the provider's default endpoint.\n * Used by managed deployments where AgentShield issues a per-deployment\n * gateway token and proxies to the upstream provider with budget tracking.\n */\n baseUrl: z.string().url().optional(),\n }),\n /**\n * Optional OpenClaw heartbeat interval (`agents.defaults.heartbeat.every`).\n * Drives how often OpenClaw wakes the agent for HEARTBEAT.md processing —\n * the primary token-cost lever. Examples: \"30m\" (active), \"6h\" (idle),\n * \"off\" (dormant — heartbeat disabled entirely). When absent, the patcher\n * preserves whatever value already lives in openclaw.json (OpenClaw's\n * built-in default of \"30m\").\n */\n heartbeatEvery: z.string().min(1).max(20).optional(),\n /**\n * Optional override for `agents.defaults.model.primary` (e.g.\n * \"anthropic/claude-haiku-4-5\" for idle agents). When absent, the patcher\n * derives the model from `aiProvider.type` as before. Format must be\n * \"<provider>/<model-id>\".\n */\n modelOverride: z.string().min(1).max(100).optional(),\n /** ISO timestamp of last config modification */\n updatedAt: z.string().datetime(),\n});\n\nexport type ConfigBundle = z.infer<typeof ConfigBundleSchema>;\n\n// ============================================================================\n// Control Server (WebSocket :18790)\n// ============================================================================\n\n/**\n * Status frame pushed from compute control server to dashboard.\n * Sent on connect + every 5 seconds.\n */\nexport const ControlStatusSchema = z.object({\n /** Whether the agent runtime is healthy */\n healthy: z.boolean(),\n /** Seconds since compute process started */\n uptimeSeconds: z.number().nonnegative(),\n /** Installed OpenClaw version */\n openclawVersion: z.string().min(1).max(50),\n /** @kya-os/compute version */\n computeVersion: z.string().min(1).max(50),\n /** Number of active WS connections to control server */\n activeConnections: z.number().int().nonnegative(),\n /** Current RSS memory in MB */\n memoryMb: z.number().nonnegative(),\n /** CPU usage percentage (0-100) */\n cpuPercent: z.number().nonnegative().max(100),\n});\n\nexport type ControlStatus = z.infer<typeof ControlStatusSchema>;\n","/**\n * Deploy Progress Event Types\n *\n * Types for real-time deployment progress tracking via SSE.\n * Used by the one-click deploy feature to stream step-by-step updates.\n *\n * @module events/deploy-progress\n */\n\nimport { z } from 'zod';\nimport { AuditDeploymentConfigSchema } from '../deploy';\n\n/**\n * All possible deployment steps in order\n */\nexport const DEPLOY_STEPS = [\n { id: 'github_verify', label: 'Verifying your GitHub connection', order: 1 },\n { id: 'repo_check', label: 'Checking your repository name', order: 2 },\n { id: 'project_create', label: 'Creating your project', order: 3 },\n { id: 'api_key', label: 'Generating your API key', order: 4 },\n { id: 'scaffold', label: 'Generating your server files', order: 5 },\n { id: 'kta_register', label: 'Setting up your agent identity', order: 6 },\n { id: 'repo_create', label: 'Creating your GitHub repository', order: 7 },\n { id: 'commit_files', label: 'Committing your server code', order: 8 },\n { id: 'add_secrets', label: 'Securing your repository secrets', order: 9 },\n { id: 'cloudflare_deploy', label: 'Deploying your server to Cloudflare', order: 10 },\n { id: 'complete', label: 'Deployment complete!', order: 11 },\n] as const;\n\n/**\n * Step ID enum\n */\nexport const DeployStepIdSchema = z.enum([\n 'github_verify',\n 'repo_check',\n 'project_create',\n 'api_key',\n 'scaffold',\n 'kta_register',\n 'repo_create',\n 'commit_files',\n 'add_secrets',\n 'cloudflare_deploy',\n 'complete',\n]);\nexport type DeployStepId = z.infer<typeof DeployStepIdSchema>;\n\n/**\n * Step status\n */\nexport const DeployStepStatusSchema = z.enum([\n 'pending',\n 'running',\n 'complete',\n 'error',\n 'skipped',\n]);\nexport type DeployStepStatus = z.infer<typeof DeployStepStatusSchema>;\n\n/**\n * Individual step state\n */\nexport const DeployStepStateSchema = z.object({\n id: DeployStepIdSchema,\n status: DeployStepStatusSchema,\n message: z.string().optional(),\n startedAt: z.number().optional(),\n completedAt: z.number().optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n })\n .optional(),\n});\nexport type DeployStepState = z.infer<typeof DeployStepStateSchema>;\n\n/**\n * Full deployment progress event\n */\nexport const DeployProgressEventSchema = z.object({\n type: z.literal('deploy_progress'),\n deploymentId: z.string(),\n timestamp: z.number(),\n currentStep: DeployStepIdSchema,\n steps: z.array(DeployStepStateSchema),\n result: z\n .object({\n repoUrl: z.string(),\n repoFullName: z.string(),\n deployUrl: z.string(),\n projectId: z.string(),\n /** Human-readable project ID for URL construction */\n friendlyId: z.string().nullable().optional(),\n /** kyaosDeployments row id — drives the live-step \"Go to server\" deployment-detail link. */\n deploymentId: z.string().optional(),\n /** Full API key - only shown once at completion! */\n apiKey: z.string(),\n /** Preview (sk_...xxx) for display after initial view */\n apiKeyPreview: z.string(),\n cloudflareUrl: z.string().optional(),\n cloudflareDeployed: z.boolean().optional(),\n /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */\n cloudflareError: z.string().optional(),\n /** Agent DID (decentralized identifier) - did:web for reputation enabled, did:key for disabled */\n agentDid: z.string().optional(),\n /** Whether agent was registered with Know That AI for reputation tracking */\n ktaRegistered: z.boolean().optional(),\n /** Claim URL for KTA registration (only when using cli-register with did:web) */\n ktaClaimUrl: z.string().optional(),\n })\n .optional(),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n step: DeployStepIdSchema.optional(),\n })\n .optional(),\n});\nexport type DeployProgressEvent = z.infer<typeof DeployProgressEventSchema>;\n\n/**\n * Deployment metadata stored in Redis\n */\nexport const DeploymentMetadataSchema = z.object({\n id: z.string(),\n userId: z.string(),\n organizationId: z.string(),\n repoName: z.string(),\n template: z.string(),\n platform: z.string(),\n /** Hosting mode: 'managed' (Checkpoint hosted) or 'byok' (Bring Your Own Cloudflare) */\n hostingMode: z.enum(['managed', 'byok']).optional().default('byok'),\n /** 'repo-only' scaffolds + pushes the repo but never triggers the Cloudflare worker upload, regardless of connection state (defaults to 'cloudflare') */\n deployTarget: z.enum(['cloudflare', 'repo-only']).optional(),\n status: z.enum(['pending', 'running', 'complete', 'error']),\n /** Enable reputation tracking via Know That AI (defaults to true) */\n enableReputation: z.boolean().optional(),\n /** Requested audit posture. Old stored metadata may omit this and resolves to AAP-0 at use. */\n audit: AuditDeploymentConfigSchema.optional(),\n /** Existing project ID to deploy to (if provided, skips project creation) - Unified Project Schema v1.3 */\n existingProjectId: z.string().uuid().optional(),\n /** Pre-generated source supplied by another intake flow (for example OpenAPI). */\n generatedFiles: z\n .array(\n z.object({\n path: z.string(),\n content: z.string(),\n isBase64: z.boolean().optional(),\n })\n )\n .optional(),\n /** Identity paired with pre-generated source. */\n generatedIdentity: z\n .object({\n did: z.string(),\n // Optional so historical metadata already sitting in Redis without a\n // kid still parses. The producing route always populates it now (see\n // KYA-956 phase 3); the deploy pipeline treats a missing kid as a\n // scaffold-time failure rather than injecting a broken identity.\n kid: z.string().optional(),\n publicKey: z.string(),\n privateKey: z.string(),\n })\n .optional(),\n /** Validated source-specific secrets forwarded to GitHub/Cloudflare. */\n additionalSecrets: z.record(z.string(), z.string()).optional(),\n /** Semantic source type used for descriptions and registry metadata. */\n agentType: z.string().optional(),\n createdAt: z.number(),\n updatedAt: z.number(),\n /** Result data (populated on completion) */\n result: z\n .object({\n /** GitHub repo URL (BYOK deploy only) */\n repoUrl: z.string().optional(),\n /** GitHub repo full name e.g. \"user/repo\" (BYOK deploy only) */\n repoFullName: z.string().optional(),\n /** GitHub Actions deploy URL (BYOK deploy only) */\n deployUrl: z.string().optional(),\n projectId: z.string(),\n /** Human-readable project ID for URL construction */\n friendlyId: z.string().nullable().optional(),\n /** kyaosDeployments row id — powers the live-step deployment-detail link (all sources). */\n deploymentId: z.string().optional(),\n /** API key preview e.g. \"sk_...xxx\" (BYOK deploy only) */\n apiKeyPreview: z.string().optional(),\n cloudflareUrl: z.string().optional(),\n cloudflareDeployed: z.boolean().optional(),\n /** User-facing reason the Cloudflare worker deploy failed (set only when cloudflareDeployed is false and a real deploy was attempted). */\n cloudflareError: z.string().optional(),\n agentDid: z.string().optional(),\n ktaRegistered: z.boolean().optional(),\n ktaClaimUrl: z.string().optional(),\n })\n .optional(),\n});\nexport type DeploymentMetadata = z.infer<typeof DeploymentMetadataSchema>;\n\n/**\n * Helper to get step info by ID\n */\nexport function getStepInfo(stepId: DeployStepId) {\n return DEPLOY_STEPS.find((s) => s.id === stepId);\n}\n\n/**\n * Helper to get step order\n */\nexport function getStepOrder(stepId: DeployStepId): number {\n const step = DEPLOY_STEPS.find((s) => s.id === stepId);\n return step?.order ?? 0;\n}\n\n/**\n * Calculate completion percentage\n */\nexport function calculateDeployProgress(\n currentStep: DeployStepId,\n status: DeployStepStatus\n): number {\n const totalSteps = DEPLOY_STEPS.length - 1; // Exclude 'complete' step\n const currentOrder = getStepOrder(currentStep);\n\n if (currentStep === 'complete') return 100;\n\n // If running, we're partially through the step\n if (status === 'running') {\n return Math.round(((currentOrder - 0.5) / totalSteps) * 100);\n }\n\n // If complete, we've finished this step\n if (status === 'complete') {\n return Math.round((currentOrder / totalSteps) * 100);\n }\n\n return Math.round(((currentOrder - 1) / totalSteps) * 100);\n}\n\n/**\n * Build initial steps state (all pending)\n */\nexport function buildInitialStepsState(): DeployStepState[] {\n return DEPLOY_STEPS.map((step) => ({\n id: step.id as DeployStepId,\n status: 'pending' as const,\n }));\n}\n\n/**\n * Update steps state for a given step\n */\nexport function updateStepsState(\n currentSteps: DeployStepState[],\n stepId: DeployStepId,\n status: DeployStepStatus,\n options?: { message?: string; error?: { code: string; message: string } }\n): DeployStepState[] {\n const now = Date.now();\n\n return currentSteps.map((step) => {\n if (step.id === stepId) {\n return {\n ...step,\n status,\n message: options?.message,\n error: options?.error,\n startedAt: status === 'running' ? now : step.startedAt,\n completedAt: status === 'complete' || status === 'error' ? now : step.completedAt,\n };\n }\n return step;\n });\n}\n","/**\n * WASM Interface Types\n *\n * These types match the Rust WASM module's JavaScript interface.\n * They serve as a bridge between the Rust detection engine and TypeScript.\n */\n\nimport { z } from 'zod';\nimport { AgentTypeSchema, type AgentType } from '../core/agent';\n\n/**\n * Known agent names (type-safe list from detection engine)\n * Re-export from core for convenience and single source of truth\n */\nexport { AgentTypeSchema as WasmAgentTypeSchema } from '../core/agent';\nexport type WasmAgentName = AgentType;\n\n/**\n * Extended agent name schema - allows known types plus custom strings\n * This provides type safety while allowing for new/unknown agents\n */\nexport const WasmAgentNameSchema = z.union([\n AgentTypeSchema,\n z.string().min(1).max(100), // Allow custom agent names but with constraints\n]);\nexport type WasmAgentNameExtended = z.infer<typeof WasmAgentNameSchema>;\n\n/**\n * WASM Detection Result\n * Matches the Rust JsDetectionResult struct\n *\n * NOTE: The 'agent' field uses extended schema to support both known and unknown agents\n */\nexport const WasmDetectionResultSchema = z.object({\n is_agent: z.boolean(),\n confidence: z.number().min(0).max(1),\n agent: WasmAgentNameSchema.optional(),\n verification_method: z.string(),\n risk_level: z.string(),\n timestamp: z.string(),\n});\nexport type WasmDetectionResult = z.infer<typeof WasmDetectionResultSchema>;\n\n/**\n * WASM Request Metadata\n * Matches the Rust JsRequestMetadata struct\n *\n * IMPORTANT: Updated to include client_fingerprint field\n */\nexport const WasmRequestMetadataSchema = z.object({\n user_agent: z.string().optional(),\n ip_address: z.string().optional(),\n headers: z.string(), // JSON string of headers\n timestamp: z.string(),\n url: z.string().optional(),\n method: z.string().optional(),\n client_fingerprint: z.string().optional(), // ✅ Added client fingerprint support\n});\nexport type WasmRequestMetadata = z.infer<typeof WasmRequestMetadataSchema>;\n\n/**\n * Verification Method enum matching Rust\n */\nexport enum WasmVerificationMethod {\n UserAgent = 'UserAgent',\n IPRange = 'IPRange',\n Signature = 'Signature',\n Headers = 'Headers',\n Behavioral = 'Behavioral',\n Combined = 'Combined',\n}\n\n/**\n * Risk Level enum matching Rust\n */\nexport enum WasmRiskLevel {\n Low = 'Low',\n Medium = 'Medium',\n High = 'High',\n Critical = 'Critical',\n}\n\n/**\n * Convert WASM result to standard DetectionResult\n */\nexport function wasmToDetectionResult(wasmResult: WasmDetectionResult): {\n isAgent: boolean;\n confidence: number;\n agentType?: string;\n verificationMethod?: string;\n riskLevel?: string;\n timestamp: Date;\n} {\n return {\n isAgent: wasmResult.is_agent,\n confidence: wasmResult.confidence,\n agentType: wasmResult.agent,\n verificationMethod: wasmResult.verification_method,\n riskLevel: wasmResult.risk_level,\n timestamp: new Date(wasmResult.timestamp),\n };\n}\n\n/**\n * Convert standard request to WASM metadata\n *\n * Updated to include client_fingerprint field\n */\nexport function toWasmRequestMetadata(request: {\n userAgent?: string;\n ipAddress?: string;\n headers?: Record<string, string>;\n url?: string;\n method?: string;\n clientFingerprint?: string; // ✅ Added client fingerprint support\n}): WasmRequestMetadata {\n return {\n user_agent: request.userAgent,\n ip_address: request.ipAddress,\n headers: JSON.stringify(request.headers || {}),\n timestamp: new Date().toISOString(),\n url: request.url,\n method: request.method,\n client_fingerprint: request.clientFingerprint, // ✅ Map camelCase to snake_case\n };\n}\n\n/**\n * WASM Performance Metrics\n */\nexport interface WasmMetrics {\n version: string;\n buildDate?: string;\n initTime: number; // milliseconds to initialize\n lastDetectionTime?: number; // milliseconds for last detection\n totalDetections: number;\n averageDetectionTime: number;\n memoryUsage?: number; // bytes\n loadStatus: 'not-initialized' | 'loading' | 'loaded' | 'failed';\n errorCount: number;\n lastError?: string;\n}\n\n/**\n * WASM Module Interface\n * Type definitions for the WASM module exports\n */\nexport interface WasmModule {\n init(): void;\n detect_agent(metadata: WasmRequestMetadata): WasmDetectionResult;\n version(): string;\n get_version(): string;\n get_build_info(): string;\n}\n\n/**\n * WASM Module Initialization\n */\nexport interface WasmInitOptions {\n wasmPath?: string;\n enableLogging?: boolean;\n cacheResults?: boolean;\n}\n\n/**\n * Type Guards and Validation Utilities\n */\n\n/**\n * Check if a string is a known agent type\n *\n * @example\n * ```ts\n * if (isKnownAgentType(agentName)) {\n * // TypeScript knows agentName is AgentType\n * console.log(`Known agent: ${agentName}`);\n * }\n * ```\n */\nexport function isKnownAgentType(value: string): value is WasmAgentName {\n return AgentTypeSchema.safeParse(value).success;\n}\n\n/**\n * Validate a WASM detection result\n *\n * @example\n * ```ts\n * const result = await wasmModule.detect_agent(metadata);\n * if (isValidWasmDetectionResult(result)) {\n * // Type-safe result access\n * }\n * ```\n */\nexport function isValidWasmDetectionResult(value: unknown): value is WasmDetectionResult {\n return WasmDetectionResultSchema.safeParse(value).success;\n}\n\n/**\n * Validate WASM request metadata\n *\n * @example\n * ```ts\n * const metadata = toWasmRequestMetadata(request);\n * if (isValidWasmRequestMetadata(metadata)) {\n * // Safe to pass to WASM\n * }\n * ```\n */\nexport function isValidWasmRequestMetadata(value: unknown): value is WasmRequestMetadata {\n return WasmRequestMetadataSchema.safeParse(value).success;\n}\n\n/**\n * Safely parse and validate agent name from unknown input\n *\n * Returns the agent name if valid, otherwise returns 'unknown'\n *\n * @example\n * ```ts\n * const agentName = parseAgentName(userInput); // Never throws\n * ```\n */\nexport function parseAgentName(value: unknown): WasmAgentName {\n const result = AgentTypeSchema.safeParse(value);\n return result.success ? result.data : 'unknown';\n}\n\n/**\n * Normalize agent name to consistent format\n *\n * @example\n * ```ts\n * normalizeAgentName('ChatGPT') // 'chatgpt'\n * normalizeAgentName('claude-3-opus') // 'claude'\n * normalizeAgentName('unknown-bot') // 'unknown'\n * ```\n */\nexport function normalizeAgentName(value: string): WasmAgentName {\n const normalized = value.toLowerCase().trim();\n\n // Direct match\n if (isKnownAgentType(normalized)) {\n return normalized;\n }\n\n // Try partial matches for common variations\n const partialMatches: Record<string, WasmAgentName> = {\n chatgpt: 'chatgpt',\n 'gpt-': 'openai',\n 'claude-': 'claude',\n 'gemini-': 'google',\n 'llama-': 'meta',\n 'mistral-': 'mistral',\n 'mixtral-': 'mistral',\n };\n\n for (const [pattern, agentType] of Object.entries(partialMatches)) {\n if (normalized.includes(pattern)) {\n return agentType;\n }\n }\n\n return 'unknown';\n}\n\n/**\n * Get agent display name from agent type\n *\n * @example\n * ```ts\n * getAgentDisplayName('chatgpt') // 'ChatGPT'\n * getAgentDisplayName('anthropic') // 'Claude'\n * ```\n */\nexport function getAgentDisplayName(agentType: WasmAgentName): string {\n const displayNames: Record<WasmAgentName, string> = {\n openai: 'OpenAI',\n chatgpt: 'ChatGPT',\n claude: 'Claude',\n anthropic: 'Anthropic',\n perplexity: 'Perplexity',\n phind: 'Phind',\n you: 'You.com',\n neeva: 'Neeva',\n google: 'Google',\n microsoft: 'Microsoft',\n meta: 'Meta',\n alibaba: 'Alibaba',\n mistral: 'Mistral AI',\n cohere: 'Cohere',\n huggingface: 'HuggingFace',\n inflection: 'Inflection AI',\n stability: 'Stability AI',\n replicate: 'Replicate',\n together: 'Together AI',\n '01ai': '01.AI',\n writer: 'Writer',\n jasper: 'Jasper',\n xai: 'xAI',\n deepseek: 'DeepSeek',\n amazon: 'Amazon',\n kya: 'KYA',\n unknown: 'Unknown',\n };\n\n return displayNames[agentType] || agentType;\n}\n","/**\n * Session Tracking Types\n *\n * Types for tracking and managing user/agent sessions\n * across different packages and storage adapters\n */\n\nimport { z } from 'zod';\nimport { DetectionResultSchema } from '../core/detection';\nimport { BehavioralSignalsSchema } from './pixel';\n\n/**\n * Session State\n */\nexport const SessionStateSchema = z.enum(['active', 'idle', 'expired', 'terminated']);\nexport type SessionState = z.infer<typeof SessionStateSchema>;\n\n/**\n * Session Storage Adapter Types\n */\nexport const SessionStorageTypeSchema = z.enum(['memory', 'redis', 'database', 'cookie', 'custom']);\nexport type SessionStorageType = z.infer<typeof SessionStorageTypeSchema>;\n\n/**\n * Core Session Data\n */\nexport const SessionDataSchema = z.object({\n id: z.string(),\n userId: z.string().optional(),\n pixelId: z.string().optional(),\n projectId: z.string().optional(),\n\n // Timestamps\n createdAt: z.date(),\n updatedAt: z.date(),\n expiresAt: z.date(),\n lastActivityAt: z.date(),\n\n // State\n state: SessionStateSchema,\n\n // Detection Data\n isAgent: z.boolean().default(false),\n detectionResult: DetectionResultSchema.optional(),\n confidence: z.number().min(0).max(1).optional(),\n\n // Request Context\n userAgent: z.string().optional(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n\n // Behavioral Data\n behavioral: BehavioralSignalsSchema.optional(),\n pageViews: z.number().int().min(0).default(0),\n interactions: z.number().int().min(0).default(0),\n\n // Custom Metadata\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type SessionData = z.infer<typeof SessionDataSchema>;\n\n/**\n * Session Create Request\n */\nexport const SessionCreateRequestSchema = z.object({\n userId: z.string().optional(),\n pixelId: z.string().optional(),\n projectId: z.string().optional(),\n userAgent: z.string().optional(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n ttl: z.number().min(60).default(3600), // Time to live in seconds\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type SessionCreateRequest = z.infer<typeof SessionCreateRequestSchema>;\n\n/**\n * Session Update Request\n */\nexport const SessionUpdateRequestSchema = z.object({\n sessionId: z.string(),\n updates: z.object({\n state: SessionStateSchema.optional(),\n detectionResult: DetectionResultSchema.optional(),\n behavioral: BehavioralSignalsSchema.optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n lastActivityAt: z.date().optional(),\n }),\n extendTtl: z.boolean().default(true),\n});\nexport type SessionUpdateRequest = z.infer<typeof SessionUpdateRequestSchema>;\n\n/**\n * Session Query Options\n */\nexport const SessionQueryOptionsSchema = z.object({\n userId: z.string().optional(),\n pixelId: z.string().optional(),\n projectId: z.string().optional(),\n state: SessionStateSchema.optional(),\n isAgent: z.boolean().optional(),\n createdAfter: z.date().optional(),\n createdBefore: z.date().optional(),\n limit: z.number().min(1).max(100).default(10),\n offset: z.number().min(0).default(0),\n});\nexport type SessionQueryOptions = z.infer<typeof SessionQueryOptionsSchema>;\n\n/**\n * Session Storage Adapter Interface\n */\nexport interface SessionStorageAdapter {\n type: SessionStorageType;\n\n // CRUD Operations\n create(data: SessionCreateRequest): Promise<SessionData>;\n get(sessionId: string): Promise<SessionData | null>;\n update(request: SessionUpdateRequest): Promise<SessionData>;\n delete(sessionId: string): Promise<boolean>;\n\n // Query Operations\n find(options: SessionQueryOptions): Promise<SessionData[]>;\n count(options: SessionQueryOptions): Promise<number>;\n\n // Maintenance\n cleanup(expiredBefore?: Date): Promise<number>;\n touch(sessionId: string): Promise<boolean>;\n\n // Bulk Operations\n bulkCreate?(sessions: SessionCreateRequest[]): Promise<SessionData[]>;\n bulkDelete?(sessionIds: string[]): Promise<number>;\n}\n\n/**\n * Session Configuration\n */\nexport const SessionConfigSchema = z.object({\n // Storage\n storage: SessionStorageTypeSchema.default('memory'),\n storageOptions: z.record(z.string(), z.unknown()).optional(),\n\n // Timing\n ttl: z.number().min(60).default(3600), // Default 1 hour\n idleTimeout: z.number().min(60).default(1800), // Default 30 minutes\n absoluteTimeout: z.number().min(60).default(86400), // Default 24 hours\n\n // Behavior\n rollingSession: z.boolean().default(true),\n destroyOnLogout: z.boolean().default(true),\n regenerateOnLogin: z.boolean().default(true),\n\n // Security\n secure: z.boolean().default(true),\n sameSite: z.enum(['strict', 'lax', 'none']).default('lax'),\n httpOnly: z.boolean().default(true),\n domain: z.string().optional(),\n path: z.string().default('/'),\n\n // Cookie Options (if using cookie storage)\n cookieName: z.string().default('__agentshield_session'),\n cookieSecret: z.string().optional(),\n\n // Redis Options (if using Redis storage)\n redisPrefix: z.string().default('as:session:'),\n redisUrl: z.string().optional(),\n\n // Database Options (if using database storage)\n tableName: z.string().default('sessions'),\n\n // Features\n trackBehavior: z.boolean().default(true),\n trackPageViews: z.boolean().default(true),\n\n // Cleanup\n cleanupInterval: z.number().min(60000).default(300000), // Default 5 minutes\n maxSessions: z.number().min(1).optional(), // Max sessions per user\n});\nexport type SessionConfig = z.infer<typeof SessionConfigSchema>;\n\n/**\n * Session Event Types\n */\nexport const SessionEventTypeSchema = z.enum([\n 'created',\n 'updated',\n 'expired',\n 'terminated',\n 'activity',\n 'detection',\n]);\nexport type SessionEventType = z.infer<typeof SessionEventTypeSchema>;\n\n/**\n * Session Event\n */\nexport const SessionEventSchema = z.object({\n type: SessionEventTypeSchema,\n sessionId: z.string(),\n timestamp: z.date(),\n data: z.record(z.string(), z.unknown()).optional(),\n});\nexport type SessionEvent = z.infer<typeof SessionEventSchema>;\n\n/**\n * Session Manager Interface\n */\nexport interface SessionManager {\n // Core Operations\n createSession(request: SessionCreateRequest): Promise<SessionData>;\n getSession(sessionId: string): Promise<SessionData | null>;\n updateSession(request: SessionUpdateRequest): Promise<SessionData>;\n destroySession(sessionId: string): Promise<boolean>;\n\n // Activity Tracking\n recordActivity(sessionId: string, activity: Record<string, unknown>): Promise<void>;\n recordDetection(sessionId: string, detection: Record<string, unknown>): Promise<void>;\n\n // Queries\n findSessions(options: SessionQueryOptions): Promise<SessionData[]>;\n getActiveSessions(): Promise<SessionData[]>;\n getAgentSessions(): Promise<SessionData[]>;\n\n // Maintenance\n cleanup(): Promise<number>;\n\n // Events\n on(event: SessionEventType, handler: (data: SessionEvent) => void): void;\n off(event: SessionEventType, handler: (data: SessionEvent) => void): void;\n}\n\n/**\n * Session Token Payload\n */\nexport const SessionTokenPayloadSchema = z.object({\n sessionId: z.string(),\n userId: z.string().optional(),\n isAgent: z.boolean().default(false),\n iat: z.number(), // Issued at\n exp: z.number(), // Expires at\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type SessionTokenPayload = z.infer<typeof SessionTokenPayloadSchema>;\n","/**\n * Transport Layer Types\n *\n * Types for the beacon transport layer including batching, retry, and offline support\n */\n\nimport { z } from 'zod';\n\n/**\n * Transport configuration\n */\nexport const TransportConfigSchema = z.object({\n batchSize: z.number().min(1).max(100).default(10),\n flushInterval: z.number().min(1000).max(60000).default(5000),\n maxRetries: z.number().min(0).max(10).default(3),\n retryDelayBase: z.number().min(100).max(5000).default(1000),\n compressionThreshold: z.number().min(512).default(1024),\n offlineQueueSize: z.number().min(10).max(1000).default(100),\n networkAdaptation: z.boolean().default(true),\n useCompression: z.boolean().default(true),\n dedupWindow: z.number().min(0).max(60000).default(5000),\n});\nexport type TransportConfig = z.infer<typeof TransportConfigSchema>;\n\n/**\n * Batch event with metadata\n */\nexport const BatchEventSchema = z.object({\n id: z.string(),\n event: z.any(), // Will be BeaconEvent\n timestamp: z.number(),\n retryCount: z.number().default(0),\n hash: z.string().optional(),\n priority: z.enum(['low', 'normal', 'high', 'critical']).default('normal'),\n});\nexport type BatchEvent = z.infer<typeof BatchEventSchema>;\n\n/**\n * Network information\n */\nexport const NetworkInfoSchema = z.object({\n type: z.string().optional(),\n effectiveType: z.enum(['4g', '3g', '2g', 'slow-2g']).optional(),\n downlink: z.number().optional(),\n rtt: z.number().optional(),\n saveData: z.boolean().optional(),\n});\nexport type NetworkInfo = z.infer<typeof NetworkInfoSchema>;\n\n/**\n * Retry strategy configuration\n */\nexport const RetryStrategySchema = z.object({\n maxAttempts: z.number().min(0).max(10).default(3),\n baseDelay: z.number().min(100).max(5000).default(1000),\n maxDelay: z.number().min(1000).max(60000).default(30000),\n factor: z.number().min(1).max(5).default(2),\n jitter: z.boolean().default(true),\n});\nexport type RetryStrategy = z.infer<typeof RetryStrategySchema>;\n\n/**\n * Offline queue entry\n */\nexport const OfflineQueueEntrySchema = z.object({\n id: z.string(),\n events: z.array(z.any()), // Will be BeaconEvent[]\n timestamp: z.number(),\n expiresAt: z.number(),\n retryCount: z.number().default(0),\n size: z.number().optional(),\n});\nexport type OfflineQueueEntry = z.infer<typeof OfflineQueueEntrySchema>;\n\n/**\n * Transport state\n */\nexport const TransportStateSchema = z.enum([\n 'idle',\n 'batching',\n 'sending',\n 'retrying',\n 'offline',\n 'error',\n 'paused',\n]);\nexport type TransportState = z.infer<typeof TransportStateSchema>;\n\n/**\n * Transport metrics\n */\nexport const TransportMetricsSchema = z.object({\n eventsSent: z.number().default(0),\n eventsFailed: z.number().default(0),\n eventsQueued: z.number().default(0),\n batchesSent: z.number().default(0),\n batchesFailed: z.number().default(0),\n bytesTransferred: z.number().default(0),\n compressionRatio: z.number().optional(),\n averageLatency: z.number().optional(),\n lastSuccessTimestamp: z.number().optional(),\n lastErrorTimestamp: z.number().optional(),\n});\nexport type TransportMetrics = z.infer<typeof TransportMetricsSchema>;\n\n/**\n * Circuit breaker state\n */\nexport const CircuitBreakerStateSchema = z.enum(['closed', 'open', 'half-open']);\nexport type CircuitBreakerState = z.infer<typeof CircuitBreakerStateSchema>;\n\n/**\n * Circuit breaker configuration\n */\nexport const CircuitBreakerConfigSchema = z.object({\n threshold: z.number().min(1).max(100).default(5),\n timeout: z.number().min(1000).max(300000).default(60000),\n resetTimeout: z.number().min(1000).max(300000).default(30000),\n});\nexport type CircuitBreakerConfig = z.infer<typeof CircuitBreakerConfigSchema>;\n\n/**\n * Transport options for send operations\n */\nexport const TransportOptionsSchema = z.object({\n immediate: z.boolean().optional(),\n priority: z.enum(['low', 'normal', 'high', 'critical']).optional(),\n compress: z.boolean().optional(),\n retry: z.boolean().optional(),\n timeout: z.number().optional(),\n});\nexport type TransportOptions = z.infer<typeof TransportOptionsSchema>;\n\n/**\n * Transport response\n */\nexport const TransportResponseSchema = z.object({\n success: z.boolean(),\n batchId: z.string().optional(),\n timestamp: z.number(),\n retryAfter: z.number().optional(),\n error: z.string().optional(),\n});\nexport type TransportResponse = z.infer<typeof TransportResponseSchema>;\n","/**\n * Worker Infrastructure Types\n *\n * Comprehensive types for WebWorker implementation with lifecycle management\n */\n\nimport { z } from 'zod';\n\n/**\n * Worker state\n */\nexport const WorkerStateSchema = z.enum([\n 'idle',\n 'initializing',\n 'ready',\n 'busy',\n 'error',\n 'terminating',\n 'terminated',\n]);\nexport type WorkerState = z.infer<typeof WorkerStateSchema>;\n\n/**\n * Worker health status\n */\nexport const WorkerHealthStatusSchema = z.enum(['healthy', 'degraded', 'unhealthy', 'unknown']);\nexport type WorkerHealthStatus = z.infer<typeof WorkerHealthStatusSchema>;\n\n/**\n * Message priority levels\n */\nexport const MessagePrioritySchema = z.enum(['critical', 'high', 'normal', 'low']);\nexport type MessagePriority = z.infer<typeof MessagePrioritySchema>;\n\n/**\n * Worker action types\n */\nexport const WorkerActionSchema = z.enum([\n 'init',\n 'process',\n 'flush',\n 'status',\n 'health',\n 'terminate',\n 'config',\n 'error',\n]);\nexport type WorkerAction = z.infer<typeof WorkerActionSchema>;\n\n/**\n * Worker message types\n */\nexport const WorkerMessageTypeSchema = z.enum([\n 'request',\n 'response',\n 'error',\n 'heartbeat',\n 'status',\n]);\nexport type WorkerMessageType = z.infer<typeof WorkerMessageTypeSchema>;\n\n/**\n * Worker message structure\n */\nexport const WorkerMessageSchema = z.object({\n id: z.string(),\n type: WorkerMessageTypeSchema,\n action: WorkerActionSchema,\n payload: z.any().optional(),\n priority: MessagePrioritySchema.default('normal'),\n timestamp: z.number(),\n correlationId: z.string().optional(),\n compressed: z.boolean().default(false),\n});\nexport type WorkerMessage = z.infer<typeof WorkerMessageSchema>;\n\n/**\n * Worker configuration\n */\nexport const WorkerConfigSchema = z.object({\n // Lifecycle\n maxRestartAttempts: z.number().min(0).max(10).default(3),\n restartDelay: z.number().min(100).max(30000).default(1000),\n terminationTimeout: z.number().min(1000).max(60000).default(5000),\n\n // Health monitoring\n heartbeatInterval: z.number().min(1000).max(60000).default(5000),\n healthCheckTimeout: z.number().min(1000).max(30000).default(3000),\n maxUnhealthyCount: z.number().min(1).max(10).default(3),\n\n // Performance\n maxConcurrentTasks: z.number().min(1).max(100).default(10),\n taskTimeout: z.number().min(1000).max(300000).default(30000),\n messageCompressionThreshold: z.number().min(512).default(5120), // 5KB\n\n // Resource limits\n maxMemoryUsage: z.number().min(10).max(500).default(100), // MB\n maxCpuUsage: z.number().min(10).max(100).default(80), // Percentage\n\n // Fallback\n enableFallback: z.boolean().default(true),\n fallbackDelay: z.number().min(0).max(5000).default(100),\n\n // Features\n useSharedArrayBuffer: z.boolean().default(false),\n useTransferableObjects: z.boolean().default(true),\n enableCrossOrigin: z.boolean().default(false),\n});\nexport type WorkerConfig = z.infer<typeof WorkerConfigSchema>;\n\n/**\n * Worker metrics\n */\nexport const WorkerMetricsSchema = z.object({\n // Performance\n tasksProcessed: z.number().default(0),\n tasksFailed: z.number().default(0),\n averageTaskTime: z.number().optional(),\n lastTaskTime: z.number().optional(),\n\n // Health\n healthStatus: WorkerHealthStatusSchema,\n lastHeartbeat: z.number().optional(),\n restartCount: z.number().default(0),\n errorCount: z.number().default(0),\n\n // Resources\n memoryUsage: z.number().optional(), // MB\n cpuUsage: z.number().optional(), // Percentage\n messageQueueSize: z.number().default(0),\n\n // Timing\n startTime: z.number(),\n uptime: z.number().default(0),\n lastActivityTime: z.number().optional(),\n});\nexport type WorkerMetrics = z.infer<typeof WorkerMetricsSchema>;\n\n/**\n * Worker error types\n */\nexport const WorkerErrorTypeSchema = z.enum([\n 'initialization',\n 'communication',\n 'processing',\n 'timeout',\n 'memory',\n 'permission',\n 'network',\n 'validation',\n 'unknown',\n]);\nexport type WorkerErrorType = z.infer<typeof WorkerErrorTypeSchema>;\n\n/**\n * Worker error structure\n */\nexport const WorkerErrorSchema = z.object({\n type: WorkerErrorTypeSchema,\n message: z.string(),\n code: z.string().optional(),\n stack: z.string().optional(),\n timestamp: z.number(),\n context: z.record(z.string(), z.any()).optional(),\n recoverable: z.boolean().default(true),\n retryAfter: z.number().optional(),\n});\nexport type WorkerError = z.infer<typeof WorkerErrorSchema>;\n\n/**\n * Worker capabilities\n */\nexport const WorkerCapabilitiesSchema = z.object({\n workerAPI: z.boolean(),\n sharedArrayBuffer: z.boolean(),\n transferableObjects: z.boolean(),\n offscreenCanvas: z.boolean(),\n webAssembly: z.boolean(),\n atomics: z.boolean(),\n bigInt: z.boolean(),\n csp: z.object({\n workerSrc: z.boolean(),\n scriptSrc: z.boolean(),\n blobUrls: z.boolean(),\n inlineWorkers: z.boolean(),\n }),\n performance: z.object({\n memory: z.boolean(),\n measureUserAgentSpecificMemory: z.boolean(),\n }),\n});\nexport type WorkerCapabilities = z.infer<typeof WorkerCapabilitiesSchema>;\n\n/**\n * Worker task\n */\nexport const WorkerTaskSchema = z.object({\n id: z.string(),\n type: z.string(),\n data: z.any(),\n priority: MessagePrioritySchema.default('normal'),\n timeout: z.number().optional(),\n retries: z.number().default(0),\n maxRetries: z.number().default(3),\n createdAt: z.number(),\n startedAt: z.number().optional(),\n completedAt: z.number().optional(),\n error: WorkerErrorSchema.optional(),\n});\nexport type WorkerTask = z.infer<typeof WorkerTaskSchema>;\n\n/**\n * Fallback execution options\n */\nexport const FallbackOptionsSchema = z.object({\n useRequestIdleCallback: z.boolean().default(true),\n idleTimeout: z.number().min(0).max(10000).default(1000),\n chunkSize: z.number().min(1).max(1000).default(10),\n throttleMs: z.number().min(0).max(1000).default(16), // ~60fps\n maxExecutionTime: z.number().min(100).max(60000).default(5000),\n});\nexport type FallbackOptions = z.infer<typeof FallbackOptionsSchema>;\n\n/**\n * Resource usage\n */\nexport const ResourceUsageSchema = z.object({\n memory: z.object({\n used: z.number(), // MB\n limit: z.number(), // MB\n percentage: z.number(),\n }),\n cpu: z.object({\n usage: z.number(), // Percentage\n limit: z.number(), // Percentage\n }),\n tasks: z.object({\n pending: z.number(),\n active: z.number(),\n completed: z.number(),\n failed: z.number(),\n }),\n});\nexport type ResourceUsage = z.infer<typeof ResourceUsageSchema>;\n\n/**\n * Worker pool configuration\n */\nexport const WorkerPoolConfigSchema = z.object({\n minWorkers: z.number().min(0).max(10).default(1),\n maxWorkers: z.number().min(1).max(20).default(4),\n workerIdleTimeout: z.number().min(10000).max(300000).default(60000),\n autoScale: z.boolean().default(true),\n scaleUpThreshold: z.number().min(0).max(100).default(70), // CPU %\n scaleDownThreshold: z.number().min(0).max(100).default(30), // CPU %\n});\nexport type WorkerPoolConfig = z.infer<typeof WorkerPoolConfigSchema>;\n\n/**\n * Communication protocol version\n */\nexport const ProtocolVersionSchema = z.literal('1.0.0');\nexport type ProtocolVersion = z.infer<typeof ProtocolVersionSchema>;\n","/**\n * Database and Transaction Types\n *\n * Types for database operations, transactions, and queries\n */\n\nimport { z } from 'zod';\n\n/**\n * Database transaction type for bulk operations\n * Generic type representing a database transaction context\n */\nexport type DatabaseTransaction<T = unknown> = {\n rollback: () => Promise<void>;\n commit: () => Promise<void>;\n // Additional transaction methods can be added here\n} & T;\n\n/**\n * Bulk operation parameters\n */\nexport const BulkOperationParamsSchema = z.object({\n operation: z.enum(['create', 'update', 'delete', 'upsert']),\n data: z.array(z.record(z.string(), z.unknown())),\n options: z\n .object({\n skipValidation: z.boolean().optional(),\n returnResults: z.boolean().optional(),\n batchSize: z.number().min(1).max(1000).optional(),\n })\n .optional(),\n});\nexport type BulkOperationParams = z.infer<typeof BulkOperationParamsSchema>;\n\n/**\n * Bulk operation result\n */\nexport const BulkOperationResultSchema = z.object({\n success: z.boolean(),\n created: z.number().default(0),\n updated: z.number().default(0),\n deleted: z.number().default(0),\n errors: z\n .array(\n z.object({\n index: z.number(),\n error: z.string(),\n data: z.record(z.string(), z.unknown()).optional(),\n })\n )\n .default([]),\n});\nexport type BulkOperationResult = z.infer<typeof BulkOperationResultSchema>;\n\n/**\n * Database connection status\n */\nexport const DatabaseStatusSchema = z.object({\n connected: z.boolean(),\n latency: z.number().optional(),\n error: z.string().optional(),\n});\nexport type DatabaseStatus = z.infer<typeof DatabaseStatusSchema>;\n\n/**\n * Query filter operators\n */\nexport const FilterOperatorSchema = z.enum([\n 'eq',\n 'neq',\n 'gt',\n 'gte',\n 'lt',\n 'lte',\n 'in',\n 'nin',\n 'like',\n 'ilike',\n 'regex',\n 'exists',\n 'nexists',\n 'null',\n 'nnull',\n]);\nexport type FilterOperator = z.infer<typeof FilterOperatorSchema>;\n\n/**\n * Generic query filter\n */\nexport const QueryFilterSchema = z.object({\n field: z.string(),\n operator: FilterOperatorSchema,\n value: z.unknown(),\n});\nexport type QueryFilter = z.infer<typeof QueryFilterSchema>;\n\n/**\n * Pagination parameters\n */\nexport const PaginationParamsSchema = z.object({\n page: z.number().int().min(1).default(1),\n limit: z.number().int().min(1).max(100).default(20),\n sortBy: z.string().optional(),\n sortOrder: z.enum(['asc', 'desc']).default('desc'),\n});\nexport type PaginationParams = z.infer<typeof PaginationParamsSchema>;\n\n/**\n * Paginated response wrapper\n */\nexport function createPaginatedResponseSchema<T extends z.ZodType>(itemSchema: T) {\n return z.object({\n data: z.array(itemSchema),\n pagination: z.object({\n page: z.number(),\n limit: z.number(),\n total: z.number(),\n totalPages: z.number(),\n hasMore: z.boolean(),\n }),\n });\n}\n\n/**\n * Database migration status\n */\nexport const MigrationStatusSchema = z.object({\n version: z.string(),\n applied: z.boolean(),\n appliedAt: z.date().optional(),\n error: z.string().optional(),\n});\nexport type MigrationStatus = z.infer<typeof MigrationStatusSchema>;\n","/**\n * Analytics Types\n *\n * Types for analytics data, exports, and monitoring\n */\n\nimport { z } from 'zod';\n\n/**\n * Detection metadata stored in JSONB\n */\nexport const DetectionMetadataSchema = z.object({\n // Browser information\n browser: z\n .object({\n name: z.string().optional(),\n version: z.string().optional(),\n engine: z.string().optional(),\n })\n .optional(),\n\n // Device information\n device: z\n .object({\n type: z.string().optional(),\n vendor: z.string().optional(),\n model: z.string().optional(),\n })\n .optional(),\n\n // Location information\n location: z\n .object({\n country: z.string().optional(),\n region: z.string().optional(),\n city: z.string().optional(),\n timezone: z.string().optional(),\n })\n .optional(),\n\n // Behavioral data\n behavioral: z\n .object({\n mouseMovements: z.number().optional(),\n clicks: z.number().optional(),\n scrollEvents: z.number().optional(),\n keystrokes: z.number().optional(),\n touchEvents: z.number().optional(),\n })\n .optional(),\n\n // Custom fields\n custom: z.record(z.string(), z.unknown()).optional(),\n});\nexport type DetectionMetadata = z.infer<typeof DetectionMetadataSchema>;\n\n/**\n * Analytics export parameters\n */\nexport const AnalyticsExportParamsSchema = z.object({\n format: z.enum(['csv', 'json', 'xlsx']).default('json'),\n dateRange: z.object({\n start: z.string().datetime(),\n end: z.string().datetime(),\n }),\n filters: z\n .object({\n projectId: z.string().uuid().optional(),\n pixelId: z.string().uuid().optional(),\n isAgent: z.boolean().optional(),\n agentTypes: z.array(z.string()).optional(),\n minConfidence: z.number().min(0).max(100).optional(),\n })\n .optional(),\n fields: z.array(z.string()).optional(), // Specific fields to export\n includeMetadata: z.boolean().default(false),\n compression: z.boolean().default(false),\n});\nexport type AnalyticsExportParams = z.infer<typeof AnalyticsExportParamsSchema>;\n\n/**\n * Analytics time window\n */\nexport const AnalyticsTimeWindowSchema = z.enum([\n 'realtime', // Last 5 minutes\n 'hourly', // Last hour\n 'daily', // Last 24 hours\n 'weekly', // Last 7 days\n 'monthly', // Last 30 days\n 'quarterly', // Last 90 days\n 'yearly', // Last 365 days\n 'custom', // Custom date range\n]);\nexport type AnalyticsTimeWindow = z.infer<typeof AnalyticsTimeWindowSchema>;\n\n/**\n * Analytics aggregation type\n */\nexport const AggregationTypeSchema = z.enum([\n 'count',\n 'sum',\n 'avg',\n 'min',\n 'max',\n 'median',\n 'percentile',\n]);\nexport type AggregationType = z.infer<typeof AggregationTypeSchema>;\n\n/**\n * Legacy analytics rollup shapes stored in the web app's analytics_rollups JSONB\n * column. Keep these shared so background services and admin routes agree on\n * the persisted structure while the legacy rollup service is migrated away.\n */\nexport type AnalyticsRollupPeriod = 'daily' | 'weekly' | 'monthly';\n\nexport interface LegacyAnalyticsSessionMetrics {\n total: number;\n unique: number;\n events: number;\n avgDuration: number;\n}\n\nexport interface LegacyAnalyticsAiDetectionMetrics {\n total: number;\n aiAgents: number;\n bots: number;\n humans: number;\n aiRate: number;\n botRate: number;\n humanRate: number;\n}\n\nexport interface LegacyAnalyticsEventMetrics {\n total: number;\n uniquePaths: number;\n avgPerSession: number;\n}\n\nexport interface LegacyAnalyticsRollupMetrics {\n sessions: LegacyAnalyticsSessionMetrics;\n aiDetection: LegacyAnalyticsAiDetectionMetrics;\n events: LegacyAnalyticsEventMetrics;\n}\n\nexport interface LegacyAnalyticsCalculatedMetrics {\n sessionMetrics: LegacyAnalyticsSessionMetrics;\n aiMetrics: LegacyAnalyticsAiDetectionMetrics;\n eventMetrics: LegacyAnalyticsEventMetrics;\n}\n\nexport interface LegacyAnalyticsIndustryAverages {\n avgSessions: number;\n avgEvents: number;\n avgAiRate: number;\n avgDuration: number;\n}\n\nexport interface LegacyAnalyticsIndustryTrendDay {\n date: string;\n totalSessions: number;\n aiSessions: number;\n aiRate: number;\n organizations: number;\n}\n\nexport interface LegacyAnalyticsAgentBreakdownItem {\n name: string | null;\n category: string | null;\n count: number;\n}\n\nexport interface LegacyAnalyticsAgentCategoryBreakdown {\n category: string;\n total: number;\n agents: Array<{\n name: string | null;\n count: number;\n }>;\n}\n\nexport interface LegacyAnalyticsAgentTypeBreakdown {\n byAgent: LegacyAnalyticsAgentBreakdownItem[];\n byCategory: LegacyAnalyticsAgentCategoryBreakdown[];\n topAgents: Array<{\n name: string | null;\n count: number;\n }>;\n}\n\nexport interface LegacyAnalyticsPeriodMetrics {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n}\n\nexport interface LegacyAnalyticsGrowthMetrics {\n weekOverWeek: {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n };\n monthOverMonth: {\n sessions: number;\n aiDetections: number;\n aiRate: number;\n };\n current: {\n weekSessions: number;\n weekAiRate: number;\n monthSessions: number;\n monthAiRate: number;\n };\n}\n\nexport type AnalyticsCacheParamValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | { readonly [key: string]: AnalyticsCacheParamValue }\n | readonly AnalyticsCacheParamValue[];\nexport type AnalyticsCacheParams = Record<string, AnalyticsCacheParamValue>;\nexport type AnalyticsCacheType = 'realtime' | 'frequent' | 'historical';\n\nexport interface AnalyticsCacheStats {\n [cacheName: string]: {\n size: number;\n calculatedSize: number;\n };\n}\n\nexport interface AnalyticsPreloadQueryFunction<T = unknown> {\n type: string;\n params: AnalyticsCacheParams;\n fn: () => Promise<T>;\n}\n\n/**\n * Analytics data point for charts\n */\nexport const AnalyticsDataPointSchema = z.object({\n timestamp: z.date(),\n value: z.number(),\n label: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AnalyticsDataPoint = z.infer<typeof AnalyticsDataPointSchema>;\n\n/**\n * Analytics summary statistics\n */\nexport const AnalyticsSummarySchema = z.object({\n total: z.number(),\n average: z.number(),\n min: z.number(),\n max: z.number(),\n median: z.number().optional(),\n stdDev: z.number().optional(),\n percentiles: z\n .object({\n p25: z.number().optional(),\n p50: z.number().optional(),\n p75: z.number().optional(),\n p90: z.number().optional(),\n p95: z.number().optional(),\n p99: z.number().optional(),\n })\n .optional(),\n});\nexport type AnalyticsSummary = z.infer<typeof AnalyticsSummarySchema>;\n\n/**\n * Redis statistics for monitoring\n */\nexport const RedisStatsSchema = z.object({\n connected: z.boolean(),\n memoryUsage: z.number().optional(),\n totalConnections: z.number().optional(),\n commandsProcessed: z.number().optional(),\n cacheHitRate: z.number().min(0).max(1).optional(),\n keys: z.number().optional(),\n uptime: z.number().optional(), // in seconds\n error: z.string().optional(),\n});\nexport type RedisStats = z.infer<typeof RedisStatsSchema>;\n\n/**\n * System monitoring stats\n */\nexport const SystemStatsSchema = z.object({\n timestamp: z.date(),\n cpu: z.object({\n usage: z.number().min(0).max(100),\n cores: z.number(),\n }),\n memory: z.object({\n used: z.number(),\n total: z.number(),\n percentage: z.number().min(0).max(100),\n }),\n database: z.object({\n connections: z.number(),\n activeQueries: z.number(),\n latency: z.number(), // in ms\n }),\n redis: RedisStatsSchema.optional(),\n});\nexport type SystemStats = z.infer<typeof SystemStatsSchema>;\n\nexport type TrafficPatternGranularity = 'hour' | 'day' | 'week';\n\nexport interface TrafficTimeSeriesPoint {\n timestamp: string;\n totalSessions: number;\n totalEvents: number;\n uniqueIPs: number;\n avgEventsPerSession: number;\n aiAgentSessions: number;\n humanSessions: number;\n}\n\nexport interface TrafficTopPage {\n path: string;\n visits: number;\n uniqueSessions: number;\n uniqueVisitors: number;\n avgTimeOnPage: number;\n fromAI: number;\n fromHuman: number;\n bounceRate: number;\n}\n\nexport interface TrafficNavigationPath {\n fromPage: string;\n toPage: string;\n count: number;\n}\n\nexport interface OrganizationTrafficPatterns {\n timeSeries: TrafficTimeSeriesPoint[];\n topPages: TrafficTopPage[];\n navigationPaths: TrafficNavigationPath[];\n}\n\nexport interface OrganizationTrafficPatternsSummary {\n organizationId: string;\n organizationName: string;\n patterns: OrganizationTrafficPatterns;\n}\n\nexport interface SystemWideTrafficPatterns extends OrganizationTrafficPatterns {\n byOrganization: OrganizationTrafficPatternsSummary[];\n}\n\nexport type TrafficPatterns = OrganizationTrafficPatterns | SystemWideTrafficPatterns;\n\nexport interface SessionFrequencyDay {\n date: string;\n newSessions: number;\n returningSessions: number;\n totalSessions: number;\n returnRate: number;\n uniqueVisitors: number;\n}\n\nexport interface SessionFrequencyPatterns {\n daily: SessionFrequencyDay[];\n summary: {\n totalNewSessions: number;\n totalReturningSessions: number;\n averageReturnRate: number;\n };\n}\n\nexport interface PeakTrafficHour {\n hour: number;\n sessions: number;\n events: number;\n aiPercentage: number;\n}\n\nexport interface PeakTrafficDay {\n day: string;\n sessions: number;\n events: number;\n aiPercentage: number;\n}\n\nexport interface TrafficSpike {\n timestamp: string;\n sessions: number;\n magnitude: number;\n composition: {\n ai: number;\n human: number;\n };\n}\n\nexport interface PeakTrafficPatterns {\n peakHours: PeakTrafficHour[];\n peakDays: PeakTrafficDay[];\n trafficSpikes: TrafficSpike[];\n statistics?: {\n meanSessions: number;\n stdDeviation: number;\n spikeThreshold: number;\n };\n}\n\nexport interface AgentNavigationBehavior {\n agentTypes: Array<{\n type: string;\n sessions: number;\n eventsPerSession: number;\n uniquePathsVisited: number;\n avgTimeOnPage: number;\n }>;\n topPagesByAgent: Array<{\n path: string;\n agentType: string;\n visits: number;\n }>;\n}\n","/**\n * Detection Metadata Types\n *\n * Type definitions for detection metadata stored in the database\n */\n\nimport { z } from 'zod';\n\n/**\n * Detection metadata stored in database JSONB field\n * This represents the metadata field in the detections table\n */\nexport const DatabaseDetectionMetadataSchema = z.object({\n // Agent information\n detectedAgent: z\n .object({\n type: z.string(),\n name: z.string(),\n })\n .optional(),\n\n // Verification details\n verificationMethod: z.enum(['signature', 'pattern', 'mcp_i', 'none']).optional(),\n riskLevel: z.enum(['low', 'medium', 'high', 'unknown']).optional(),\n\n // Detection details\n reasons: z.array(z.string()).optional(),\n\n // Request context\n userAgent: z.string().optional(),\n ipAddress: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n\n // Browser fingerprint data\n clientDetection: z\n .object({\n headless: z.boolean().optional(),\n webrtc: z.boolean().optional(),\n canvas: z.string().optional(),\n plugins: z.number().optional(),\n automation: z.boolean().optional(),\n chrome: z.boolean().optional(),\n languages: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Additional metadata\n agent: z.string().optional(),\n processingTime: z.number().optional(),\n cached: z.boolean().optional(),\n});\n\nexport type DatabaseDetectionMetadata = z.infer<typeof DatabaseDetectionMetadataSchema>;\n\n/**\n * Session data stored in Redis cache\n */\nexport const RedisSessionDataSchema = z.object({\n timestamp: z.number(),\n detectionId: z.string().optional(),\n isAgent: z.boolean().optional(),\n confidence: z.number().optional(),\n agent: z.string().optional(),\n});\n\nexport type RedisSessionData = z.infer<typeof RedisSessionDataSchema>;\n\n/**\n * Cached detection data stored in Redis\n */\nexport const CachedDetectionDataSchema = z.object({\n version: z.string(),\n result: z\n .object({\n isAgent: z.boolean(),\n confidence: z.number(),\n agent: z.string().optional(),\n verificationMethod: z.string().optional(),\n riskLevel: z.string().optional(),\n })\n .optional(),\n timestamp: z.number().optional(),\n ttl: z.number().optional(),\n});\n\nexport type CachedDetectionData = z.infer<typeof CachedDetectionDataSchema>;\n","/**\n * Authentication & Authorization Types\n *\n * Types for authentication flows, user management, and authorization\n */\n\n/**\n * Authentication Provider Types\n */\nexport type AuthProvider = 'github' | 'google' | 'credentials';\n\n/**\n * User Authentication Credentials\n */\nexport interface AuthCredentials {\n email: string;\n password: string;\n}\n\n/**\n * User Registration Data\n */\nexport interface UserRegistration extends AuthCredentials {\n name?: string;\n confirmPassword: string;\n}\n\n/**\n * Password Reset Request\n */\nexport interface PasswordResetRequest {\n email: string;\n}\n\n/**\n * Password Reset Confirmation\n */\nexport interface PasswordResetConfirmation {\n token: string;\n password: string;\n confirmPassword: string;\n}\n\n/**\n * Change Password Request\n */\nexport interface ChangePasswordRequest {\n currentPassword?: string; // Optional for OAuth users setting first password\n newPassword: string;\n confirmPassword: string;\n}\n\n/**\n * Authentication Session\n */\nexport interface AuthSession {\n user: {\n id: string;\n email: string;\n name?: string;\n image?: string;\n emailVerified?: Date | null;\n defaultOrganizationId?: string;\n currentOrganizationId?: string;\n organizationRole?: 'owner' | 'admin' | 'member';\n };\n expires: string;\n}\n\n/**\n * JWT Token Payload\n */\nexport interface JWTPayload {\n id: string;\n email: string;\n name?: string;\n image?: string;\n defaultOrganizationId?: string;\n currentOrganizationId?: string;\n organizationRole?: 'owner' | 'admin' | 'member';\n iat?: number;\n exp?: number;\n}\n\n/**\n * OAuth Account\n */\nexport interface OAuthAccount {\n provider: string;\n providerAccountId: string;\n type: string;\n access_token?: string;\n refresh_token?: string;\n expires_at?: number;\n token_type?: string;\n scope?: string;\n id_token?: string;\n session_state?: string;\n}\n\n/**\n * Email Verification Token\n */\nexport interface EmailVerificationToken {\n identifier: string;\n token: string;\n expires: Date;\n}\n\n/**\n * Authentication Error Types\n */\nexport enum AuthErrorType {\n INVALID_CREDENTIALS = 'INVALID_CREDENTIALS',\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n EMAIL_NOT_VERIFIED = 'EMAIL_NOT_VERIFIED',\n ACCOUNT_DISABLED = 'ACCOUNT_DISABLED',\n ACCOUNT_LOCKED = 'ACCOUNT_LOCKED',\n PASSWORD_EXPIRED = 'PASSWORD_EXPIRED',\n INVALID_TOKEN = 'INVALID_TOKEN',\n TOKEN_EXPIRED = 'TOKEN_EXPIRED',\n EMAIL_ALREADY_EXISTS = 'EMAIL_ALREADY_EXISTS',\n WEAK_PASSWORD = 'WEAK_PASSWORD',\n PASSWORDS_DO_NOT_MATCH = 'PASSWORDS_DO_NOT_MATCH',\n OAUTH_ACCOUNT_NOT_LINKED = 'OAUTH_ACCOUNT_NOT_LINKED',\n OAUTH_ERROR = 'OAUTH_ERROR',\n RATE_LIMIT_EXCEEDED = 'RATE_LIMIT_EXCEEDED',\n}\n\n/**\n * Authentication Response\n */\nexport interface AuthResponse {\n success: boolean;\n message?: string;\n user?: AuthSession['user'];\n token?: string;\n redirectUrl?: string;\n error?: {\n type: AuthErrorType;\n message: string;\n };\n}\n\n/**\n * Sign In Response\n */\nexport interface SignInResponse extends AuthResponse {\n requiresVerification?: boolean;\n requiresPasswordChange?: boolean;\n twoFactorRequired?: boolean;\n}\n\n/**\n * Sign Up Response\n */\nexport interface SignUpResponse extends AuthResponse {\n requiresEmailVerification?: boolean;\n verificationEmailSent?: boolean;\n}\n\n/**\n * Password Requirements\n */\nexport interface PasswordRequirements {\n minLength: number;\n maxLength: number;\n requireUppercase: boolean;\n requireLowercase: boolean;\n requireNumbers: boolean;\n requireSpecialChars: boolean;\n preventCommonPasswords: boolean;\n preventUserInfo: boolean;\n}\n\n/**\n * Password Validation Result\n */\nexport interface PasswordValidationResult {\n isValid: boolean;\n errors: string[];\n strength: 'weak' | 'fair' | 'good' | 'strong';\n score: number; // 0-100\n}\n\n/**\n * Account Linking Request\n */\nexport interface AccountLinkingRequest {\n provider: AuthProvider;\n linkToken?: string;\n}\n\n/**\n * Account Linking Response\n */\nexport interface AccountLinkingResponse {\n success: boolean;\n linkedProvider?: AuthProvider;\n existingProviders: AuthProvider[];\n message?: string;\n error?: string;\n}\n\n/**\n * User Profile Update\n */\nexport interface UserProfileUpdate {\n name?: string;\n image?: string;\n bio?: string;\n preferences?: Record<string, unknown>;\n}\n\n/**\n * Authentication State\n */\nexport interface AuthState {\n isAuthenticated: boolean;\n isLoading: boolean;\n user: AuthSession['user'] | null;\n error: AuthErrorType | null;\n}\n\n/**\n * Authentication Context\n */\nexport interface AuthContext {\n state: AuthState;\n signIn: (credentials: AuthCredentials) => Promise<SignInResponse>;\n signUp: (registration: UserRegistration) => Promise<SignUpResponse>;\n signOut: () => Promise<void>;\n updateProfile: (profile: UserProfileUpdate) => Promise<AuthResponse>;\n changePassword: (request: ChangePasswordRequest) => Promise<AuthResponse>;\n requestPasswordReset: (email: string) => Promise<AuthResponse>;\n confirmPasswordReset: (confirmation: PasswordResetConfirmation) => Promise<AuthResponse>;\n linkAccount: (provider: AuthProvider) => Promise<AccountLinkingResponse>;\n unlinkAccount: (provider: AuthProvider) => Promise<AccountLinkingResponse>;\n verifyEmail: (token: string) => Promise<AuthResponse>;\n resendVerificationEmail: () => Promise<AuthResponse>;\n}\n\n/**\n * Default Password Requirements\n */\nexport const DEFAULT_PASSWORD_REQUIREMENTS: PasswordRequirements = {\n minLength: 8,\n maxLength: 128,\n requireUppercase: true,\n requireLowercase: true,\n requireNumbers: true,\n requireSpecialChars: false,\n preventCommonPasswords: true,\n preventUserInfo: true,\n};\n\n/**\n * Auth Error Messages\n */\nexport const AUTH_ERROR_MESSAGES: Record<AuthErrorType, string> = {\n [AuthErrorType.INVALID_CREDENTIALS]: 'Invalid email or password',\n [AuthErrorType.USER_NOT_FOUND]: 'No account found with this email',\n [AuthErrorType.EMAIL_NOT_VERIFIED]: 'Please verify your email address',\n [AuthErrorType.ACCOUNT_DISABLED]: 'Your account has been disabled',\n [AuthErrorType.ACCOUNT_LOCKED]: 'Your account has been locked due to too many failed attempts',\n [AuthErrorType.PASSWORD_EXPIRED]: 'Your password has expired. Please reset it.',\n [AuthErrorType.INVALID_TOKEN]: 'Invalid or expired token',\n [AuthErrorType.TOKEN_EXPIRED]: 'This link has expired. Please request a new one.',\n [AuthErrorType.EMAIL_ALREADY_EXISTS]: 'An account with this email already exists',\n [AuthErrorType.WEAK_PASSWORD]: 'Password does not meet security requirements',\n [AuthErrorType.PASSWORDS_DO_NOT_MATCH]: 'Passwords do not match',\n [AuthErrorType.OAUTH_ACCOUNT_NOT_LINKED]: 'Email is already associated with another account',\n [AuthErrorType.OAUTH_ERROR]: 'An error occurred during authentication',\n [AuthErrorType.RATE_LIMIT_EXCEEDED]: 'Too many attempts. Please try again later.',\n};\n","/**\n * Fingerprint Types and Schemas\n *\n * Comprehensive type definitions for the AI fingerprinting system\n * Supporting multiple integration types and detection methods\n */\n\nimport { z } from 'zod';\n\n// Re-export legacy types for backward compatibility\nexport * from './fingerprint-legacy';\n\n// Integration types that determine what data is available\nexport const IntegrationTypeSchema = z.enum([\n 'pixel', // Client-side pixel (minimal data)\n 'beacon', // Enhanced beacon (more client data)\n 'noscript', // Server-side only (headers + IP)\n 'middleware', // Full request context\n 'express', // Node.js server integration\n 'edge', // Edge runtime data\n 'wasm', // Full WASM detection\n]);\n\nexport type IntegrationType = z.infer<typeof IntegrationTypeSchema>;\n\nexport interface BrowserFingerprintMetadata {\n collectionDuration: number;\n errors: string[];\n warnings: string[];\n}\n\nexport interface BrowserFingerprintCoreData {\n userAgent: string;\n url: string;\n method: string;\n timestamp: string;\n}\n\nexport interface CanvasFingerprintData {\n supported: boolean;\n hash?: string;\n dataUrl?: string;\n renderTime?: number;\n error?: string;\n}\n\nexport interface WebGLFingerprintData {\n supported: boolean;\n vendor?: string;\n renderer?: string;\n extensions?: string[];\n error?: string;\n}\n\nexport interface AudioFingerprintData {\n supported: boolean;\n sampleRate?: number;\n channelCount?: number;\n fingerprint?: string;\n error?: string;\n}\n\nexport interface BrowserFingerprintScreenData {\n resolution: string;\n colorDepth: number;\n pixelRatio: number;\n orientation: string;\n}\n\nexport interface BrowserFingerprintFeatures {\n webWorker: boolean;\n serviceWorker: boolean;\n webAssembly: boolean;\n webRTC: boolean;\n notifications: boolean;\n bluetooth: boolean;\n battery: boolean;\n}\n\nexport interface BrowserFingerprintTouchSupport {\n maxTouchPoints: number;\n touchEvent: boolean;\n touchStart: boolean;\n}\n\nexport interface BrowserFingerprintConnectionData {\n effectiveType?: string;\n rtt?: number;\n downlink?: number;\n saveData?: boolean;\n}\n\nexport interface BrowserClientSideFingerprintData {\n canvas?: CanvasFingerprintData;\n webgl?: WebGLFingerprintData;\n audio?: AudioFingerprintData;\n screen?: BrowserFingerprintScreenData;\n features?: BrowserFingerprintFeatures;\n touchSupport?: BrowserFingerprintTouchSupport;\n connection?: BrowserFingerprintConnectionData;\n timezone?: string;\n languages?: string[];\n plugins?: string[];\n cookiesEnabled?: boolean;\n localStorage?: boolean;\n sessionStorage?: boolean;\n doNotTrack?: string | null;\n hardwareConcurrency?: number;\n deviceMemory?: number;\n fonts?: string[];\n}\n\nexport interface BrowserBehavioralFingerprintData {\n timeOnPage: number;\n mouseMovements: number;\n mouseClicks: number;\n keystrokes: number;\n scrollEvents: number;\n scrollDepth: number;\n touchEvents: number;\n visibility: DocumentVisibilityState;\n performance: {\n loadTime: number;\n domReady: number;\n firstPaint: number;\n firstContentfulPaint: number;\n };\n}\n\nexport interface BrowserFingerprintData {\n timestamp: string;\n integration: IntegrationType;\n metadata: BrowserFingerprintMetadata;\n core?: BrowserFingerprintCoreData;\n clientSide?: BrowserClientSideFingerprintData;\n behavioral?: BrowserBehavioralFingerprintData;\n}\n\nexport interface FingerprintWindow extends Window {\n webkitAudioContext?: typeof AudioContext;\n mozRTCPeerConnection?: typeof RTCPeerConnection;\n webkitRTCPeerConnection?: typeof RTCPeerConnection;\n}\n\nexport interface FingerprintNavigator extends Navigator {\n connection?: BrowserFingerprintConnectionData;\n deviceMemory?: number;\n}\n\n// Comprehensive collected data from fingerprinting\nexport const CollectedDataSchema = z.object({\n id: z.string().uuid(),\n testId: z.string().optional(), // Query parameter for lookup\n integrationType: IntegrationTypeSchema,\n timestamp: z.date(),\n\n // What each integration can see\n availableData: z.object({\n // ALWAYS available (all integrations)\n core: z.object({\n userAgent: z.string(),\n ip: z.string(),\n url: z.string(),\n method: z.string(),\n timestamp: z.date(),\n }),\n\n // HEADERS (noscript, middleware, express, edge)\n headers: z.record(z.string(), z.string()).optional(),\n\n // CLIENT-SIDE (pixel, beacon only)\n clientSide: z\n .object({\n canvas: z\n .object({\n supported: z.boolean(),\n hash: z.string().optional(),\n dataUrl: z.string().optional(),\n renderTime: z.number().optional(),\n })\n .optional(),\n webgl: z\n .object({\n supported: z.boolean(),\n vendor: z.string().optional(),\n renderer: z.string().optional(),\n extensions: z.array(z.string()).optional(),\n })\n .optional(),\n audio: z\n .object({\n supported: z.boolean(),\n sampleRate: z.number().optional(),\n channelCount: z.number().optional(),\n fingerprint: z.string().optional(),\n })\n .optional(),\n screen: z\n .object({\n resolution: z.string(),\n colorDepth: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().optional(),\n })\n .optional(),\n timezone: z.string().optional(),\n languages: z.array(z.string()).optional(),\n fonts: z.array(z.string()).optional(),\n plugins: z.array(z.string()).optional(),\n localStorage: z.boolean().optional(),\n sessionStorage: z.boolean().optional(),\n cookiesEnabled: z.boolean().optional(),\n doNotTrack: z.string().nullable().optional(),\n hardwareConcurrency: z.number().optional(),\n deviceMemory: z.number().optional(),\n connection: z\n .object({\n effectiveType: z.string().optional(),\n rtt: z.number().optional(),\n downlink: z.number().optional(),\n saveData: z.boolean().optional(),\n })\n .optional(),\n // Touch and input capabilities\n touchSupport: z\n .object({\n maxTouchPoints: z.number(),\n touchEvent: z.boolean(),\n touchStart: z.boolean(),\n })\n .optional(),\n // Browser features\n features: z\n .object({\n webWorker: z.boolean(),\n serviceWorker: z.boolean(),\n webAssembly: z.boolean(),\n webRTC: z.boolean(),\n notifications: z.boolean(),\n bluetooth: z.boolean(),\n battery: z.boolean(),\n })\n .optional(),\n })\n .optional(),\n\n // SERVER-SIDE ENHANCED (middleware, express)\n serverEnhanced: z\n .object({\n tls: z\n .object({\n version: z.string(),\n cipher: z.string(),\n ja3: z.string().optional(), // TLS fingerprint\n ja3s: z.string().optional(), // Server TLS fingerprint\n })\n .optional(),\n httpVersion: z.string(),\n protocol: z.string(),\n requestSize: z.number().optional(),\n cookies: z.record(z.string(), z.string()).optional(),\n sessionData: z.any().optional(),\n geoLocation: z\n .object({\n country: z.string(),\n region: z.string(),\n city: z.string(),\n latitude: z.number(),\n longitude: z.number(),\n timezone: z.string(),\n })\n .optional(),\n })\n .optional(),\n\n // BEHAVIORAL (pixel, beacon with time)\n behavioral: z\n .object({\n timeOnPage: z.number(),\n mouseMovements: z.number(),\n mouseClicks: z.number(),\n keystrokes: z.number(),\n scrollEvents: z.number(),\n scrollDepth: z.number(),\n touchEvents: z.number().optional(),\n visibility: z\n .array(\n z.object({\n hidden: z.boolean(),\n timestamp: z.number(),\n })\n )\n .optional(),\n performance: z\n .object({\n loadTime: z.number(),\n domReady: z.number(),\n firstPaint: z.number().optional(),\n firstContentfulPaint: z.number().optional(),\n })\n .optional(),\n interactions: z\n .array(\n z.object({\n type: z.string(),\n timestamp: z.number(),\n target: z.string().optional(),\n })\n )\n .optional(),\n })\n .optional(),\n }),\n\n // Detection results from different engines\n detectionResults: z\n .object({\n // partialRecord, not record: Zod 4 makes an enum-keyed record exhaustive, and\n // these are per-integration results where any subset of integrations may be present.\n wouldDetectAs: z\n .partialRecord(\n IntegrationTypeSchema,\n z.object({\n isAgent: z.boolean(),\n confidence: z.number(),\n agentType: z.string().optional(),\n reasons: z.array(z.string()),\n processingTime: z.number().optional(),\n })\n )\n .optional(),\n })\n .optional(),\n\n // Metadata\n metadata: z\n .object({\n collectionDuration: z.number().optional(),\n errors: z.array(z.string()).optional(),\n warnings: z.array(z.string()).optional(),\n })\n .optional(),\n});\n\nexport type CollectedData = z.infer<typeof CollectedDataSchema>;\n\n// Detection rule definition\nexport const DetectionRuleSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n description: z.string(),\n category: z.enum(['signature', 'pattern', 'behavioral', 'network', 'fingerprint']),\n\n conditions: z.array(\n z.object({\n field: z.string(), // e.g., \"headers.user-agent\"\n operator: z.enum([\n 'equals',\n 'contains',\n 'matches',\n 'notEquals',\n 'notContains',\n 'in',\n 'notIn',\n 'range',\n 'exists',\n 'notExists',\n ]),\n value: z.any(),\n weight: z.number().min(0).max(1),\n caseSensitive: z.boolean().default(false),\n })\n ),\n\n weight: z.number().min(0).max(1), // Overall rule weight\n threshold: z.number().min(0).max(1), // Min score to trigger\n priority: z.number().default(0), // Higher priority rules evaluated first\n\n applicableIntegrations: z.array(IntegrationTypeSchema),\n enabled: z.boolean().default(true),\n\n // Performance tracking\n stats: z\n .object({\n matches: z.number().default(0),\n falsePositives: z.number().default(0),\n falseNegatives: z.number().default(0),\n avgProcessingTime: z.number().optional(),\n })\n .optional(),\n\n metadata: z.object({\n createdAt: z.date(),\n updatedAt: z.date(),\n createdBy: z.string(),\n lastModifiedBy: z.string().optional(),\n version: z.number().default(1),\n tags: z.array(z.string()).optional(),\n testedWith: z.array(z.string()).optional(), // Test IDs\n }),\n});\n\nexport type DetectionRule = z.infer<typeof DetectionRuleSchema>;\n\n// Agent profile for specific AI models\nexport const AgentProfileSchema = z.object({\n id: z.string().uuid(),\n name: z.string(), // \"GPT-4\", \"Claude 3.5 Sonnet\", etc.\n displayName: z.string(), // User-friendly name\n vendor: z.enum([\n 'openai',\n 'anthropic',\n 'google',\n 'perplexity',\n 'meta',\n 'microsoft',\n 'cohere',\n 'inflection',\n 'other',\n ]),\n version: z.string().optional(), // \"4.0\", \"3.5-sonnet\", etc.\n modelFamily: z.string().optional(), // \"GPT\", \"Claude\", \"Gemini\"\n\n // Detection rules specific to this agent\n rules: z.array(z.string()), // Rule IDs\n customRules: z.array(DetectionRuleSchema).optional(), // Profile-specific rules\n\n // Collected fingerprints for training\n fingerprints: z.array(z.string()), // Fingerprint IDs\n fingerprintCount: z.number().default(0),\n\n // Aggregated patterns from fingerprints\n patterns: z.object({\n headers: z.record(z.string(), z.number()), // Header -> frequency\n userAgents: z.array(z.string()),\n ipRanges: z.array(z.string()),\n ipAsns: z.array(z.string()).optional(),\n tlsFingerprints: z.array(z.string()).optional(),\n ja3Fingerprints: z.array(z.string()).optional(),\n canvasHashes: z.array(z.string()).optional(),\n webglFingerprints: z.array(z.string()).optional(),\n audioFingerprints: z.array(z.string()).optional(),\n behavioralSignatures: z\n .array(\n z.object({\n pattern: z.string(),\n frequency: z.number(),\n confidence: z.number(),\n })\n )\n .optional(),\n // Common values for specific fields\n commonValues: z.record(z.string(), z.array(z.any())).optional(),\n }),\n\n // Detection configuration\n detection: z.object({\n minConfidence: z.number().default(0.7),\n requireSignature: z.boolean().default(false),\n requireMultipleRules: z.boolean().default(false),\n customThreshold: z.number().optional(),\n }),\n\n // Performance metrics\n metrics: z.object({\n accuracy: z.number().default(0),\n precision: z.number().default(0),\n recall: z.number().default(0),\n f1Score: z.number().default(0),\n truePositives: z.number().default(0),\n falsePositives: z.number().default(0),\n falseNegatives: z.number().default(0),\n trueNegatives: z.number().default(0),\n totalDetections: z.number().default(0),\n lastTested: z.date().optional(),\n lastUpdated: z.date().optional(),\n }),\n\n // Status and deployment\n status: z.enum(['draft', 'testing', 'published', 'deprecated', 'archived']),\n publishedToWasm: z.boolean().default(false),\n wasmVersion: z.string().optional(),\n publishedAt: z.date().optional(),\n\n // Metadata\n description: z.string().optional(),\n notes: z.string().optional(),\n tags: z.array(z.string()).optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n createdBy: z.string(),\n lastModifiedBy: z.string().optional(),\n});\n\nexport type AgentProfile = z.infer<typeof AgentProfileSchema>;\n\n// Fingerprint record stored in database\nexport const FingerprintRecordSchema = z.object({\n id: z.string().uuid(),\n testId: z.string().optional(),\n timestamp: z.date(),\n\n // Core fingerprint data\n integrationType: IntegrationTypeSchema,\n userAgent: z.string(),\n ipAddress: z.string(),\n headers: z.record(z.string(), z.string()).optional(),\n\n // Fingerprint hashes\n canvasHash: z.string().optional(),\n webglHash: z.string().optional(),\n audioHash: z.string().optional(),\n\n // Full collected data\n collectedData: CollectedDataSchema,\n\n // Classification results\n classification: z\n .object({\n aiType: z.string().optional(),\n vendor: z.string().optional(),\n confidence: z.number(),\n matchedRules: z.array(z.string()).optional(),\n patterns: z.array(z.string()).optional(),\n })\n .optional(),\n\n // Association\n profileId: z.string().uuid().optional(),\n notes: z.string().optional(),\n tags: z.array(z.string()).optional(),\n\n createdAt: z.date(),\n updatedAt: z.date(),\n});\n\nexport type FingerprintRecord = z.infer<typeof FingerprintRecordSchema>;\n\n// Search query for fingerprints\nexport const FingerprintSearchQuerySchema = z.object({\n testId: z.string().optional(),\n aiType: z.string().optional(),\n vendor: z.string().optional(),\n integrationType: IntegrationTypeSchema.optional(),\n profileId: z.string().uuid().optional(),\n dateFrom: z.date().optional(),\n dateTo: z.date().optional(),\n ipAddress: z.string().optional(),\n userAgent: z.string().optional(),\n tags: z.array(z.string()).optional(),\n limit: z.number().min(1).max(1000).default(100),\n offset: z.number().min(0).default(0),\n sortBy: z.enum(['timestamp', 'confidence', 'testId']).default('timestamp'),\n sortOrder: z.enum(['asc', 'desc']).default('desc'),\n});\n\nexport type FingerprintSearchQuery = z.infer<typeof FingerprintSearchQuerySchema>;\n\n// Test result when running detection on fingerprint\nexport const DetectionTestResultSchema = z.object({\n fingerprintId: z.string(),\n timestamp: z.date(),\n\n // Results for each integration type.\n // partialRecord, not record: Zod 4 makes an enum-keyed record exhaustive, and a test\n // run reports only the integrations it exercised.\n results: z.partialRecord(\n IntegrationTypeSchema,\n z.object({\n isAgent: z.boolean(),\n confidence: z.number(),\n agentType: z.string().optional(),\n vendor: z.string().optional(),\n reasons: z.array(z.string()),\n matchedRules: z\n .array(\n z.object({\n ruleId: z.string(),\n ruleName: z.string(),\n score: z.number(),\n matched: z.boolean(),\n })\n )\n .optional(),\n processingTime: z.number(),\n error: z.string().optional(),\n })\n ),\n\n // Overall analysis\n summary: z.object({\n consensusIsAgent: z.boolean(),\n averageConfidence: z.number(),\n mostLikelyAgent: z.string().optional(),\n integrationAgreement: z.number(), // % of integrations that agree\n }),\n\n // Recommendations\n recommendations: z.array(z.string()).optional(),\n});\n\nexport type DetectionTestResult = z.infer<typeof DetectionTestResultSchema>;\n\n// Export request/response types for API\nexport const CollectFingerprintRequestSchema = z.object({\n testId: z.string().optional(),\n integrationType: IntegrationTypeSchema,\n data: z.any(), // Will be validated based on integration type\n});\n\nexport const CollectFingerprintResponseSchema = z.object({\n success: z.boolean(),\n sessionId: z.string(),\n fingerprintId: z.string(),\n message: z.string().optional(),\n});\n\n// Admin API types\nexport const CreateProfileRequestSchema = z.object({\n name: z.string(),\n displayName: z.string(),\n vendor: z.string(),\n version: z.string().optional(),\n description: z.string().optional(),\n});\n\nexport const UpdateProfileRequestSchema = CreateProfileRequestSchema.partial();\n\nexport const AddFingerprintToProfileRequestSchema = z.object({\n fingerprintId: z.string(),\n profileId: z.string(),\n});\n\nexport const PublishProfileRequestSchema = z.object({\n profileId: z.string(),\n version: z.string().optional(),\n});\n\nexport const TestDetectionRequestSchema = z.object({\n fingerprintId: z.string(),\n integrationTypes: z.array(IntegrationTypeSchema).optional(), // Test specific integrations or all\n});\n\n// Helper function to generate test ID\nexport function generateTestId(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 8);\n return `test-${timestamp}-${random}`;\n}\n\n// Helper to check if integration supports client-side data\nexport function supportsClientSide(integration: IntegrationType): boolean {\n return ['pixel', 'beacon'].includes(integration);\n}\n\n// Helper to check if integration supports headers\nexport function supportsHeaders(integration: IntegrationType): boolean {\n return ['noscript', 'middleware', 'express', 'edge', 'wasm'].includes(integration);\n}\n\n// Helper to check if integration supports enhanced server data\nexport function supportsServerEnhanced(integration: IntegrationType): boolean {\n return ['middleware', 'express'].includes(integration);\n}\n","// GENERATED FILE — do not hand-edit.\n//\n// Source of truth: rust/crates/kya-os-engine/data/vendor-keys/*.json —\n// the RFC 9421 vendor key directories the engine actually pins and\n// verifies at the edge. Regenerate with:\n//\n// pnpm tsx scripts/sync-signing-vendors.ts\n//\n// apps/web/tests/unit/lib/signing-vendors-parity.test.ts fails the build\n// when this list drifts from the directory, so adding or removing a\n// vendor key file forces this manifest (and therefore every derived\n// `signatureSupport` flag) to follow. Existing agent_types rows in\n// deployed databases still need a data migration when the list changes —\n// the sync script prints a reminder.\n\n/** Vendors with a pinned, edge-verified RFC 9421 signing-key directory. */\nexport const PINNED_SIGNING_VENDORS: readonly string[] = ['openai'];\n","/**\n * Agent Classification Types\n *\n * Centralized type definitions for agent classification system\n */\n\nimport { z } from 'zod';\n\nimport { PINNED_SIGNING_VENDORS } from './signing-vendors.generated';\n\n/**\n * True iff any of the agent's signature-vendor aliases has a pinned,\n * edge-verified RFC 9421 key directory in the engine\n * (rust/crates/kya-os-engine/data/vendor-keys, via the generated\n * manifest). This is the ONLY way `signatureSupport` may become true —\n * hand-seeding it let `claude` claim verified signatures for months\n * while Anthropic published no keys and the engine pinned none.\n */\nexport function hasPinnedSigningVendor(aliases: readonly string[] | undefined): boolean {\n return aliases?.some((alias) => PINNED_SIGNING_VENDORS.includes(alias)) ?? false;\n}\n\n/**\n * Agent categories for classification\n */\nexport const AgentCategorySchema = z.enum([\n 'ai_assistant', // ChatGPT, Claude, Gemini, Perplexity\n 'search_engine', // Googlebot, Bingbot, DuckDuckBot\n 'social_media', // Facebook, Twitter, LinkedIn crawlers\n 'monitoring', // Uptime monitors, health checkers\n 'scraper', // Web scrapers, data extractors\n 'automation', // Puppeteer, Playwright, Selenium\n 'security', // Security scanners, vulnerability testers\n 'analytics', // Analytics bots, SEO tools\n 'unknown', // Unclassified agents\n]);\nexport type AgentCategory = z.infer<typeof AgentCategorySchema>;\n\n/**\n * Operator-facing vocabulary for `agent_category`.\n *\n * ## Why this lives here\n *\n * Beside `AgentCategorySchema`, not in a UI package, because the same\n * words have to hold across the dashboard, the gateway, exports, the\n * public API, and the .NET plane. A display map that lives in one app is\n * a map the other surfaces will silently disagree with.\n *\n * `Record<AgentCategory, …>` is load-bearing: TypeScript refuses to\n * compile a missing key, so widening the enum without designing its copy\n * cannot ship. The previous web-only map had a `titleCase` fallback that\n * silently invented a label for any new value, which is exactly the drift\n * this replaces.\n *\n * ## What `unknown` means, and why it is labelled \"Other\"\n *\n * `agent_category` answers *which named family is this*. It is a\n * DIFFERENT axis from `detection_class`, which answers *is this human, an\n * agent, or a bot*. A miss on `detection_class` is a detection gap and\n * has its own value (`incomplete_data`). A miss here is an ATTRIBUTION\n * gap: the request was detected and classified, we just have not matched\n * it to a named vendor.\n *\n * `getAgentCategory` (apps/web/lib/utils/agent-category.ts) writes\n * `'unknown'` for exactly two cases: traffic matched only a generic\n * bot/crawler/spider/scraper signature, and the final default. Both are\n * \"real traffic, no vendor attributed\" — the ordinary long tail of the\n * internet, not a failure. Labelling it \"Unrecognized\" or \"Uncategorized\"\n * describes the engine as having failed at something it did not attempt,\n * and reads as weakness on a chart where it is routinely the largest\n * slice.\n *\n * \"Other\" is the sibling term to the eight named families and carries no\n * such claim. Where the bucket deserves a second look (it is where an\n * agent nobody has written a signature for shows up first) that belongs\n * in prose and drill-in, not compressed into a bar label.\n */\nexport interface AgentCategoryMeta {\n /** Title-case form for chart axes, table cells, chips, filters. */\n label: string;\n /**\n * Lower-case form for mid-sentence prose (\"led by search engine\n * traffic\"). Acronyms keep their casing — lowercasing \"AI\" is a worse\n * error than an odd-looking capital.\n */\n inline: string;\n /**\n * One-line operator-facing definition. Single source for tooltips and\n * for the knowledge-base article, so the docs cannot drift from the\n * code the way they did before.\n */\n definition: string;\n}\n\nexport const AGENT_CATEGORY_META: Record<AgentCategory, AgentCategoryMeta> = {\n ai_assistant: {\n label: 'AI assistant',\n inline: 'AI assistant',\n definition: 'An AI assistant acting for a person in real time (ChatGPT, Claude, Perplexity).',\n },\n search_engine: {\n label: 'Search engine',\n inline: 'search engine',\n definition: 'An indexing crawler that makes your pages findable (Googlebot, Bingbot).',\n },\n social_media: {\n label: 'Social media',\n inline: 'social media',\n definition: 'A crawler building link previews for a social platform.',\n },\n monitoring: {\n label: 'Monitoring',\n inline: 'monitoring',\n definition: 'An uptime or health checker polling your endpoints.',\n },\n scraper: {\n label: 'Scraper',\n inline: 'scraper',\n definition:\n 'Bulk content extraction, including AI training crawlers such as GPTBot and ClaudeBot.',\n },\n automation: {\n label: 'Automation',\n inline: 'automation',\n definition: 'A headless browser or scripted driver (Puppeteer, Playwright, Selenium).',\n },\n security: {\n label: 'Security',\n inline: 'security',\n definition: 'A vulnerability scanner or security research crawler.',\n },\n analytics: {\n label: 'Analytics',\n inline: 'analytics',\n definition: 'An SEO or analytics tool sampling your pages.',\n },\n unknown: {\n label: 'Other',\n inline: 'other',\n definition:\n 'Detected and classified traffic that has not been attributed to a named vendor, ' +\n 'usually because it matched only a generic bot signature. Not a detection failure, ' +\n 'and worth sampling periodically: a new agent lands here before anyone writes a ' +\n 'signature for it.',\n },\n};\n\n/**\n * Non-canonical values reach the formatters only from pre-CHECK-constraint\n * rows in old snapshots and jsonb (`ai_crawler` is the known example, see\n * `docs/taxonomy/canonical-entities.md`).\n *\n * They get underscores expanded and nothing else. Expanding keeps them\n * readable where they land mid-sentence; NOT title-casing them is the\n * point, because inventing a polished label is exactly how an undesigned\n * value slips into the UI looking official. A stray `ai crawler` among\n * `AI assistant` and `Search engine` is legible and visibly not one of\n * the family.\n */\nfunction formatUnrecognizedValue(value: string): string {\n return value.replace(/_/g, ' ');\n}\n\n/**\n * Sentinels a previous revision briefly wrote into the category axis.\n *\n * #4875 replaced the `COALESCE`'s inline `'unknown'` with `__uncategorized__`\n * / `__unidentified__`. That shipped, so the strings are now sitting in\n * persisted chat history as jsonb, and history has no backfill. Dropping the\n * mapping when the sentinels were removed would leave rehydrated turns\n * rendering the raw `uncategorized` and treating the bucket as a real family\n * rather than the catch-all.\n *\n * Reads stay tolerant even though writes never produce these again.\n */\nconst LEGACY_CATEGORY_SENTINELS = new Set(['__uncategorized__', '__unidentified__']);\n\n/**\n * Render an `agent_category` value for display.\n *\n * `null` / `undefined` fold into the catch-all: `getAgentCategory` returns\n * NULL for humans and no-signal rows, which should never reach a category\n * chart, but folding beats crashing or rendering blank if one does.\n */\nexport function formatAgentCategory(value: string | null | undefined): string {\n if (!value || LEGACY_CATEGORY_SENTINELS.has(value)) return AGENT_CATEGORY_META.unknown.label;\n const meta = AGENT_CATEGORY_META[value as AgentCategory];\n return meta ? meta.label : formatUnrecognizedValue(value);\n}\n\n/** Lower-case form of {@link formatAgentCategory} for use inside a sentence. */\nexport function formatAgentCategoryInline(value: string | null | undefined): string {\n if (!value || LEGACY_CATEGORY_SENTINELS.has(value)) return AGENT_CATEGORY_META.unknown.inline;\n const meta = AGENT_CATEGORY_META[value as AgentCategory];\n return meta ? meta.inline : formatUnrecognizedValue(value);\n}\n\n/**\n * Display name for an agent whose `agent_type` was never resolved.\n *\n * Deliberately NOT one of the category words. This appears on the\n * top-agents table, a different surface from the category bars, so it\n * never sits beside them and does not need to be told apart from them by\n * spelling. Callers should prefer the agent's CATEGORY when they have one\n * (\"Scraper\" says more than \"Unnamed agent\") and fall back to this only\n * when both name and category are missing.\n */\nexport const UNNAMED_AGENT_LABEL = 'Unnamed agent';\n\n/**\n * Agent type definition (full entity)\n * Named as AgentTypeDefinition to avoid conflict with existing AgentType enum\n */\nexport const AgentTypeDefinitionSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n description: z.string().optional(),\n isLegitimate: z.boolean(),\n confidenceThreshold: z.number().min(0).max(100),\n detectionPatterns: z.array(z.string()),\n signatureSupport: z.boolean(),\n // Vendor tokens (own name + company aliases, e.g. ['chatgpt','openai']) matched\n // against a host-VERIFIED RFC 9421 Signature-Agent value to attribute a signed\n // agent to this type at ingest. Optional/additive; empty or absent ⇒ this type is\n // not resolvable by signature (only signatureSupport vendors carry aliases).\n signatureVendorAliases: z.array(z.string()).optional(),\n documentationUrl: z.string().optional(),\n createdAt: z.date(),\n updatedAt: z.date(),\n});\nexport type AgentTypeDefinition = z.infer<typeof AgentTypeDefinitionSchema>;\n\n/**\n * Agent classification result\n */\nexport const AgentClassificationResultSchema = z.object({\n agentTypeId: z.string().uuid(),\n agentType: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n confidence: z.number().min(0).max(100),\n isLegitimate: z.boolean(),\n signatureVerified: z.boolean().optional(),\n matchedPatterns: z.array(z.string()),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AgentClassificationResult = z.infer<typeof AgentClassificationResultSchema>;\n\n/**\n * Agent classification request\n */\nexport const AgentClassificationRequestSchema = z.object({\n userAgent: z.string().optional(),\n headers: z.record(z.string(), z.string()).optional(),\n ipAddress: z.string().optional(),\n sessionId: z.string().optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n});\nexport type AgentClassificationRequest = z.infer<typeof AgentClassificationRequestSchema>;\n\n/**\n * Agent statistics for analytics\n */\nexport const AgentStatisticsSchema = z.object({\n agentTypeId: z.string().uuid(),\n agentType: z.string(),\n displayName: z.string(),\n category: AgentCategorySchema,\n detectionCount: z.number(),\n sessionCount: z.number(),\n averageConfidence: z.number(),\n lastSeen: z.date(),\n isLegitimate: z.boolean(),\n percentageOfTotal: z.number().optional(),\n});\nexport type AgentStatistics = z.infer<typeof AgentStatisticsSchema>;\n\n/**\n * Helper functions\n */\n\n/**\n * Check if an agent category is considered legitimate\n */\nexport function isLegitimateCategory(category: AgentCategory): boolean {\n const legitimateCategories: AgentCategory[] = [\n 'ai_assistant',\n 'search_engine',\n 'social_media',\n 'monitoring',\n 'analytics',\n ];\n return legitimateCategories.includes(category);\n}\n\n/**\n * Get display color for agent category (for UI)\n */\nexport function getCategoryColor(category: AgentCategory): string {\n const colors: Record<AgentCategory, string> = {\n ai_assistant: '#10b981', // green\n search_engine: '#3b82f6', // blue\n social_media: '#8b5cf6', // purple\n monitoring: '#06b6d4', // cyan\n scraper: '#ef4444', // red\n automation: '#f97316', // orange\n security: '#dc2626', // dark red\n analytics: '#6366f1', // indigo\n unknown: '#6b7280', // gray\n };\n return colors[category] || '#6b7280';\n}\n\n/**\n * Get category badge variant for UI\n */\nexport function getCategoryBadgeVariant(\n category: AgentCategory\n): 'default' | 'success' | 'warning' | 'destructive' {\n switch (category) {\n case 'ai_assistant':\n case 'search_engine':\n return 'success';\n case 'social_media':\n case 'monitoring':\n case 'analytics':\n return 'default';\n case 'scraper':\n case 'automation':\n case 'security':\n return 'destructive';\n case 'unknown':\n default:\n return 'warning';\n }\n}\n\n/**\n * Default agent types (for initialization)\n */\nexport const DEFAULT_AGENT_TYPES: Partial<AgentTypeDefinition>[] = [\n {\n name: 'chatgpt',\n displayName: 'ChatGPT',\n category: 'ai_assistant',\n description: 'OpenAI ChatGPT Browser',\n isLegitimate: true,\n confidenceThreshold: 95,\n signatureSupport: hasPinnedSigningVendor(['chatgpt', 'openai']),\n signatureVendorAliases: ['chatgpt', 'openai'],\n detectionPatterns: ['GPTBot', 'ChatGPT-User', 'x-gpt-signature'],\n },\n {\n name: 'claude',\n displayName: 'Claude',\n category: 'ai_assistant',\n description: 'Anthropic Claude Assistant',\n isLegitimate: true,\n confidenceThreshold: 95,\n // Derived FALSE today: Anthropic publishes no web-bot-auth key\n // directory (verified 2026-08-26) and the engine pins no anthropic\n // key. Flips automatically once anthropic.json lands in vendor-keys\n // and the manifest is regenerated.\n signatureSupport: hasPinnedSigningVendor(['claude', 'anthropic']),\n signatureVendorAliases: ['claude', 'anthropic'],\n detectionPatterns: ['Claude-Web', 'Claude-User', 'anthropic-ai', 'x-claude-signature'],\n },\n {\n name: 'perplexity',\n displayName: 'Perplexity',\n category: 'ai_assistant',\n description: 'Perplexity AI Assistant',\n isLegitimate: true,\n confidenceThreshold: 90,\n signatureSupport: false,\n detectionPatterns: ['PerplexityBot', 'Perplexica'],\n },\n {\n name: 'googlebot',\n displayName: 'Googlebot',\n category: 'search_engine',\n description: 'Google Search Crawler',\n isLegitimate: true,\n confidenceThreshold: 95,\n signatureSupport: false,\n detectionPatterns: ['Googlebot', 'Googlebot-Image', 'Googlebot-Video'],\n },\n {\n name: 'puppeteer',\n displayName: 'Puppeteer',\n category: 'automation',\n description: 'Headless Chrome Automation',\n isLegitimate: false,\n confidenceThreshold: 75,\n signatureSupport: false,\n detectionPatterns: ['HeadlessChrome', 'Puppeteer'],\n },\n];\n","/**\n * Admin API Types\n *\n * Types for administrative endpoints and operations\n */\n\nimport { z } from 'zod';\n\n/**\n * Project Reset Request Schema\n */\nexport const projectResetRequestSchema = z.object({\n confirmation: z.literal('RESET_PROJECT_DATA'),\n dryRun: z.boolean().optional().default(false),\n preserveMembers: z.boolean().optional().default(true),\n includeFingerprints: z.boolean().optional().default(true),\n});\n\nexport type ProjectResetRequest = z.infer<typeof projectResetRequestSchema>;\n\n/**\n * Project Reset Statistics\n */\nexport interface ProjectResetStats {\n detectionsDeleted: number;\n pixelsDeleted: number; // @deprecated Always 0 - pixels are never deleted during reset\n apiKeysDeleted: number;\n activityLogsDeleted: number;\n permissionCacheCleared: number;\n fingerprintLogsDeleted: number;\n onboardingProgressDeleted: number;\n membersRemoved: number;\n}\n\n/**\n * Project Reset Response\n */\nexport interface ProjectResetResponse {\n success: boolean;\n dryRun: boolean;\n project: {\n id: string;\n name: string;\n domain: string | null;\n friendlyId: string | null;\n };\n stats: ProjectResetStats;\n message: string;\n totalRecordsAffected: number;\n timestamp: string;\n}\n\n/**\n * Project Reset Preview Response\n */\nexport interface ProjectResetPreviewResponse {\n project: {\n id: string;\n name: string;\n domain: string | null;\n friendlyId: string | null;\n createdAt: Date;\n };\n preview: ProjectResetStats;\n totalRecords: number;\n message: string;\n requiredConfirmation: string;\n options: {\n preserveMembers: {\n description: string;\n default: boolean;\n };\n includeFingerprints: {\n description: string;\n default: boolean;\n };\n dryRun: {\n description: string;\n default: boolean;\n };\n };\n}\n\n/**\n * Admin Route Context\n * Used for admin-specific routes that require superadmin access\n */\nexport interface AdminRouteContext {\n adminId: string;\n adminEmail: string;\n isAdmin: boolean;\n}\n\n/**\n * Admin Project Route Context\n * Used for admin project management routes\n */\nexport interface AdminProjectRouteContext extends AdminRouteContext {\n params: {\n projectId: string;\n };\n}\n\n/**\n * User-Organization Assignment Types\n */\n\n/**\n * User Organization Assignment\n */\nexport interface UserOrganizationAssignment {\n userId: string;\n organizationId: string;\n role: 'owner' | 'admin' | 'member';\n joinedAt: Date;\n organizationName: string;\n organizationSlug: string;\n}\n\n/**\n * Assignment Change Request Schema\n */\nexport const assignmentChangeRequestSchema = z.object({\n userId: z.string().uuid('Invalid user ID'),\n organizationId: z.string().uuid('Invalid organization ID'),\n role: z.enum(['owner', 'admin', 'member'], {\n error: 'Role must be owner, admin, or member',\n }),\n action: z.enum(['assign', 'remove', 'update_role']),\n});\n\nexport type AssignmentChangeRequest = z.infer<typeof assignmentChangeRequestSchema>;\n\n/**\n * Batch Assignment Request Schema\n */\nexport const batchAssignmentRequestSchema = z.object({\n userIds: z.array(z.string().uuid()).min(1, 'At least one user ID required'),\n organizationId: z.string().uuid('Invalid organization ID'),\n role: z.enum(['owner', 'admin', 'member']),\n action: z.enum(['assign', 'remove']),\n});\n\nexport type BatchAssignmentRequest = z.infer<typeof batchAssignmentRequestSchema>;\n\n/**\n * Organization Membership Response\n */\nexport interface OrganizationMembershipResponse {\n success: boolean;\n data: UserOrganizationAssignment[];\n pagination?: {\n page: number;\n limit: number;\n total: number;\n hasNext: boolean;\n hasPrev: boolean;\n };\n error?: {\n code: string;\n message: string;\n details?: unknown;\n };\n}\n\n/**\n * Extended Audit Log Entry for User-Organization Operations\n */\nexport interface UserOrgAuditLogEntry {\n id: string;\n adminId: string;\n adminEmail: string;\n action: string;\n targetType: 'user' | 'organization' | 'system' | 'project';\n targetId?: string;\n details: {\n userId?: string;\n userEmail?: string;\n organizationId?: string;\n organizationName?: string;\n previousRole?: string;\n newRole?: string;\n role?: string;\n reason?: string;\n [key: string]: unknown;\n };\n ipAddress?: string;\n userAgent?: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Audit Log Query Request Schema\n */\nexport const auditLogQuerySchema = z.object({\n page: z.coerce.number().min(1).default(1).optional(),\n limit: z.coerce.number().min(1).max(100).default(50).optional(),\n adminId: z.string().uuid().optional(),\n action: z.string().optional(),\n targetType: z.enum(['user', 'organization', 'system', 'project']).optional(),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n search: z.string().optional(),\n});\n\nexport type AuditLogQueryRequest = z.infer<typeof auditLogQuerySchema>;\n\nexport type GrowthConfigurationType = 'bouncer' | 'enterprise' | 'support' | 'integration';\n\nexport type GrowthOpportunityType = GrowthConfigurationType;\n\nexport type GrowthPriority = 'low' | 'medium' | 'high' | 'critical';\n\nexport interface GrowthBouncerThresholds {\n minAiTrafficRate: number;\n aiTrafficSpikeMultiplier: number;\n highAiTrafficThreshold: number;\n consistentHighTrafficDays: number;\n criticalAiTrafficRate: number;\n}\n\nexport interface GrowthEnterpriseThresholds {\n highVolumeThreshold: number;\n rapidGrowthRate: number;\n multiDomainCount: number;\n largeTeamSize: number;\n multiProjectCount: number;\n highPercentileThreshold: number;\n minEnterpriseIndicators: number;\n}\n\nexport interface GrowthSupportThresholds {\n inactiveDays: number;\n minSupportIndicators: number;\n criticalSupportScore: number;\n}\n\nexport interface GrowthIntegrationThresholds {\n minSessionsForBenefit: number;\n minAiRateForBenefit: number;\n}\n\nexport interface GrowthConfigurationThresholdMap {\n bouncer: GrowthBouncerThresholds;\n enterprise: GrowthEnterpriseThresholds;\n support: GrowthSupportThresholds;\n integration: GrowthIntegrationThresholds;\n}\n\nexport type GrowthConfigurationThreshold = GrowthConfigurationThresholdMap[GrowthConfigurationType];\n\nexport interface GrowthAgentConcentration {\n name: string;\n percentage: number;\n}\n\nexport interface GrowthBouncerOpportunityDetails {\n avgAiRate: number;\n latestAiRate: number;\n weekOverWeekChange: number;\n highTrafficDays: number;\n topAgents: GrowthAgentConcentration[];\n}\n\nexport interface GrowthBouncerOpportunityMetrics {\n sessionVolume: number;\n aiDetections: number;\n trend: 'increasing' | 'stable';\n}\n\nexport interface GrowthEnterpriseOpportunityDetails {\n sessionVolume: number;\n growthRate: number;\n domainCount: number;\n memberCount: number;\n projectCount: number;\n percentileRank: number | null;\n}\n\nexport interface GrowthEnterpriseOpportunityMetrics {\n weeklyVolume: number;\n monthlyGrowth: number;\n enterpriseIndicators: number;\n}\n\nexport interface GrowthSupportOpportunityDetails {\n unverifiedCount: number;\n inactiveCount: number;\n patterns: Record<string, number>;\n}\n\nexport interface GrowthSupportOpportunityMetrics {\n supportIndicators: number;\n integrationHealth: 'none' | 'partial' | 'healthy';\n}\n\nexport interface GrowthIntegrationOpportunityDetails {\n pixelCount: number;\n domainCount: number;\n wasmEnabled: boolean;\n}\n\nexport interface GrowthIntegrationOpportunityMetrics {\n sessionVolume: number;\n aiRate: number;\n}\n\ninterface BaseGrowthOpportunity<\n TType extends GrowthOpportunityType,\n TDetails extends object,\n TMetrics extends object,\n> {\n type: TType;\n score: number;\n priority: GrowthPriority;\n reason: string;\n details: TDetails;\n metrics: TMetrics;\n}\n\nexport type GrowthOpportunityDetails =\n | BaseGrowthOpportunity<\n 'bouncer',\n GrowthBouncerOpportunityDetails,\n GrowthBouncerOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'enterprise',\n GrowthEnterpriseOpportunityDetails,\n GrowthEnterpriseOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'support',\n GrowthSupportOpportunityDetails,\n GrowthSupportOpportunityMetrics\n >\n | BaseGrowthOpportunity<\n 'integration',\n GrowthIntegrationOpportunityDetails,\n GrowthIntegrationOpportunityMetrics\n >;\n\nexport interface GrowthRecommendationPerformance {\n sessionGrowthRate?: number | null;\n sessionCount?: number | null;\n overallPercentile?: number | null;\n}\n\nexport interface GrowthRecommendationAnalytics {\n totalSessions?: number | null;\n averageDuration?: number | null;\n bounceRate?: number | null;\n timestamp?: string | number | Date | null;\n}\n\nexport interface GrowthRecommendationOnboarding {\n createdAt?: Date | string | null;\n hasActiveProjects: boolean;\n hasPixels: boolean;\n activePixels: number;\n teamSize: number;\n}\n\nexport interface GrowthRecommendationIntegration {\n projectCount: number;\n pixelCount: number;\n activePixels: number;\n}\n\nexport interface GrowthRecommendationContext {\n organizationId: string;\n performance?: GrowthRecommendationPerformance | null;\n analytics?: GrowthRecommendationAnalytics | null;\n onboarding?: GrowthRecommendationOnboarding;\n integration?: GrowthRecommendationIntegration;\n}\n\nexport type AdminExecutiveSummaryPeriod = '7d' | '30d' | '90d' | 'all';\n\nexport interface AdminExecutiveSummaryResponse {\n period: AdminExecutiveSummaryPeriod;\n platformHealth: {\n totals: {\n orgs: number;\n projects: number;\n users: number;\n signupsInPeriod: number;\n newOrgsInPeriod: number;\n };\n activeUsers: {\n last7d: number;\n last30d: number;\n };\n setupCompletion: {\n totalUsers: number;\n qualified: number;\n createdProject: number;\n completedOnboarding: number;\n };\n };\n enforce: {\n checkpoints: Record<string, unknown> | undefined;\n sessions: Record<string, unknown> | undefined;\n proofs: Record<string, unknown> | undefined;\n topAgents: Array<{\n agentName: string;\n proofCount: number;\n successCount: number;\n blockedCount: number;\n }>;\n };\n govern: {\n deployments: Record<string, unknown> | undefined;\n delegations: Record<string, unknown> | undefined;\n managedUsage: Record<string, unknown> | undefined;\n oneClickDeploys: {\n total: number;\n cfDeployed: number;\n newInPeriod: number;\n byTemplate: Array<{\n template: string | null;\n count: number;\n }>;\n };\n pendingApprovals: Record<string, unknown> | undefined;\n customDomains: Record<string, unknown> | undefined;\n };\n molti: {\n status: Record<string, unknown> | undefined;\n health: Record<string, unknown> | undefined;\n hostingBreakdown: Array<{\n hostingMode: string | null;\n region: string;\n aiProvider: string | null;\n count: number;\n }>;\n };\n detect: {\n trend: {\n currentPeriod: number | null;\n previousPeriod: number | null;\n changePercent: number | null;\n };\n classification: Array<{\n class: string;\n count: number;\n }>;\n pixels: Record<string, unknown> | undefined;\n };\n growthPipeline: {\n leads: {\n total: number;\n inPeriod: number;\n uncontacted: number;\n bySource: Array<{\n source: string | null;\n count: number;\n }>;\n };\n assessments: {\n total: number;\n inPeriod: number;\n withEmail: number;\n byTier: Array<{\n tier: string | null;\n count: number;\n }>;\n };\n integrations: Record<string, unknown> | undefined;\n };\n generatedAt: string;\n}\n\nexport interface AdminMetricsResponse {\n totals: {\n users: number;\n organizations: number;\n projects: number;\n };\n planDistribution: Array<{\n plan: string | null;\n count: number;\n }>;\n verificationStats:\n | {\n verified: number;\n unverified: number;\n }\n | undefined;\n onboardingStats:\n | {\n completed: number;\n incomplete: number;\n }\n | undefined;\n signupTrends: Array<{\n date: string;\n count: number;\n }>;\n organizationSizes: {\n small: number;\n medium: number;\n large: number;\n };\n detection: {\n totalDetectionsToday: number;\n totalDetections7d: number;\n totalDetections30d: number;\n aiAgentRate: number;\n activeOrgsWithTraffic: number;\n orgsWithEnforcement: number;\n };\n enforcement: {\n totalDecisions: number;\n blocked: number;\n allowed: number;\n challenged: number;\n blockRate: number;\n allowRate: number;\n topBlockedAgents: Array<{ agentName: string; count: number }>;\n topAllowedAgents: Array<{ agentName: string; count: number }>;\n dataQuality: {\n partial: boolean;\n includedSources: string[];\n omittedSources: string[];\n message: string | null;\n };\n };\n timestamp: string;\n}\n\nexport interface AdminSessionDurationBucket {\n range: string;\n min: number;\n max: number;\n count: number;\n percentage: number;\n}\n\nexport interface AdminOrganizationSessionAnalytics {\n organizationId: string;\n organizationName: string;\n metrics: {\n totalSessions: number;\n uniqueSessions: number;\n averageDuration: number;\n medianDuration: number;\n minDuration: number;\n maxDuration: number;\n distribution: AdminSessionDurationBucket[];\n bounceRate: number;\n pagesPerSession: number;\n isSampled: boolean;\n sampleSize?: number;\n };\n comparison: {\n aiAgentSessions: number;\n botSessions: number;\n humanSessions: number;\n aiAgentPercentage: number;\n botPercentage: number;\n humanPercentage: number;\n };\n patterns: {\n peakHours: unknown[];\n mostVisitedPages: unknown[];\n navigationPatterns: unknown[];\n };\n trends: {\n sessionGrowth: number;\n durationTrend: number;\n bounceRateTrend: number;\n };\n}\n\nexport interface AdminSessionIndustryAverages {\n averageSessionDuration: number;\n averageBounceRate: number;\n averagePagesPerSession: number;\n averageSessionsPerOrg: number;\n medianSessionDuration: number;\n distribution: {\n aiAgentPercentage: number;\n botPercentage: number;\n humanPercentage: number;\n };\n}\n\nexport interface AdminSessionAnomaly {\n organizationId: string;\n organizationName: string;\n reasons: string[];\n severity: 'low' | 'medium' | 'high';\n metrics: {\n sessions: number;\n duration: number;\n bounceRate: number;\n aiPercentage: number;\n botPercentage: number;\n };\n}\n\nexport interface AdminSessionInsights {\n topPerformers: Array<{\n organizationName: string;\n reason: string;\n metrics: {\n bounceRate: number;\n pagesPerSession: number;\n };\n }>;\n needsAttention: Array<{\n organizationName: string;\n reason: string;\n recommendation: string;\n }>;\n opportunities: Array<{\n organizationName: string;\n opportunity: string;\n description: string;\n }>;\n trends: {\n growingOrganizations: Array<{\n organizationName: string;\n growth: number;\n }>;\n decliningOrganizations: Array<{\n organizationName: string;\n decline: number;\n }>;\n };\n}\n\nexport interface AdminSessionAnalyticsResponse {\n success: true;\n data: {\n organizations: AdminOrganizationSessionAnalytics[];\n industryAverages: AdminSessionIndustryAverages;\n anomalies: AdminSessionAnomaly[];\n insights: AdminSessionInsights;\n dateRange: {\n start: string;\n end: string;\n };\n metadata: {\n totalOrganizations: number;\n sortBy: 'sessions' | 'duration' | 'bounceRate' | 'growth';\n sortOrder: 'asc' | 'desc';\n };\n };\n}\n","/**\n * Wire contract for GET /api/admin/overview.\n *\n * `meta.warnings` carries every methodology caveat the response embeds\n * (attribution gaps, partial sections, stale rollups, and so on) so the\n * dashboard never hides one behind a silently-dropped field. All\n * timestamps are ISO-8601 strings; all dates are YYYY-MM-DD strings.\n */\n\nimport { z } from 'zod';\n\n/** Supported lookback windows for the admin overview. */\nexport const ADMIN_OVERVIEW_WINDOWS = ['7d', '30d', '90d'] as const;\nexport type AdminOverviewWindow = (typeof ADMIN_OVERVIEW_WINDOWS)[number];\n/** Window applied when the request omits one. */\nexport const DEFAULT_ADMIN_OVERVIEW_WINDOW: AdminOverviewWindow = '30d';\n/** Row cap applied to each list section when the request omits `listLimit`. */\nexport const ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT = 100;\n/** Hard ceiling on `listLimit`, regardless of what the request asks for. */\nexport const ADMIN_OVERVIEW_LIST_LIMIT_MAX = 500;\n\n/**\n * Split on '-' and round-trip through `Date.UTC` so a value like\n * 2026-02-30 (day overflow) or 2026-13-01 (month overflow) is rejected\n * instead of silently rolling into the next month or year.\n */\nfunction isCalendarDate(value: string): boolean {\n const [year, month, day] = value.split('-').map(Number);\n if (!year || !month || !day) return false;\n const date = new Date(Date.UTC(year, month - 1, day));\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n );\n}\n\n/** Query params for GET /api/admin/overview (parsed from URLSearchParams, so numbers are coerced). */\nexport const adminOverviewQuerySchema = z.object({\n window: z.enum(ADMIN_OVERVIEW_WINDOWS).default(DEFAULT_ADMIN_OVERVIEW_WINDOW),\n // YYYY-MM-DD, must be a real calendar date (reject 2026-02-30, 2026-13-01, '2026-1-5', ISO datetimes)\n compareTo: z\n .string()\n .regex(/^\\d{4}-\\d{2}-\\d{2}$/)\n .refine(isCalendarDate, {\n message: 'compareTo must be a real calendar date in YYYY-MM-DD form',\n })\n .optional(),\n listLimit: z.coerce\n .number()\n .int()\n .min(1)\n .max(ADMIN_OVERVIEW_LIST_LIMIT_MAX)\n .default(ADMIN_OVERVIEW_LIST_LIMIT_DEFAULT),\n});\nexport type AdminOverviewQuery = z.infer<typeof adminOverviewQuerySchema>;\n/**\n * Pre-parse shape: numbers are already numeric here (zod's coerce does not\n * widen the input type), so do not annotate a raw\n * `Object.fromEntries(url.searchParams)` object with this type; pass that\n * object to `adminOverviewQuerySchema.safeParse` directly.\n */\nexport type AdminOverviewQueryInput = z.input<typeof adminOverviewQuerySchema>;\n\n/** How a headline delta's `previous` value was computed. */\nexport const ADMIN_DELTA_BASES = ['created_at', 'rollup', 'none'] as const;\nexport type AdminDeltaBasis = (typeof ADMIN_DELTA_BASES)[number];\n/** A headline number with its value as of `compareTo`. previous is null when no prior value is computable (basis 'none'). */\nexport interface AdminDelta {\n current: number;\n previous: number | null;\n basis: AdminDeltaBasis;\n}\n\n/** The kinds of instrumentation an organization can have installed. */\nexport const INSTALLATION_KINDS = [\n 'agent',\n 'pixel',\n 'middleware',\n 'dns_gateway',\n 'mcp_server',\n 'beacon',\n] as const;\nexport type InstallationKind = (typeof INSTALLATION_KINDS)[number];\n/** The distinct installation records tracked, one level more specific than InstallationKind (middleware splits by runtime). */\nexport const INSTALLATION_TYPES = [\n 'pixel',\n 'middleware_node',\n 'middleware_dotnet',\n 'middleware_jvm',\n 'middleware_android',\n 'middleware_no_traffic',\n 'dns_gateway',\n 'beacon',\n] as const;\nexport type InstallationType = (typeof INSTALLATION_TYPES)[number];\n/** The four buckets the admin overview classifies every traffic event into. */\nexport const TRAFFIC_TAXONOMY_BUCKETS = [\n 'human',\n 'ai_agent',\n 'ai_crawler',\n 'other_automation',\n] as const;\nexport type TrafficTaxonomyBucket = (typeof TRAFFIC_TAXONOMY_BUCKETS)[number];\n/** Order is precedence: a user matching several rules is attributed to the first. */\nexport const EXCLUSION_BUCKETS = [\n 'vouched',\n 'internal_team',\n 'test_pattern',\n 'shopify_review',\n 'cohort',\n] as const;\nexport type ExclusionBucket = (typeof EXCLUSION_BUCKETS)[number];\n/** The independently-fetchable sections of the admin overview response. */\nexport const ADMIN_OVERVIEW_SECTIONS = [\n 'ladder',\n 'installations',\n 'traffic',\n 'lists',\n 'hiAi',\n] as const;\nexport type AdminOverviewSection = (typeof ADMIN_OVERVIEW_SECTIONS)[number];\n/** Cache states a section can report in `meta.cache.status`. */\nexport const ADMIN_OVERVIEW_CACHE_STATUSES = ['hit', 'stale', 'miss', 'bypass'] as const;\nexport type AdminOverviewCacheStatus = (typeof ADMIN_OVERVIEW_CACHE_STATUSES)[number];\n\n/** events in the bucket, share = events / totalEvents (0 when totalEvents is 0), totalEvents = denominator for the whole scope. */\nexport interface TaxonomyTotals {\n events: number;\n share: number;\n totalEvents: number;\n}\nexport type TaxonomyBreakdown = Record<TrafficTaxonomyBucket, TaxonomyTotals>;\n\n/** The customer-acquisition funnel headline row, each stage a delta against `compareTo`. */\nexport interface AdminOverviewLadder {\n emailsCollected: AdminDelta;\n users: AdminDelta;\n signedInProxy: AdminDelta;\n onboarded: AdminDelta;\n activated: AdminDelta;\n}\n\n/** One per InstallationKind, customer-scoped. activeInWindow = installs with activity inside the window. orgCount = distinct customer organizations behind those installs (an org with 3 middleware pixels still counts once). */\nexport interface InstallationCard {\n kind: InstallationKind;\n total: AdminDelta;\n activeInWindow: number;\n orgCount: number;\n}\n/** Count of installations of one InstallationType, split into customer-owned vs excluded. */\nexport interface InstallationTypeCount {\n type: InstallationType;\n customer: number;\n excluded: number;\n total: number;\n}\n/** The installations section: per-kind summary cards plus the finer-grained type breakdown. */\nexport interface AdminOverviewInstallations {\n cards: InstallationCard[];\n byType: InstallationTypeCount[];\n}\n\n/**\n * Keys for the by-service traffic table. By-service traffic is attributed\n * per project installation profile: a project with exactly one\n * InstallationKind lands under that kind, a project with more than one kind\n * lands in 'mixed' (counting it under a single kind would double count), and\n * a project with none lands in 'none'.\n */\nexport const SERVICE_TRAFFIC_KEYS = [...INSTALLATION_KINDS, 'mixed', 'none'] as const;\nexport type ServiceTrafficKey = (typeof SERVICE_TRAFFIC_KEYS)[number];\n\n/** attribution is always 'project-profile' until the rollups carry a source dimension; the server adds a standing warning. */\nexport interface ServiceTrafficRow {\n service: ServiceTrafficKey;\n events: number;\n share: number;\n projects: number;\n attribution: 'project-profile';\n}\n/** One project's traffic for the window, broken into the four taxonomy buckets. */\nexport interface SiteTrafficRow {\n projectId: string;\n projectName: string;\n domain: string | null;\n organizationId: string;\n organizationName: string;\n events: number;\n share: number;\n buckets: Record<TrafficTaxonomyBucket, number>;\n}\n/** The traffic section: taxonomy breakdowns, per-service rollups, and the per-site list. */\nexport interface AdminOverviewTraffic {\n taxonomy: { window: TaxonomyBreakdown; allTime: TaxonomyBreakdown };\n byService: ServiceTrafficRow[];\n /** Capped by listLimit; bySiteTotal is the uncapped count. */\n bySite: SiteTrafficRow[];\n bySiteTotal: number;\n /** Earliest rollup date (YYYY-MM-DD); allTime means \"since this date\". null when no rollups exist. */\n coverageFrom: string | null;\n}\n\n/** An onboarded user who is a member of an org with at least one installation. */\nexport interface ActivatedUserRow {\n userId: string;\n email: string;\n name: string | null;\n organizationId: string;\n organizationName: string;\n installationKinds: InstallationKind[];\n onboardingCompletedAt: string | null;\n createdAt: string;\n}\n/**\n * Every new user, NOT gated on onboarding/installation status at all —\n * unlike `ActivatedUserRow`'s two lists (both scoped to a qualifying org's\n * membership), this is the raw `users` population itself: a user with zero\n * org membership and zero installs still appears here, with `organizationId`/\n * `organizationName` null and `installationKinds` empty. Exists to close the\n * gap where a legitimate signup with no installs was invisible in every\n * other per-person list.\n */\nexport interface NewSignupRow {\n userId: string;\n email: string;\n name: string | null;\n /** The user's earliest-joined organization, if any; null for a user with no org membership at all. */\n organizationId: string | null;\n organizationName: string | null;\n installationKinds: InstallationKind[];\n createdAt: string;\n}\n/**\n * The three person-level funnel stages the admin Customer Journey view\n * classifies every non-excluded user into. Deliberately three, not four:\n * the schema has no \"installed\" step distinct from \"onboarded\" (see\n * `orgActiveInstallationsCte`'s doc comment: activated is a strictly\n * stronger condition over the SAME verified-installation evidence\n * `orgInstallationsCte` checks, not a separate install event), so a row is\n * exactly one of:\n * - `signed_up`: a non-excluded user with no qualifying (onboarded) org.\n * - `onboarded`: member of a qualifying org (see `ActivatedUserRow`'s own\n * doc comment for what \"qualifying\" means) that is NOT also activated.\n * - `activated`: member of a qualifying org that also satisfies\n * `orgActiveInstallationsCte` (verified AND active in the window).\n * The admin Customer Journey page labels the `onboarded` stage \"Installed\"\n * in its own UI copy (plainer for a fast scan) while this type keeps the\n * same word Overview's ladder already uses for the identical population,\n * so the two never drift into two different predicates under two different\n * names.\n */\nexport type CustomerJourneyStage = 'signed_up' | 'onboarded' | 'activated';\n\n/**\n * One row per non-excluded user, for the admin Customer Journey view: the\n * per-person drill-down behind the aggregate ladder/funnel-breakdown numbers\n * already on `/admin`: same population, same exclusion rules, same\n * onboarded/activated predicates, just one row per person instead of one\n * count per stage. `organizationId`/`organizationName` are the org this\n * row's stage is attributed to (the qualifying org for `onboarded`/\n * `activated`, or the user's earliest-joined org of any kind for\n * `signed_up`, mirroring `NewSignupRow`'s `first_membership` for a user\n * with no qualifying org); both are null for a user with no org membership\n * at all.\n */\nexport interface CustomerJourneyRow {\n userId: string;\n email: string;\n name: string | null;\n organizationId: string | null;\n organizationName: string | null;\n /** Distinct members of organizationId; null when organizationId is null. */\n teamSize: number | null;\n /**\n * Installations configured for the attributed org, from the same source\n * the ladder's own rows use. Not gated on the verified/counted-kind\n * predicate that decides `stage`: an org can appear here with an\n * unverified pixel, or with the `agent` kind, even though neither counts\n * toward `onboarded`/`activated`. [] when the attributed org has none.\n */\n installationKinds: InstallationKind[];\n stage: CustomerJourneyStage;\n /**\n * Days since this row entered its current stage. null when not\n * computable: always for `activated` (no per-user activation timestamp\n * exists today, so this is never fabricated from a proxy), and for\n * `onboarded` when the qualifying org's install came from a teammate\n * (this user's own `onboardingCompletedAt` was never set, and the\n * installation tables only carry \"last seen/detected\" timestamps, not\n * \"first verified\" ones, so no honest fallback exists either).\n */\n daysInStage: number | null;\n /** True once daysInStage reaches or exceeds the stage's threshold (inclusive at the boundary). Always false when daysInStage is null. */\n stalled: boolean;\n createdAt: string; // ISO\n}\n\n/** One `pixels` row joined to its project and org; `type` is derived from the middleware marker and engine probe. */\nexport interface PixelInstallationRow {\n pixelId: string;\n pixelName: string;\n type: InstallationType;\n projectId: string;\n projectName: string;\n domain: string | null;\n organizationId: string;\n organizationName: string;\n scope: 'customer' | 'excluded';\n detectionCount: number;\n lastDetectionAt: string | null;\n activeInWindow: boolean;\n createdAt: string;\n}\n/** An email that never became a user, sourced from `email_leads` or `assessments.lead_email`; sourceDetail is the raw source string. */\nexport interface LeadRow {\n email: string;\n source: 'email_lead' | 'assessment';\n sourceDetail: string | null;\n company: string | null;\n firstSeenAt: string;\n lastSeenAt: string;\n}\n/** How many users and organizations one exclusion rule (bucket) removed from the counts. */\nexport interface ExclusionAuditRow {\n bucket: ExclusionBucket;\n users: number;\n organizations: number;\n}\n/** A server-capped list: rows.length <= listLimit, total is the uncapped count. */\nexport interface AdminOverviewList<T> {\n rows: T[];\n total: number;\n}\n/**\n * A Hi-AI report requested by email, linked to the exact host that was\n * audited (apps/web/app/api/hi-ai/share/route.ts inserts `sourceUrl` from\n * the already-validated `host` at request time). `sourceUrl` is null for a\n * row recorded before that column existed, until\n * `scripts/backfill-hi-ai-lead-source-url.ts` fills it in from the legacy\n * `referer` header.\n */\nexport interface HiAiLeadRow {\n email: string;\n sourceUrl: string | null;\n createdAt: string;\n}\n/**\n * One host audited through the public Hi-AI tool (`/hi-ai/<host>`), sourced\n * from Amplitude `Page Viewed` events rather than a database row —\n * unattributed to any person, unlike {@link HiAiLeadRow}: this counts every\n * visit, with or without an email capture. `visits` is unique visitors in\n * the selected window (Amplitude `uniques`).\n */\nexport interface HiAiAuditRow {\n host: string;\n visits: number;\n}\n/** The Hi-AI section: leads linked to a person (email -> audited host) alongside the unattributed per-host audit breakdown. */\nexport interface AdminOverviewHiAi {\n leads: AdminOverviewList<HiAiLeadRow>;\n audits: AdminOverviewList<HiAiAuditRow>;\n}\n/**\n * The lists section shown below the headline numbers. `activatedUsers`,\n * `installationUsers`, `pixelInstallations`, and `leads` are server-capped by\n * listLimit; `exclusionAudit` is one row per ExclusionBucket and is not\n * capped.\n */\nexport interface AdminOverviewLists {\n activatedUsers: AdminOverviewList<ActivatedUserRow>;\n /**\n * Every member of a customer org with >=1 installation, regardless of\n * whether that individual user has personally completed the onboarding\n * wizard — the superset `activatedUsers` is filtered down from. Tag a row\n * to a specific installation kind client-side via\n * `installationKinds.includes(kind)`.\n */\n installationUsers: AdminOverviewList<ActivatedUserRow>;\n /**\n * Every new user, not gated on onboarding/installation status at all — a\n * strict superset of `installationUsers`' membership. See `NewSignupRow`.\n */\n newSignups: AdminOverviewList<NewSignupRow>;\n pixelInstallations: AdminOverviewList<PixelInstallationRow>;\n leads: AdminOverviewList<LeadRow>;\n exclusionAudit: ExclusionAuditRow[];\n}\n\n/** Everything the UI needs to explain the numbers, including every methodology caveat in `warnings`. */\nexport interface AdminOverviewMeta {\n generatedAt: string;\n window: AdminOverviewWindow;\n windowStart: string;\n windowEnd: string;\n /** The compareTo date the deltas were computed against, or null when no compareTo was given. */\n previousSnapshotAt: string | null;\n partial: boolean;\n failedSections: AdminOverviewSection[];\n warnings: string[];\n exclusions: { version: string; hash: string; buckets: ExclusionBucket[] };\n cache: { status: AdminOverviewCacheStatus; ageSeconds: number | null };\n rollupFreshness: { refreshedAt: string | null; fresh: boolean; ageSeconds: number | null };\n durationsMs: Partial<Record<AdminOverviewSection | 'total', number>>;\n}\n\n/** The full GET /api/admin/overview payload. */\nexport interface AdminOverviewResponse {\n ladder: AdminOverviewLadder;\n installations: AdminOverviewInstallations;\n traffic: AdminOverviewTraffic;\n lists: AdminOverviewLists;\n hiAi: AdminOverviewHiAi;\n meta: AdminOverviewMeta;\n}\n","/**\n * API Route Context Types\n *\n * Common types for API route contexts and parameters\n * Used across all API endpoints for consistency\n */\n\n// Generic request/response types to avoid Next.js dependency\nexport interface GenericRequest {\n method?: string;\n url?: string;\n headers?: Record<string, string>;\n body?: unknown;\n nextUrl?: {\n searchParams: URLSearchParams;\n };\n}\n\nexport interface GenericResponse {\n status?: number;\n headers?: Record<string, string>;\n body?: unknown;\n}\n\nexport type RouteParamValue = string | string[];\nexport type RouteParams = Record<string, RouteParamValue>;\n\nexport interface NextRouteContext<TParams extends RouteParams = RouteParams> {\n params: Promise<TParams>;\n}\n\nexport interface OptionalNextRouteContext<TParams extends RouteParams = RouteParams> {\n params?: Promise<TParams>;\n}\n\nexport type RouteParamsFromContext<TContext> = TContext extends {\n params: Promise<infer TParams extends RouteParams>;\n}\n ? TParams\n : TContext extends { params?: Promise<infer TParams extends RouteParams> }\n ? TParams\n : RouteParams;\n\n/**\n * Base Route Context\n * Foundation for all route context types\n */\nexport interface BaseRouteContext {\n params: Record<string, string>;\n}\n\n/**\n * Authenticated Route Context\n * Used for routes that require authentication\n */\nexport interface AuthenticatedRouteContext extends BaseRouteContext {\n auth: {\n userId: string;\n organizationId?: string;\n role?: string;\n };\n}\n\n/**\n * Project Route Context\n * Used for project-specific API routes\n */\nexport interface ProjectRouteContext extends AuthenticatedRouteContext {\n params:\n | {\n id: string;\n }\n | {\n projectId: string;\n };\n}\n\n/**\n * API Key Route Context\n * Used for API key management routes\n */\nexport interface ApiKeyRouteContext extends AuthenticatedRouteContext {\n params:\n | {\n id: string;\n }\n | {\n apiKeyId: string;\n };\n}\n\n/**\n * Pixel Route Context\n * Used for pixel management routes\n */\nexport interface PixelRouteContext extends AuthenticatedRouteContext {\n params: {\n pixelId: string;\n };\n}\n\n/**\n * Organization Route Context\n * Used for organization-specific routes\n */\nexport interface OrganizationRouteContext extends AuthenticatedRouteContext {\n params: {\n organizationId: string;\n };\n}\n\n/**\n * User Route Context\n * Used for user-specific routes\n */\nexport interface UserRouteContext extends AuthenticatedRouteContext {\n params: {\n userId?: string;\n };\n}\n\n/**\n * Detection Route Context\n * Used for detection-related routes\n */\nexport interface DetectionRouteContext extends AuthenticatedRouteContext {\n params: {\n projectId: string;\n detectionId?: string;\n };\n}\n\n/**\n * Analytics Route Context\n * Used for analytics routes\n */\nexport interface AnalyticsRouteContext extends AuthenticatedRouteContext {\n params: {\n projectId?: string;\n pixelId?: string;\n };\n}\n\n/**\n * Route Handler Type Definitions\n * Standard handler signatures for different route types\n */\nexport type RouteHandler<\n TContext = BaseRouteContext,\n TRequest = GenericRequest,\n TResponse = GenericResponse,\n> = (request: TRequest, context: TContext) => Promise<TResponse>;\n\nexport type AuthenticatedRouteHandler = RouteHandler<AuthenticatedRouteContext>;\nexport type ProjectRouteHandler = RouteHandler<ProjectRouteContext>;\nexport type ApiKeyRouteHandler = RouteHandler<ApiKeyRouteContext>;\nexport type PixelRouteHandler = RouteHandler<PixelRouteContext>;\nexport type OrganizationRouteHandler = RouteHandler<OrganizationRouteContext>;\nexport type UserRouteHandler = RouteHandler<UserRouteContext>;\nexport type DetectionRouteHandler = RouteHandler<DetectionRouteContext>;\nexport type AnalyticsRouteHandler = RouteHandler<AnalyticsRouteContext>;\n\n/**\n * API Error Codes\n * Standard error codes used across all API endpoints\n */\nexport const API_ERROR_CODES = {\n // Authentication & Authorization\n UNAUTHORIZED: 'UNAUTHORIZED',\n FORBIDDEN: 'FORBIDDEN',\n INVALID_TOKEN: 'INVALID_TOKEN',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n\n // Validation\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n INVALID_INPUT: 'INVALID_INPUT',\n MISSING_PARAMETER: 'MISSING_PARAMETER',\n\n // Resources\n NOT_FOUND: 'NOT_FOUND',\n ALREADY_EXISTS: 'ALREADY_EXISTS',\n CONFLICT: 'CONFLICT',\n\n // Rate Limiting\n RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',\n QUOTA_EXCEEDED: 'QUOTA_EXCEEDED',\n\n // Server Errors\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n SERVICE_UNAVAILABLE: 'SERVICE_UNAVAILABLE',\n DATABASE_ERROR: 'DATABASE_ERROR',\n\n // Business Logic\n INSUFFICIENT_PERMISSIONS: 'INSUFFICIENT_PERMISSIONS',\n OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED',\n RESOURCE_LIMIT_EXCEEDED: 'RESOURCE_LIMIT_EXCEEDED',\n} as const;\n\nexport type ApiErrorCode = (typeof API_ERROR_CODES)[keyof typeof API_ERROR_CODES];\n\n/**\n * HTTP Status Codes\n * Standard HTTP status codes used in API responses\n */\nexport const HTTP_STATUS = {\n // Success\n OK: 200,\n CREATED: 201,\n NO_CONTENT: 204,\n\n // Client Errors\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n CONFLICT: 409,\n UNPROCESSABLE_ENTITY: 422,\n TOO_MANY_REQUESTS: 429,\n\n // Server Errors\n INTERNAL_SERVER_ERROR: 500,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n} as const;\n\nexport type HttpStatus = (typeof HTTP_STATUS)[keyof typeof HTTP_STATUS];\n\n/**\n * API Method Types\n * Standard HTTP methods used in API routes\n */\nexport type ApiMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';\n\n/**\n * Route Configuration\n * Metadata for API route configuration\n */\nexport interface RouteConfig {\n method: ApiMethod;\n path: string;\n auth: boolean;\n rateLimit?: {\n windowMs: number;\n maxRequests: number;\n };\n validation?: {\n params?: Record<string, unknown>;\n query?: Record<string, unknown>;\n body?: Record<string, unknown>;\n };\n permissions?: string[];\n description?: string;\n tags?: string[];\n}\n\n/**\n * API Route Metadata\n * Extended metadata for API documentation\n */\nexport interface ApiRouteMetadata extends RouteConfig {\n operationId: string;\n summary: string;\n description: string;\n responses: Record<\n number,\n {\n description: string;\n schema?: Record<string, unknown>;\n }\n >;\n examples?: Record<string, unknown>;\n}\n\n/**\n * Middleware Context\n * Context passed through middleware chain\n */\nexport interface MiddlewareContext {\n request: GenericRequest;\n response?: GenericResponse;\n auth?: {\n userId: string;\n organizationId?: string;\n role?: string;\n permissions?: string[];\n };\n rateLimit?: {\n remaining: number;\n resetTime: number;\n };\n validation?: {\n params?: Record<string, unknown>;\n query?: Record<string, unknown>;\n body?: Record<string, unknown>;\n };\n startTime: number;\n requestId: string;\n}\n\n/**\n * Pagination Parameters\n * Standard pagination parameters for list endpoints\n */\nexport interface PaginationParams {\n page?: number;\n limit?: number;\n offset?: number;\n sortBy?: string;\n order?: 'asc' | 'desc';\n}\n\n/**\n * Search Parameters\n * Standard search parameters for filtered endpoints\n */\nexport interface SearchParams extends PaginationParams {\n search?: string;\n filter?: Record<string, unknown>;\n include?: string[];\n exclude?: string[];\n}\n\n/**\n * Date Range Parameters\n * Standard date range parameters for time-based queries\n */\nexport interface DateRangeParams {\n startDate?: string;\n endDate?: string;\n timezone?: string;\n}\n\n/**\n * Export Parameters\n * Standard parameters for data export endpoints\n */\nexport interface ExportParams extends DateRangeParams {\n format?: 'json' | 'csv' | 'excel';\n includeHeaders?: boolean;\n includeMetadata?: boolean;\n compression?: 'none' | 'gzip' | 'zip';\n}\n","/**\n * Standard API Response Types\n *\n * Common response type definitions for consistent API responses\n * Complements existing response schemas in src/api/response.ts\n */\n\nimport { z } from 'zod';\nimport type { ApiErrorCode } from './api';\n\n/**\n * Base Success Response\n * Generic success response wrapper\n */\nexport interface SuccessResponse<T = any> {\n success: true;\n data: T;\n meta?: ResponseMeta;\n}\n\n/**\n * Base Error Response\n * Standard error response structure\n */\nexport interface ErrorResponse {\n success: false;\n error: {\n code: ApiErrorCode;\n message: string;\n // Pinned to `any` until a major: this is read by external consumers of\n // the published package, and `unknown` breaks every one of them.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n details?: any;\n field?: string;\n stack?: string; // Only in development\n };\n meta?: ResponseMeta;\n}\n\n/**\n * Generic API Response\n * Union of success and error responses\n */\nexport type ApiResponse<T = any> = SuccessResponse<T> | ErrorResponse;\n\n/**\n * Response Metadata\n * Additional metadata included in responses\n */\nexport interface ResponseMeta {\n timestamp?: string;\n requestId?: string;\n version?: string;\n processingTime?: number;\n rateLimit?: {\n remaining: number;\n resetTime: number;\n limit: number;\n };\n}\n\n/**\n * Pagination Metadata\n * Metadata for paginated responses\n */\nexport interface PaginationMeta {\n page: number;\n limit: number;\n total: number;\n totalPages: number;\n hasMore: boolean;\n hasPrevious: boolean;\n filteredCount?: number; // For client-side filtered results\n}\n\n/**\n * Paginated Response\n * Response wrapper for paginated data\n */\nexport interface PaginatedResponse<T> {\n success: true;\n data: T[];\n pagination: PaginationMeta;\n meta?: ResponseMeta;\n}\n\n/**\n * List Response\n * Response wrapper for simple lists (no pagination)\n */\nexport interface ListResponse<T> {\n success: true;\n data: T[];\n meta?: ResponseMeta & {\n count: number;\n totalAvailable?: number;\n };\n}\n\n/**\n * Created Response\n * Response for resource creation\n */\nexport interface CreatedResponse<T> {\n success: true;\n data: T;\n meta?: ResponseMeta & {\n location?: string; // Resource URL\n };\n}\n\n/**\n * Updated Response\n * Response for resource updates\n */\nexport interface UpdatedResponse<T> {\n success: true;\n data: T;\n meta?: ResponseMeta & {\n changes?: string[]; // List of changed fields\n };\n}\n\n/**\n * Deleted Response\n * Response for resource deletion\n */\nexport interface DeletedResponse {\n success: true;\n data: {\n id: string;\n deletedAt: string;\n };\n meta?: ResponseMeta;\n}\n\n/**\n * Batch Operation Response\n * Response for batch operations\n */\nexport interface BatchResponse<T> {\n success: true;\n data: {\n successful: T[];\n failed: Array<{\n index: number;\n id?: string;\n error: {\n code: ApiErrorCode;\n message: string;\n };\n }>;\n summary: {\n total: number;\n successful: number;\n failed: number;\n };\n };\n meta?: ResponseMeta;\n}\n\n/**\n * Export Response\n * Response for data export operations\n */\nexport interface ExportResponse {\n success: true;\n data: {\n downloadUrl: string;\n filename: string;\n format: string;\n size: number;\n expiresAt: string;\n recordCount: number;\n };\n meta?: ResponseMeta;\n}\n\n/**\n * Validation Error Details\n * Detailed validation error information\n */\nexport interface ValidationErrorDetail {\n field: string;\n message: string;\n code: string;\n // Pinned to `any` until a major (read position, published surface).\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value?: any;\n}\n\n/**\n * Validation Error Response\n * Specialized error response for validation failures\n */\nexport interface ValidationErrorResponse {\n success: false;\n error: {\n code: 'VALIDATION_ERROR';\n message: string;\n details: ValidationErrorDetail[];\n };\n meta?: ResponseMeta;\n}\n\n/**\n * Rate Limit Error Response\n * Specialized error response for rate limit exceeded\n */\nexport interface RateLimitErrorResponse {\n success: false;\n error: {\n code: 'RATE_LIMIT_EXCEEDED';\n message: string;\n details: {\n limit: number;\n remaining: number;\n resetTime: number;\n retryAfter: number;\n };\n };\n meta?: ResponseMeta;\n}\n\n/**\n * Response Schemas for Runtime Validation\n */\n\nexport const ResponseMetaSchema = z.object({\n timestamp: z.string().optional(),\n requestId: z.string().optional(),\n version: z.string().optional(),\n processingTime: z.number().optional(),\n rateLimit: z\n .object({\n remaining: z.number(),\n resetTime: z.number(),\n limit: z.number(),\n })\n .optional(),\n});\n\nexport const PaginationMetaSchema = z.object({\n page: z.number().positive(),\n limit: z.number().positive(),\n total: z.number().nonnegative(),\n totalPages: z.number().nonnegative(),\n hasMore: z.boolean(),\n hasPrevious: z.boolean(),\n filteredCount: z.number().nonnegative().optional(),\n});\n\nexport const SuccessResponseSchema = <T extends z.ZodType>(dataSchema: T) =>\n z.object({\n success: z.literal(true),\n data: dataSchema,\n meta: ResponseMetaSchema.optional(),\n });\n\nexport const ErrorResponseSchema = z.object({\n success: z.literal(false),\n error: z.object({\n code: z.string(),\n message: z.string(),\n details: z.any().optional(),\n field: z.string().optional(),\n stack: z.string().optional(),\n }),\n meta: ResponseMetaSchema.optional(),\n});\n\nexport const PaginatedResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.literal(true),\n data: z.array(itemSchema),\n pagination: PaginationMetaSchema,\n meta: ResponseMetaSchema.optional(),\n });\n\nexport const ListResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.literal(true),\n data: z.array(itemSchema),\n meta: ResponseMetaSchema.extend({\n count: z.number().nonnegative(),\n totalAvailable: z.number().nonnegative().optional(),\n }).optional(),\n });\n\nexport const CreatedResponseSchema = <T extends z.ZodType>(dataSchema: T) =>\n z.object({\n success: z.literal(true),\n data: dataSchema,\n meta: ResponseMetaSchema.extend({\n location: z.string().optional(),\n }).optional(),\n });\n\nexport const UpdatedResponseSchema = <T extends z.ZodType>(dataSchema: T) =>\n z.object({\n success: z.literal(true),\n data: dataSchema,\n meta: ResponseMetaSchema.extend({\n changes: z.array(z.string()).optional(),\n }).optional(),\n });\n\nexport const DeletedResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n id: z.string(),\n deletedAt: z.string().datetime(),\n }),\n meta: ResponseMetaSchema.optional(),\n});\n\nexport const BatchResponseSchema = <T extends z.ZodType>(itemSchema: T) =>\n z.object({\n success: z.literal(true),\n data: z.object({\n successful: z.array(itemSchema),\n failed: z.array(\n z.object({\n index: z.number().nonnegative(),\n id: z.string().optional(),\n error: z.object({\n code: z.string(),\n message: z.string(),\n }),\n })\n ),\n summary: z.object({\n total: z.number().nonnegative(),\n successful: z.number().nonnegative(),\n failed: z.number().nonnegative(),\n }),\n }),\n meta: ResponseMetaSchema.optional(),\n });\n\nexport const ExportResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n downloadUrl: z.string().url(),\n filename: z.string(),\n format: z.string(),\n size: z.number().nonnegative(),\n expiresAt: z.string().datetime(),\n recordCount: z.number().nonnegative(),\n }),\n meta: ResponseMetaSchema.optional(),\n});\n\nexport const ValidationErrorDetailSchema = z.object({\n field: z.string(),\n message: z.string(),\n code: z.string(),\n value: z.any().optional(),\n});\n\nexport const ValidationErrorResponseSchema = z.object({\n success: z.literal(false),\n error: z.object({\n code: z.literal('VALIDATION_ERROR'),\n message: z.string(),\n details: z.array(ValidationErrorDetailSchema),\n }),\n meta: ResponseMetaSchema.optional(),\n});\n\nexport const RateLimitErrorResponseSchema = z.object({\n success: z.literal(false),\n error: z.object({\n code: z.literal('RATE_LIMIT_EXCEEDED'),\n message: z.string(),\n details: z.object({\n limit: z.number().positive(),\n remaining: z.number().nonnegative(),\n resetTime: z.number().positive(),\n retryAfter: z.number().positive(),\n }),\n }),\n meta: ResponseMetaSchema.optional(),\n});\n\n/**\n * Response Helper Functions\n */\n\n/**\n * Create a success response\n */\nexport function createSuccessResponse<T>(data: T, meta?: ResponseMeta): SuccessResponse<T> {\n return {\n success: true,\n data,\n meta,\n };\n}\n\n/**\n * Create an error response\n */\nexport function createErrorResponse(\n code: ApiErrorCode,\n message: string,\n details?: unknown,\n meta?: ResponseMeta\n): ErrorResponse {\n return {\n success: false,\n error: {\n code,\n message,\n details,\n },\n meta,\n };\n}\n\n/**\n * Create a paginated response\n */\nexport function createPaginatedResponse<T>(\n data: T[],\n pagination: PaginationMeta,\n meta?: ResponseMeta\n): PaginatedResponse<T> {\n return {\n success: true,\n data,\n pagination,\n meta,\n };\n}\n\n/**\n * Create a validation error response\n */\nexport function createValidationErrorResponse(\n message: string,\n details: ValidationErrorDetail[],\n meta?: ResponseMeta\n): ValidationErrorResponse {\n return {\n success: false,\n error: {\n code: 'VALIDATION_ERROR',\n message,\n details,\n },\n meta,\n };\n}\n","/**\n * Utilities for converting between DetectionClass discriminated union and database enum\n */\n\nimport type { DetectionClass } from '../core/detection';\n\n// Database enum values (post-migration 0029)\n// Legacy values ('automation', 'unknown') are handled in conversion functions for backwards compatibility\nexport type DetectionClassEnum = 'human' | 'ai_agent' | 'bot' | 'incomplete_data';\n\n/**\n * Convert DetectionClass discriminated union to database enum string\n * Note: Automation and Unknown are legacy types, converted to Bot and IncompleteData respectively\n */\nexport function detectionClassToEnum(detectionClass: DetectionClass): DetectionClassEnum {\n switch (detectionClass.type) {\n case 'Human':\n return 'human';\n case 'AiAgent':\n return 'ai_agent';\n case 'Automation':\n // Legacy: Automation → Bot (migration 0029)\n return 'bot';\n case 'Bot':\n return 'bot';\n case 'IncompleteData':\n return 'incomplete_data';\n case 'Unknown':\n default:\n // Legacy: Unknown → IncompleteData (migration 0029)\n return 'incomplete_data';\n }\n}\n\n/**\n * Convert database enum string to DetectionClass discriminated union\n * Handles both current and legacy enum values for backwards compatibility\n */\nexport function enumToDetectionClass(enumValue: DetectionClassEnum | string): DetectionClass {\n switch (enumValue) {\n case 'human':\n return { type: 'Human' };\n case 'ai_agent':\n return { type: 'AiAgent' };\n case 'automation':\n // Legacy value: convert to Bot for consistency\n return { type: 'Bot' };\n case 'bot':\n return { type: 'Bot' };\n case 'incomplete_data':\n return { type: 'IncompleteData' };\n case 'unknown':\n // Legacy value: convert to IncompleteData for consistency\n return { type: 'IncompleteData' };\n default:\n return { type: 'IncompleteData' };\n }\n}\n\n/**\n * Check if a value is a valid string-based detection class (current or legacy)\n */\nexport function isLegacyDetectionClass(value: unknown): value is DetectionClassEnum {\n return (\n typeof value === 'string' &&\n // Current values + legacy values for backwards compatibility\n ['human', 'ai_agent', 'bot', 'incomplete_data', 'automation', 'unknown'].includes(value)\n );\n}\n\n/**\n * Migrate legacy string detection class to new discriminated union\n * @deprecated Use enumToDetectionClass instead\n */\nexport function migrateLegacyDetectionClass(value: string): DetectionClass {\n return enumToDetectionClass(value);\n}\n\n/**\n * Safely convert any detection class value to the discriminated union format\n */\nexport function normalizeDetectionClass(value: unknown): DetectionClass {\n // If it's already a discriminated union, return as-is\n if (value && typeof value === 'object' && 'type' in value) {\n return value as DetectionClass;\n }\n\n // If it's a valid string enum (current or legacy), convert it\n if (isLegacyDetectionClass(value)) {\n return enumToDetectionClass(value);\n }\n\n // Default fallback (migration 0029)\n return { type: 'IncompleteData' };\n}\n\n/**\n * Safely convert any detection class value to database enum format\n */\nexport function normalizeDetectionClassEnum(value: unknown): DetectionClassEnum {\n // If it's a discriminated union, convert to enum\n if (value && typeof value === 'object' && 'type' in value) {\n return detectionClassToEnum(value as DetectionClass);\n }\n\n // If it's a valid string enum (current or legacy), convert to current enum\n if (isLegacyDetectionClass(value)) {\n // Convert through discriminated union to handle legacy values properly\n return detectionClassToEnum(enumToDetectionClass(value));\n }\n\n // Default fallback (migration 0029)\n return 'incomplete_data';\n}\n","/**\n * Display-time Claude runtime delineation.\n *\n * The user-visible problem: every Claude assistant runtime — Claude Code (the\n * CLI), Claude on the web, the user-initiated fetcher, the search assistant —\n * collapses into one undifferentiated \"Claude\" row, so the dashboard can't tell\n * an operator *which* Claude touched their site. The ratified taxonomy north-star\n * (`docs/architecture/agent-identity-taxonomy.md` §3.1) is explicit that this is\n * \"one product, one vendor, three runtimes — NOT three catalog rows.\" So we do\n * NOT split `agent_types`; we refine the *rendered* label from the request's\n * User-Agent at display time.\n *\n * Pure and display-only: these helpers MUST NEVER influence `category` /\n * `detection_class` / classification — they only change the string shown to a\n * human. Keyed off the real `anthropic-claude` SSOT tokens in\n * `constants/agents.ts`; mirrors the UA→variant precedent in\n * `apps/web/lib/agents/canonical-ids.ts` (which already splits claude-code vs\n * claude-desktop for the connect flow).\n *\n * @module utils/agent-runtime-label\n */\n\n/** Canonical display name of the single Claude product row (SSOT `anthropic-claude`, name: 'Claude'). */\nconst CLAUDE_CANONICAL_DISPLAY = 'Claude';\n\n/**\n * The retired-duplicate Claude twin keeps `display_name` of the form\n * \"Claude (deprecated duplicate — see <uuid>)\" (only its `name` slug is mutated\n * with `-DEPRECATED-`). Per-event surfaces that aren't WHERE-guarded can still\n * render a historical detection FK'd to it, so the gate matches the twin too —\n * refining it cleans the ugly label down to a real runtime label.\n */\nconst CLAUDE_DEPRECATED_TWIN = /^Claude \\(deprecated/i;\n\n/**\n * True when a *displayed* agent label refers to the canonical Claude product\n * (or its retired twin). Deliberately does NOT match the separate catalog rows\n * \"ClaudeBot\" (training crawler) or \"Anthropic AI Crawler\" — those are distinct\n * agents, not Claude runtimes, and must keep their own labels.\n */\nexport function isClaudeProductLabel(displayName: string | null | undefined): boolean {\n if (!displayName) return false;\n const d = displayName.trim();\n return d === CLAUDE_CANONICAL_DISPLAY || CLAUDE_DEPRECATED_TWIN.test(d);\n}\n\n/**\n * The Claude UA-token vocabulary, exported so KYA-1099's runtime_surface\n * derivation (`apps/web/lib/services/detections/claude-runtime-surface.ts`)\n * shares this ONE tokenization with the display label above, rather than\n * hand-copying the token list into a second, independently-maintained regex.\n * Case-insensitive; `userAgent` is lowercased once per call.\n */\nexport function hasClaudeCodeToken(userAgent: string | null | undefined): boolean {\n const ua = (userAgent ?? '').toLowerCase();\n return ua.includes('claude-code') || ua.includes('claude code');\n}\n\nexport function hasClaudeUserToken(userAgent: string | null | undefined): boolean {\n return (userAgent ?? '').toLowerCase().includes('claude-user');\n}\n\nexport function hasClaudeSearchBotToken(userAgent: string | null | undefined): boolean {\n return (userAgent ?? '').toLowerCase().includes('claude-searchbot');\n}\n\n/**\n * Map a Claude request's User-Agent (plus, KYA-1099, the persisted\n * `detections.runtime_surface`) to its runtime sub-label. Always returns a\n * \"Claude…\"-prefixed string (never a non-Claude label), so a caller that has\n * already established the agent is Claude can use the result directly.\n *\n * Token source (`constants/agents.ts` `anthropic-claude.patterns`):\n * - `claude-code` AND `Claude-User` (Claude Code's OWN WebFetch UA embeds\n * both) → \"Claude Code (web fetch)\"\n * - `claude-code` / `claude code` alone → \"Claude Code\" (the CLI)\n * - `Claude-SearchBot` → \"Claude SearchBot\"\n * - `Claude-User` alone → \"Claude (web fetch)\" (assistant browsing for a user)\n * - `Claude-Web` / model UAs / unknown → \"Claude\"\n *\n * `runtimeSurface` (KYA-1099 W1/W2, optional — existing callers compile\n * unchanged) is consulted ONLY when none of the UA tokens above matched: a\n * plain `curl`/`Wget` (or Claude Desktop) request carries no\n * Claude-identifying UA token at all — including an EMPTY UA, checked here\n * too (Bugbot KYA-1099 review: an empty UA used to short-circuit to bare\n * \"Claude\" before runtimeSurface was ever read; KYA-1099 W7's session-grain\n * rows have no UA at ALL, so this path is their only signal) — so a request\n * that a VERIFIED delegation (not a UA guess — see\n * `resolve-delegation-rung-agent-type.ts`) resolved to Claude still gets a\n * runtime-flavored label:\n * - `runtimeSurface === 'cli'` AND UA starts with `curl/` → \"Claude Code (curl)\"\n * - `runtimeSurface === 'cli'` AND UA starts with `Wget/`/`wget/` → \"Claude Code (wget)\"\n * - `runtimeSurface === 'cli'`, anything else → \"Claude Code\"\n * - `runtimeSurface === 'native_app'` → \"Claude Desktop\"\n * - `runtimeSurface === 'browser'` → \"Claude (browser)\"\n *\n * The `claude-cowork` branch is DORMANT (Part C, capture-first): Claude Cowork\n * has no published User-Agent as of 2026-06 (it runs in a sandboxed VM behind a\n * MITM proxy; absent from Anthropic's crawler docs). The branch is keyed on a\n * placeholder token and must be reconfirmed against real traffic before it can\n * fire on anything live.\n */\nexport function claudeRuntimeLabel(\n userAgent: string | null | undefined,\n runtimeSurface?: string | null\n): string {\n const ua = (userAgent ?? '').toLowerCase();\n if (ua) {\n const hasClaudeCode = hasClaudeCodeToken(ua);\n const hasClaudeUser = hasClaudeUserToken(ua);\n if (hasClaudeCode && hasClaudeUser) return 'Claude Code (web fetch)';\n if (hasClaudeCode) return 'Claude Code';\n if (ua.includes('claude-cowork')) return 'Claude Cowork'; // Part C: placeholder token, capture-first\n if (hasClaudeSearchBotToken(ua)) return 'Claude SearchBot';\n if (hasClaudeUser) return 'Claude (web fetch)';\n }\n if (runtimeSurface === 'cli') {\n if (ua.startsWith('curl/')) return 'Claude Code (curl)';\n if (ua.startsWith('wget/')) return 'Claude Code (wget)';\n return 'Claude Code';\n }\n if (runtimeSurface === 'native_app') return 'Claude Desktop';\n // KYA-1099 W7 — session rows have no UA at all (the carrier is the only\n // signal), so 'browser' needs its own label here too, not just 'cli'/\n // 'native_app'.\n if (runtimeSurface === 'browser') return 'Claude (browser)';\n return 'Claude';\n}\n\n/**\n * Refine a displayed agent label: when it's the canonical Claude product (or its\n * retired twin), return the UA-derived (+ KYA-1099 runtime_surface-derived)\n * runtime sub-label; otherwise return the label unchanged. Idempotent —\n * re-applying to an already-refined label (e.g. \"Claude Code\") is a no-op,\n * because the gate fires only on exact \"Claude\" or the deprecated twin.\n * Preserves `null` / `undefined` so it can sit directly on a nullable display\n * column. `runtimeSurface` is optional and additive — existing 2-arg call\n * sites compile and behave unchanged.\n */\nexport function refineClaudeDisplayLabel<T extends string | null | undefined>(\n displayName: T,\n userAgent: string | null | undefined,\n runtimeSurface?: string | null\n): T | string {\n return isClaudeProductLabel(displayName)\n ? claudeRuntimeLabel(userAgent, runtimeSurface)\n : displayName;\n}\n\n/**\n * `refineClaudeDisplayLabel` for a SESSION-grain row (KYA-1099 W7):\n * `unified_agent_sessions` carries no raw User-Agent at all, so every\n * session-row read path (`activity-lens.service.ts`, `recent-agent-sessions\n * .service.ts`, `agent-session-detail.service.ts`) was pinning `userAgent` to\n * `null` at the call site. Pinning it here instead means each of those three\n * call sites, and any future one, can't accidentally pass a stale/wrong UA to\n * a session-grain row.\n */\nexport function refineSessionGrainClaudeLabel<T extends string | null | undefined>(\n displayName: T,\n runtimeSurface: string | null | undefined\n): T | string {\n return refineClaudeDisplayLabel(displayName, null, runtimeSurface);\n}\n","/**\n * Runtime-agnostic Cloudflare bot-management signal resolution.\n *\n * Ports the client-ip.ts trust-policy pattern (#4814) to bot signals, for\n * the class of bug PR #4269 shipped and #4282 reverted same-day: #4269 set\n * `KYA-CF-Bot-Score`/`KYA-CF-Verified-Bot` headers on the gateway's\n * origin-bound proxy request, then read them back from a completely\n * different request object (the ingest API call) — a header handoff across\n * a trust boundary. It also treated Cloudflare's bot score `0` as the\n * strongest possible bot signal, when Cloudflare defines `0` as \"Bot\n * Management did not run for this request,\" not \"confirmed bot.\"\n *\n * Same-request-object rule: this resolver only ever consumes the candidate\n * object the trusted runtime handed the CALLER directly (`request.cf` on a\n * Cloudflare Worker) — never a value forwarded via a header on a different\n * request object. Callers must pass their own `request.cf` straight through,\n * not something re-derived from headers.\n */\n\nexport type BotSignalsSource = 'cloudflare-bot-management' | 'explicit' | 'none';\n\nexport interface BotSignalsResolution {\n /**\n * 1-99 only. Cloudflare defines `0` as \"not computed\" (Bot Management\n * didn't run), not \"confirmed bot\" — `0` and any out-of-range value\n * normalize to `undefined` here, never surfaced as a real score.\n */\n score?: number;\n verifiedBot?: boolean;\n ja4?: string;\n asn?: number;\n asOrganization?: string;\n source: BotSignalsSource;\n}\n\nexport type BotSignalsTrustPolicy =\n | { platform: 'cloudflare' }\n | { platform: 'vercel' }\n | { platform: 'trusted-proxy' }\n | { platform: 'direct' };\n\n/**\n * The subset of Cloudflare's `request.cf` this resolver reads. Pass\n * `request.cf` (or an equivalent test double) directly — `botManagement`\n * only populates when Bot Management is enabled on the zone; `asn`/\n * `asOrganization` are separate top-level `request.cf` fields, not nested\n * inside `botManagement`.\n */\nexport interface CloudflareRequestCf {\n botManagement?: {\n score?: number;\n verifiedBot?: boolean;\n ja4?: string;\n } | null;\n asn?: number | null;\n asOrganization?: string | null;\n}\n\nexport interface ResolveBotSignalsInput {\n /**\n * `request.cf` from the SAME request object being classified. Cloudflare\n * is the only platform with a bot-management surface today — no\n * framework-provided equivalent exists yet on Vercel/Express/etc., so\n * this is the sole real candidate source; `policy` still selects per\n * runtime so a future platform's equivalent slots in without a redesign.\n */\n cloudflareRequestCf?: CloudflareRequestCf | null;\n /** Only honored when the caller has independently authenticated it (tests). */\n explicitBotSignals?: Omit<BotSignalsResolution, 'source'> | null;\n explicitBotSignalsTrusted?: boolean;\n policy: BotSignalsTrustPolicy;\n}\n\n/** Cloudflare bot score: only 1-99 are real values; 0 or out-of-range normalize to absent. */\nfunction normalizeBotScore(raw: number | null | undefined): number | undefined {\n if (typeof raw !== 'number' || !Number.isFinite(raw) || !Number.isInteger(raw)) return undefined;\n if (raw < 1 || raw > 99) return undefined;\n return raw;\n}\n\nfunction normalizeVerifiedBot(raw: boolean | null | undefined): boolean | undefined {\n return typeof raw === 'boolean' ? raw : undefined;\n}\n\nfunction normalizeString(raw: string | null | undefined): string | undefined {\n return raw && raw.length > 0 ? raw : undefined;\n}\n\nfunction normalizeAsn(raw: number | null | undefined): number | undefined {\n return typeof raw === 'number' && Number.isFinite(raw) && Number.isInteger(raw) && raw > 0\n ? raw\n : undefined;\n}\n\nfunction resolveExplicit(input: ResolveBotSignalsInput): BotSignalsResolution | null {\n if (input.explicitBotSignalsTrusted !== true || !input.explicitBotSignals) return null;\n const explicit = input.explicitBotSignals;\n return {\n score: normalizeBotScore(explicit.score),\n verifiedBot: normalizeVerifiedBot(explicit.verifiedBot),\n ja4: normalizeString(explicit.ja4),\n asn: normalizeAsn(explicit.asn),\n asOrganization: normalizeString(explicit.asOrganization),\n source: 'explicit',\n };\n}\n\nfunction resolveCloudflare(input: ResolveBotSignalsInput): BotSignalsResolution {\n const cf = input.cloudflareRequestCf;\n if (!cf) return { source: 'none' };\n\n return {\n score: normalizeBotScore(cf.botManagement?.score),\n verifiedBot: normalizeVerifiedBot(cf.botManagement?.verifiedBot),\n ja4: normalizeString(cf.botManagement?.ja4),\n asn: normalizeAsn(cf.asn),\n asOrganization: normalizeString(cf.asOrganization),\n source: 'cloudflare-bot-management',\n };\n}\n\n/** Resolve bot signals using an explicit deployment trust profile. */\nexport function resolveBotSignals(input: ResolveBotSignalsInput): BotSignalsResolution {\n const explicit = resolveExplicit(input);\n if (explicit) return explicit;\n\n switch (input.policy.platform) {\n case 'cloudflare':\n return resolveCloudflare(input);\n case 'vercel':\n case 'trusted-proxy':\n case 'direct':\n // No bot-management (or equivalent) surface on these platforms today —\n // resolves cleanly absent rather than guessing at a shape that doesn't\n // exist yet. Add a resolve function here if/when one does.\n return { source: 'none' };\n }\n}\n","/**\n * Isomorphic request correlation-id derivation.\n *\n * Every detection surface — the Cloudflare gateway worker, the published SDK\n * middleware (Next.js / Express), the Next.js detector route, and the browser\n * beacon — needs the SAME canonical id for a request so its records can be\n * correlated across surfaces. This module is the single producer of that id:\n * one 32-hex `correlation_id` derived from request headers, with a fixed\n * precedence and a guaranteed-valid output.\n *\n * Precedence (first match wins):\n * 1. W3C `traceparent` trace-id (the 32-hex middle segment), rejecting the\n * all-zero \"invalid\" sentinel,\n * 2. the `x-kya-correlation-id` header,\n * 3. a caller-provided `fallback` (e.g. an existing per-surface request id),\n * 4. a freshly minted UUIDv4 (dashes stripped → 32-hex).\n *\n * Edge/Node/browser safe: the mint path uses `globalThis.crypto.randomUUID`,\n * available on Node 18+, Cloudflare Workers, and browsers. Header lookup accepts\n * a `Headers` instance OR a plain record (case-insensitive), so it works on\n * every surface without callers pre-normalizing.\n */\n\nimport { z } from 'zod';\n\n/** Header carrying our canonical 32-hex correlation id between surfaces. */\nexport const CORRELATION_ID_HEADER = 'x-kya-correlation-id';\n\n/** Canonical stored shape: 32 lowercase hex chars. */\nexport const CorrelationIdSchema = z.string().regex(/^[0-9a-f]{32}$/);\n\n/**\n * W3C `traceparent` grammar: `version-traceId-spanId-flags`.\n * Only `trace` is used downstream; `ver`/`span`/`flags` are matched but ignored.\n */\nconst TRACEPARENT_RE =\n /^(?<ver>[0-9a-f]{2})-(?<trace>[0-9a-f]{32})-(?<span>[0-9a-f]{16})-(?<flags>[0-9a-f]{2})$/;\n\n/** The W3C \"invalid\" trace-id sentinel — must never be used as a correlation id. */\nconst ZERO_TRACE_ID = '0'.repeat(32);\n\n/**\n * Case-insensitive single-header lookup over both a `Headers` instance and a\n * plain record. For a record, keys are matched case-insensitively and a\n * `string[]` value resolves to its first element. Returns `null` for a missing\n * or empty value.\n */\nfunction getHeader(\n headers: Headers | Record<string, string | string[] | undefined>,\n name: string\n): string | null {\n const lower = name.toLowerCase();\n\n if (typeof (headers as Headers).get === 'function') {\n const value = (headers as Headers).get(lower);\n return value && value.length > 0 ? value : null;\n }\n\n const record = headers as Record<string, string | string[] | undefined>;\n for (const key of Object.keys(record)) {\n if (key.toLowerCase() !== lower) continue;\n const raw = record[key];\n const value = Array.isArray(raw) ? raw[0] : raw;\n return value && value.length > 0 ? value : null;\n }\n return null;\n}\n\n/**\n * Normalize any candidate to canonical 32-hex (lowercase, dashes stripped) or\n * `null` if it does not validate. Both bare 32-hex strings and dashed UUIDs\n * funnel through here.\n */\nfunction normalizeHex(value: string | null | undefined): string | null {\n if (typeof value !== 'string' || value.length === 0) return null;\n const candidate = value.toLowerCase().replace(/-/g, '');\n const parsed = CorrelationIdSchema.safeParse(candidate);\n return parsed.success ? parsed.data : null;\n}\n\n/**\n * Extract the trace-id from a `traceparent` value, or `null` when it is absent,\n * malformed, or carries the all-zero invalid sentinel. The extracted trace-id is\n * already canonical 32 lowercase hex by the grammar.\n */\nfunction extractTraceId(traceparent: string | null): string | null {\n if (!traceparent) return null;\n const match = TRACEPARENT_RE.exec(traceparent);\n const trace = match?.groups?.trace;\n if (!trace || trace === ZERO_TRACE_ID) return null;\n return trace;\n}\n\n/**\n * Normalize any candidate to 32-hex, or `null` if it isn't valid. Lowercases and\n * strips dashes (so a canonical UUID is accepted) before validating against\n * {@link CorrelationIdSchema}.\n */\nexport function toStoredCorrelationId(value: string | null | undefined): string | null {\n return normalizeHex(value);\n}\n\n/**\n * Derive the correlation id for a request, by precedence:\n * 1. W3C `traceparent` trace-id (the 32-hex middle segment; reject the\n * all-zero \"invalid\" sentinel),\n * 2. `x-kya-correlation-id` header,\n * 3. the provided `fallback` (e.g. an existing per-surface request id),\n * 4. a freshly minted UUIDv4 (dashes stripped → 32-hex).\n * Always returns a valid 32-hex string. Accepts a `Headers` instance OR a\n * plain record (case-insensitive lookup) so it works on every surface.\n *\n * NOTE on a client-supplied BODY id: `fallback` is the LOWEST trusted source\n * (below transport `traceparent` / header). Surfaces vary intentionally on where\n * a client-body correlation id sits: the pixel surfaces (pixel identify / track,\n * log-detection) trust their own SDK's body id ABOVE traceparent — they pass it\n * as a pre-check, not via `fallback` — while bouncer (proof.service) trusts the\n * inbound transport `traceparent` over a client claim and passes the body id AS\n * the `fallback`. That asymmetry is a deliberate per-surface trust decision, not\n * a uniform rule — match the surface's existing pattern when adding a caller.\n */\n/**\n * Extract a correlation id that was PROPAGATED on the request headers (W3C\n * `traceparent` trace-id, else `x-kya-correlation-id`), or `null` when neither\n * is present. Unlike {@link deriveCorrelationId} this NEVER falls back or mints —\n * use it when a minted id would be useless, e.g. an alias anchor that must match\n * an id actually stamped on another surface's row rather than a fresh orphan.\n */\nexport function extractCorrelationIdFromHeaders(\n headers: Headers | Record<string, string | string[] | undefined>\n): string | null {\n const fromTrace = extractTraceId(getHeader(headers, 'traceparent'));\n if (fromTrace) return fromTrace;\n\n return normalizeHex(getHeader(headers, CORRELATION_ID_HEADER));\n}\n\nexport function deriveCorrelationId(\n headers: Headers | Record<string, string | string[] | undefined>,\n fallback?: string | null\n): string {\n const fromHeaders = extractCorrelationIdFromHeaders(headers);\n if (fromHeaders) return fromHeaders;\n\n const fromFallback = normalizeHex(fallback);\n if (fromFallback) return fromFallback;\n\n return globalThis.crypto.randomUUID().replace(/-/g, '').toLowerCase();\n}\n","/**\n * Authentication Validation Schemas\n *\n * Zod schemas for validating authentication-related data\n * Used across the application for consistent validation\n */\n\nimport { z } from 'zod';\n\n/**\n * Base password validation schema\n * Enforces password security requirements\n */\nexport const passwordSchema = z\n .string()\n .min(8, 'Password must be at least 8 characters long')\n .max(128, 'Password must not exceed 128 characters')\n .regex(\n /^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)/,\n 'Password must contain at least one lowercase letter, one uppercase letter, and one number'\n );\n\n/**\n * Sign in validation schema\n */\nexport const signInSchema = z.object({\n email: z.string().email('Invalid email address'),\n password: z.string().min(1, 'Password is required'),\n});\n\n/**\n * Sign up validation schema\n */\nexport const signUpSchema = z\n .object({\n email: z.string().email('Invalid email address'),\n name: z.string().optional(),\n password: passwordSchema,\n confirmPassword: z.string(),\n })\n .refine((data) => data.password === data.confirmPassword, {\n message: \"Passwords don't match\",\n path: ['confirmPassword'],\n });\n\n/**\n * Password reset request validation schema\n */\nexport const forgotPasswordSchema = z.object({\n email: z.string().email('Invalid email address'),\n});\n\n/**\n * Password reset confirmation validation schema\n * Validates token and ensures passwords match\n */\nexport const resetPasswordSchema = z\n .object({\n token: z.string().min(1, 'Token is required'),\n password: passwordSchema,\n confirmPassword: z.string(),\n })\n .refine((data) => data.password === data.confirmPassword, {\n message: \"Passwords don't match\",\n path: ['confirmPassword'],\n });\n\n/**\n * Change password validation schema\n * For authenticated users changing their password\n */\nexport const changePasswordSchema = z\n .object({\n currentPassword: z.string().optional(), // Optional for OAuth users setting first password\n newPassword: passwordSchema,\n confirmPassword: z.string(),\n })\n .refine((data) => data.newPassword === data.confirmPassword, {\n message: \"Passwords don't match\",\n path: ['confirmPassword'],\n });\n\n/**\n * Email verification validation schema\n */\nexport const verifyEmailSchema = z.object({\n token: z.string().min(1, 'Token is required'),\n});\n\n/**\n * Type exports for use in TypeScript\n */\nexport type SignInData = z.infer<typeof signInSchema>;\nexport type SignUpData = z.infer<typeof signUpSchema>;\nexport type ForgotPasswordData = z.infer<typeof forgotPasswordSchema>;\nexport type ResetPasswordData = z.infer<typeof resetPasswordSchema>;\nexport type ChangePasswordData = z.infer<typeof changePasswordSchema>;\nexport type VerifyEmailData = z.infer<typeof verifyEmailSchema>;\n","/**\n * Admin API Validation Schemas\n *\n * Schemas for admin-specific endpoints\n * Used for validation and type safety in admin routes\n */\n\nimport { z } from 'zod';\n\n/**\n * Performance recalculation request schema\n * Used for POST /api/admin/organizations/[id]/performance\n */\nexport const PerformanceRecalculationRequestSchema = z.object({\n periodType: z.enum(['daily', 'weekly', 'monthly']).optional().default('weekly'),\n});\nexport type PerformanceRecalculationRequest = z.infer<typeof PerformanceRecalculationRequestSchema>;\n\n/**\n * Growth opportunity status update schema\n * Used for PATCH /api/admin/growth-opportunities\n */\nexport const GrowthOpportunityUpdateSchema = z.object({\n opportunityId: z.string().min(1, 'Opportunity ID is required'),\n status: z.enum(['active', 'contacted', 'converted', 'dismissed']).optional(),\n assignedTo: z.string().nullable().optional(),\n notes: z.string().nullable().optional(),\n priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n dismissedReason: z.string().nullable().optional(),\n});\nexport type GrowthOpportunityUpdate = z.infer<typeof GrowthOpportunityUpdateSchema>;\n\n/**\n * Growth batch identification request schema\n * Used for POST /api/admin/growth-opportunities\n */\nexport const GrowthBatchRequestSchema = z\n .object({\n runBatch: z.boolean().optional().default(false),\n organizationIds: z.array(z.string()).optional(),\n })\n .refine((data) => data.runBatch || (data.organizationIds && data.organizationIds.length > 0), {\n message: 'Either runBatch must be true or organizationIds must be provided',\n });\nexport type GrowthBatchRequest = z.infer<typeof GrowthBatchRequestSchema>;\n\n/**\n * Growth configuration thresholds schema\n * Used for PUT /api/admin/growth-configurations\n */\nexport const GrowthConfigurationThresholdsSchema = z\n .object({\n // Bouncer thresholds\n minAiTrafficRate: z.number().min(0).max(100).optional(),\n highAiTrafficThreshold: z.number().min(0).max(100).optional(),\n aiTrafficSpikeMultiplier: z.number().min(1).optional(),\n consistentHighTrafficDays: z.number().int().min(1).optional(),\n criticalAiTrafficRate: z.number().min(0).max(100).optional(),\n\n // Enterprise thresholds\n highVolumeThreshold: z.number().int().min(1).optional(),\n rapidGrowthRate: z.number().min(0).optional(),\n multiDomainCount: z.number().int().min(1).optional(),\n largeTeamSize: z.number().int().min(1).optional(),\n multiProjectCount: z.number().int().min(1).optional(),\n highPercentileThreshold: z.number().min(0).max(100).optional(),\n minEnterpriseIndicators: z.number().int().min(1).optional(),\n\n // Support thresholds\n minIntegrationMethods: z.number().int().min(1).optional(),\n maxInactivePixels: z.number().int().min(0).optional(),\n inactiveDays: z.number().int().min(1).optional(),\n minSupportIndicators: z.number().int().min(1).optional(),\n criticalSupportScore: z.number().min(0).optional(),\n\n // Integration thresholds\n minSessionsForBenefit: z.number().int().min(1).optional(),\n minAiRateForBenefit: z.number().min(0).max(100).optional(),\n })\n .strict();\nexport type GrowthConfigurationThresholds = z.infer<typeof GrowthConfigurationThresholdsSchema>;\n\n/**\n * Growth configuration update request schema\n */\nexport const GrowthConfigurationUpdateSchema = z.object({\n configType: z.enum(['bouncer', 'enterprise', 'support', 'integration']),\n thresholds: GrowthConfigurationThresholdsSchema,\n});\nexport type GrowthConfigurationUpdate = z.infer<typeof GrowthConfigurationUpdateSchema>;\n\n/**\n * Growth configuration reset request schema\n */\nexport const GrowthConfigurationResetSchema = z.object({\n configType: z.enum(['bouncer', 'enterprise', 'support', 'integration', 'all']),\n});\nexport type GrowthConfigurationReset = z.infer<typeof GrowthConfigurationResetSchema>;\n\n/**\n * Admin query parameters validation\n */\nexport const AdminQueryParamsSchema = z.object({\n limit: z.coerce.number().min(1).max(500).optional().default(100),\n offset: z.coerce.number().min(0).optional().default(0),\n sortBy: z.string().optional(),\n sortOrder: z.enum(['asc', 'desc']).optional().default('desc'),\n});\nexport type AdminQueryParams = z.infer<typeof AdminQueryParamsSchema>;\n\n/**\n * Growth opportunities query parameters\n */\nexport const GrowthOpportunitiesQuerySchema = AdminQueryParamsSchema.extend({\n type: z.enum(['bouncer', 'enterprise', 'support', 'integration']).optional(),\n priority: z.enum(['low', 'medium', 'high', 'critical']).optional(),\n status: z.enum(['active', 'contacted', 'converted', 'dismissed']).optional(),\n assignedTo: z.string().optional(),\n});\nexport type GrowthOpportunitiesQuery = z.infer<typeof GrowthOpportunitiesQuerySchema>;\n\n/**\n * Recommendation query parameters\n * Used for GET /api/admin/recommendations\n */\nexport const RecommendationQuerySchema = z.object({\n organizationId: z.string().min(1).optional(),\n type: z.enum(['bouncer', 'enterprise', 'support', 'integration']).optional(),\n minConfidence: z.coerce.number().min(0).max(1).optional(),\n limit: z.coerce.number().min(1).max(100).optional().default(10),\n});\nexport type RecommendationQuery = z.infer<typeof RecommendationQuerySchema>;\n\n/**\n * Recommendation generation request schema\n * Used for POST /api/admin/recommendations\n */\nexport const RecommendationGenerationSchema = z.object({\n organizationId: z.string().min(1, 'Organization ID is required'),\n forceRefresh: z.boolean().optional().default(false),\n});\nexport type RecommendationGeneration = z.infer<typeof RecommendationGenerationSchema>;\n","/**\n * Wire contract for the Fly gateway's internal tools endpoints\n * (#2029, #2027).\n *\n * Routes:\n * GET /api/gateway/internal/tools/:orgId\n * — org-level aggregated tool list from the 60s cache\n * POST /api/gateway/internal/tools/:orgId/discover\n * — user-scoped single-upstream discovery (Phase 4 #1990)\n *\n * These are Fly → Vercel bodies. The Vercel dashboard's proxy\n * routes and hooks validate incoming responses against these\n * schemas, and the gateway route handlers validate their outgoing\n * body to keep both sides pinned to the same shape.\n */\n\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// Discovered tool (shared shape across endpoints)\n// ---------------------------------------------------------------------------\n\nexport const discoveredToolSchema = z\n .object({\n name: z.string(),\n description: z.string().optional(),\n /**\n * JSON-schema object describing the tool's arguments. Shape\n * comes from the upstream MCP server and varies widely —\n * permissive `record(unknown)` rather than pinning the JSON\n * Schema draft here. The Tool Testing Panel renders a\n * skeleton from whatever it gets.\n */\n inputSchema: z.record(z.string(), z.unknown()).optional(),\n })\n .strict();\n\nexport type DiscoveredTool = z.infer<typeof discoveredToolSchema>;\n\n// ---------------------------------------------------------------------------\n// Per-upstream error — new in #2027's partial-success envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Categorized failure mode for a single upstream during org-level\n * aggregation. The dashboard uses the `code` to drive retry\n * behavior and the user-facing label; `message` surfaces in the\n * tooltip so operators can diagnose.\n */\nexport const upstreamDiscoveryErrorSchema = z\n .object({\n code: z.enum([\n /** Upstream returned 401/403 or the MCP handshake was rejected. */\n 'auth_failed',\n /** Upstream was healthy but refused tools/list (e.g. requires per-user auth). */\n 'per_user_auth_required',\n /** Upstream timed out during the handshake or tools/list call. */\n 'timeout',\n /** MCP handshake failed — protocol negotiation, bad JSON, etc. */\n 'handshake_failed',\n /** Upstream returned a non-MCP error shape we couldn't classify. */\n 'unknown',\n ]),\n message: z.string(),\n /** Upstream HTTP status if we got one. */\n status: z.number().int().optional(),\n })\n .strict();\n\nexport type UpstreamDiscoveryError = z.infer<typeof upstreamDiscoveryErrorSchema>;\n\n// ---------------------------------------------------------------------------\n// GET /api/gateway/internal/tools/:orgId — aggregated list\n// ---------------------------------------------------------------------------\n\n/**\n * Partial-success envelope (#2027). `tools` carries every tool the\n * gateway successfully discovered; `upstreamCounts` is the\n * histogram by slug; `errors` is a sparse map of upstream slug →\n * categorized failure for every upstream that *couldn't* contribute\n * tools this call. An empty `errors` map means full success.\n *\n * Callers render per-upstream error state from `errors` instead of\n * collapsing a failed upstream to a silent `0` count. Before #2027\n * the gateway cached empty results as success and the dashboard\n * had no signal that an upstream was broken.\n */\nexport const gatewayInternalToolsListSchema = z\n .object({\n totalCount: z.number().int().min(0),\n upstreamCounts: z.record(z.string(), z.number().int().min(0)),\n tools: z.array(discoveredToolSchema),\n /**\n * Sparse map keyed by upstream slug. Empty / absent when every\n * upstream contributed successfully. Present as an empty object\n * when serialized — always-object keeps the shape stable for\n * consumers that read `Object.keys(errors).length`.\n */\n errors: z.record(z.string(), upstreamDiscoveryErrorSchema),\n })\n .strict();\n\nexport type GatewayInternalToolsList = z.infer<typeof gatewayInternalToolsListSchema>;\n\n// ---------------------------------------------------------------------------\n// POST /api/gateway/internal/tools/:orgId/discover — user-scoped\n// ---------------------------------------------------------------------------\n\nexport const gatewayInternalDiscoverSuccessSchema = z\n .object({\n tools: z.array(discoveredToolSchema),\n })\n .strict();\n\nexport type GatewayInternalDiscoverSuccess = z.infer<typeof gatewayInternalDiscoverSuccessSchema>;\n\nexport const gatewayInternalDiscoverErrorSchema = z\n .object({\n error: z.string(),\n })\n .strict();\n\nexport type GatewayInternalDiscoverError = z.infer<typeof gatewayInternalDiscoverErrorSchema>;\n","/**\n * Gateway Schemas\n *\n * Zod schemas for gateway configuration, upstream server validation,\n * and tool call audit records.\n *\n * SSRF Protection: The safeUrl validator blocks private/reserved IPs\n * at config time. Runtime DNS resolution checks (in GatewayProxy) are\n * still required to defeat DNS rebinding and redirect-based bypasses.\n */\n\nimport { z } from 'zod';\n\nimport { discoveredToolSchema } from '../wire/gateway-internal-tools';\n\n// ---------------------------------------------------------------------------\n// SSRF-safe URL validator\n// ---------------------------------------------------------------------------\n\n/**\n * Checks whether a hostname or IP string resolves to a private, reserved,\n * or link-local address that must never be used as an upstream target.\n *\n * This is a config-time check on the literal URL string. It does NOT\n * replace runtime DNS resolution validation (needed for DNS rebinding\n * and redirect attacks).\n */\n/**\n * Exported for direct unit testing of the defense-in-depth path. Production\n * code should go through `safeUrl` instead — the WHATWG URL parser does most\n * IPv4 normalization up front, but this function still has to be correct on\n * its own so the blocklist holds if a runtime's URL parser ever changes.\n */\nexport function isPrivateOrReservedHost(hostname: string): boolean {\n const lower = hostname.toLowerCase();\n\n // Block localhost and any *.localhost subdomain.\n // Per RFC 6761 the entire `.localhost` TLD is reserved and compliant\n // resolvers map all names under it to loopback (e.g. evil.localhost → 127.0.0.1).\n if (lower === 'localhost' || lower === 'localhost.') return true;\n if (lower.endsWith('.localhost') || lower.endsWith('.localhost.')) return true;\n\n // Strip IPv6 brackets for uniform parsing\n const bare = lower.startsWith('[') && lower.endsWith(']') ? lower.slice(1, -1) : lower;\n\n // IPv6 loopback\n if (bare === '::1' || bare === '0:0:0:0:0:0:0:1') return true;\n\n // IPv6 unspecified / all-zeros (::) — routes to localhost on most systems,\n // analogous to IPv4 0.0.0.0\n if (bare === '::' || bare === '0:0:0:0:0:0:0:0') return true;\n\n // IPv6 ULA (fc00::/7 → fc00:: – fdff::)\n if (/^f[cd][0-9a-f]{2}:/.test(bare)) return true;\n\n // IPv6 link-local (fe80::/10 → fe80:: – febf::) — direct analog of\n // IPv4 169.254.x.x, same class of bug as reaching the cloud metadata endpoint\n if (/^fe[89ab][0-9a-f]:/.test(bare)) return true;\n\n // IPv4-mapped IPv6 (::ffff:x.x.x.x or ::ffff:0a00:0001 etc.)\n const v4MappedMatch = bare.match(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/);\n if (v4MappedMatch) {\n return isPrivateIPv4(v4MappedMatch[1]);\n }\n // Hex form: ::ffff:XXYY:ZZWW\n const v4MappedHexMatch = bare.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n if (v4MappedHexMatch) {\n const hi = parseInt(v4MappedHexMatch[1], 16);\n const lo = parseInt(v4MappedHexMatch[2], 16);\n const a = (hi >> 8) & 0xff;\n const b = hi & 0xff;\n const c = (lo >> 8) & 0xff;\n const d = lo & 0xff;\n return isPrivateIPv4(`${a}.${b}.${c}.${d}`);\n }\n\n // Dotted-quad IPv4 — per WHATWG URL spec and historical BSD convention,\n // each octet may independently be decimal, octal (leading zero), or hex\n // (`0x` prefix). Examples: `127.0.0.1`, `0177.0.0.01`, `0x7f.0.0.1`,\n // `0177.0x0.0.01`. This unified handler replaces three separate branches\n // that had a subtle ordering bug — the old decimal check matched any\n // string of digit characters, so `0177.0.0.01` fell through and was\n // parsed as decimal 177 instead of octal 127.\n const dottedParts = bare.split('.');\n if (dottedParts.length === 4) {\n const octets: number[] = [];\n let allValid = true;\n for (const part of dottedParts) {\n const n = parseIPv4Octet(part);\n if (n === null || n < 0 || n > 255) {\n allValid = false;\n break;\n }\n octets.push(n);\n }\n if (allValid) {\n return isPrivateIPv4(octets.join('.'));\n }\n }\n\n // Single-integer IPv4 encodings (no dots) — per BSD/WHATWG conventions,\n // a bare 32-bit integer is equivalent to its dotted-quad representation.\n // Examples: `0x7f000001` (hex), `017700000001` (octal), `2130706433` (decimal)\n // all mean `127.0.0.1`.\n //\n // Order matters: hex (`0x` prefix) and octal (leading `0`) must be tested\n // before decimal, otherwise `/^(0|[1-9]\\d*)$/` would eat the literal `0`\n // (harmless but the octal and hex branches have their own shape).\n if (/^0x[0-9a-f]+$/i.test(bare)) {\n const num = parseInt(bare, 16);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n if (/^0[0-7]+$/.test(bare)) {\n const num = parseInt(bare, 8);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n if (/^(0|[1-9]\\d*)$/.test(bare)) {\n const num = parseInt(bare, 10);\n if (num >= 0 && num <= 0xffffffff) {\n return isPrivateIPv4(numToIPv4(num));\n }\n }\n\n return false;\n}\n\n/**\n * Parses a single IPv4 octet in decimal, octal (leading zero), or hex\n * (`0x` prefix). Returns null for anything that isn't a valid octet in any\n * of the three bases. Used by the dotted-quad handler to defeat\n * octal/hex-encoded SSRF bypasses like `0177.0.0.01` → `127.0.0.1`.\n */\nfunction parseIPv4Octet(part: string): number | null {\n if (/^0x[0-9a-f]+$/i.test(part)) {\n const n = parseInt(part, 16);\n return Number.isNaN(n) ? null : n;\n }\n if (/^0[0-7]+$/.test(part)) {\n const n = parseInt(part, 8);\n return Number.isNaN(n) ? null : n;\n }\n if (/^(0|[1-9]\\d*)$/.test(part)) {\n return parseInt(part, 10);\n }\n return null;\n}\n\nfunction isPrivateIPv4(ip: string): boolean {\n const parts = ip.split('.').map(Number);\n if (parts.length !== 4 || parts.some((p) => isNaN(p) || p < 0 || p > 255)) return false;\n\n const [a, b] = parts;\n\n // 0.0.0.0/8 — entire range routes to localhost on Linux/Unix\n if (a === 0) return true;\n\n // 127.0.0.0/8 (loopback)\n if (a === 127) return true;\n\n // 10.0.0.0/8\n if (a === 10) return true;\n\n // 172.16.0.0/12\n if (a === 172 && b >= 16 && b <= 31) return true;\n\n // 192.168.0.0/16\n if (a === 192 && b === 168) return true;\n\n // 169.254.0.0/16 (link-local, includes cloud metadata 169.254.169.254)\n if (a === 169 && b === 254) return true;\n\n // 100.64.0.0/10 (RFC 6598 Shared Address Space / CGNAT) — may reach\n // internal services in AWS VPCs and other cloud environments.\n // Matches the existing blocklist in apps/web/lib/utils/url-security.ts.\n if (a === 100 && b >= 64 && b <= 127) return true;\n\n return false;\n}\n\nfunction numToIPv4(num: number): string {\n return [(num >>> 24) & 0xff, (num >>> 16) & 0xff, (num >>> 8) & 0xff, num & 0xff].join('.');\n}\n\n/**\n * Zod refinement that rejects URLs pointing at private/reserved addresses.\n * Only http and https schemes are permitted.\n */\nexport const safeUrl = z\n .string()\n .url()\n .superRefine((val, ctx) => {\n let parsed: URL;\n try {\n parsed = new URL(val);\n } catch {\n ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Invalid URL' });\n return;\n }\n\n // Scheme allowlist\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Scheme \"${parsed.protocol.replace(':', '')}\" is not allowed; use http or https`,\n });\n return;\n }\n\n if (isPrivateOrReservedHost(parsed.hostname)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL points to a private or reserved IP address',\n });\n }\n });\n\n// ---------------------------------------------------------------------------\n// Slug regex — no consecutive underscores (__ is reserved as namespace sep)\n// ---------------------------------------------------------------------------\n\n/**\n * Upstream slug regex — lowercase alphanumerics with single underscores\n * between groups. No leading/trailing underscores. No consecutive `__`\n * (reserved as the namespace separator in the gateway proxy's\n * `parseNamespacedTool`).\n *\n * Single source of truth. Imported by:\n * - `upstreamServerSchema.slug` (this file) — admin-time validation\n * - `apps/gateway/src/lib/namespace.ts` — `slugify` output contract\n *\n * If this regex ever tightens (e.g. forbid leading digits, require min\n * length), both consumers pick up the change automatically.\n */\nexport const SLUG_REGEX = /^[a-z0-9]+(_[a-z0-9]+)*$/;\n\n// ---------------------------------------------------------------------------\n// Upstream Server Schema\n// ---------------------------------------------------------------------------\n\nexport const upstreamServerSchema = z.object({\n id: z.string().uuid(),\n name: z.string().min(1).max(100),\n slug: z.string().regex(SLUG_REGEX, {\n message:\n 'Slug must be lowercase alphanumeric with single underscores (no consecutive underscores)',\n }),\n url: safeUrl,\n transport: z.enum(['http', 'sse']).default('http'),\n authType: z.enum(['none', 'vault', 'static']).default('none'),\n envVarNames: z.array(z.string()).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Static-header credential plane (hygiene-scorecard gap #1)\n //\n // `staticHeaders` (plaintext) is DEPRECATED as an at-rest field —\n // kept here only so `.parse()` doesn't silently drop rows written\n // before this fix while they wait to be re-encrypted. It remains the\n // wire-input field name (the admin form still submits plaintext\n // header values; the PUT handler encrypts them into\n // `staticHeadersEncrypted` before persisting and opportunistically\n // migrates any legacy plaintext it finds on every save that touches\n // an upstream). Never populated in an API response.\n staticHeaders: z.record(z.string(), z.string()).optional(),\n // AES-256-GCM ciphertext (base64: iv|ciphertext|authTag) of the\n // JSON-serialized staticHeaders map — the at-rest form going\n // forward. Encrypt/decrypt via `@kya-os/checkpoint-db/crypto`'s\n // `encryptStaticHeaders`/`resolveStaticHeaders`. Never populated in\n // an API response — see `staticHeaderKeys` for the redacted view.\n staticHeadersEncrypted: z.string().nullable().optional(),\n // Read-only projection of the configured header NAMES (never\n // values). Populated by the gateway-mcp config GET/PUT response\n // serializer (`redactGatewayConfig`) so the dashboard can render\n // \"N headers configured\" without ever receiving secret material or\n // ciphertext. Ignored on write — `upstreamServerInputSchema` omits it.\n staticHeaderKeys: z.array(z.string()).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // #1600 Phase 1 Part 2 — credential flow method selection\n //\n // `supportedAuthMethods` declares which of the two user-facing\n // credential-entry flows this upstream exposes to end users. The\n // admin picks this at upstream-create time; the user credential\n // modal reads it to decide whether to render the \"Connect GitHub\"\n // OAuth button, the paste-a-token form, or both (hybrid).\n //\n // Default `['paste']` keeps every pre-#1600 upstream row working\n // unchanged on read: the modal shows only the paste form, which\n // is what Bouncer + existing vault-authType upstreams expect.\n //\n // `oauthProvider` is only meaningful when `supportedAuthMethods`\n // includes `'oauth'`. It names a provider in the static registry\n // at `apps/web/lib/gateway/oauth-providers.ts`. Validation here\n // is the narrow enum of known IDs — the same set declared in\n // `OAUTH_PROVIDER_IDS` on the registry side. If a future Phase 3+\n // PR adds Slack/Notion/Linear to the registry, the enum here\n // must expand in lockstep (both are source-controlled, both\n // changes land in the same PR).\n //\n // Intentionally omitted: per-upstream custom scope overrides.\n // Scopes live on the registry entry's `defaultScopes` field and\n // are NOT admin-configurable in v1 — see the operator setup doc\n // at `content/docs/govern/connections-github.mdx` for the\n // rationale (scope sprawl hesitancy).\n // ─────────────────────────────────────────────────────────────────\n supportedAuthMethods: z.array(z.enum(['paste', 'oauth'])).default(['paste']),\n oauthProvider: z.enum(['github', 'slack', 'notion', 'linear']).optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Stateless (UCP-style) upstreams\n //\n // Some MCP-transport endpoints reject `initialize` and `tools/list`\n // outright and treat every POST as an independent request — UCP\n // servers (ucp.dev) such as the Shopify Global Catalog are the\n // motivating case. `sessionMode: 'stateless'` tells the gateway to\n // skip the initialize handshake and the per-user session cache for\n // this upstream, and to serve its tool list ONLY from a persisted\n // manifest (live discovery cannot succeed by design, and attempting\n // it would feed the health tracker until the upstream is marked\n // down). Absent means the standard MCP handshake — optional rather\n // than defaulted so the field stays optional on the inferred type\n // and pre-existing rows/fixtures parse unchanged.\n //\n // `ucpProfileUrl` is the UCP agent-profile document the gateway\n // injects as `arguments.meta[\"ucp-agent\"].profile` on tools/call\n // when the caller didn't supply its own — UCP servers reject calls\n // without it. `safeUrl` (not a plain URL check) because the value\n // is fetched by third-party upstreams and must never point at a\n // private/internal host.\n // ─────────────────────────────────────────────────────────────────\n sessionMode: z.enum(['standard', 'stateless']).optional(),\n ucpProfileUrl: safeUrl.optional(),\n\n enabled: z.boolean().default(true),\n // No default on purpose: the gateway's health-tracker persistence is a\n // v1 no-op (see apps/gateway/src/bootstrap.ts), so nothing writes real\n // status yet. A `.default('healthy')` here made every upstream render a\n // false green \"Healthy\" dot. `undefined` means \"never checked\" and\n // consumers must render a neutral \"Unchecked\" state for it.\n healthStatus: z.enum(['healthy', 'degraded', 'down']).optional(),\n consecutiveFailures: z.number().int().min(0).default(0),\n\n // ─────────────────────────────────────────────────────────────────\n // v1.1 KTA Trust Layer forward-compat (see #1549)\n // All fields nullable/optional. v1 code does NOT populate or read these.\n // v1.1 Phase A populates them from KTA registry lookups on upstream add.\n // DO NOT wire these to KTA in this sprint.\n // ─────────────────────────────────────────────────────────────────\n ktaRegistryId: z.string().nullable().optional(),\n ktaVerifiedOperator: z.boolean().nullable().optional(),\n ktaReputationScore: z.number().min(0).max(5).nullable().optional(),\n ktaFlaggedIssues: z\n .array(\n z.object({\n severity: z.enum(['info', 'warning', 'critical']),\n category: z.string(),\n message: z.string(),\n })\n )\n .nullable()\n .optional(),\n ktaLastFetchedAt: z.string().datetime().nullable().optional(),\n\n // ─────────────────────────────────────────────────────────────────\n // Per-upstream project lifecycle (Option A — #1566)\n // Links this upstream to a dedicated Checkpoint project for\n // per-upstream detection, policy, and audit isolation.\n // ─────────────────────────────────────────────────────────────────\n projectId: z.string().uuid().nullable().optional(),\n\n // draft-kya-http-02 §7 Authorization Host (H1.1 #3244). The RESOLVED bare\n // host for this upstream's project — where the Hono gateway points a\n // Delegation challenge's consent_uri / pickup_uri. Forward contract: the\n // wire shape is established here in H1.1; the gateway populates it per\n // upstream from `projects.authorization_host` when its challenge emitter\n // lands (H2.1-WF), resolved out-of-band from `DbGatewayConfigProvider` so\n // that provider keeps its single-query invariant. Never authored by the\n // dashboard. The same resolved value is already live on the per-project\n // policy config the gateway worker fetches (`/api/internal/policies`), which\n // is AUTHORITATIVE — consumers prefer it and treat this copy as a hint.\n authorizationHost: z.string().max(255).nullable().optional(),\n});\n\nexport type UpstreamServer = z.infer<typeof upstreamServerSchema>;\n\n/**\n * Input variant — id/slug optional for new upstreams (auto-generated by PUT\n * handler). Also omits the two server-managed static-headers fields:\n * `staticHeadersEncrypted` (ciphertext — clients never author this\n * directly) and `staticHeaderKeys` (a read-only projection echoed back on\n * GET/PUT responses). The plaintext `staticHeaders` field is intentionally\n * NOT omitted — it's still how the admin form submits new/changed header\n * values; the PUT handler encrypts it before persisting.\n */\nexport const upstreamServerInputSchema = upstreamServerSchema\n .omit({ staticHeadersEncrypted: true, staticHeaderKeys: true })\n .extend({\n id: z.string().uuid().optional(),\n slug: z\n .string()\n .regex(/^[a-z0-9]+(?:_[a-z0-9]+)*$/, {\n message:\n 'Slug must be lowercase alphanumeric with single underscores (no consecutive underscores)',\n })\n .optional(),\n });\nexport type UpstreamServerInput = z.infer<typeof upstreamServerInputSchema>;\n\n// ---------------------------------------------------------------------------\n// Upstream Tool Manifest — DB row shape\n// ---------------------------------------------------------------------------\n\n/**\n * Shape of a cached tool manifest row (`upstream_tool_manifests` table).\n * The gateway reads this at runtime to serve org-level `tools/list`\n * without needing a per-user OAuth token — the manifest was captured\n * at add-time using the viewing user's credential, which is the only\n * moment in the flow where per-user auth is available to us.\n *\n * Validated on writes from the dashboard and on reads by the Fly\n * gateway; the table's `tools` column is `jsonb` so nothing DB-side\n * enforces the shape.\n */\nexport const upstreamToolManifestSchema = z\n .object({\n upstreamId: z.string().uuid(),\n orgId: z.string().uuid(),\n tools: z.array(discoveredToolSchema),\n discoveredByUserId: z.string().uuid().nullable().optional(),\n discoveredAt: z.string().datetime(),\n updatedAt: z.string().datetime(),\n })\n .strict();\n\nexport type UpstreamToolManifest = z.infer<typeof upstreamToolManifestSchema>;\n\n/**\n * Insert/upsert variant — omits DB-managed timestamps so callers can\n * pass the payload they actually own. The DB defaults `discovered_at`\n * and `updated_at` to `now()` on insert; updates bump `updated_at`\n * explicitly via the write path.\n */\nexport const upstreamToolManifestInputSchema = z\n .object({\n upstreamId: z.string().uuid(),\n orgId: z.string().uuid(),\n tools: z.array(discoveredToolSchema),\n discoveredByUserId: z.string().uuid().nullable().optional(),\n })\n .strict();\n\nexport type UpstreamToolManifestInput = z.infer<typeof upstreamToolManifestInputSchema>;\n\n// ---------------------------------------------------------------------------\n// Gateway Config Schema\n// ---------------------------------------------------------------------------\n\nexport const oauthClientSchema = z.object({\n clientId: z.string().min(1),\n name: z.string().min(1),\n redirectUris: z.array(z.string().url()).min(1),\n});\n\nexport type OAuthClient = z.infer<typeof oauthClientSchema>;\n\n// Defaults for nested config objects — single source of truth to prevent\n// inner-field and outer-object defaults from drifting apart.\nconst DEFAULT_RATE_LIMITS = { toolCallsPerMinute: 600 } as const;\nconst DEFAULT_EXTERNAL_ACCESS = {\n enabled: false,\n allowedDids: [] as string[],\n externalScopes: {} as Record<string, string[]>,\n} as const;\n\nexport const gatewayConfigSchema = z.object({\n enabled: z.boolean().default(false),\n upstreamServers: z.array(upstreamServerSchema).default([]),\n roleScopes: z.record(z.string(), z.array(z.string())).optional(),\n oauthClients: z.array(oauthClientSchema).default([]),\n rateLimits: z\n .object({\n toolCallsPerMinute: z\n .number()\n .int()\n .positive()\n .default(DEFAULT_RATE_LIMITS.toolCallsPerMinute),\n })\n .default(DEFAULT_RATE_LIMITS),\n externalAccess: z\n .object({\n enabled: z.boolean().default(DEFAULT_EXTERNAL_ACCESS.enabled),\n allowedDids: z.array(z.string()).default(DEFAULT_EXTERNAL_ACCESS.allowedDids),\n externalScopes: z\n .record(z.string(), z.array(z.string()))\n .default(DEFAULT_EXTERNAL_ACCESS.externalScopes),\n })\n .default(DEFAULT_EXTERNAL_ACCESS),\n // T6 #2899 M2 — per-org fleet-server endpoint. When set, the gateway's\n // DiscoveryUpstreamProvider injects a synthetic `fleet` upstream so\n // callers can dispatch tools by capability or name (not just raw DID).\n // Validated via `safeUrl` so a misconfigured endpoint targeting\n // private-network IPs cannot become an SSRF pivot.\n fleetEndpoint: safeUrl.optional(),\n});\n\nexport type GatewayConfig = z.infer<typeof gatewayConfigSchema>;\n/** Gateway config input variant for PUT — uses optional id/slug */\nexport const gatewayConfigInputSchema = gatewayConfigSchema.extend({\n upstreamServers: z.array(upstreamServerInputSchema).default([]),\n});\n\n// ---------------------------------------------------------------------------\n// Gateway Tool Call Schema (audit record — mirrors gateway_tool_calls table)\n// ---------------------------------------------------------------------------\n\nexport const gatewayToolCallSchema = z.object({\n id: z.string().uuid(),\n orgId: z.string().uuid(),\n projectId: z.string().uuid().nullable().optional(),\n userId: z.string().uuid().nullable().optional(),\n userEmail: z.string().email(),\n sessionId: z.string().min(1).max(100),\n upstreamId: z.string().uuid(),\n upstreamName: z.string().min(1).max(255),\n toolName: z.string().min(1).max(500),\n prefixedName: z.string().min(1).max(500),\n argsHash: z.string().max(64).nullable().optional(),\n status: z.enum(['success', 'error', 'denied', 'timeout']).default('success'),\n latencyMs: z.number().int().min(0).nullable().optional(),\n errorMessage: z.string().nullable().optional(),\n // Provenance identity (Phase 2, #1979)\n clientDid: z.string().max(500).nullable().optional(),\n clientName: z.string().max(100).nullable().optional(),\n serverDid: z.string().max(500).nullable().optional(),\n agentName: z.string().max(255).nullable().optional(),\n delegationId: z.string().max(255).nullable().optional(),\n attestationHash: z.string().max(64).nullable().optional(),\n verificationMethod: z.string().max(50).nullable().optional(),\n createdAt: z.coerce.date().default(() => new Date()),\n});\n\nexport type GatewayToolCall = z.infer<typeof gatewayToolCallSchema>;\n\n// ---------------------------------------------------------------------------\n// Gateway Connections Summary (derived aggregate over gateway_tool_calls)\n// ---------------------------------------------------------------------------\n\n/**\n * One distinct agent/client observed calling the gateway within the lookback\n * window. Identity is keyed on `clientDid` (canonical) falling back to\n * `agentName` when a client hasn't presented a DID.\n */\nexport const gatewayConnectedAgentSchema = z.object({\n clientDid: z.string().nullable(),\n clientName: z.string().nullable(),\n agentName: z.string().nullable(),\n lastSeenAt: z.coerce.date(),\n callCount: z.number().int().min(1),\n /** Calls carrying an attestation hash — the cryptographically signed subset. */\n verifiedCalls: z.number().int().min(0),\n});\n\nexport type GatewayConnectedAgent = z.infer<typeof gatewayConnectedAgentSchema>;\n\n/**\n * Aggregate of the agents/clients that have connected *in* to an org's gateway\n * over a lookback window, derived from `gateway_tool_calls`. Powers the\n * Connections hub hero (\"agents in\" side) — distinct from the upstream servers\n * the org reaches *out* to (those live in `GatewayConfig.upstreamServers`).\n */\nexport const gatewayConnectionsSummarySchema = z.object({\n orgId: z.string().uuid(),\n windowHours: z.number().int().positive(),\n /** Distinct agents (by clientDid|agentName) active in the window. */\n distinctAgents: z.number().int().min(0),\n /** Total gateway tool calls in the window. */\n totalCalls: z.number().int().min(0),\n agents: z.array(gatewayConnectedAgentSchema),\n});\n\nexport type GatewayConnectionsSummary = z.infer<typeof gatewayConnectionsSummarySchema>;\n","/**\n * Schemas Export\n *\n * Central export point for all Zod schemas\n * These schemas are used for runtime validation across all packages\n *\n * ## Provider Registry Integration\n *\n * As of v0.3.0, provider types are imported from @kya-os/provider-registry\n * to ensure type parity between Checkpoint and KYA-OS. See provider-registry.ts\n * for re-exports and backward compatibility helpers.\n */\n\n// Detection schemas\nexport {\n DetectionInputSchema,\n RequestContextSchema,\n DetectionDetailSchema,\n DetectionResultSchema,\n DetectionModeSchema,\n CustomRuleSchema,\n DetectionOptionsSchema,\n} from '../core/detection';\n\n// Agent schemas\nexport {\n AgentTypeSchema,\n AgentInfoSchema,\n AgentPatternSchema,\n AgentClassificationSchema,\n} from '../core/agent';\n\n// Confidence schemas\nexport {\n ConfidenceLevelSchema,\n ForgeabilityRiskSchema,\n ConfidenceBreakdownSchema,\n} from '../core/confidence';\n\n// Configuration schemas\nexport {\n AgentShieldConfigSchema,\n CacheConfigSchema,\n NetworkConfigSchema,\n LoggingConfigSchema,\n WasmConfigSchema,\n} from '../config/shield';\n\nexport {\n MiddlewareConfigSchema,\n MiddlewareActionSchema,\n MiddlewareSessionConfigSchema,\n MiddlewareSessionDataSchema,\n ResponseActionSchema,\n EventConfigSchema,\n ExpressMiddlewareOptionsSchema,\n NextMiddlewareOptionsSchema,\n} from '../config/middleware';\n\n// API schemas\nexport { BatchDetectionRequestSchema, VerificationRequestSchema } from '../api/request';\n\nexport {\n ApiResponseSchema,\n DetectionResponseSchema,\n BatchDetectionResponseSchema,\n VerificationResponseSchema,\n HealthResponseSchema,\n StatsResponseSchema,\n} from '../api/response';\n\n// Internal API schemas\nexport {\n CreateApiKeySchema,\n UpdateApiKeySchema,\n CreateOrganizationSchema,\n UpdateOrganizationSchema,\n CreateProjectSchema,\n UpdateProjectSchema,\n AnalyticsQuerySchema,\n ApiKeysQuerySchema,\n ProjectsQuerySchema,\n PixelsQuerySchema,\n ProjectIdSchema,\n ExportAnalyticsSchema,\n} from '../api/internal';\n\n// Event schemas\nexport {\n MouseEventSchema,\n KeyboardEventSchema,\n ScrollEventSchema,\n ClickEventSchema,\n TouchEventSchema,\n BehavioralDataSchema,\n BehavioralAnalysisSchema,\n} from '../events/behavioral';\n\nexport {\n RealtimeEventTypeSchema,\n RealtimeEventSchema,\n DetectionEventSchema,\n BlockEventSchema,\n StatsUpdateEventSchema,\n} from '../events/realtime';\n\n// WASM schemas\nexport { WasmDetectionResultSchema, WasmRequestMetadataSchema } from '../types/wasm';\n\n// Entity schemas\nexport {\n UserPlanSchema,\n ApiKeyPermissionSchema,\n UserSchema,\n ProjectSettingsSchema,\n ProjectSchema,\n PixelConfigurationSchema,\n PixelSchema,\n PixelStatsSchema,\n ApiKeyRateLimitsSchema,\n ApiKeySchema,\n DetectionLogSchema,\n SessionSchema,\n AccountSchema,\n VerificationTokenSchema,\n} from '../types/entities';\n\n// Pixel schemas\nexport {\n PixelEventTypeSchema,\n BrowserInfoSchema,\n PageContextSchema,\n BehavioralSignalsSchema,\n PixelEventSchema,\n BatchPixelEventRequestSchema,\n PixelInstallConfigSchema,\n PixelInitSchema,\n PixelTrackingRequestSchema,\n PixelTrackingResponseSchema,\n PixelAnalyticsSchema,\n PixelSessionSchema,\n PixelVerificationStatusSchema,\n DetectionViewTypeSchema,\n DetectionStatusSchema,\n DetectionErrorDetailsSchema,\n} from '../types/pixel';\n\n// Session schemas\nexport {\n SessionStateSchema,\n SessionStorageTypeSchema,\n SessionDataSchema,\n SessionCreateRequestSchema,\n SessionUpdateRequestSchema,\n SessionQueryOptionsSchema,\n SessionConfigSchema,\n SessionEventTypeSchema,\n SessionEventSchema,\n SessionTokenPayloadSchema,\n} from '../types/session';\n\n// Auth schemas\nexport {\n passwordSchema,\n signInSchema,\n signUpSchema,\n forgotPasswordSchema,\n resetPasswordSchema,\n changePasswordSchema,\n verifyEmailSchema,\n type SignInData,\n type SignUpData,\n type ForgotPasswordData,\n type ResetPasswordData,\n type ChangePasswordData,\n type VerifyEmailData,\n} from './auth';\n\n// Admin schemas\nexport {\n PerformanceRecalculationRequestSchema,\n GrowthOpportunityUpdateSchema,\n GrowthBatchRequestSchema,\n GrowthConfigurationThresholdsSchema,\n GrowthConfigurationUpdateSchema,\n GrowthConfigurationResetSchema,\n AdminQueryParamsSchema,\n GrowthOpportunitiesQuerySchema,\n RecommendationQuerySchema,\n RecommendationGenerationSchema,\n type PerformanceRecalculationRequest,\n type GrowthOpportunityUpdate,\n type GrowthBatchRequest,\n type GrowthConfigurationThresholds,\n type GrowthConfigurationUpdate,\n type GrowthConfigurationReset,\n type AdminQueryParams,\n type GrowthOpportunitiesQuery,\n type RecommendationQuery,\n type RecommendationGeneration,\n} from './admin';\n\n// Bouncer schemas\nexport {\n OAuthProviderTypeSchema,\n OAuthConnectionStatusSchema,\n OAuthModeSchema,\n ScopeSchema,\n CRISPBudgetSchema,\n BouncerConfigSchema,\n UpdateBouncerConfigSchema,\n RefreshScopesRequestSchema,\n DelegationStatusSchema,\n DelegationSchema,\n BouncerOutcomeSchema,\n BouncerProofSchema,\n DelegationPollingStatusSchema,\n OAuthProviderMetadataSchema,\n ProvidersResponseSchema,\n OAuthTokensResponseSchema,\n // Multi-provider OAuth types (CRED-001)\n AuthProviderTypeSchema,\n BaseAuthProviderSchema,\n OAuth2ProviderSchema,\n CredentialProviderSchema,\n ConfiguredProviderSchema,\n OAuthProvidersMapSchema,\n AddUpdateProviderRequestSchema,\n // Provider Definition (Provider Registry aligned)\n ProviderDefinitionSchema,\n // Consent schemas (CRED-002)\n ConsentBrandingSchema,\n ConsentTermsSchema,\n ConsentUISchema,\n ConsentConfigSchema,\n ConsentConfigMetadataSchema,\n ConsentCapabilitySchema,\n ConsentCapabilityGroupSchema,\n ConsentAgentMetadataSchema,\n ToolConsentOverridesSchema,\n // Format conversion helpers (Provider Registry <-> Checkpoint)\n toProviderRegistryFormat,\n fromProviderRegistryFormat,\n fromProviderRegistryFormatSafe,\n isSupportedAuthType,\n mapLegacyAuthType,\n mapToLegacyAuthType,\n type SupportedProviderAuthType,\n type OAuthProviderType,\n type OAuthConnectionStatus,\n type OAuthMode,\n type Scope,\n type CRISPBudget,\n type BouncerConfig,\n type UpdateBouncerConfig,\n type RefreshScopesRequest,\n type DelegationStatus,\n type Delegation,\n type BouncerOutcome,\n type BouncerProof,\n type DelegationPollingStatus,\n type OAuthProviderMetadata,\n type ProvidersResponse,\n type OAuthTokensResponse,\n // Multi-provider OAuth types (CRED-001)\n type AuthProviderType,\n type AuthProviderTypeInput,\n type LegacyAuthProviderType,\n type BaseAuthProvider,\n type OAuth2Provider,\n type CredentialProvider,\n type ConfiguredProvider,\n type OAuthProvidersMap,\n type AddUpdateProviderRequest,\n // Provider Definition types\n type ProviderDefinition,\n type ProviderRegistryDefinition,\n // Canonical types from provider-registry\n type ProviderAuthType,\n type ConsentProviderType,\n // Consent types (CRED-002)\n type ConsentBranding,\n type ConsentTerms,\n type ConsentUI,\n type ConsentConfig,\n type ConsentConfigMetadata,\n type ConsentCapability,\n type ConsentCapabilityGroup,\n type ConsentAgentMetadata,\n type ToolConsentOverrides,\n} from './bouncer';\n\n// Gateway schemas\nexport {\n SLUG_REGEX,\n safeUrl,\n isPrivateOrReservedHost,\n upstreamServerSchema,\n oauthClientSchema,\n gatewayConfigSchema,\n gatewayConfigInputSchema,\n upstreamServerInputSchema,\n gatewayToolCallSchema,\n gatewayConnectedAgentSchema,\n gatewayConnectionsSummarySchema,\n type UpstreamServer,\n type OAuthClient,\n type GatewayConfig,\n type GatewayToolCall,\n type GatewayConnectedAgent,\n type GatewayConnectionsSummary,\n} from './gateway';\n\n// Provider Registry exports (canonical types from @kya-os/provider-registry)\n// NOTE: Runtime registry (defaultProviderRegistry) should be imported directly\n// from @kya-os/provider-registry in server-side code to avoid bundling issues.\nexport {\n // Core types\n AUTH_MODES,\n PROVIDER_AUTH_TYPES,\n AUTHORIZATION_MODES,\n type AuthMode,\n type AuthorizationMode,\n // Type definitions for registry (runtime should be imported directly)\n type IProviderRegistry,\n type RegistryLogger,\n // Canonical schemas\n ProviderRegistryDefinitionSchema,\n OAuthProviderConfigSchema,\n CredentialProviderConfigSchema,\n ProviderConfigSchema,\n validateProviderDefinition,\n validateProviderConfig,\n // Canonical config types\n type OAuthProviderConfig,\n type CredentialProviderConfig,\n type ProviderConfig,\n} from './provider-registry';\n\n/**\n * Schema validation utilities\n */\nimport { z } from 'zod';\n\n/**\n * Validate data against a schema\n */\nexport function validate<T>(\n schema: z.ZodSchema<T>,\n data: unknown\n): { success: true; data: T } | { success: false; error: z.ZodError } {\n const result = schema.safeParse(data);\n if (result.success) {\n return { success: true, data: result.data };\n }\n return { success: false, error: result.error };\n}\n\n/**\n * Validate and throw on error\n */\nexport function validateOrThrow<T>(schema: z.ZodSchema<T>, data: unknown): T {\n return schema.parse(data);\n}\n\n/**\n * Create a partial schema (all fields optional)\n */\nexport function partial<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.partial();\n}\n\n/**\n * Create a strict schema (no additional properties)\n */\nexport function strict<T extends z.ZodRawShape>(schema: z.ZodObject<T>) {\n return schema.strict();\n}\n","/**\n * Analytics Schemas\n *\n * Schemas for analytics API endpoints\n * Used for validation and type safety in analytics routes\n */\n\nimport { z } from 'zod';\n\n/**\n * Base Analytics Query Schema\n * Extended by specific analytics endpoints\n */\nexport const AnalyticsQuerySchema = z.object({\n duration: z.enum(['week', 'month', 'quarter', 'year']).optional().default('week'),\n groupBy: z.enum(['day', 'hour', 'week', 'month']).optional().default('day'),\n startDate: z.string().datetime().optional(),\n endDate: z.string().datetime().optional(),\n});\nexport type AnalyticsQuery = z.infer<typeof AnalyticsQuerySchema>;\n\n/**\n * Sessions Analytics Query Schema\n * Used for session-specific analytics endpoints\n */\nexport const AnalyticsSessionsQuerySchema = z.object({\n duration: z.enum(['week', 'month']).optional().default('week'),\n groupBy: z.enum(['day', 'hour']).optional().default('day'),\n});\nexport type AnalyticsSessionsQuery = z.infer<typeof AnalyticsSessionsQuerySchema>;\n\n/**\n * Agent Sources Analytics Query Schema\n * Used for agent source analytics endpoints\n */\nexport const AnalyticsAgentSourcesQuerySchema = z.object({\n duration: z.enum(['week', 'month', 'quarter']).optional().default('week'),\n limit: z.coerce.number().min(1).max(100).optional().default(10),\n sortBy: z.enum(['count', 'name', 'confidence']).optional().default('count'),\n order: z.enum(['asc', 'desc']).optional().default('desc'),\n});\nexport type AnalyticsAgentSourcesQuery = z.infer<typeof AnalyticsAgentSourcesQuerySchema>;\n\n/**\n * Agent Types Analytics Query Schema\n * Used for agent type analytics endpoints\n */\nexport const AnalyticsAgentTypesQuerySchema = z.object({\n duration: z.enum(['week', 'month', 'quarter']).optional().default('week'),\n limit: z.coerce.number().min(1).max(100).optional().default(10),\n includeRaw: z.coerce.boolean().optional().default(false),\n});\nexport type AnalyticsAgentTypesQuery = z.infer<typeof AnalyticsAgentTypesQuerySchema>;\n\n/**\n * Analytics Export Query Schema\n * Used for data export endpoints\n */\nexport const AnalyticsExportQuerySchema = z.object({\n format: z.enum(['csv', 'json', 'excel']).optional().default('csv'),\n startDate: z.string().datetime(),\n endDate: z.string().datetime(),\n includeMetadata: z.coerce.boolean().optional().default(false),\n includeRawData: z.coerce.boolean().optional().default(false),\n});\nexport type AnalyticsExportQuery = z.infer<typeof AnalyticsExportQuerySchema>;\n\n/**\n * Real-time Analytics Query Schema\n * Used for real-time analytics endpoints\n */\nexport const AnalyticsRealtimeQuerySchema = z.object({\n timeWindow: z.enum(['1h', '6h', '24h']).optional().default('1h'),\n refreshInterval: z.coerce.number().min(5).max(300).optional().default(30), // seconds\n});\nexport type AnalyticsRealtimeQuery = z.infer<typeof AnalyticsRealtimeQuerySchema>;\n\n/**\n * Analytics Time Series Data Schema\n * Response schema for time series data\n */\nexport const AnalyticsTimeSeriesSchema = z.object({\n timestamp: z.string().datetime(),\n totalDetections: z.number().nonnegative(),\n agentDetections: z.number().nonnegative(),\n humanDetections: z.number().nonnegative(),\n uniqueSessions: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n});\nexport type AnalyticsTimeSeries = z.infer<typeof AnalyticsTimeSeriesSchema>;\n\n/**\n * Analytics Summary Stats Schema\n * Response schema for summary statistics\n */\nexport const AnalyticsSummarySchema = z.object({\n totalAgentDetections: z.number().nonnegative(),\n totalDetections: z.number().nonnegative(),\n uniqueAgentSessions: z.number().nonnegative(),\n totalSessions: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n agentDetectionsChange: z.number(),\n agentDetectionsChangeCount: z.number(),\n totalDetectionsChange: z.number(),\n totalDetectionsChangeCount: z.number(),\n agentSessionsChange: z.number(),\n agentSessionsChangeCount: z.number(),\n});\nexport type AnalyticsSummary = z.infer<typeof AnalyticsSummarySchema>;\n\n/**\n * Analytics Chart Data Schema\n * Response schema for chart data points\n */\nexport const AnalyticsChartDataSchema = z.object({\n month: z.string(), // Display label (e.g., \"Jan 15\", \"3 PM\")\n timestamp: z.string().datetime(),\n agentDetections: z.number().nonnegative(),\n totalDetections: z.number().nonnegative(),\n humanDetections: z.number().nonnegative(),\n uniqueSessions: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n});\nexport type AnalyticsChartData = z.infer<typeof AnalyticsChartDataSchema>;\n\n/**\n * Analytics Sessions Response Schema\n * Complete response schema for sessions analytics\n */\nexport const AnalyticsSessionsResponseSchema = z.object({\n success: z.literal(true),\n data: z.object({\n chartData: z.array(AnalyticsChartDataSchema),\n stats: AnalyticsSummarySchema,\n period: z.enum(['week', 'month']),\n dateRange: z.object({\n start: z.string().datetime(),\n end: z.string().datetime(),\n }),\n }),\n});\nexport type AnalyticsSessionsResponse = z.infer<typeof AnalyticsSessionsResponseSchema>;\n\n/**\n * Agent Type Distribution Schema\n * Used for agent type analytics\n */\nexport const AgentTypeDistributionSchema = z.object({\n agentType: z.string(),\n count: z.number().nonnegative(),\n uniqueSessions: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n percentage: z.number().min(0).max(100),\n});\nexport type AgentTypeDistribution = z.infer<typeof AgentTypeDistributionSchema>;\n\n/**\n * Agent Source Distribution Schema\n * Used for agent source analytics\n */\nexport const AgentSourceDistributionSchema = z.object({\n source: z.string(),\n count: z.number().nonnegative(),\n avgConfidence: z.number().min(0).max(1),\n percentage: z.number().min(0).max(100),\n userAgents: z.array(z.string()).optional(),\n});\nexport type AgentSourceDistribution = z.infer<typeof AgentSourceDistributionSchema>;\n\n/**\n * Confidence Distribution Schema\n * Used for confidence distribution analytics\n */\nexport const ConfidenceDistributionSchema = z.object({\n range: z.string(), // e.g., \"0.8-0.9\", \"0.9-1.0\"\n count: z.number().nonnegative(),\n percentage: z.number().min(0).max(100),\n});\nexport type ConfidenceDistribution = z.infer<typeof ConfidenceDistributionSchema>;\n","/**\n * Rule Validation Schemas\n *\n * Zod schemas for runtime validation of detection rules\n * Ensures rule integrity at build time and runtime\n */\n\nimport { z } from 'zod';\n\n/**\n * User agent rule schema\n */\nexport const UserAgentRuleSchema = z.object({\n patterns: z.array(z.string().min(1)).min(1),\n confidence: z.number().min(0).max(1),\n flags: z.string().optional(),\n description: z.string().optional(),\n});\n\n/**\n * IP range rule schema\n */\nexport const IpRangeRuleSchema = z.object({\n ranges: z.array(z.string().regex(/^(\\d{1,3}\\.){3}\\d{1,3}\\/\\d{1,2}$/)).min(1),\n confidence: z.number().min(0).max(1),\n provider: z.string().optional(),\n lastUpdated: z.string().optional(),\n});\n\n/**\n * Signature rule schema\n */\nexport const SignatureRuleSchema = z.object({\n publicKey: z.string().min(1),\n algorithm: z.enum([\n 'RS256',\n 'RS384',\n 'RS512',\n 'HS256',\n 'HS384',\n 'HS512',\n 'ES256',\n 'ES384',\n 'ES512',\n ]),\n headerName: z.string().min(1),\n confidence: z.number().min(0).max(1),\n issuer: z.string().optional(),\n});\n\n/**\n * Behavioral threshold schema\n */\nexport const BehavioralThresholdSchema = z.object({\n minTimeOnPage: z.number().min(0).optional(),\n maxRequestsPerSecond: z.number().min(0).optional(),\n minMouseMovements: z.number().min(0).optional(),\n minKeyboardEvents: z.number().min(0).optional(),\n maxScrollVariance: z.number().min(0).optional(),\n timeWindow: z.number().min(0).optional(),\n});\n\n/**\n * Behavioral pattern schema\n */\nexport const BehavioralPatternSchema = z.object({\n name: z.string().min(1),\n type: z.enum(['rapid_requests', 'no_interaction', 'perfect_scrolling', 'sequential_access']),\n config: z.record(z.string(), z.any()),\n confidenceModifier: z.number().min(-1).max(1),\n});\n\n/**\n * Behavioral rules schema\n */\nexport const BehavioralRulesSchema = z.object({\n thresholds: BehavioralThresholdSchema,\n patterns: z.array(BehavioralPatternSchema).optional(),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Header rule schema\n */\nexport const HeaderRuleSchema = z.object({\n name: z.string().min(1),\n pattern: z.string().optional(),\n required: z.boolean().optional(),\n suspiciousIfMissing: z.boolean().optional(),\n confidence: z.number().min(0).max(1),\n});\n\n/**\n * Header rules schema\n */\nexport const HeaderRulesSchema = z.object({\n suspicious: z.array(HeaderRuleSchema),\n required: z.array(HeaderRuleSchema),\n forbidden: z.array(HeaderRuleSchema).optional(),\n});\n\n/**\n * IP range collection schema\n * Flexible to handle both old (with providers) and new (direct) structures\n */\nexport const IpRangeCollectionSchema = z.union([\n // Old structure with providers\n z.object({\n providers: z.record(z.string(), IpRangeRuleSchema),\n updateUrl: z.string().url().optional(),\n updateFrequency: z.enum(['hourly', 'daily', 'weekly', 'monthly']).optional(),\n cacheDuration: z.number().min(0).optional(),\n }),\n // New merged structure - IP ranges directly as properties\n z.record(z.string(), IpRangeRuleSchema).refine(\n (val) => {\n // Ensure at least one valid IP range entry exists\n return Object.values(val).some(\n (v) => v && typeof v === 'object' && 'ranges' in v && Array.isArray(v.ranges)\n );\n },\n { message: 'At least one valid IP range entry required' }\n ),\n]);\n\n/**\n * Complete detection rules schema\n */\nexport const DetectionRulesSchema = z.object({\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+$/),\n lastUpdated: z.string(),\n metadata: z\n .object({\n author: z.string().optional(),\n description: z.string().optional(),\n minVersion: z.string().optional(),\n source: z.string().optional(),\n })\n .optional(),\n rules: z.object({\n userAgents: z.record(z.string(), UserAgentRuleSchema),\n ipRanges: IpRangeCollectionSchema,\n signatures: z.record(z.string(), SignatureRuleSchema),\n behavioral: BehavioralRulesSchema,\n headers: HeaderRulesSchema,\n }),\n});\n\n/**\n * Rule load options schema\n */\nexport const RuleLoadOptionsSchema = z.object({\n cdnUrl: z.string().url().optional(),\n forceRefresh: z.boolean().optional(),\n cacheDuration: z.number().min(0).optional(),\n validationMode: z.enum(['strict', 'loose', 'none']).optional(),\n});\n\n/**\n * Rule validation result schema\n */\nexport const RuleValidationResultSchema = z.object({\n valid: z.boolean(),\n errors: z\n .array(\n z.object({\n path: z.string(),\n message: z.string(),\n type: z.string(),\n })\n )\n .optional(),\n warnings: z\n .array(\n z.object({\n path: z.string(),\n message: z.string(),\n })\n )\n .optional(),\n});\n\n/**\n * Rule update event schema\n */\nexport const RuleUpdateEventSchema = z.object({\n previousVersion: z.string(),\n newVersion: z.string(),\n timestamp: z.string(),\n changes: z\n .object({\n added: z.array(z.string()),\n modified: z.array(z.string()),\n removed: z.array(z.string()),\n })\n .optional(),\n});\n\n/**\n * Rule match result schema\n */\nexport const RuleMatchResultSchema = z.object({\n matched: z.boolean(),\n rule: z.string().optional(),\n category: z.enum(['userAgent', 'ipRange', 'signature', 'behavioral', 'header']).optional(),\n confidence: z.number().min(0).max(1).optional(),\n details: z.record(z.string(), z.any()).optional(),\n});\n\n/**\n * Type exports inferred from schemas\n */\nexport type UserAgentRule = z.infer<typeof UserAgentRuleSchema>;\nexport type IpRangeRule = z.infer<typeof IpRangeRuleSchema>;\nexport type SignatureRule = z.infer<typeof SignatureRuleSchema>;\nexport type BehavioralThreshold = z.infer<typeof BehavioralThresholdSchema>;\nexport type BehavioralPattern = z.infer<typeof BehavioralPatternSchema>;\nexport type BehavioralRules = z.infer<typeof BehavioralRulesSchema>;\nexport type HeaderRule = z.infer<typeof HeaderRuleSchema>;\nexport type HeaderRules = z.infer<typeof HeaderRulesSchema>;\nexport type IpRangeCollection = z.infer<typeof IpRangeCollectionSchema>;\nexport type DetectionRules = z.infer<typeof DetectionRulesSchema>;\nexport type RuleLoadOptions = z.infer<typeof RuleLoadOptionsSchema>;\nexport type RuleValidationResult = z.infer<typeof RuleValidationResultSchema>;\nexport type RuleUpdateEvent = z.infer<typeof RuleUpdateEventSchema>;\nexport type RuleMatchResult = z.infer<typeof RuleMatchResultSchema>;\n\n/**\n * Validate detection rules\n */\nexport function validateRules(rules: unknown): RuleValidationResult {\n try {\n DetectionRulesSchema.parse(rules);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return {\n valid: false,\n errors: error.issues.map((e) => ({\n path: e.path.join('.'),\n message: e.message,\n type: e.code,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: '',\n message: 'Unknown validation error',\n type: 'unknown',\n },\n ],\n };\n }\n}\n\n/**\n * Validate and parse rules with type safety\n */\nexport function parseRules(rules: unknown): DetectionRules {\n return DetectionRulesSchema.parse(rules);\n}\n\n/**\n * Validate rules with loose mode (allows extra fields)\n */\nexport function validateRulesLoose(rules: unknown): RuleValidationResult {\n try {\n DetectionRulesSchema.passthrough().parse(rules);\n return { valid: true };\n } catch (error) {\n if (error instanceof z.ZodError) {\n return {\n valid: false,\n errors: error.issues.map((e) => ({\n path: e.path.join('.'),\n message: e.message,\n type: e.code,\n })),\n };\n }\n return {\n valid: false,\n errors: [\n {\n path: '',\n message: 'Unknown validation error',\n type: 'unknown',\n },\n ],\n };\n }\n}\n","/**\n * Rule Validator\n *\n * Validates detection rules against schemas\n */\n\nimport { z } from 'zod';\nimport { DetectionRulesSchema, validateRules, validateRulesLoose } from '../schemas/rules';\nimport { DetectionRules, RuleValidationResult } from '../types/rules';\nimport { RULE_ERRORS } from '../constants/rules';\n\n/**\n * Rule validation utilities\n */\nexport class RuleValidator {\n /**\n * Validate rules with specified mode\n */\n static validate(\n rules: unknown,\n mode: 'strict' | 'loose' | 'none' = 'strict'\n ): RuleValidationResult {\n switch (mode) {\n case 'strict':\n return validateRules(rules);\n case 'loose':\n return validateRulesLoose(rules);\n case 'none':\n return { valid: true };\n default:\n return validateRules(rules);\n }\n }\n\n /**\n * Validate and throw on error\n */\n static validateOrThrow(\n rules: unknown,\n mode: 'strict' | 'loose' | 'none' = 'strict'\n ): DetectionRules {\n const result = this.validate(rules, mode);\n\n if (!result.valid) {\n const errors = result.errors?.map((e) => `${e.path}: ${e.message}`).join(', ');\n throw new Error(`${RULE_ERRORS.VALIDATION_FAILED}: ${errors}`);\n }\n\n return rules as DetectionRules;\n }\n\n /**\n * Parse and validate rules\n */\n static parse(rules: unknown): DetectionRules {\n try {\n return DetectionRulesSchema.parse(rules);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errors = error.issues.map((e) => `${e.path.join('.')}: ${e.message}`).join(', ');\n throw new Error(`${RULE_ERRORS.VALIDATION_FAILED}: ${errors}`);\n }\n throw error;\n }\n }\n\n /**\n * Check if rules are valid\n */\n static isValid(rules: unknown): boolean {\n return this.validate(rules).valid;\n }\n\n /**\n * Validate rule version compatibility\n */\n static validateVersion(rules: DetectionRules, minVersion: string): boolean {\n const [ruleMajor, ruleMinor, rulePatch] = rules.version.split('.').map(Number);\n const [minMajor, minMinor, minPatch] = minVersion.split('.').map(Number);\n\n if (ruleMajor > minMajor) return true;\n if (ruleMajor < minMajor) return false;\n\n if (ruleMinor > minMinor) return true;\n if (ruleMinor < minMinor) return false;\n\n return rulePatch >= minPatch;\n }\n\n /**\n * Validate confidence scores\n */\n static validateConfidenceScores(rules: DetectionRules): boolean {\n // Check user agent confidence scores\n for (const rule of Object.values(rules.rules.userAgents)) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check IP range confidence scores\n // Handle both old (with providers) and new (direct) structures\n const ipRanges =\n 'providers' in rules.rules.ipRanges ? rules.rules.ipRanges.providers : rules.rules.ipRanges;\n\n for (const rule of Object.values(ipRanges)) {\n // Skip non-rule entries\n if (!rule || typeof rule !== 'object' || !('confidence' in rule)) continue;\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check signature confidence scores\n for (const rule of Object.values(rules.rules.signatures)) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n // Check behavioral confidence\n if (rules.rules.behavioral.confidence < 0 || rules.rules.behavioral.confidence > 1) {\n return false;\n }\n\n // Check header confidence scores\n for (const rule of [...rules.rules.headers.suspicious, ...rules.rules.headers.required]) {\n if (rule.confidence < 0 || rule.confidence > 1) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Get validation errors as formatted string\n */\n static formatErrors(result: RuleValidationResult): string {\n if (result.valid) {\n return '';\n }\n\n const errors = result.errors || [];\n return errors.map((e) => ` - ${e.path}: ${e.message}`).join('\\n');\n }\n\n /**\n * Get validation warnings as formatted string\n */\n static formatWarnings(result: RuleValidationResult): string {\n const warnings = result.warnings || [];\n return warnings.map((w) => ` - ${w.path}: ${w.message}`).join('\\n');\n }\n}\n","/**\n * Rule Parser\n *\n * Parses YAML/JSON rule definitions\n */\n\nimport * as yaml from 'js-yaml';\nimport { DetectionRules } from '../types/rules';\nimport { RULE_ERRORS } from '../constants/rules';\n\n/**\n * Parse rule content (YAML or JSON)\n */\nexport class RuleParser {\n /**\n * Parse rule content from string\n */\n static parse(content: string): DetectionRules {\n if (!content || content.trim().length === 0) {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n\n // Try to detect format\n const trimmed = content.trim();\n\n try {\n // Try JSON first (faster)\n if (trimmed.startsWith('{')) {\n return JSON.parse(trimmed);\n }\n\n // Try YAML\n const parsed = yaml.load(trimmed);\n\n if (!parsed || typeof parsed !== 'object') {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n\n return parsed as DetectionRules;\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n // Format error message to match test expectations\n if (\n errorMessage.includes('JSON') ||\n errorMessage.includes('Unexpected') ||\n errorMessage.includes('Expected')\n ) {\n throw new Error('Parse failed: Invalid JSON');\n }\n throw new Error(`Parse failed: ${errorMessage}`);\n }\n }\n\n /**\n * Parse JSON rules\n */\n static parseJSON(content: string): DetectionRules {\n try {\n return JSON.parse(content);\n } catch (error) {\n throw new Error('Parse failed: Invalid JSON');\n }\n }\n\n /**\n * Parse YAML rules\n */\n static parseYAML(content: string): DetectionRules {\n try {\n const parsed = yaml.load(content);\n // Check if parsed result is a plain object (not array, string, number, etc.)\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(RULE_ERRORS.INVALID_FORMAT);\n }\n return parsed as DetectionRules;\n } catch (error) {\n // If we threw INVALID_FORMAT, re-throw it\n if (error instanceof Error && error.message === RULE_ERRORS.INVALID_FORMAT) {\n throw error;\n }\n const errorMessage = error instanceof Error ? error.message : 'Unknown error';\n // Format error message to match test expectations\n if (\n errorMessage.includes('unknown escape sequence') ||\n errorMessage.includes('YAML') ||\n errorMessage.includes('bad indentation')\n ) {\n throw new Error('Parse failed: Invalid YAML');\n }\n throw new Error('Parse failed: Invalid YAML');\n }\n }\n\n /**\n * Convert rules to JSON string\n */\n static toJSON(rules: DetectionRules, pretty = false): string {\n return JSON.stringify(rules, null, pretty ? 2 : 0);\n }\n\n /**\n * Convert rules to YAML string\n */\n static toYAML(rules: DetectionRules): string {\n return yaml.dump(rules, {\n indent: 2,\n lineWidth: -1,\n noRefs: true,\n sortKeys: false,\n });\n }\n\n /**\n * Validate basic rule structure\n */\n static validateStructure(rules: unknown): boolean {\n if (!rules || typeof rules !== 'object') return false;\n const candidate = rules as Record<string, unknown>;\n return !!(\n typeof candidate.version === 'string' &&\n typeof candidate.lastUpdated === 'string' &&\n candidate.rules &&\n typeof candidate.rules === 'object'\n );\n }\n}\n","","/**\n * Rule Loader\n *\n * Loads and manages detection rules\n * NO FALLBACKS - Fail fast if rules cannot be loaded\n */\n\nimport { DetectionRules, RuleLoadOptions } from '../types/rules';\nimport { RuleValidator } from './rule-validator';\nimport { RuleParser } from './rule-parser';\nimport { RULE_CACHE, RULE_CDN, RULE_ERRORS } from '../constants/rules';\n\n/**\n * Rule loader class - Singleton pattern\n */\nexport class RuleLoader {\n private static instance: RuleLoader | null = null;\n private rules: DetectionRules | null = null;\n private lastFetch: number = 0;\n private readonly isBrowser = typeof window !== 'undefined';\n\n /**\n * Private constructor for singleton\n */\n private constructor() {}\n\n /**\n * Get singleton instance\n */\n static getInstance(): RuleLoader {\n if (!this.instance) {\n this.instance = new RuleLoader();\n }\n return this.instance;\n }\n\n /**\n * Load rules synchronously from bundled JSON\n * This is the primary method for middleware packages\n * NO FALLBACKS - If this fails, the package should not work\n */\n static loadSync(): DetectionRules {\n try {\n // Load compiled rules - FAIL FAST if missing\n // NO fallback to prevent using stale/buggy rules\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const rules = require('../data/compiled/merged-rules.json');\n\n // Validate the rules - fail fast if invalid\n const validated = RuleValidator.validateOrThrow(rules, 'strict');\n\n return validated;\n } catch (error) {\n // NO FALLBACK - Fail immediately\n throw new Error(\n `${RULE_ERRORS.LOAD_FAILED}: Cannot load detection rules from merged-rules.json. ` +\n `This is likely a package build issue - run 'npm run compile-rules' to regenerate. ` +\n `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n /**\n * Load rules asynchronously (for beacon/browser with optional CDN)\n */\n async loadRules(options: RuleLoadOptions = {}): Promise<DetectionRules> {\n const validationMode = options.validationMode || 'strict';\n\n // Check cache first (browser only)\n if (!options.forceRefresh && this.rules && this.isCacheValid(options.cacheDuration)) {\n return this.rules;\n }\n\n // If CDN URL is provided, try to fetch from CDN\n if (options.cdnUrl) {\n try {\n const response = await this.fetchFromCDN(options.cdnUrl);\n const content = await response.text();\n const parsed = RuleParser.parse(content);\n\n // Validate rules - fail if invalid\n this.rules = RuleValidator.validateOrThrow(parsed, validationMode);\n this.lastFetch = Date.now();\n\n // Cache in localStorage (browser only)\n if (this.isBrowser) {\n this.cacheRules(this.rules);\n }\n\n return this.rules;\n } catch (error) {\n // NO FALLBACK - Fail immediately\n throw new Error(\n `${RULE_ERRORS.CDN_UNAVAILABLE}: Failed to load rules from CDN. ` +\n `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n // Load bundled rules (synchronous)\n this.rules = RuleLoader.loadSync();\n this.lastFetch = Date.now();\n return this.rules;\n }\n\n /**\n * Get current loaded rules\n */\n getRules(): DetectionRules | null {\n return this.rules;\n }\n\n /**\n * Check if cached rules are valid\n */\n private isCacheValid(customDuration?: number): boolean {\n if (!this.rules || !this.lastFetch) {\n return false;\n }\n\n const duration = customDuration || RULE_CACHE.DEFAULT_DURATION;\n return Date.now() - this.lastFetch < duration;\n }\n\n /**\n * Fetch rules from CDN\n */\n private async fetchFromCDN(url: string): Promise<Response> {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), RULE_CDN.TIMEOUT);\n\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: {\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n return response;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n /**\n * Cache rules in localStorage (browser only)\n */\n private cacheRules(rules: DetectionRules): void {\n if (!this.isBrowser) return;\n\n try {\n localStorage.setItem(RULE_CACHE.STORAGE_KEY, JSON.stringify(rules));\n localStorage.setItem(RULE_CACHE.TIMESTAMP_KEY, String(Date.now()));\n } catch (error) {\n // localStorage might be full or disabled\n console.warn('Failed to cache rules in localStorage:', error);\n }\n }\n\n /**\n * Clear cached rules\n */\n clearCache(): void {\n this.rules = null;\n this.lastFetch = 0;\n\n if (this.isBrowser) {\n try {\n localStorage.removeItem(RULE_CACHE.STORAGE_KEY);\n localStorage.removeItem(RULE_CACHE.TIMESTAMP_KEY);\n } catch {\n // Ignore localStorage errors\n }\n }\n }\n\n /**\n * Reset singleton instance (mainly for testing)\n */\n static reset(): void {\n if (this.instance) {\n this.instance.clearCache();\n this.instance = null;\n }\n }\n}\n\n// `loadRulesSync` convenience function was removed in Phase-D.8.\n// All consumers now call `RuleLoader.loadSync()` directly. The class\n// surface didn't change.\n\n/**\n * Export convenience function for async loading\n */\nexport async function loadRulesAsync(options?: RuleLoadOptions): Promise<DetectionRules> {\n const loader = RuleLoader.getInstance();\n return loader.loadRules(options);\n}\n","/**\n * vendor-range-freshness.ts (checkpoint P35).\n *\n * Independent staleness gate for the AIVF-1 vendor IP-range catalogue\n * (`packages/checkpoint-rules/data/agent-types.yaml`). Deliberately\n * decoupled from `scripts/refresh-ai-vendor-ips.ts`'s own exit-code\n * contract: that script exits 1 only when EVERY enabled vendor's fetch\n * fails in a single run (a runner-side incident signal), so one vendor\n * that has been failing quietly for weeks — DNS drift, a moved feed URL,\n * a persistent 403 — never fails the job as long as the other rows keep\n * succeeding. This module checks the RESULT (how long since we last\n * successfully checked this vendor) rather than the process (did today's\n * fetch succeed), so it catches the failure mode the exit code can't see.\n *\n * This is the same shape of defect that let the Tier-1 OpenAI signing-key\n * pin (rust/crates/kya-os-engine/data/vendor-keys/openai.json) sit\n * expired for ~2 months: a refresh script existed, nothing ran it on a\n * schedule, and nothing alarmed when the pinned data went stale. See that\n * file's `_meta.comment` for the incident this module exists to prevent\n * from recurring here.\n *\n * Reads `ip_feed.last_checked`, NOT `ip_feed.last_refreshed`. Those two\n * fields answer different questions — `last_refreshed` is the VENDOR's\n * own `creationTime` for the data currently stored (can legitimately sit\n * unchanged for months on a vendor whose prefix list simply hasn't\n * moved), while `last_checked` is the RUNNER's wall clock, stamped on\n * every successful evaluation regardless of whether the data changed.\n * An earlier version of this module read `last_refreshed`, which made\n * every low-churn vendor read as permanently stale even on a perfectly\n * healthy refresh cadence (Cursor Bugbot finding on the PR that\n * introduced this gate — fixed before merge, kept here as the\n * cautionary note for why this distinction matters).\n */\n\nexport interface VendorFreshnessInput {\n id: string;\n /** Vendor rows with `enabled === false` are skipped — they aren't refreshed, so their age is expected and not an incident. */\n enabled?: boolean;\n /** The vendor's `ip_feed.last_checked` value (runner wall clock, stamped on every successful check — see file header for why this is NOT `last_refreshed`), in whatever ISO-ish shape agent-types.yaml stores (with or without a `Z`/offset). A missing/empty value is treated as unparseable, i.e. maximally stale — see `findStaleVendorRanges`. */\n lastCheckedIso: string;\n}\n\nexport interface StaleVendorDetail {\n id: string;\n lastCheckedIso: string;\n /** Milliseconds between `now` and the parsed `lastCheckedIso`. `Infinity` when the timestamp couldn't be parsed at all. */\n ageMs: number;\n}\n\n// Daily cron cadence (see .github/workflows/refresh-ai-vendor-ips.yml) plus\n// a 3-day grace window: one missed run shouldn't page anyone, but three in\n// a row — or one vendor silently failing for that long — should.\nexport const DEFAULT_MAX_VENDOR_RANGE_AGE_MS = 4 * 24 * 60 * 60 * 1000;\n\n/**\n * Returns every ENABLED vendor whose `lastCheckedIso` is older than\n * `maxAgeMs`. An unparseable (or missing/empty) timestamp is treated as\n * maximally stale (`ageMs: Infinity`) rather than skipped — a row this\n * module can't prove is fresh must never be reported as fresh; failing\n * closed toward alarming is the whole point of this module (see file\n * header).\n */\nexport function findStaleVendorRanges(\n vendors: VendorFreshnessInput[],\n now: Date,\n maxAgeMs: number = DEFAULT_MAX_VENDOR_RANGE_AGE_MS\n): StaleVendorDetail[] {\n const stale: StaleVendorDetail[] = [];\n for (const v of vendors) {\n if (v.enabled === false) continue;\n\n const parsedMs = Date.parse(v.lastCheckedIso);\n const ageMs = Number.isNaN(parsedMs) ? Infinity : now.getTime() - parsedMs;\n\n if (ageMs > maxAgeMs) {\n stale.push({ id: v.id, lastCheckedIso: v.lastCheckedIso, ageMs });\n }\n }\n return stale;\n}\n\nexport class StaleVendorRangesError extends Error {\n constructor(readonly stale: StaleVendorDetail[]) {\n const detail = stale\n .map((s) => {\n const age =\n s.ageMs === Infinity\n ? `unparseable/missing last_checked (${JSON.stringify(s.lastCheckedIso)})`\n : `${(s.ageMs / (24 * 60 * 60 * 1000)).toFixed(1)}d old`;\n return `${s.id} (${age})`;\n })\n .join(', ');\n super(\n `${stale.length} vendor range set(s) exceeded the staleness threshold and must not be ` +\n `served quietly: ${detail}. Refresh has stopped keeping up for these vendors — ` +\n `investigate scripts/refresh-ai-vendor-ips.ts's recent runs before treating the ` +\n `existing data as trustworthy.`\n );\n this.name = 'StaleVendorRangesError';\n }\n}\n\n/**\n * Throws `StaleVendorRangesError` when any enabled vendor's range set is\n * older than `maxAgeMs`. This is the \"raise rather than serve quietly\"\n * half of the contract — callers that need a hard stop (the CI freshness\n * gate in scripts/check-vendor-ranges-freshness.ts) call this directly;\n * a caller on a hot request path that must never throw (e.g. a future\n * runtime consumer) should use `findStaleVendorRanges` and log instead.\n */\nexport function assertVendorRangesFresh(\n vendors: VendorFreshnessInput[],\n now: Date,\n maxAgeMs: number = DEFAULT_MAX_VENDOR_RANGE_AGE_MS\n): void {\n const stale = findStaleVendorRanges(vendors, now, maxAgeMs);\n if (stale.length > 0) {\n throw new StaleVendorRangesError(stale);\n }\n}\n","/**\n * Policy Constants\n *\n * Default values and constants for policy enforcement.\n * Aligned with Rust types in agentshield-types/src/policy.rs\n */\n\n/**\n * Available enforcement actions.\n *\n * **Vocab-1 migration (2026-05-13, see [[ADR-001]] amendment + Vocab-1\n * #2501).** The old vocabulary mixed two orthogonal axes — `'allow'` /\n * `'block'` (a Decision) and `'log'` (an EnforcementMode). The new\n * vocabulary separates them:\n *\n * - **Decision** (the engine's verdict): one of\n * `'permit' | 'block' | 'redirect' | 'challenge' | 'instruct'`.\n * - **EnforcementMode** (whether the host wrapper acts on the verdict):\n * one of `'enforce' | 'observe'` — see ENFORCEMENT_MODES below.\n *\n * `ALLOW` is kept as an alias for `PERMIT` during the cutover window\n * (per [[checkpoint-engine-phase-1-cutover]] runbook Cutover-2 — drop\n * after 30 days of zero `'allow'` writes). `LOG` is kept similarly —\n * a stored `'log'` row should be read as Permit + Observe mode.\n *\n * Producers (SDK middleware, gateway worker) emit `'permit'` going\n * forward. Consumers (dashboard, ingest validators) accept both during\n * the alias period and alias `'allow'` → display \"Permit\".\n */\nexport const ENFORCEMENT_ACTIONS = {\n /** New canonical name for \"the engine permits this request through.\" */\n PERMIT: 'permit',\n /**\n * @deprecated Use PERMIT. Kept as wire alias for the Vocab-1\n * cutover window. Drop after 30 days of zero stored writes.\n */\n ALLOW: 'allow',\n BLOCK: 'block',\n REDIRECT: 'redirect',\n CHALLENGE: 'challenge',\n /**\n * @deprecated Pre-Vocab-1: a stored `'log'` action was \"permit but\n * record.\" Post-Vocab-1: the same shape is `action: 'permit'` +\n * `mode: 'observe'` (orthogonal axes). Kept for read-back only;\n * producers should not emit `'log'` after Vocab-1 lands.\n */\n LOG: 'log',\n INSTRUCT: 'instruct',\n} as const;\n\nexport type EnforcementAction = (typeof ENFORCEMENT_ACTIONS)[keyof typeof ENFORCEMENT_ACTIONS];\n\n/**\n * EnforcementMode — orthogonal to EnforcementAction.\n *\n * Vocab-1 (2026-05-13) split \"what to do\" (the action / Decision) from\n * \"whether to act on it\" (the mode). Customers — especially regulated\n * enterprises — want a low-stakes evaluation ramp: install in Observe,\n * watch the dashboard for two weeks to see what *would have been*\n * blocked, then flip to Enforce. CISO-friendly.\n *\n * The host wrapper (Express middleware, Next.js middleware, .NET\n * filter, Cloudflare Worker) reads the mode and:\n *\n * - **Enforce**: applies the Decision — returns 401/403 for Block,\n * forwards Challenge headers, performs Redirect, etc.\n * - **Observe**: passes the request through to the origin regardless\n * of Decision, but records the would-have-been action in metadata\n * so the dashboard can render \"Would have been: Block(OutOfScope)\"\n * instead of \"Block(OutOfScope)\". Dash-1 (#2492) acceptance\n * criterion mandates this rendering distinction.\n */\nexport const ENFORCEMENT_MODES = {\n ENFORCE: 'enforce',\n OBSERVE: 'observe',\n} as const;\n\nexport type EnforcementMode = (typeof ENFORCEMENT_MODES)[keyof typeof ENFORCEMENT_MODES];\n\n/**\n * Match types for policy evaluation\n */\nexport const POLICY_MATCH_TYPES = {\n ALLOW_LIST: 'allow-list',\n DENY_LIST: 'deny-list',\n THRESHOLD: 'threshold',\n RULE: 'rule',\n DEFAULT: 'default',\n} as const;\n\nexport type PolicyMatchType = (typeof POLICY_MATCH_TYPES)[keyof typeof POLICY_MATCH_TYPES];\n\n/**\n * Condition operators for policy rules\n */\nexport const CONDITION_OPERATORS = {\n EQUALS: 'equals',\n NOT_EQUALS: 'notEquals',\n CONTAINS: 'contains',\n NOT_CONTAINS: 'notContains',\n STARTS_WITH: 'startsWith',\n ENDS_WITH: 'endsWith',\n GREATER_THAN: 'greaterThan',\n LESS_THAN: 'lessThan',\n GREATER_THAN_OR_EQUALS: 'greaterThanOrEquals',\n LESS_THAN_OR_EQUALS: 'lessThanOrEquals',\n MATCHES: 'matches',\n IN: 'in',\n NOT_IN: 'notIn',\n} as const;\n\nexport type ConditionOperator = (typeof CONDITION_OPERATORS)[keyof typeof CONDITION_OPERATORS];\n\n/**\n * Fields that can be matched in policy conditions\n */\nexport const CONDITION_FIELDS = {\n // Agent identification\n AGENT_TYPE: 'agentType',\n AGENT_NAME: 'agentName',\n AGENT_VENDOR: 'agentVendor',\n CLIENT_DID: 'clientDid',\n AGENT_DID: 'agentDid',\n // Detection metrics\n CONFIDENCE: 'confidence',\n REPUTATION_SCORE: 'reputationScore',\n RISK_LEVEL: 'riskLevel',\n // Request context\n PATH: 'path',\n METHOD: 'method',\n ORIGIN: 'origin',\n USER_AGENT: 'userAgent',\n // Verification status\n SIGNATURE_VERIFIED: 'signatureVerified',\n IS_AUTHENTICATED: 'isAuthenticated',\n HAS_VALID_DELEGATION: 'hasValidDelegation',\n} as const;\n\nexport type ConditionField = (typeof CONDITION_FIELDS)[keyof typeof CONDITION_FIELDS];\n\n/**\n * Default threshold configuration\n */\nexport const DEFAULT_THRESHOLDS = {\n confidenceThreshold: 80,\n confidenceAction: ENFORCEMENT_ACTIONS.BLOCK,\n minReputationScore: 0,\n lowReputationAction: ENFORCEMENT_ACTIONS.CHALLENGE,\n trustedReputationThreshold: 90,\n trustSignedRequests: true,\n} as const;\n\n/**\n * Default policy configuration\n */\nexport const DEFAULT_POLICY = {\n version: '1.0.0',\n enabled: true,\n // Vocab-1 (#2501): canonical default is PERMIT. ALLOW is still accepted on\n // the wire via the alias schema for stored rows, but new defaults emit the\n // canonical form so DEFAULT_POLICY and PolicyConfigSchema's default agree.\n defaultAction: ENFORCEMENT_ACTIONS.PERMIT,\n thresholds: DEFAULT_THRESHOLDS,\n denyList: [],\n allowList: [],\n rules: [],\n excludedPaths: [],\n} as const;\n\n/**\n * Default rule priority (lower = higher priority)\n */\nexport const DEFAULT_RULE_PRIORITY = 100;\n\n/**\n * Cache TTL values (in seconds)\n */\nexport const CACHE_TTL = {\n POLICY: 300, // 5 minutes\n API_KEY: 900, // 15 minutes\n} as const;\n\n/**\n * Policy version for schema migrations\n */\nexport const CURRENT_POLICY_VERSION = '1.0.0';\n","/**\n * Policy Zod Schemas\n *\n * Runtime validation schemas for policy configuration.\n * Aligned with Rust types in agentshield-types/src/policy.rs\n *\n * Policy evaluation order:\n * 1. Allow list (exempt agents, always allowed)\n * 2. Deny list (blocked agents, always blocked)\n * 3. Threshold checks (confidence, reputation)\n * 4. Custom rules (evaluated by priority, first match wins)\n * 5. Default action (if no rules match)\n */\n\nimport { z } from 'zod';\nimport {\n ENFORCEMENT_ACTIONS,\n ENFORCEMENT_MODES,\n CONDITION_OPERATORS,\n CONDITION_FIELDS,\n POLICY_MATCH_TYPES,\n DEFAULT_THRESHOLDS,\n DEFAULT_RULE_PRIORITY,\n CURRENT_POLICY_VERSION,\n} from './constants';\n\n// ============================================================================\n// Enforcement Actions + Mode (Vocab-1, 2026-05-13)\n// ============================================================================\n//\n// EnforcementActionSchema is in the alias-period of the Vocab-1\n// migration (#2501). The wire accepts both `'allow'` (legacy) and\n// `'permit'` (new canonical); the dashboard read-side displays both\n// as \"Permit.\" Producers (SDK, worker) emit `'permit'` going forward.\n// `'log'` is similarly accepted for read-back of legacy rows but\n// producers should emit `'permit'` + `EnforcementMode = 'observe'`\n// instead — those are orthogonal axes now.\n//\n// Drop the alias after 30 consecutive days of zero stored `'allow'`\n// or `'log'` writes (verify SQL in Cutover-2 runbook).\n\nexport const EnforcementActionSchema = z.enum([\n // New canonical:\n ENFORCEMENT_ACTIONS.PERMIT,\n ENFORCEMENT_ACTIONS.BLOCK,\n ENFORCEMENT_ACTIONS.REDIRECT,\n ENFORCEMENT_ACTIONS.CHALLENGE,\n ENFORCEMENT_ACTIONS.INSTRUCT,\n // Alias-period (deprecated; will be removed post-cutover):\n ENFORCEMENT_ACTIONS.ALLOW,\n ENFORCEMENT_ACTIONS.LOG,\n]);\n\n/**\n * Strict-mode action schema — drops the alias period entirely. Used by\n * conformance tests that prove producers no longer emit the deprecated\n * forms. After Cutover-2 completes, `EnforcementActionSchema` is\n * replaced by this strict version; the alias-tolerant schema retires.\n */\nexport const StrictEnforcementActionSchema = z.enum([\n ENFORCEMENT_ACTIONS.PERMIT,\n ENFORCEMENT_ACTIONS.BLOCK,\n ENFORCEMENT_ACTIONS.REDIRECT,\n ENFORCEMENT_ACTIONS.CHALLENGE,\n ENFORCEMENT_ACTIONS.INSTRUCT,\n]);\n\n/**\n * EnforcementMode — orthogonal to EnforcementAction. See\n * `ENFORCEMENT_MODES` in constants.ts for the full rationale.\n */\nexport const EnforcementModeSchema = z.enum([ENFORCEMENT_MODES.ENFORCE, ENFORCEMENT_MODES.OBSERVE]);\n\nexport type EnforcementMode = z.infer<typeof EnforcementModeSchema>;\n\n// ============================================================================\n// Decision schemas (Vocab-1) — TS mirror of the Rust `Decision` enum\n// defined by D-design (#2484). The engine doesn't emit these on the\n// TS side yet (it's the Rust engine's output); these schemas exist so\n// the dashboard ingest can validate them once the engine ships, and\n// so dashboard rendering code can derive its types from the canonical\n// shape rather than hand-paste a union. See [[ADR-001]] amendment +\n// TDD Spec Layer 1.\n// ============================================================================\n\n/**\n * Block reasons — priority order (Rust declaration order): Revoked >\n * InvalidSignature > Unauthenticated > Expired > OutOfScope >\n * LowReputation > PolicyDenied > AgentAttribution > ParseError >\n * Tier3UAMatch. The engine returns the most-actionable reason; this\n * schema accepts any of them. See TDD Spec Layer 1 for the priority\n * rules and `rust/crates/kya-os-engine/src/types.rs` for the wire SSOT.\n */\nexport const BlockReasonSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('Revoked') }),\n z.object({ kind: z.literal('InvalidSignature') }),\n z.object({ kind: z.literal('Unauthenticated') }),\n z.object({ kind: z.literal('Expired') }),\n z.object({\n kind: z.literal('OutOfScope'),\n requested: z.string(),\n granted: z.array(z.string()),\n }),\n z.object({\n kind: z.literal('LowReputation'),\n score: z.number(),\n threshold: z.number(),\n }),\n z.object({\n kind: z.literal('PolicyDenied'),\n detail: z.string(),\n // #3272 PR2: the determining policy's authored Cedar @id (the policies\n // index join key). Optional + additive — absent on pre-PR2 payloads.\n policyId: z.string().optional(),\n }),\n z.object({\n // Tier-2 IP+UA cross-match against the vendor SSOT (AIVF-1 Path B).\n // Emitted when the request carries both a vendor-published IP and a\n // matching UA pattern. `confidence` is f32 in [0, 1] — NOT the 0-100\n // scale the rest of the detection detail uses.\n kind: z.literal('AgentAttribution'),\n vendor: z.string(),\n tier: z.number().int(),\n confidence: z.number().min(0).max(1),\n }),\n z.object({ kind: z.literal('ParseError'), detail: z.string() }),\n z.object({\n // Tier-3 UA-only pattern-match short-circuit (engine default policy).\n // Field names are snake_case ON THE WIRE (the Rust enum has no\n // `rename_all`) and mirror the Rust struct fields verbatim.\n // `pattern_kind` is `KnownAiAgent` | `AiCrawler` | `HeadlessBrowser`\n // today; kept a loose string so future engine kinds stay additive.\n // `confidence` is an integer percent (0-100), unlike AgentAttribution.\n kind: z.literal('Tier3UAMatch'),\n pattern_id: z.string(),\n pattern_kind: z.string(),\n confidence: z.number().int().min(0).max(100),\n }),\n]);\n\nexport type BlockReason = z.infer<typeof BlockReasonSchema>;\n\n/**\n * The draft-kya-http-02 §1 assurance ladder, monotone floor → top. These are\n * the exact wire strings the merged kya-http fixtures pin\n * (`packages/checkpoint-shared/fixtures/kya-http`, e.g. `min_assurance`); the\n * Rust engine emits them on the verdict and reads them as `context.assurance`.\n * Canonical SSOT for the assurance tier / `min_assurance` enum.\n */\nexport const AssuranceTierSchema = z.enum([\n 'anonymous',\n 'attested-bearer',\n 'key-bound',\n 'registered',\n 'delegated',\n]);\n\n/** One draft-kya-http-02 §1 assurance tier. See {@link AssuranceTierSchema}. */\nexport type AssuranceTier = z.infer<typeof AssuranceTierSchema>;\n\n/**\n * ChallengeParams MUST be the KYA-OS L2+ handshake envelope shape, not\n * a parallel Checkpoint definition. Reusing the spec donated to DIF\n * gives every KYA-OS implementer free interop with Checkpoint's\n * Challenge flow. See [[ADR-001]] amendment.\n */\nexport const ChallengeParamsSchema = z.object({\n nonce: z.string(),\n audience: z.string(),\n expiresAt: z.number(), // unix seconds\n algorithmsAccepted: z.array(z.string()),\n // draft-kya-http-02 §1/§8 — the minimum assurance tier the policy demands\n // of the retry, set by a Cedar `@min_assurance(...)` annotation and\n // advertised by the PEP as `min_assurance` in the WWW-Authenticate\n // Delegation challenge. Optional + additive: absent for KYA-OS L2+ handshake\n // challenges, so the DIF interop shape is unchanged when unset.\n minAssurance: AssuranceTierSchema.optional(),\n // #3272 PR2: the determining policy's authored Cedar @id. Optional + additive.\n policyId: z.string().optional(),\n // Which handshake this challenge demands, set by a Cedar\n // `@challenge_type(...)` annotation. Kept a loose string (like\n // `Tier3UAMatch.pattern_kind` above) rather than a strict `z.enum` so a\n // FUTURE engine-added kind an older deployed dashboard doesn't know yet\n // stays additive instead of failing validation. Absent means\n // `'delegation'` — the pre-existing MCP-I Level 2+ handshake — and every\n // renderer MUST treat an unrecognized value the same way. See\n // `normalizeChallengeType`.\n challengeType: z.string().optional(),\n});\n\nexport type ChallengeParams = z.infer<typeof ChallengeParamsSchema>;\n\n/**\n * Normalize a wire `challengeType` to the kind every renderer must treat it\n * as. Absent or unrecognized (a future engine-added kind) falls closed to\n * `'delegation'` — the pre-existing MCP-I Level 2+ handshake every renderer\n * already understands — never thrown or silently dropped.\n */\nexport function normalizeChallengeType(\n challengeType: string | undefined\n): 'delegation' | 'browser_integrity' | 'human_step_up' {\n return challengeType === 'browser_integrity' || challengeType === 'human_step_up'\n ? challengeType\n : 'delegation';\n}\n\nexport const RedirectTargetSchema = z.object({\n url: z.string().url(),\n reason: z.string(),\n state: z.string().optional(),\n // #3272 PR2: the determining policy's authored Cedar @id. Optional + additive.\n policyId: z.string().optional(),\n});\n\nexport type RedirectTarget = z.infer<typeof RedirectTargetSchema>;\n\nexport const SuggestedActionSchema = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('UseDifferentScope'), scope: z.string() }),\n z.object({\n kind: z.literal('UpdateRequestField'),\n field: z.string(),\n acceptedValues: z.array(z.string()),\n }),\n z.object({ kind: z.literal('UpgradeProtocolVersion'), version: z.string() }),\n z.object({ kind: z.literal('Other'), code: z.string(), detail: z.string() }),\n]);\n\nexport type SuggestedAction = z.infer<typeof SuggestedActionSchema>;\n\nexport const InstructPayloadSchema = z.object({\n problem: z.string(),\n title: z.string(),\n suggestedActions: z.array(SuggestedActionSchema),\n // #3272 PR2: the determining policy's authored Cedar @id. Optional + additive.\n policyId: z.string().optional(),\n});\n\nexport type InstructPayload = z.infer<typeof InstructPayloadSchema>;\n\n/**\n * Decision — the Detect → Verify → **Decide** axis. Five variants\n * with per-variant payload via discriminated union. Mirrors the Rust\n * `Decision` enum (D-design #2484); the dashboard renders one badge\n * per variant (see Dash-1 #2492). The wire-side EnforcementAction\n * string above is the legacy flat encoding; this is the canonical\n * structured replacement.\n */\nexport const DecisionSchema = z.discriminatedUnion('kind', [\n // #3272 PR2: optional policyId = the authored Cedar @id of the determining\n // permit policy (\"which rule admitted this\"). Absent on pre-PR2 payloads and\n // non-policy-determined permits.\n z.object({ kind: z.literal('Permit'), policyId: z.string().optional() }),\n z.object({ kind: z.literal('Block'), reason: BlockReasonSchema }),\n z.object({ kind: z.literal('Challenge'), params: ChallengeParamsSchema }),\n z.object({ kind: z.literal('Redirect'), target: RedirectTargetSchema }),\n z.object({ kind: z.literal('Instruct'), payload: InstructPayloadSchema }),\n]);\n\nexport type Decision = z.infer<typeof DecisionSchema>;\n\n// ============================================================================\n// Threshold Configuration\n// ============================================================================\n\nexport const ThresholdConfigSchema = z.object({\n /** Detection confidence threshold (0-100) */\n confidenceThreshold: z.number().min(0).max(100).default(DEFAULT_THRESHOLDS.confidenceThreshold),\n /** Action to take when confidence threshold is exceeded */\n confidenceAction: EnforcementActionSchema.default(DEFAULT_THRESHOLDS.confidenceAction),\n /** Minimum reputation score (0-100) required to allow access */\n minReputationScore: z.number().min(0).max(100).default(DEFAULT_THRESHOLDS.minReputationScore),\n /** Action to take when reputation is below threshold */\n lowReputationAction: EnforcementActionSchema.default(DEFAULT_THRESHOLDS.lowReputationAction),\n /** High reputation score threshold (0-100) - trusted agents bypass other checks */\n trustedReputationThreshold: z\n .number()\n .min(0)\n .max(100)\n .default(DEFAULT_THRESHOLDS.trustedReputationThreshold),\n /** Whether cryptographically signed requests bypass thresholds */\n trustSignedRequests: z.boolean().default(DEFAULT_THRESHOLDS.trustSignedRequests),\n});\n\n// ============================================================================\n// List Entries\n// ============================================================================\n\nexport const DenyListEntrySchema = z.object({\n /** KYA-OS client DID */\n clientDid: z.string().optional(),\n /** Agent DID from KYA-OS identity */\n agentDid: z.string().optional(),\n /** Human-readable client name (e.g., \"ChatGPT\") */\n clientName: z.string().optional(),\n /** Agent type to block (e.g., \"ai_agent\", \"bot\") */\n agentType: z.string().optional(),\n /** Reason for denial */\n reason: z.string().optional(),\n /** ISO 8601 timestamp when entry was added */\n blockedAt: z.string().optional(),\n /** Who added this entry */\n addedBy: z.string().optional(),\n /** Whether this entry is currently active */\n active: z.boolean().default(true),\n /** Optional expiration date for temporary blocks */\n expiresAt: z.string().optional(),\n});\n\nexport const AllowListEntrySchema = z.object({\n /** KYA-OS client DID */\n clientDid: z.string().optional(),\n /** Agent DID from KYA-OS identity */\n agentDid: z.string().optional(),\n /** Human-readable client name */\n clientName: z.string().optional(),\n /** Agent type to allow */\n agentType: z.string().optional(),\n /** Reason for allowing */\n reason: z.string().optional(),\n /** ISO 8601 timestamp when entry was added */\n addedAt: z.string().optional(),\n /** Who added this entry */\n addedBy: z.string().optional(),\n});\n\n// ============================================================================\n// Policy Conditions\n// ============================================================================\n\nexport const ConditionOperatorSchema = z.enum([\n CONDITION_OPERATORS.EQUALS,\n CONDITION_OPERATORS.NOT_EQUALS,\n CONDITION_OPERATORS.CONTAINS,\n CONDITION_OPERATORS.NOT_CONTAINS,\n CONDITION_OPERATORS.STARTS_WITH,\n CONDITION_OPERATORS.ENDS_WITH,\n CONDITION_OPERATORS.GREATER_THAN,\n CONDITION_OPERATORS.LESS_THAN,\n CONDITION_OPERATORS.GREATER_THAN_OR_EQUALS,\n CONDITION_OPERATORS.LESS_THAN_OR_EQUALS,\n CONDITION_OPERATORS.MATCHES,\n CONDITION_OPERATORS.IN,\n CONDITION_OPERATORS.NOT_IN,\n]);\n\nexport const ConditionFieldSchema = z.enum([\n // Agent identification\n CONDITION_FIELDS.AGENT_TYPE,\n CONDITION_FIELDS.AGENT_NAME,\n CONDITION_FIELDS.AGENT_VENDOR,\n CONDITION_FIELDS.CLIENT_DID,\n CONDITION_FIELDS.AGENT_DID,\n // Detection metrics\n CONDITION_FIELDS.CONFIDENCE,\n CONDITION_FIELDS.REPUTATION_SCORE,\n CONDITION_FIELDS.RISK_LEVEL,\n // Request context\n CONDITION_FIELDS.PATH,\n CONDITION_FIELDS.METHOD,\n CONDITION_FIELDS.ORIGIN,\n CONDITION_FIELDS.USER_AGENT,\n // Verification status\n CONDITION_FIELDS.SIGNATURE_VERIFIED,\n CONDITION_FIELDS.IS_AUTHENTICATED,\n CONDITION_FIELDS.HAS_VALID_DELEGATION,\n]);\n\nexport const ConditionValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.array(z.string()),\n]);\n\nexport const PolicyConditionSchema = z.object({\n /** Field to match against */\n field: ConditionFieldSchema,\n /** Comparison operator */\n operator: ConditionOperatorSchema,\n /** Value to compare against */\n value: ConditionValueSchema,\n /** Whether this condition is case-insensitive */\n caseInsensitive: z.boolean().optional(),\n});\n\n// ============================================================================\n// Policy Rules\n// ============================================================================\n\nexport const RuleMetadataSchema = z.object({\n createdAt: z.string().optional(),\n updatedAt: z.string().optional(),\n createdBy: z.string().optional(),\n});\n\nexport const PolicyRuleSchema = z.object({\n /** Unique identifier for this rule */\n id: z.string(),\n /** Human-readable name */\n name: z.string(),\n /** Description of what this rule does */\n description: z.string().optional(),\n /** Priority (lower = higher priority, evaluated first) */\n priority: z.number().int().default(DEFAULT_RULE_PRIORITY),\n /** Conditions that must ALL match for this rule to apply (AND logic) */\n conditions: z.array(PolicyConditionSchema),\n /** Action to take when conditions match */\n action: EnforcementActionSchema,\n /** Redirect URL (required if action is 'redirect') */\n redirectUrl: z.string().url().optional(),\n /** Custom message to show/log */\n message: z.string().optional(),\n /** Whether this rule is currently active */\n enabled: z.boolean().default(true),\n /** Metadata for auditing */\n metadata: RuleMetadataSchema.optional(),\n});\n\n// ============================================================================\n// Policy Configuration\n// ============================================================================\n\nexport const PolicyMetadataSchema = z.object({\n lastUpdated: z.string().optional(),\n updatedBy: z.string().optional(),\n policyId: z.string().optional(),\n});\n\nexport const PolicyConfigSchema = z.object({\n /** Schema version for migrations */\n version: z.string().default(CURRENT_POLICY_VERSION),\n /** Whether policy enforcement is enabled */\n enabled: z.boolean().default(true),\n /** Default action when no rules match. Updated to PERMIT (was ALLOW)\n * per Vocab-1 (#2501); the wire still accepts both via the alias\n * schema so existing stored policies continue to load. */\n defaultAction: EnforcementActionSchema.default(ENFORCEMENT_ACTIONS.PERMIT),\n /** Default redirect URL for redirect actions */\n redirectUrl: z.string().url().optional(),\n /** Threshold-based enforcement settings */\n // prefault, not default: Zod 4 returns a default value as is, so `{}` would skip the\n // per-field defaults inside ThresholdConfigSchema. prefault parses it, as Zod 3 did.\n thresholds: ThresholdConfigSchema.prefault({}),\n /** Deny list entries (checked after allow list, before rules) */\n denyList: z.array(DenyListEntrySchema).default([]),\n /** Allow list entries (exempt from all checks) */\n allowList: z.array(AllowListEntrySchema).default([]),\n /** Custom policy rules (evaluated by priority after threshold checks) */\n rules: z.array(PolicyRuleSchema).default([]),\n /** Paths to exclude from policy enforcement (glob patterns supported) */\n excludedPaths: z.array(z.string()).default([]),\n /** Paths to include (if set, only these paths are enforced) */\n includedPaths: z.array(z.string()).optional(),\n /** Metadata for the policy configuration */\n metadata: PolicyMetadataSchema.optional(),\n\n // ── Composed-policy (kya-os-engine) fields ──────────────────────────────\n // The policy API (`/api/internal/policies/[projectId]`) serves these so a\n // runtime that embeds the engine's Cedar evaluator can enforce the composed\n // `/policy-compose` output — identically to the DNS gateway worker — instead\n // of (or alongside) the structured fields above. They are carried through the\n // fetch contract here so the middleware (Express / Next.js / .NET) receives\n // them; runtimes that don't run the engine simply ignore them. Optional +\n // safe defaults: a policy without a composed bundle is unaffected.\n\n /**\n * Composed policy source (Cedar today). `null`/absent → no composed policy\n * (the runtime uses the structured fields). Empty/blank is treated as \"no\n * policy\" by the engine path (an empty bundle compiles to deny-all), so the\n * runtime MUST normalize blank → absent before handing it to the evaluator.\n */\n policySourceText: z.string().nullish(),\n /**\n * Language of `policySourceText`. `cedar` today; kept as a free string (not an\n * enum) so a future Rego/OPA bundle flows through the same contract without a\n * schema-version bump. A runtime enforces only languages it actually embeds.\n */\n policyLanguage: z.string().nullish(),\n /**\n * Hex sha256 of `policySourceText` as served by the SSOT — byte-identical to\n * `policy_revisions.composed_blob_hash` (#3246 PR5). Runtimes ECHO it onto\n * acted decisions (`enforcement.composedBlobHash`) and Delegation challenges\n * (`challenge.composed_blob_hash`) as the point-in-time revision pin; they\n * never hash locally. Absent/null → plane omits the pin (older dashboards).\n */\n policySourceHash: z.string().nullish(),\n /**\n * Whether the engine should ACT on the composed policy (deployed-to-enforce).\n * False → the composed policy is at most shadow-evaluated; the structured\n * path / bespoke decision governs. Mirrors the gateway worker's act-gate\n * (`engineEnforcementEnabled === true && enabled !== false`).\n */\n engineEnforcementEnabled: z.boolean().optional().default(false),\n\n /**\n * Trusted Layer-2 delegation root DIDs for the project's org (P2 / DR-1),\n * server-resolved by the policy API. A consuming middleware forwards these\n * into the engine's `ContextSpec.trustedDelegationRoots` so L2 delegation\n * chains are pinned to the org DID. Absent ⇒ omitted (root pinning disabled —\n * the engine's open default, byte-identical to pre-P2). Optional (no default)\n * so a policy without the field round-trips as `undefined`, matching the\n * policy API's `PolicyResponse` shape and the orchestrator's omit-when-unset\n * contract.\n */\n trustedDelegationRoots: z.array(z.string()).optional(),\n});\n\n// ============================================================================\n// Evaluation Context & Result\n// ============================================================================\n\nexport const PolicyEvaluationContextSchema = z.object({\n // Agent identification\n agentType: z.string().optional(),\n agentName: z.string().optional(),\n agentVendor: z.string().optional(),\n clientDid: z.string().optional(),\n agentDid: z.string().optional(),\n // Detection metrics\n confidence: z.number().min(0).max(100).optional(),\n reputationScore: z.number().min(0).max(100).optional(),\n riskLevel: z.string().optional(),\n // Request context\n path: z.string().optional(),\n method: z.string().optional(),\n origin: z.string().optional(),\n userAgent: z.string().optional(),\n // Verification status\n signatureVerified: z.boolean().default(false),\n isAuthenticated: z.boolean().default(false),\n hasValidDelegation: z.boolean().default(false),\n});\n\nexport const PolicyMatchTypeSchema = z.enum([\n POLICY_MATCH_TYPES.ALLOW_LIST,\n POLICY_MATCH_TYPES.DENY_LIST,\n POLICY_MATCH_TYPES.THRESHOLD,\n POLICY_MATCH_TYPES.RULE,\n POLICY_MATCH_TYPES.DEFAULT,\n]);\n\nexport const PolicyEvaluationResultSchema = z.object({\n /** Enforcement action to take */\n action: EnforcementActionSchema,\n /** Reason for the action */\n reason: z.string(),\n /** Rule ID that matched (if any) */\n ruleId: z.string().optional(),\n /** Rule name that matched (if any) */\n ruleName: z.string().optional(),\n /** Redirect URL (if action is 'redirect') */\n redirectUrl: z.string().optional(),\n /** Custom message from the matched rule */\n message: z.string().optional(),\n /** What type of match triggered this decision */\n matchType: PolicyMatchTypeSchema,\n});\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type EnforcementAction = z.infer<typeof EnforcementActionSchema>;\nexport type ThresholdConfig = z.infer<typeof ThresholdConfigSchema>;\nexport type DenyListEntry = z.infer<typeof DenyListEntrySchema>;\nexport type AllowListEntry = z.infer<typeof AllowListEntrySchema>;\nexport type ConditionOperator = z.infer<typeof ConditionOperatorSchema>;\nexport type ConditionField = z.infer<typeof ConditionFieldSchema>;\nexport type ConditionValue = z.infer<typeof ConditionValueSchema>;\nexport type PolicyCondition = z.infer<typeof PolicyConditionSchema>;\nexport type RuleMetadata = z.infer<typeof RuleMetadataSchema>;\nexport type PolicyRule = z.infer<typeof PolicyRuleSchema>;\nexport type PolicyMetadata = z.infer<typeof PolicyMetadataSchema>;\nexport type PolicyConfig = z.infer<typeof PolicyConfigSchema>;\nexport type PolicyEvaluationContext = z.infer<typeof PolicyEvaluationContextSchema>;\nexport type PolicyMatchType = z.infer<typeof PolicyMatchTypeSchema>;\nexport type PolicyEvaluationResult = z.infer<typeof PolicyEvaluationResultSchema>;\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Validate and parse a policy configuration\n */\nexport function parsePolicyConfig(data: unknown): PolicyConfig {\n return PolicyConfigSchema.parse(data);\n}\n\n/**\n * Safely parse a policy configuration (returns null on error)\n */\nexport function safeParsePolicyConfig(data: unknown): PolicyConfig | null {\n const result = PolicyConfigSchema.safeParse(data);\n return result.success ? result.data : null;\n}\n\n/**\n * Validate a policy evaluation context\n */\nexport function parseEvaluationContext(data: unknown): PolicyEvaluationContext {\n return PolicyEvaluationContextSchema.parse(data);\n}\n","/**\n * Policy Evaluator\n *\n * TypeScript implementation of policy evaluation, aligned with Rust's\n * checkpoint/src/policy/evaluation.rs for parity.\n *\n * Evaluation order:\n * 1. Allow list (exempt agents, always allowed)\n * 2. Deny list (blocked agents, always blocked)\n * 3. Threshold checks (confidence, reputation, signature)\n * 4. Custom rules (evaluated by priority, first match wins)\n * 5. Default action (if no rules match)\n */\n\nimport {\n ENFORCEMENT_ACTIONS,\n POLICY_MATCH_TYPES,\n CONDITION_OPERATORS,\n CONDITION_FIELDS,\n} from './constants';\n\nimport type {\n PolicyConfig,\n PolicyRule,\n PolicyCondition,\n PolicyEvaluationContext,\n PolicyEvaluationResult,\n DenyListEntry,\n AllowListEntry,\n ConditionValue,\n EnforcementAction,\n} from './schemas';\n\n// ============================================================================\n// Main Evaluator\n// ============================================================================\n\n/**\n * Evaluate a policy against a context and return the enforcement decision.\n *\n * This is the main entry point for policy evaluation. It follows the same\n * evaluation order as the Rust implementation for parity.\n */\nexport function evaluatePolicy(\n policy: PolicyConfig,\n context: PolicyEvaluationContext\n): PolicyEvaluationResult {\n // Check if policy is disabled\n if (!policy.enabled) {\n return createResult(\n ENFORCEMENT_ACTIONS.ALLOW,\n 'Policy enforcement disabled',\n POLICY_MATCH_TYPES.DEFAULT\n );\n }\n\n // Check path exclusions/inclusions\n if (context.path) {\n if (isPathExcluded(context.path, policy.excludedPaths)) {\n return createResult(\n ENFORCEMENT_ACTIONS.ALLOW,\n 'Path is excluded from policy enforcement',\n POLICY_MATCH_TYPES.DEFAULT\n );\n }\n\n if (policy.includedPaths && policy.includedPaths.length > 0) {\n if (!isPathIncluded(context.path, policy.includedPaths)) {\n return createResult(\n ENFORCEMENT_ACTIONS.ALLOW,\n 'Path is not in included paths',\n POLICY_MATCH_TYPES.DEFAULT\n );\n }\n }\n }\n\n // 1. Check allow list (highest priority)\n const allowMatch = matchAllowList(context, policy.allowList);\n if (allowMatch) {\n return createResult(\n ENFORCEMENT_ACTIONS.ALLOW,\n `Matched allow list: ${allowMatch.reason || allowMatch.clientName || 'entry'}`,\n POLICY_MATCH_TYPES.ALLOW_LIST\n );\n }\n\n // 2. Check deny list\n const denyMatch = matchDenyList(context, policy.denyList);\n if (denyMatch) {\n return createResult(\n ENFORCEMENT_ACTIONS.BLOCK,\n `Matched deny list: ${denyMatch.reason || denyMatch.clientName || 'entry'}`,\n POLICY_MATCH_TYPES.DENY_LIST,\n { message: denyMatch.reason || 'Access denied - agent is blocked' }\n );\n }\n\n // 3. Check threshold configuration\n const thresholdResult = evaluateThresholds(policy, context);\n if (thresholdResult) {\n return thresholdResult;\n }\n\n // 4. Evaluate custom rules (sorted by priority, first match wins)\n const ruleResult = evaluateRules(policy.rules, context, policy.redirectUrl);\n if (ruleResult) {\n return ruleResult;\n }\n\n // 5. Default action\n return createResult(\n policy.defaultAction,\n 'No rules matched, applying default action',\n POLICY_MATCH_TYPES.DEFAULT,\n {\n redirectUrl:\n policy.defaultAction === ENFORCEMENT_ACTIONS.REDIRECT ||\n policy.defaultAction === ENFORCEMENT_ACTIONS.INSTRUCT\n ? policy.redirectUrl\n : undefined,\n }\n );\n}\n\n// ============================================================================\n// Allow/Deny List Matching\n// ============================================================================\n\n/**\n * Check if the context matches any allow list entry\n */\nfunction matchAllowList(\n context: PolicyEvaluationContext,\n allowList: AllowListEntry[]\n): AllowListEntry | null {\n for (const entry of allowList) {\n if (matchListEntry(context, entry)) {\n return entry;\n }\n }\n return null;\n}\n\n/**\n * Check if the context matches any deny list entry\n */\nfunction matchDenyList(\n context: PolicyEvaluationContext,\n denyList: DenyListEntry[]\n): DenyListEntry | null {\n for (const entry of denyList) {\n // Skip inactive entries\n if (entry.active === false) {\n continue;\n }\n\n // Check if entry has expired\n if (entry.expiresAt && new Date(entry.expiresAt) < new Date()) {\n continue;\n }\n\n if (matchListEntry(context, entry)) {\n return entry;\n }\n }\n return null;\n}\n\n/**\n * Match a context against an allow/deny list entry\n */\nfunction matchListEntry(\n context: PolicyEvaluationContext,\n entry: AllowListEntry | DenyListEntry\n): boolean {\n // Match by client DID\n if (entry.clientDid && context.clientDid) {\n if (entry.clientDid === context.clientDid) {\n return true;\n }\n }\n\n // Match by agent DID\n if (entry.agentDid && context.agentDid) {\n if (entry.agentDid === context.agentDid) {\n return true;\n }\n }\n\n // Match by client name (case-insensitive substring match)\n if (entry.clientName && context.agentName) {\n if (context.agentName.toLowerCase().includes(entry.clientName.toLowerCase())) {\n return true;\n }\n }\n\n // Match by agent type\n if (entry.agentType && context.agentType) {\n if (entry.agentType.toLowerCase() === context.agentType.toLowerCase()) {\n return true;\n }\n }\n\n return false;\n}\n\n// ============================================================================\n// Threshold Evaluation\n// ============================================================================\n\n/**\n * Evaluate threshold-based rules\n */\nfunction evaluateThresholds(\n policy: PolicyConfig,\n context: PolicyEvaluationContext\n): PolicyEvaluationResult | null {\n const { thresholds } = policy;\n\n // Check if signed requests bypass thresholds\n if (thresholds.trustSignedRequests && context.signatureVerified) {\n return createResult(\n ENFORCEMENT_ACTIONS.ALLOW,\n 'Request has valid cryptographic signature',\n POLICY_MATCH_TYPES.THRESHOLD\n );\n }\n\n // Check trusted reputation threshold (bypass other checks)\n if (\n context.reputationScore !== undefined &&\n context.reputationScore >= thresholds.trustedReputationThreshold\n ) {\n return createResult(\n ENFORCEMENT_ACTIONS.ALLOW,\n `High reputation score (${context.reputationScore} >= ${thresholds.trustedReputationThreshold})`,\n POLICY_MATCH_TYPES.THRESHOLD\n );\n }\n\n // Check low reputation threshold\n if (\n context.reputationScore !== undefined &&\n context.reputationScore < thresholds.minReputationScore\n ) {\n return createResult(\n thresholds.lowReputationAction,\n `Low reputation score (${context.reputationScore} < ${thresholds.minReputationScore})`,\n POLICY_MATCH_TYPES.THRESHOLD,\n {\n redirectUrl:\n thresholds.lowReputationAction === ENFORCEMENT_ACTIONS.REDIRECT ||\n thresholds.lowReputationAction === ENFORCEMENT_ACTIONS.INSTRUCT\n ? policy.redirectUrl\n : undefined,\n }\n );\n }\n\n // Check confidence threshold\n if (context.confidence !== undefined && context.confidence >= thresholds.confidenceThreshold) {\n return createResult(\n thresholds.confidenceAction,\n `Confidence threshold exceeded (${context.confidence} >= ${thresholds.confidenceThreshold})`,\n POLICY_MATCH_TYPES.THRESHOLD,\n {\n redirectUrl:\n thresholds.confidenceAction === ENFORCEMENT_ACTIONS.REDIRECT ||\n thresholds.confidenceAction === ENFORCEMENT_ACTIONS.INSTRUCT\n ? policy.redirectUrl\n : undefined,\n }\n );\n }\n\n return null;\n}\n\n// ============================================================================\n// Rule Evaluation\n// ============================================================================\n\n/**\n * Evaluate custom policy rules\n */\nfunction evaluateRules(\n rules: PolicyRule[],\n context: PolicyEvaluationContext,\n defaultRedirectUrl?: string\n): PolicyEvaluationResult | null {\n // Sort rules by priority (lower = higher priority)\n const sortedRules = [...rules].sort((a, b) => a.priority - b.priority);\n\n for (const rule of sortedRules) {\n // Skip disabled rules\n if (!rule.enabled) {\n continue;\n }\n\n // Skip rules with empty conditions to prevent accidental match-all behavior\n // (JavaScript's every() returns true for empty arrays)\n if (rule.conditions.length === 0) {\n continue;\n }\n\n // All conditions must match (AND logic)\n const allConditionsMatch = rule.conditions.every((condition) =>\n evaluateCondition(condition, context)\n );\n\n if (allConditionsMatch) {\n return createResult(\n rule.action,\n rule.message || `Matched rule: ${rule.name}`,\n POLICY_MATCH_TYPES.RULE,\n {\n ruleId: rule.id,\n ruleName: rule.name,\n message: rule.message,\n redirectUrl:\n rule.action === ENFORCEMENT_ACTIONS.REDIRECT ||\n rule.action === ENFORCEMENT_ACTIONS.INSTRUCT\n ? rule.redirectUrl || defaultRedirectUrl\n : undefined,\n }\n );\n }\n }\n\n return null;\n}\n\n/**\n * Evaluate a single condition against the context\n */\nfunction evaluateCondition(condition: PolicyCondition, context: PolicyEvaluationContext): boolean {\n const contextValue = getFieldValue(condition.field, context);\n const { operator, value, caseInsensitive } = condition;\n\n // Handle undefined context values\n if (contextValue === undefined || contextValue === null) {\n // For \"not\" operators, undefined means the condition passes\n if (\n operator === CONDITION_OPERATORS.NOT_EQUALS ||\n operator === CONDITION_OPERATORS.NOT_CONTAINS ||\n operator === CONDITION_OPERATORS.NOT_IN\n ) {\n return true;\n }\n return false;\n }\n\n return compareValues(contextValue, operator, value, caseInsensitive);\n}\n\n/**\n * Get the value of a field from the context\n */\nfunction getFieldValue(\n field: string,\n context: PolicyEvaluationContext\n): string | number | boolean | undefined {\n switch (field) {\n // Agent identification\n case CONDITION_FIELDS.AGENT_TYPE:\n return context.agentType;\n case CONDITION_FIELDS.AGENT_NAME:\n return context.agentName;\n case CONDITION_FIELDS.AGENT_VENDOR:\n return context.agentVendor;\n case CONDITION_FIELDS.CLIENT_DID:\n return context.clientDid;\n case CONDITION_FIELDS.AGENT_DID:\n return context.agentDid;\n\n // Detection metrics\n case CONDITION_FIELDS.CONFIDENCE:\n return context.confidence;\n case CONDITION_FIELDS.REPUTATION_SCORE:\n return context.reputationScore;\n case CONDITION_FIELDS.RISK_LEVEL:\n return context.riskLevel;\n\n // Request context\n case CONDITION_FIELDS.PATH:\n return context.path;\n case CONDITION_FIELDS.METHOD:\n return context.method;\n case CONDITION_FIELDS.ORIGIN:\n return context.origin;\n case CONDITION_FIELDS.USER_AGENT:\n return context.userAgent;\n\n // Verification status\n case CONDITION_FIELDS.SIGNATURE_VERIFIED:\n return context.signatureVerified;\n case CONDITION_FIELDS.IS_AUTHENTICATED:\n return context.isAuthenticated;\n case CONDITION_FIELDS.HAS_VALID_DELEGATION:\n return context.hasValidDelegation;\n\n default:\n return undefined;\n }\n}\n\n/**\n * Compare values using the specified operator\n */\nfunction compareValues(\n contextValue: string | number | boolean,\n operator: string,\n conditionValue: ConditionValue,\n caseInsensitive?: boolean\n): boolean {\n // Normalize strings for case-insensitive comparison\n const normalizeStr = (v: unknown): string => {\n const str = String(v);\n return caseInsensitive ? str.toLowerCase() : str;\n };\n\n switch (operator) {\n case CONDITION_OPERATORS.EQUALS:\n if (typeof contextValue === 'string' && typeof conditionValue === 'string') {\n return normalizeStr(contextValue) === normalizeStr(conditionValue);\n }\n return contextValue === conditionValue;\n\n case CONDITION_OPERATORS.NOT_EQUALS:\n if (typeof contextValue === 'string' && typeof conditionValue === 'string') {\n return normalizeStr(contextValue) !== normalizeStr(conditionValue);\n }\n return contextValue !== conditionValue;\n\n case CONDITION_OPERATORS.CONTAINS:\n if (typeof contextValue === 'string' && typeof conditionValue === 'string') {\n return normalizeStr(contextValue).includes(normalizeStr(conditionValue));\n }\n return false;\n\n case CONDITION_OPERATORS.NOT_CONTAINS:\n if (typeof contextValue === 'string' && typeof conditionValue === 'string') {\n return !normalizeStr(contextValue).includes(normalizeStr(conditionValue));\n }\n return true;\n\n case CONDITION_OPERATORS.STARTS_WITH:\n if (typeof contextValue === 'string' && typeof conditionValue === 'string') {\n return normalizeStr(contextValue).startsWith(normalizeStr(conditionValue));\n }\n return false;\n\n case CONDITION_OPERATORS.ENDS_WITH:\n if (typeof contextValue === 'string' && typeof conditionValue === 'string') {\n return normalizeStr(contextValue).endsWith(normalizeStr(conditionValue));\n }\n return false;\n\n case CONDITION_OPERATORS.GREATER_THAN:\n if (typeof contextValue === 'number' && typeof conditionValue === 'number') {\n return contextValue > conditionValue;\n }\n return false;\n\n case CONDITION_OPERATORS.LESS_THAN:\n if (typeof contextValue === 'number' && typeof conditionValue === 'number') {\n return contextValue < conditionValue;\n }\n return false;\n\n case CONDITION_OPERATORS.GREATER_THAN_OR_EQUALS:\n if (typeof contextValue === 'number' && typeof conditionValue === 'number') {\n return contextValue >= conditionValue;\n }\n return false;\n\n case CONDITION_OPERATORS.LESS_THAN_OR_EQUALS:\n if (typeof contextValue === 'number' && typeof conditionValue === 'number') {\n return contextValue <= conditionValue;\n }\n return false;\n\n case CONDITION_OPERATORS.MATCHES:\n if (typeof contextValue === 'string' && typeof conditionValue === 'string') {\n try {\n const flags = caseInsensitive ? 'i' : '';\n const regex = new RegExp(conditionValue, flags);\n return regex.test(contextValue);\n } catch {\n return false;\n }\n }\n return false;\n\n case CONDITION_OPERATORS.IN:\n if (Array.isArray(conditionValue)) {\n const contextStr = normalizeStr(contextValue);\n return conditionValue.some((v) => normalizeStr(v) === contextStr);\n }\n return false;\n\n case CONDITION_OPERATORS.NOT_IN:\n if (Array.isArray(conditionValue)) {\n const contextStr = normalizeStr(contextValue);\n return !conditionValue.some((v) => normalizeStr(v) === contextStr);\n }\n return true;\n\n default:\n return false;\n }\n}\n\n// ============================================================================\n// Path Matching\n// ============================================================================\n\n/**\n * Check if a path matches any excluded pattern\n */\nfunction isPathExcluded(path: string, excludedPaths: string[]): boolean {\n return excludedPaths.some((pattern) => matchPath(path, pattern));\n}\n\n/**\n * Check if a path matches any included pattern\n */\nfunction isPathIncluded(path: string, includedPaths: string[]): boolean {\n return includedPaths.some((pattern) => matchPath(path, pattern));\n}\n\n/**\n * Match a path against a glob pattern\n */\nexport function matchPath(path: string, pattern: string): boolean {\n // Exact match\n if (pattern === path) {\n return true;\n }\n\n // Glob pattern with wildcards\n if (pattern.includes('*')) {\n const regexPattern = pattern\n .replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&') // Escape regex special chars\n .replace(/\\*\\*/g, '<<GLOBSTAR>>') // Temporarily replace **\n .replace(/\\*/g, '[^/]*') // Single * matches anything except /\n .replace(/<<GLOBSTAR>>/g, '.*'); // ** matches anything including /\n try {\n return new RegExp(`^${regexPattern}$`).test(path);\n } catch {\n return false;\n }\n }\n\n // Prefix match (pattern ends with /)\n if (pattern.endsWith('/')) {\n return path.startsWith(pattern) || path === pattern.slice(0, -1);\n }\n\n // Prefix match with segment boundary check\n // Pattern /api should match /api and /api/users but NOT /apiv2/users\n if (!path.startsWith(pattern)) {\n return false;\n }\n\n // Exact match\n if (path === pattern) {\n return true;\n }\n\n // Check that the next character after the pattern is a segment boundary\n const nextChar = path[pattern.length];\n return nextChar === '/';\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Create a policy evaluation result\n */\nfunction createResult(\n action: EnforcementAction,\n reason: string,\n matchType: (typeof POLICY_MATCH_TYPES)[keyof typeof POLICY_MATCH_TYPES],\n extras?: {\n ruleId?: string;\n ruleName?: string;\n redirectUrl?: string;\n message?: string;\n }\n): PolicyEvaluationResult {\n return {\n action,\n reason,\n matchType,\n ruleId: extras?.ruleId,\n ruleName: extras?.ruleName,\n redirectUrl: extras?.redirectUrl,\n message: extras?.message,\n };\n}\n","/**\n * The Cedar double-quoted string grammar shared by the compose engine's emitter/\n * parser and every enforcement-path TEXT reader (required-scopes, cedar-rule-match).\n * Keeping the escape codec AND the capture pattern in one place means a value the\n * emitter escapes is decoded identically wherever a reader parses it back — they\n * can never drift. (Rust/.NET parse Cedar with a real parser and are unaffected.)\n */\n\n/** Escape a value for embedding inside a Cedar double-quoted string literal. */\nexport function escapeCedarString(value: string): string {\n return value\n .replace(/\\\\/g, '\\\\\\\\')\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, '\\\\n')\n .replace(/\\r/g, '\\\\r')\n .replace(/\\t/g, '\\\\t');\n}\n\n/** Inverse of {@link escapeCedarString} — decode Cedar string escapes to raw text. */\nexport function unescapeCedarString(value: string): string {\n return value.replace(/\\\\([\\\\\"nrt])/g, (_m, ch: string) =>\n ch === 'n' ? '\\n' : ch === 'r' ? '\\r' : ch === 't' ? '\\t' : ch\n );\n}\n\n/**\n * Build a RegExp matching `<prefixSource>\"<body>\"`, where <body> is an escape-aware\n * Cedar string. Capture group 1 is the RAW (still-escaped) body — pass it through\n * {@link unescapeCedarString} before use. `prefixSource` is a regex-source fragment\n * (escape its own metacharacters). This is the single source of the quoted-string\n * capture pattern.\n */\nexport function cedarQuotedValueRegExp(prefixSource: string, flags = ''): RegExp {\n return new RegExp(`${prefixSource}\"((?:\\\\\\\\.|[^\"\\\\\\\\])*)\"`, flags);\n}\n","/**\n * Shared best-effort matchers for reading a composed Cedar policy's per-rule\n * annotations (`@scopes`, `@approvers`, …) WITHOUT a Cedar AST. Both\n * `requiredScopesForRequest` (consent scopes) and `approvalQuorumForRequest`\n * (step-up quorum) narrow a rule's annotation to a request the same way the\n * compose engine's own `parseExistingCedar` does: blocks split on blank lines,\n * a rule contributes only when EVERY request fact it constrains matches.\n *\n * A fact is matched against the SAME projection the gateway/edge feeds the\n * engine (`name = agentName`, `category = scraper|detectionClass`), so the\n * narrowing mirrors the engine's own evaluation. An UNKNOWN fact never narrows.\n */\nimport { cedarQuotedValueRegExp, unescapeCedarString } from './cedar-string';\n\nexport interface RequestFacts {\n path?: string;\n /** Agent label → `principal.name`. */\n name?: string;\n /** Agent category → `principal.category` (e.g. `\"scraper\"`). */\n category?: string;\n}\n\n/**\n * A block applies when its path AND principal conditions all match the KNOWN\n * request facts. An unknown fact never narrows (so the no-`request` case unions\n * every matching rule's annotation).\n */\nexport function blockApplies(block: string, request?: RequestFacts): boolean {\n if (request?.path !== undefined && !blockMatchesPath(block, request.path)) return false;\n if (request?.name !== undefined && !blockMatchesEquality(block, 'principal.name', request.name)) {\n return false;\n }\n if (\n request?.category !== undefined &&\n !blockMatchesEquality(block, 'principal.category', request.category)\n ) {\n return false;\n }\n return true;\n}\n\n/** The `resource.path` literals appearing anywhere in `text` (no `when`/\n * `unless` scoping — callers that care about scope use `splitWhenUnless`\n * first). Shared regex extraction for `pathLiteralsInBlock` and the\n * scope-aware helpers below. */\nfunction pathLiteralsInText(text: string): string[] {\n return Array.from(\n text.matchAll(cedarQuotedValueRegExp('resource\\\\.path (?:like|==) ', 'g')),\n (m) => unescapeCedarString(m[1])\n );\n}\n\n/**\n * The `resource.path` literals a block MENTIONS anywhere — `when` or\n * `unless` alike (empty = the block never mentions a path). Used for\n * enumeration (which concrete paths does this bundle reference at all),\n * NOT for \"does this block's condition match path\" — that's\n * `blockMatchesPath`, which is `unless`-aware. Mixing the two up is exactly\n * the bug Bugbot caught (2026-09-10): a literal that appears ONLY inside\n * `unless { … }` names a path this block does NOT apply to, not one it\n * targets.\n */\nexport function pathLiteralsInBlock(block: string): string[] {\n return pathLiteralsInText(block);\n}\n\n/**\n * Split `block` into its `when`-scoped text and its `unless`-scoped inner\n * text, mirroring the compose engine's own excision order\n * (`apps/web/lib/compose/cedar.ts`'s `unless` handling): `unless { … }` is\n * located first and excised, so its own literals never leak into what\n * counts as the block's `when` (narrowing) scope.\n *\n * CodeQL js/polynomial-redos: a single `/unless\\s*\\{([\\s\\S]*?)\\}\\s*;?/`\n * regex is quadratic on a policy blob containing many \"unless{\"\n * substrings with no closing brace (composed policy text is untrusted,\n * customer-authored input evaluated on the request hot path) — an\n * unanchored match retries the unbounded `[\\s\\S]*?` scan-to-end at every\n * failed start position. `search()` for the fixed-length \"unless\\s*{\"\n * prefix has no such ambiguity (each position fails fast), and the\n * closing brace is then found with a single linear `indexOf`, so the\n * whole split stays O(n) regardless of how many false \"unless{\" starts\n * the text contains.\n */\nfunction splitWhenUnless(block: string): { whenText: string; unlessText: string } {\n const unlessIndex = block.search(/unless\\s*\\{/);\n if (unlessIndex === -1) return { whenText: block, unlessText: '' };\n const openBraceIndex = block.indexOf('{', unlessIndex);\n const closeBraceIndex = block.indexOf('}', openBraceIndex + 1);\n if (closeBraceIndex === -1) return { whenText: block, unlessText: '' };\n return {\n whenText: block.slice(0, unlessIndex),\n unlessText: block.slice(openBraceIndex + 1, closeBraceIndex),\n };\n}\n\n/**\n * A block applies to `path` when: no `unless` literal excludes it, AND\n * either the `when` scope has no path constraint at all (unconstrained →\n * matches every path except what `unless` just excluded), or one of the\n * `when` scope's path literals matches (exact, or a `*`-prefix glob).\n *\n * Bugbot (2026-09-10): the previous version read path literals from the\n * WHOLE block regardless of `when` vs `unless`, so a site-wide forbid whose\n * only path mention was an `unless { resource.path == \"/checkout\" }`\n * exemption got scored as \"targets only /checkout\" — backwards. It applies\n * to every path EXCEPT the excepted one, not ONLY the excepted one.\n */\nexport function blockMatchesPath(block: string, path: string): boolean {\n const { whenText, unlessText } = splitWhenUnless(block);\n const unlessLiterals = pathLiteralsInText(unlessText);\n if (unlessLiterals.some((literal) => pathLiteralMatches(literal, path))) return false;\n const whenLiterals = pathLiteralsInText(whenText);\n if (whenLiterals.length === 0) return true;\n return whenLiterals.some((literal) => pathLiteralMatches(literal, path));\n}\n\n/** Escape every regex metacharacter in `s` (so it matches literally). */\nexport function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Split a composed Cedar bundle into per-rule blocks (blank-line separated),\n * trimmed and with empties dropped. Mirrors the compose engine's own block\n * split (`apps/web/lib/compose/cedar.ts` `parseCedarBlocks`).\n */\nexport function splitCedarBlocks(cedar: string): string[] {\n return cedar\n .split(/\\n\\s*\\n/)\n .map((b) => b.trim())\n .filter((b) => b.length > 0);\n}\n\n/**\n * The set of values a block positively constrains `attr` to via `== ` literals.\n * Empty = the block places no `==` constraint on `attr` (unconstrained).\n */\nexport function blockEqualityLiterals(block: string, attr: string): string[] {\n const a = escapeRegExp(attr);\n return Array.from(block.matchAll(cedarQuotedValueRegExp(`${a} == `, 'g')), (m) =>\n unescapeCedarString(m[1])\n );\n}\n\n/**\n * The set of values a block EXCLUDES `attr` from via `!= ` literals.\n * Empty = the block places no `!=` constraint on `attr`.\n */\nexport function blockExclusionLiterals(block: string, attr: string): string[] {\n const a = escapeRegExp(attr);\n return Array.from(block.matchAll(cedarQuotedValueRegExp(`${a} != `, 'g')), (m) =>\n unescapeCedarString(m[1])\n );\n}\n\n/** A block applies to `value` when it is NOT excluded by a `!=` literal AND\n * (it declares no `==` literal — unconstrained → applies to all — or `value` is\n * one of them; compose emits an OR-disjunction for a name set). Without the `!=`\n * arm a rule that challenges everyone EXCEPT X (`principal.name != \"X\"`) would\n * over-advertise its annotation to X — a broader grant than the rule meant. */\nexport function blockMatchesEquality(block: string, attr: string, value: string): boolean {\n const eq = blockEqualityLiterals(block, attr);\n const neq = blockExclusionLiterals(block, attr);\n if (neq.includes(value)) return false; // explicitly excluded\n if (eq.length > 0) return eq.includes(value); // positively narrowed to a set\n return true; // unconstrained (and not excluded)\n}\n\n/**\n * Match a `resource.path` literal against the request path with CEDAR `like`\n * semantics — NOT the package's `matchPath`. Cedar `*` matches any sequence\n * INCLUDING `/` (regex `.*`), whereas `matchPath` treats a single `*` as\n * `[^/]*` (no slash); using it here would disagree with what the engine\n * actually matched. A `==`/non-wildcard literal is an exact match; a `like`\n * literal maps each `*` (and `**`) to `.*`, anchored.\n */\nexport function pathLiteralMatches(literal: string, path: string): boolean {\n if (!literal.includes('*')) return path === literal;\n const pattern = escapeRegExp(literal).replace(/\\\\\\*/g, '.*');\n try {\n return new RegExp(`^${pattern}$`).test(path);\n } catch {\n return false;\n }\n}\n\n/**\n * True when the block contains a Cedar `forbid` statement (a deny rule). A bare\n * `forbid` defaults to BLOCK; a `@verdict(...)` annotation refines the kind.\n */\nexport function isForbidBlock(block: string): boolean {\n return /\\bforbid\\s*\\(/.test(block);\n}\n\n/** True when the block narrows the principal — by category/name equality, a\n * Cedar entity-type test (`principal is X`), or a scope-position binding\n * (`forbid(principal == X::\"…\"`). An un-narrowed deny matches every principal.\n *\n * Cursor Bugbot (2026-09-11, High): this used to scan the WHOLE block for\n * a principal literal, `when`/`unless` alike — the exact same class of bug\n * `blockMatchesPath` above was already fixed for on the path dimension\n * (see that function's doc comment). `unless { principal.category ==\n * \"search_engine\" }` on an otherwise site-wide `forbid` only exempts\n * search engines from the deny — the rule still denies every OTHER\n * principal, humans included — but scanning the whole block found the\n * `==` literal and called the rule \"narrowed,\" so `pathHasUnnarrowedDenyRule`\n * missed it and a real browser hitting that path reached Cedar only to be\n * denied by the very rule this check exists to catch. Split `when`/`unless`\n * first: a WHEN-scope (or scope-position) literal genuinely targets the\n * deny, narrowing it away from every principal not named — whatever value\n * it names, since an un-narrowed literal search wouldn't have found one at\n * all. An UNLESS-scope literal does the opposite: it exempts ONLY that\n * specific principal, so it narrows the rule away from humans only when\n * the exempted value is literally `\"human\"` (the #3297 carve-out idiom) —\n * exempting anyone else leaves the deny fully un-narrowed with respect to\n * humans. */\nfunction narrowsPrincipal(block: string): boolean {\n const { whenText, unlessText } = splitWhenUnless(block);\n\n if (blockEqualityLiterals(whenText, 'principal.category').length > 0) return true;\n // A rule that excludes humans (`principal.category != \"human\"`, the #3297\n // carve-out) is narrowed away from human traffic — it is NOT the silent\n // human-impact footgun, so the lint must agree with the engine. WHEN-scope\n // only: the same literal inside `unless` would mean the opposite (the\n // deny applies ONLY to humans), which must NOT count as narrowed.\n if (blockExclusionLiterals(whenText, 'principal.category').includes('human')) return true;\n if (blockEqualityLiterals(whenText, 'principal.name').length > 0) return true;\n if (/principal\\s+is\\s+\\w/.test(whenText)) return true;\n if (/forbid\\s*\\(\\s*principal\\s*==/.test(whenText)) return true;\n // UNLESS-scope carve-out: exempts humans specifically from this deny,\n // regardless of what the rule otherwise targets.\n if (blockEqualityLiterals(unlessText, 'principal.category').includes('human')) return true;\n return false;\n}\n\n/** A deny rule that targets EVERY principal — the silent-human-impact footgun. */\nexport function isUnnarrowedDenyBlock(block: string): boolean {\n return isForbidBlock(block) && !narrowsPrincipal(block);\n}\n\n/**\n * True when some un-narrowed deny rule in the bundle matches `path` — i.e. a\n * human hitting `path` is denied by a rule that never narrowed the principal.\n * The single shared definition of \"this path catches humans by accident,\"\n * used by the deploy gate AND the preview banner.\n */\nexport function pathHasUnnarrowedDenyRule(cedar: string, path: string): boolean {\n return splitCedarBlocks(cedar).some(\n (block) => isUnnarrowedDenyBlock(block) && blockMatchesPath(block, path)\n );\n}\n","/**\n * Consent scopes a composed Cedar policy REQUIRES for a request — the\n * `@scopes(...)` annotations the compose engine writes on CHALLENGE-verdict\n * rules (alongside `unless { context.granted_scopes.contains(\"S\") }`).\n *\n * WHY: when a scope-gated rule challenges a request, the step-up must request\n * EXACTLY the scopes the policy demands, so the consent flow mints a delegation\n * carrying them (and the agent's retry then satisfies the carve-out). The\n * policy is the source of truth for \"what this route requires\", so reading its\n * `@scopes` is reading the SSOT — not re-deriving an engine-computed value.\n *\n * Best-effort TEXT parse (no Cedar AST), mirroring the compose engine's own\n * `parseExistingCedar`: blocks are split on blank lines. A CHALLENGE block\n * contributes its scopes only when EVERY request fact it constrains matches —\n * `resource.path`, `principal.name`, and `principal.category` — so on a shared\n * path the scopes of ANOTHER agent's CHALLENGE rule are not advertised (the\n * engine challenged on the rule whose `when` matched, not merely the path).\n *\n * A fact is matched against the SAME projection the gateway feeds the engine\n * (`name = detection.agentName`, `category = scraper|detectionClass`), so the\n * narrowing mirrors the engine's own evaluation. An UNKNOWN fact never narrows:\n * with no `request` (the consent allow-list case) this returns the union of\n * every CHALLENGE rule's scopes — exactly what consent must be able to grant.\n */\nimport { blockApplies, type RequestFacts } from './cedar-rule-match';\nimport { cedarQuotedValueRegExp, unescapeCedarString } from './cedar-string';\n\nexport type { RequestFacts };\n\nexport function requiredScopesForRequest(\n policySource: string | null | undefined,\n request?: RequestFacts\n): string[] {\n if (!policySource || !policySource.trim()) return [];\n const out = new Set<string>();\n for (const block of policySource.split(/\\n\\s*\\n/)) {\n if (!/@verdict\\(\"CHALLENGE\"\\)/.test(block)) continue;\n const scopesMatch = block.match(cedarQuotedValueRegExp('@scopes\\\\('));\n if (!scopesMatch) continue;\n // Split on whitespace FIRST (the emitter joins escaped tokens with a real\n // space), THEN decode each token — an escaped \\t must not act as a separator.\n const scopes = scopesMatch[1].split(/\\s+/).filter(Boolean).map(unescapeCedarString);\n if (scopes.length === 0) continue;\n if (!blockApplies(block, request)) continue;\n for (const scope of scopes) out.add(scope);\n }\n return [...out];\n}\n","/**\n * `decisionPolicyId` — extract the determining policy's authored Cedar `@id`\n * from an engine `Decision` (#3272 PR2 wire; consumed by #3236 attribution).\n *\n * The optional `policyId` rides a different position per decision kind:\n * `Permit` root, the `PolicyDenied` reason for `Block`, and the\n * `params` / `target` / `payload` for Challenge / Redirect / Instruct. This\n * helper is the single owner of that position-per-kind knowledge — the TS\n * mirror of .NET's `DecisionMapping.TryGetPolicyId` — so the middleware\n * reporter, the gateway worker, and ingest never duplicate it.\n *\n * `undefined` for pre-PR2 payloads, non-policy blocks (`Revoked`, etc.),\n * deny-by-default, and anything malformed — never throws.\n */\n/**\n * Structural input so BOTH Decision flavors fit without casts: the canonical\n * zod-inferred `Decision` from `./schemas` AND the wasm-runtime's\n * `engine/types` mirror (which carries extra Block variants the zod union\n * doesn't, e.g. Tier3UAMatch). Only the fields this extraction reads are\n * named; everything else is ignored.\n */\nexport interface DecisionLike {\n kind: string;\n policyId?: string;\n reason?: { kind: string; policyId?: string };\n params?: { policyId?: string };\n target?: { policyId?: string };\n payload?: { policyId?: string };\n}\n\nexport function decisionPolicyId(decision: DecisionLike): string | undefined {\n switch (decision.kind) {\n case 'Permit':\n return decision.policyId;\n case 'Block':\n return decision.reason?.kind === 'PolicyDenied' ? decision.reason.policyId : undefined;\n case 'Challenge':\n return decision.params?.policyId;\n case 'Redirect':\n return decision.target?.policyId;\n case 'Instruct':\n return decision.payload?.policyId;\n default:\n return undefined;\n }\n}\n","/**\n * Synthetic `@id`s for the gateway's \"bespoke\" (non-composed-Cedar) policy\n * mechanisms — KYA-862 follow-up.\n *\n * The gateway worker has two policy-evaluation paths: composed Cedar (whose\n * decisions carry an authored `@id`) and the bespoke evaluator\n * (`evaluateGatewayPolicy`) that runs when a project has no composed bundle, is\n * in shadow mode, or the engine faults. Bespoke decisions historically carried\n * no `policyId`, so they landed with `detections.policy_id = NULL` and rendered\n * as an em-dash on `/activity` with no attribution.\n *\n * A bespoke decision made by an EXPLICIT configured rule (deny-list, allow-list,\n * path-rule, confidence threshold) now carries one of these stable ids, so\n * `/activity` can attribute it. The slug style (`bespoke-<match-type>`) mirrors\n * composed-Cedar `@id`s (a slug of the rule title; cf. the reserved\n * `baseline-allow`) and the `POLICY_MATCH_TYPES` taxonomy.\n *\n * These are NOT authored Cedar policies — there is no policy-detail page for a\n * built-in mechanism — so the dashboard renders them as a friendly label, NOT a\n * deep link (`isBespokePolicyId` gates the href off). Implicit decisions\n * (below-threshold allow, enforcement disabled) carry no id and keep the\n * em-dash, since no explicit rule decided them.\n */\n\n/** Shared naming convention: every bespoke `@id` starts with this. */\nexport const BESPOKE_POLICY_ID_PREFIX = 'bespoke-';\n\n/** Stable synthetic `@id` per explicit bespoke mechanism. */\nexport const BESPOKE_POLICY_IDS = {\n denyList: 'bespoke-deny-list',\n allowList: 'bespoke-allow-list',\n pathRule: 'bespoke-path-rule',\n threshold: 'bespoke-threshold',\n} as const;\n\nexport type BespokePolicyId = (typeof BESPOKE_POLICY_IDS)[keyof typeof BESPOKE_POLICY_IDS];\n\nconst BESPOKE_POLICY_LABELS: Record<string, string> = {\n [BESPOKE_POLICY_IDS.denyList]: 'Deny list',\n [BESPOKE_POLICY_IDS.allowList]: 'Allow list',\n [BESPOKE_POLICY_IDS.pathRule]: 'Path rule',\n [BESPOKE_POLICY_IDS.threshold]: 'Confidence threshold',\n};\n\n// Exact membership, NOT a prefix test: a `bespoke-` prefix check would\n// misclassify an authored Cedar policy whose title slugs to `bespoke-…`. Both\n// the worker (stamping) and the reader (display) use this same set, so there is\n// no drift — a new mechanism is recognized everywhere the moment it's added to\n// BESPOKE_POLICY_IDS.\nconst BESPOKE_POLICY_ID_SET: ReadonlySet<string> = new Set(Object.values(BESPOKE_POLICY_IDS));\n\n/** True when `policyId` is one of our synthetic bespoke ids (vs. an authored Cedar `@id`). */\nexport function isBespokePolicyId(policyId: string | null | undefined): boolean {\n return typeof policyId === 'string' && BESPOKE_POLICY_ID_SET.has(policyId);\n}\n\n/**\n * Human-readable label for a bespoke `@id`; `null` for an unrecognized id so the\n * caller can fall back to showing the raw id.\n */\nexport function bespokePolicyLabel(policyId: string): string | null {\n return BESPOKE_POLICY_LABELS[policyId] ?? null;\n}\n\n/**\n * The compose engine's implicit default-allow baseline rule `@id`. The engine\n * emits it into every composed Cedar bundle (see\n * `apps/web/lib/compose/cedar.ts` `DEFAULT_ALLOW_BASELINE`), but the policy\n * list/detail derivation excludes it — \"the implicit allow-all, not a user\n * rule\" — so it has NO detail page. `/activity` attributes a row to it but must\n * never link it (a deep link 404s). Kept here so the activity reader recognizes\n * it without importing the compose engine into the client bundle; a test pins\n * that this string still matches the emitter's `@id`.\n */\nexport const BASELINE_ALLOW_POLICY_ID = 'baseline-allow';\n\n/**\n * `policyId`s that have NO policy-detail page: the synthetic bespoke mechanisms\n * AND the implicit `baseline-allow`. `/activity` attributes these but must not\n * deep-link them.\n */\nexport function isNonNavigablePolicyId(policyId: string | null | undefined): boolean {\n return isBespokePolicyId(policyId) || policyId === BASELINE_ALLOW_POLICY_ID;\n}\n\n/**\n * Friendly label for a non-navigable policy id (bespoke mechanism or\n * `baseline-allow`); `null` for a real authored policy id (caller resolves the\n * projection name / raw `@id` instead).\n */\nexport function nonNavigablePolicyLabel(policyId: string | null | undefined): string | null {\n if (policyId === BASELINE_ALLOW_POLICY_ID) return 'Default allow';\n return typeof policyId === 'string' ? bespokePolicyLabel(policyId) : null;\n}\n","import { splitCedarBlocks, isUnnarrowedDenyBlock } from './cedar-rule-match';\n\nexport interface LintFinding {\n /** The rule's `@id(\"…\")` annotation, when present. */\n ruleId?: string;\n /** 1-based line where the offending block starts (for editor gutters). */\n line: number;\n /** Operator-facing explanation. */\n message: string;\n}\n\nconst UNNARROWED_DENY_MESSAGE =\n 'This rule denies every principal — including humans — because it does not narrow the principal. ' +\n 'Add a `principal.category == \"ai_agent\"` (or `principal.name`) condition, or confirm you intend to affect humans.';\n\nfunction blockIdAnnotation(block: string): string | undefined {\n const m = block.match(/@id\\(\"((?:\\\\.|[^\"\\\\])*)\"\\)/);\n return m ? m[1] : undefined;\n}\n\n/**\n * Flag every un-narrowed deny rule in a composed Cedar bundle. Pure and\n * parity-irrelevant: a heuristic author-time WARNING, never an enforcement\n * decision. Shares its \"un-narrowed deny\" definition with the deploy gate\n * (`pathHasUnnarrowedDenyRule`) so the editor and the gate agree.\n */\nexport function lintUnnarrowedDenyRules(cedar: string): LintFinding[] {\n const findings: LintFinding[] = [];\n let searchFrom = 0;\n for (const block of splitCedarBlocks(cedar)) {\n if (!isUnnarrowedDenyBlock(block)) continue;\n const idx = cedar.indexOf(block, searchFrom);\n const line = idx < 0 ? 1 : cedar.slice(0, idx).split('\\n').length;\n if (idx >= 0) searchFrom = idx + block.length;\n findings.push({ ruleId: blockIdAnnotation(block), line, message: UNNARROWED_DENY_MESSAGE });\n }\n return findings;\n}\n","/**\n * The step-up APPROVAL QUORUM a composed Cedar policy requires for a request —\n * the `@approvers(...)` (+ optional `@quorum(\"N\")`) annotations on a\n * CHALLENGE-verdict rule.\n *\n * WHY (ADR D7 — distinct verdict): the engine emits a single `Challenge` for\n * both consent (`@scopes`) and human-approval step-up (`@approvers`). They are\n * DIFFERENT security flows and must not collide — a consent challenge mints a\n * delegation; an approval-quorum challenge demands N-of-M humans cryptographically\n * sign. This classifier is the seam that tells them apart from the policy text:\n * - a CHALLENGE rule carrying `@approvers` → an approval quorum (this returns it)\n * - a CHALLENGE rule with only `@scopes` (or neither) → consent (returns null)\n *\n * It mirrors {@link requiredScopesForRequest}: the SAME best-effort block parse\n * and the SAME request narrowing (shared {@link blockApplies}), so the rule it\n * reads the quorum off is the rule the engine actually challenged on — not merely\n * one that shares a path. Reading the annotation is reading the SSOT (the policy\n * is the source of truth for \"what this action requires\"), not re-deriving it.\n *\n * The engine carries no rule id on its Challenge, so the classifier re-matches by\n * request facts and is FAIL-CLOSED on ambiguity:\n * - if a CONSENT-only CHALLENGE rule ALSO applies, it returns null — the engine\n * may have challenged on THAT, and reading approval off a different rule would\n * conflate the two flows (ADR D7)\n * - if two applying approval rules disagree on {n, approvers}, it returns null —\n * enforcing the wrong approver roster is a worse failure than a clean deny\n * Each caller feeds it the SAME facts its engine evaluated, so it narrows to the\n * rule the engine could have fired on. The EDGE worker sets resource.path +\n * principal.name and narrows on them; the Fly gateway sets NEITHER (it populates\n * category + the resource entity, leaving resource.path==\"\" and principal.name=\"\"),\n * so it passes those as \"\" — path/name-scoped rules don't fire there, exactly as\n * the engine sees it, and a same-scope tie falls to the fail-closed guard above.\n */\nimport { blockApplies, type RequestFacts } from './cedar-rule-match';\n\nexport type { RequestFacts };\n\nexport interface ApprovalQuorum {\n /** Distinct allow-listed approvers that must sign — `>= 1`. */\n n: number;\n /** The approver DIDs the org sovereignly authorizes for this action. */\n approvers: string[];\n}\n\nexport function approvalQuorumForRequest(\n policySource: string | null | undefined,\n request?: RequestFacts\n): ApprovalQuorum | null {\n if (!policySource || !policySource.trim()) return null;\n\n let chosen: ApprovalQuorum | null = null;\n for (const block of policySource.split(/\\n\\s*\\n/)) {\n if (!/@verdict\\(\"CHALLENGE\"\\)/.test(block)) continue;\n if (!blockApplies(block, request)) continue; // not a rule the engine could have fired on\n\n const approvers = parseApprovers(block);\n if (!approvers) {\n // A consent-only CHALLENGE rule also applies — the engine may have fired it.\n // Without a rule id we can't tell, so never read an approval quorum off a\n // different rule (ADR D7): fail to the consent/deny path.\n return null;\n }\n const candidate: ApprovalQuorum = { n: parseQuorumN(block), approvers };\n if (chosen && !sameQuorum(chosen, candidate)) {\n // Two distinct approval quorums both apply — ambiguous without a rule id, so\n // enforcing either risks the wrong approver roster. Fail closed.\n return null;\n }\n chosen = candidate;\n }\n return chosen;\n}\n\n/** The DIDs of an `@approvers(\"did … did\")` annotation, or null when the rule\n * carries none (a consent challenge) or an empty/whitespace list (no real gate). */\nfunction parseApprovers(block: string): string[] | null {\n const m = block.match(/@approvers\\(\"([^\"]*)\"\\)/);\n if (!m) return null;\n const approvers = m[1].split(/\\s+/).filter(Boolean);\n return approvers.length > 0 ? approvers : null;\n}\n\n/** Two quorums match iff same n and same ordered approver list. */\nfunction sameQuorum(a: ApprovalQuorum, b: ApprovalQuorum): boolean {\n return (\n a.n === b.n &&\n a.approvers.length === b.approvers.length &&\n a.approvers.every((did, i) => did === b.approvers[i])\n );\n}\n\n/**\n * The `@quorum(\"N\")` count, or 1 when absent/malformed. Fail-secure: an\n * unparseable or `< 1` value falls back to 1 (the smallest real quorum), never 0\n * — which would make the step-up gate a no-op. The route's own\n * `validateStepUpQuorum` is the second line of defence on a misconfigured n.\n */\nfunction parseQuorumN(block: string): number {\n const m = block.match(/@quorum\\(\"([^\"]*)\"\\)/);\n if (!m) return 1;\n const n = Number(m[1]);\n return Number.isInteger(n) && n >= 1 ? n : 1;\n}\n","/**\n * Step-up quorum validation — the fail-closed guard the enforce-path PEP runs\n * BEFORE attempting approval-signature verification.\n *\n * Moved from the gateway (`apps/gateway/src/lib/step-up-quorum.ts`) into\n * `@kya-os/checkpoint-shared` so every runtime that enforces N-of-M step-up at\n * the edge — not only the central gateway — applies the SAME fail-closed gate\n * (T3-edge keystone). Pure, with the quorum typed STRUCTURALLY ({@link\n * StepUpQuorumLike}) so the dependency-graph root package takes no\n * `@kya-os/mcp` dependency; the `@kya-os/mcp` `Quorum` is structurally\n * assignable to it.\n *\n * A `step_up` decision names an N-of-M approval quorum. Two shapes can never be\n * legitimately satisfied and MUST be denied rather than passed through to the\n * verifier:\n *\n * - `n` not a positive integer — a misconfigured engine emitting `{ n: 0 }`\n * (e.g. a Cedar Challenge defaulting to zero) would otherwise auto-pass.\n * - an EMPTY approver allowlist. Per the `@kya-os/mcp` quorum contract an\n * empty `approvers` means \"any identity may approve\". In ENFORCE mode that\n * is NOT authorization: once a real approval-signature verifier replaces\n * today's reject-all kill switch, any signer would satisfy the quorum. A\n * `step_up` that names no eligible approvers can never be a real\n * authorization gate, so it is denied — the policy author must name the\n * approvers.\n *\n * Extracted as a pure function so the fail-closed posture is unit-testable\n * independently of the deep request handlers that invoke it.\n */\n\n/**\n * The N-of-M quorum shape the validator inspects. Structural mirror of the\n * `@kya-os/mcp` `Quorum` (`{ n, approvers }`) — kept local so this module (and\n * thus the checkpoint-shared dependency-graph root) takes no `@kya-os/mcp`\n * dependency. The `@kya-os/mcp` `Quorum` is structurally assignable here.\n */\nexport interface StepUpQuorumLike {\n n: number;\n approvers: string[];\n}\n\n/**\n * Why a step-up quorum is rejected. Surfaced as the `policy_denied` reason and\n * in the enforce-path structured log.\n */\nexport type InvalidStepUpReason = 'invalid_step_up_quorum' | 'step_up_no_approvers';\n\n/** Result of {@link validateStepUpQuorum}: pass, or a fail-closed deny reason. */\nexport type StepUpQuorumCheck = { ok: true } | { ok: false; reason: InvalidStepUpReason };\n\n/**\n * Validate a `step_up` decision's quorum before approval verification.\n * Fail-closed: returns a deny `reason` for any quorum that can never be\n * legitimately met; `{ ok: true }` only when the quorum is a real gate.\n *\n * Ordering is load-bearing: the `n` guard runs first, so an invalid quorum that\n * is both non-positive AND has no approvers reports `invalid_step_up_quorum`\n * (stable/deterministic reason).\n */\nexport function validateStepUpQuorum(quorum: StepUpQuorumLike): StepUpQuorumCheck {\n if (!Number.isInteger(quorum.n) || quorum.n < 1) {\n return { ok: false, reason: 'invalid_step_up_quorum' };\n }\n if (!Array.isArray(quorum.approvers) || quorum.approvers.length === 0) {\n return { ok: false, reason: 'step_up_no_approvers' };\n }\n return { ok: true };\n}\n","/**\n * Policy Fetcher\n *\n * Runtime-agnostic policy fetching with caching support.\n * Works in Edge (Cloudflare Workers, Next.js Edge), Node.js, and browser environments.\n *\n * The fetcher supports:\n * - In-memory caching with TTL\n * - External cache adapter interface for KV/Redis\n * - Fallback to default policy on errors\n * - Configurable API endpoints\n */\n\nimport { CACHE_TTL, DEFAULT_POLICY } from './constants';\nimport { PolicyConfigSchema, safeParsePolicyConfig } from './schemas';\nimport type { PolicyConfig } from './schemas';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Cache adapter interface for external caches (KV, Redis, etc.)\n */\nexport interface PolicyCacheAdapter {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, ttlSeconds: number): Promise<void>;\n /** Delete a cache entry. If not implemented, invalidation will only clear memory cache. */\n delete?(key: string): Promise<boolean>;\n}\n\n/**\n * Configuration for the policy fetcher\n */\nexport interface PolicyFetcherConfig {\n /** Base URL for the policy API */\n apiBaseUrl: string;\n /** API key for authentication (optional) */\n apiKey?: string;\n /** Cache TTL in seconds (default: 300) */\n cacheTtlSeconds?: number;\n /** External cache adapter (optional) */\n cacheAdapter?: PolicyCacheAdapter;\n /** Disable in-memory caching (default: false) */\n disableMemoryCache?: boolean;\n /** Request timeout in milliseconds (default: 5000) */\n timeoutMs?: number;\n /** Custom fetch function (for testing or custom transport) */\n fetchFn?: typeof fetch;\n}\n\n/**\n * Cached policy entry with metadata\n */\nexport interface CachedPolicy {\n policy: PolicyConfig;\n projectId: string;\n cachedAt: string;\n expiresAt: string;\n}\n\n// ============================================================================\n// In-Memory Cache\n// ============================================================================\n\n/**\n * Simple in-memory cache with TTL support\n */\nclass MemoryCache {\n private cache = new Map<string, { value: string; expiresAt: number }>();\n\n get(key: string): string | null {\n const entry = this.cache.get(key);\n if (!entry) {\n return null;\n }\n\n if (Date.now() > entry.expiresAt) {\n this.cache.delete(key);\n return null;\n }\n\n return entry.value;\n }\n\n set(key: string, value: string, ttlSeconds: number): void {\n this.cache.set(key, {\n value,\n expiresAt: Date.now() + ttlSeconds * 1000,\n });\n }\n\n delete(key: string): boolean {\n return this.cache.delete(key);\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n /**\n * Remove expired entries (for memory management)\n */\n cleanup(): void {\n const now = Date.now();\n for (const [key, entry] of this.cache.entries()) {\n if (now > entry.expiresAt) {\n this.cache.delete(key);\n }\n }\n }\n}\n\n// Global in-memory cache instance\nconst globalMemoryCache = new MemoryCache();\n\n// ============================================================================\n// Policy Fetcher Class\n// ============================================================================\n\n/**\n * Policy fetcher with caching and fallback support\n */\nexport class PolicyFetcher {\n private config: Required<Omit<PolicyFetcherConfig, 'cacheAdapter' | 'apiKey'>> & {\n cacheAdapter?: PolicyCacheAdapter;\n apiKey?: string;\n };\n private memoryCache: MemoryCache;\n\n constructor(config: PolicyFetcherConfig) {\n this.config = {\n apiBaseUrl: config.apiBaseUrl,\n apiKey: config.apiKey,\n cacheTtlSeconds: config.cacheTtlSeconds ?? CACHE_TTL.POLICY,\n cacheAdapter: config.cacheAdapter,\n disableMemoryCache: config.disableMemoryCache ?? false,\n timeoutMs: config.timeoutMs ?? 5000,\n fetchFn: config.fetchFn ?? globalThis.fetch,\n };\n this.memoryCache = config.disableMemoryCache ? new MemoryCache() : globalMemoryCache;\n }\n\n /**\n * Generate a cache key that includes the API base URL and TTL to prevent\n * cache collisions when multiple fetchers use different backends or TTL settings.\n */\n private getCacheKey(projectId: string): string {\n // Use a hash of the apiBaseUrl to keep keys reasonably short\n const urlHash = this.config.apiBaseUrl\n .split('')\n .reduce((hash, char) => ((hash << 5) - hash + char.charCodeAt(0)) | 0, 0)\n .toString(36);\n // Include TTL in key to prevent cross-fetcher cache interference\n // (fetcher with TTL=60 shouldn't read cache written by fetcher with TTL=300)\n return `policy:${urlHash}:${this.config.cacheTtlSeconds}:${projectId}`;\n }\n\n /**\n * Get policy for a project, with caching\n */\n async getPolicy(projectId: string): Promise<PolicyConfig> {\n const cacheKey = this.getCacheKey(projectId);\n\n // Try in-memory cache first\n if (!this.config.disableMemoryCache) {\n const memoryCached = this.memoryCache.get(cacheKey);\n if (memoryCached) {\n const cached = JSON.parse(memoryCached) as CachedPolicy;\n if (!this.isExpired(cached.expiresAt)) {\n return cached.policy;\n }\n }\n }\n\n // Try external cache adapter\n if (this.config.cacheAdapter) {\n try {\n const externalCached = await this.config.cacheAdapter.get(cacheKey);\n if (externalCached) {\n const cached = JSON.parse(externalCached) as CachedPolicy;\n if (!this.isExpired(cached.expiresAt)) {\n // Populate memory cache\n if (!this.config.disableMemoryCache) {\n this.memoryCache.set(cacheKey, externalCached, this.config.cacheTtlSeconds);\n }\n return cached.policy;\n }\n }\n } catch (error) {\n console.error('[PolicyFetcher] External cache error:', error);\n }\n }\n\n // Cache miss - fetch from API\n try {\n const policy = await this.fetchPolicyFromApi(projectId);\n\n // Store in caches\n const now = new Date();\n const cached: CachedPolicy = {\n policy,\n projectId,\n cachedAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + this.config.cacheTtlSeconds * 1000).toISOString(),\n };\n\n const cacheValue = JSON.stringify(cached);\n\n if (!this.config.disableMemoryCache) {\n this.memoryCache.set(cacheKey, cacheValue, this.config.cacheTtlSeconds);\n }\n\n if (this.config.cacheAdapter) {\n try {\n await this.config.cacheAdapter.set(cacheKey, cacheValue, this.config.cacheTtlSeconds);\n } catch (error) {\n console.error('[PolicyFetcher] Failed to write to external cache:', error);\n }\n }\n\n return policy;\n } catch (error) {\n console.error(`[PolicyFetcher] Failed to fetch policy for ${projectId}:`, error);\n return this.getDefaultPolicy();\n }\n }\n\n /**\n * Fetch policy from the API\n */\n private async fetchPolicyFromApi(projectId: string): Promise<PolicyConfig> {\n const url = `${this.config.apiBaseUrl}/api/internal/policies/${projectId}`;\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'User-Agent': 'AgentShield-PolicyFetcher/1.0',\n };\n\n if (this.config.apiKey) {\n headers['Authorization'] = `Bearer ${this.config.apiKey}`;\n }\n\n const response = await this.config.fetchFn(url, {\n method: 'GET',\n headers,\n signal: AbortSignal.timeout(this.config.timeoutMs),\n });\n\n if (!response.ok) {\n throw new Error(`API returned ${response.status}: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n // Parse and validate the response\n const policy = safeParsePolicyConfig(data);\n if (!policy) {\n throw new Error('Invalid policy response format');\n }\n\n return policy;\n }\n\n /**\n * Get the default policy\n */\n getDefaultPolicy(): PolicyConfig {\n return PolicyConfigSchema.parse(DEFAULT_POLICY);\n }\n\n /**\n * Invalidate cached policy for a project.\n * Clears both memory cache and external cache (if configured and supports delete).\n */\n async invalidateCache(projectId: string): Promise<void> {\n const cacheKey = this.getCacheKey(projectId);\n\n // Clear memory cache\n if (!this.config.disableMemoryCache) {\n this.memoryCache.delete(cacheKey);\n }\n\n // Clear external cache if adapter supports delete\n if (this.config.cacheAdapter?.delete) {\n try {\n await this.config.cacheAdapter.delete(cacheKey);\n } catch (error) {\n console.error('[PolicyFetcher] Failed to delete from external cache:', error);\n }\n }\n }\n\n /**\n * Clear all cached policies\n */\n clearCache(): void {\n if (!this.config.disableMemoryCache) {\n this.memoryCache.clear();\n }\n }\n\n /**\n * Check if a date string is expired\n */\n private isExpired(dateString: string): boolean {\n return new Date(dateString).getTime() < Date.now();\n }\n}\n\n// ============================================================================\n// Singleton Instance\n// ============================================================================\n\nlet defaultFetcher: PolicyFetcher | null = null;\n\n/**\n * Get or create the default policy fetcher\n */\nexport function getDefaultPolicyFetcher(config?: PolicyFetcherConfig): PolicyFetcher {\n if (!defaultFetcher && config) {\n defaultFetcher = new PolicyFetcher(config);\n }\n\n if (!defaultFetcher) {\n throw new Error(\n 'PolicyFetcher not initialized. Call getDefaultPolicyFetcher with config first.'\n );\n }\n\n return defaultFetcher;\n}\n\n/**\n * Initialize the default policy fetcher\n */\nexport function initializePolicyFetcher(config: PolicyFetcherConfig): PolicyFetcher {\n defaultFetcher = new PolicyFetcher(config);\n return defaultFetcher;\n}\n\n/**\n * Reset the default policy fetcher (for testing)\n */\nexport function resetPolicyFetcher(): void {\n defaultFetcher = null;\n}\n\n// ============================================================================\n// Convenience Functions\n// ============================================================================\n\n/**\n * Fetch policy for a project using the default fetcher\n */\nexport async function fetchPolicy(\n projectId: string,\n config?: PolicyFetcherConfig\n): Promise<PolicyConfig> {\n const fetcher = config ? new PolicyFetcher(config) : getDefaultPolicyFetcher();\n return fetcher.getPolicy(projectId);\n}\n\n/**\n * Create a policy fetcher for a specific configuration\n */\nexport function createPolicyFetcher(config: PolicyFetcherConfig): PolicyFetcher {\n return new PolicyFetcher(config);\n}\n","/**\n * Policy Module\n *\n * Shared policy types, schemas, and evaluation logic for Checkpoint.\n * Used by both agentshield-nextjs and checkpoint-express packages.\n *\n * @example\n * ```typescript\n * import {\n * evaluatePolicy,\n * PolicyConfig,\n * PolicyEvaluationContext,\n * } from '@kya-os/checkpoint-shared/policy';\n *\n * const policy: PolicyConfig = { ... };\n * const context: PolicyEvaluationContext = {\n * agentType: 'ai_agent',\n * agentName: 'ChatGPT',\n * confidence: 95,\n * path: '/api/data',\n * };\n *\n * const result = evaluatePolicy(policy, context);\n * console.log(result.action); // 'block' | 'allow' | 'redirect' | 'challenge' | 'log'\n * ```\n */\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nexport {\n // Enforcement actions (Vocab-1: PERMIT canonical, ALLOW + LOG deprecated aliases)\n ENFORCEMENT_ACTIONS,\n type EnforcementAction,\n // Enforcement modes (Vocab-1: orthogonal axis to Decision)\n ENFORCEMENT_MODES,\n type EnforcementMode,\n // Match types\n POLICY_MATCH_TYPES,\n type PolicyMatchType,\n // Condition operators\n CONDITION_OPERATORS,\n type ConditionOperator,\n // Condition fields\n CONDITION_FIELDS,\n type ConditionField,\n // Defaults\n DEFAULT_THRESHOLDS,\n DEFAULT_POLICY,\n DEFAULT_RULE_PRIORITY,\n CACHE_TTL,\n CURRENT_POLICY_VERSION,\n} from './constants';\n\n// ============================================================================\n// Schemas (for runtime validation)\n// ============================================================================\n\nexport {\n // Action & match schemas (Vocab-1)\n EnforcementActionSchema,\n StrictEnforcementActionSchema,\n EnforcementModeSchema,\n // Decision schemas (Vocab-1: TS mirror of Rust Decision enum)\n BlockReasonSchema,\n AssuranceTierSchema,\n ChallengeParamsSchema,\n RedirectTargetSchema,\n SuggestedActionSchema,\n InstructPayloadSchema,\n DecisionSchema,\n PolicyMatchTypeSchema,\n // Threshold schemas\n ThresholdConfigSchema,\n // List entry schemas\n DenyListEntrySchema,\n AllowListEntrySchema,\n // Condition schemas\n ConditionOperatorSchema,\n ConditionFieldSchema,\n ConditionValueSchema,\n PolicyConditionSchema,\n // Rule schemas\n RuleMetadataSchema,\n PolicyRuleSchema,\n // Policy config schemas\n PolicyMetadataSchema,\n PolicyConfigSchema,\n // Evaluation schemas\n PolicyEvaluationContextSchema,\n PolicyEvaluationResultSchema,\n // Validation helpers\n parsePolicyConfig,\n safeParsePolicyConfig,\n parseEvaluationContext,\n // Human step-up (gateway-enforcement-step-up, build item 5): normalize a\n // wire `challengeType` to the kind every renderer must treat it as.\n normalizeChallengeType,\n} from './schemas';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type {\n ThresholdConfig,\n DenyListEntry,\n AllowListEntry,\n ConditionValue,\n PolicyCondition,\n RuleMetadata,\n PolicyRule,\n PolicyMetadata,\n PolicyConfig,\n PolicyEvaluationContext,\n PolicyEvaluationResult,\n // Vocab-1 Decision types (TS mirror of Rust Decision enum)\n BlockReason,\n AssuranceTier,\n ChallengeParams,\n RedirectTarget,\n SuggestedAction,\n InstructPayload,\n Decision,\n // Note: EnforcementMode is exported above from constants.ts (the\n // value-side const lives there; the schema lives here). Re-exporting\n // both keeps consumers from having to import from two paths.\n} from './schemas';\n\n// ============================================================================\n// Evaluator\n// ============================================================================\n\nexport { evaluatePolicy, matchPath } from './evaluator';\n\n// ============================================================================\n// Composed-policy required scopes (the @scopes a CHALLENGE rule demands)\n// ============================================================================\n\nexport { requiredScopesForRequest } from './required-scopes';\n// #3236 / #3272 PR3: position-per-kind extraction of the determining policy's\n// authored @id from a Decision (the policies-index join key).\nexport { decisionPolicyId, type DecisionLike } from './decision-policy-id';\n// KYA-862 follow-up: synthetic `@id`s for the gateway's bespoke (non-Cedar)\n// policy mechanisms, so `/activity` attributes them (friendly non-linked label)\n// instead of an em-dash. (The `bespoke-` prefix const + id type stay internal to\n// the module — readers use exact membership via `isBespokePolicyId`, not the\n// prefix.)\nexport {\n BASELINE_ALLOW_POLICY_ID,\n BESPOKE_POLICY_IDS,\n bespokePolicyLabel,\n isBespokePolicyId,\n isNonNavigablePolicyId,\n nonNavigablePolicyLabel,\n} from './bespoke-policy';\nexport type { RequestFacts } from './cedar-rule-match';\nexport {\n splitCedarBlocks,\n blockEqualityLiterals,\n isForbidBlock,\n isUnnarrowedDenyBlock,\n pathLiteralsInBlock,\n pathHasUnnarrowedDenyRule,\n} from './cedar-rule-match';\n\n// ============================================================================\n// Author-time lint (Task 3)\n// ============================================================================\n\nexport type { LintFinding } from './policy-lint';\nexport { lintUnnarrowedDenyRules } from './policy-lint';\n\n// ============================================================================\n// Cedar string grammar (escape codec + capture) — shared by the compose engine\n// emitter/parser and the enforcement-path readers so the grammar can't drift.\n// ============================================================================\n\nexport { escapeCedarString, unescapeCedarString, cedarQuotedValueRegExp } from './cedar-string';\n\n// ============================================================================\n// Composed-policy approval quorum (the @approvers / @quorum a CHALLENGE demands)\n// — the step-up case, distinct from the consent @scopes case (ADR D7).\n// ============================================================================\n\nexport { approvalQuorumForRequest, type ApprovalQuorum } from './approval-quorum';\n\n// ============================================================================\n// Step-up quorum validation (T3-edge) — the fail-closed guard the enforce path\n// runs before approval-signature verification. Shared so every edge runtime\n// applies the same gate as the central gateway PEP.\n// ============================================================================\n\nexport {\n validateStepUpQuorum,\n type InvalidStepUpReason,\n type StepUpQuorumCheck,\n type StepUpQuorumLike,\n} from './step-up';\n\n// ============================================================================\n// Fetcher\n// ============================================================================\n\nexport {\n // Types\n type PolicyCacheAdapter,\n type PolicyFetcherConfig,\n type CachedPolicy,\n // Class\n PolicyFetcher,\n // Singleton management\n getDefaultPolicyFetcher,\n initializePolicyFetcher,\n resetPolicyFetcher,\n // Convenience functions\n fetchPolicy,\n createPolicyFetcher,\n} from './fetcher';\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Check if an action is a \"pass-through\" action.\n *\n * Vocab-1 (#2501): `permit` is the new canonical pass-through; `allow` is the\n * legacy alias and stays accepted during the alias period so historical rows\n * and policies still classify correctly. `log` is the deprecated action-form\n * (now `EnforcementMode = 'observe'`) but historical rows can still hold it.\n */\nexport function isPassThroughAction(action: string): boolean {\n return action === 'permit' || action === 'allow' || action === 'log';\n}\n\n/**\n * Check if an action is a \"blocking\" action — i.e. one where the host wrapper\n * does NOT pass the original request/response through unchanged. `instruct` is\n * blocking-class because the request is held pending guidance (matches the\n * dashboard's outcome bucket and the Decision-priority ordering in ADR-001).\n */\nexport function isBlockingAction(action: string): boolean {\n return (\n action === 'block' || action === 'redirect' || action === 'challenge' || action === 'instruct'\n );\n}\n\n/**\n * Create a basic evaluation context from detection result\n */\nexport function createEvaluationContext(options: {\n agentType?: string;\n agentName?: string;\n agentVendor?: string;\n confidence?: number;\n riskLevel?: string;\n path?: string;\n method?: string;\n signatureVerified?: boolean;\n isAuthenticated?: boolean;\n userAgent?: string;\n}): import('./schemas').PolicyEvaluationContext {\n return {\n agentType: options.agentType,\n agentName: options.agentName,\n agentVendor: options.agentVendor,\n confidence: options.confidence,\n riskLevel: options.riskLevel,\n path: options.path,\n method: options.method,\n signatureVerified: options.signatureVerified ?? false,\n isAuthenticated: options.isAuthenticated ?? false,\n hasValidDelegation: false,\n userAgent: options.userAgent,\n };\n}\n","/**\n * Verdict cookie — byte-format contract shared across host runtimes.\n *\n * Sites-1's Sonner toast depends on `__checkpoint_verdict=%7B%22verdict%22\n * %3A%22<v>%22...%7D` (single URL-encoded JSON). If this format drifts,\n * the toast renders incorrectly or not at all.\n *\n * Phase E (#TBD) extracted these helpers from `checkpoint-nextjs/src/\n * adapt.ts` so the Express host (and any future host) can reproduce the\n * exact same cookie shape. The runtime-specific cookie-write call (e.g.\n * `NextResponse.cookies.set()` vs `express.Response.cookie()`) stays in\n * each host's `adapt.ts`; only the encoding logic is shared.\n *\n * **Return raw JSON, not URL-encoded.** Both Next.js's cookies API and\n * Express's `res.cookie()` URL-encode the value when serializing to the\n * Set-Cookie header (per RFC 6265 + each framework's cookie library).\n * Pre-encoding here would double-encode (`%7B` → `%257B`) and break\n * Sonner.\n */\n\n/**\n * Structural view of the orchestrator's `RenderedResponse` — just the\n * fields these helpers need. Defined locally to avoid a circular\n * dependency between `checkpoint-shared` and `checkpoint-wasm-runtime`\n * (the canonical owner of the full type). The actual type from\n * `@kya-os/checkpoint-wasm-runtime/orchestrator` is structurally\n * assignable to this.\n */\nexport interface RenderedResponseLike {\n /** HTTP status — `null` means pass-through (Permit / Observe). */\n status: number | null;\n /** Engine-emitted response headers. */\n headers: Record<string, string>;\n}\n\n/**\n * Canonical cookie name. Sites-1's `/blocked` page reads from this\n * exact key; do not rename without updating the dashboard route.\n */\nexport const VERDICT_COOKIE_NAME = '__checkpoint_verdict';\n\n/**\n * The three-state verdict surfaced to client-side UI. Maps from the\n * `RenderedResponse.status` field (which itself maps from the engine's\n * `Decision` variant).\n *\n * - `'allowed'` — Permit, or Observe-mode (any verdict, status null)\n * - `'redirected'` — Decision::Redirect → status 302\n * - `'denied'` — Decision::Block / Challenge / Instruct (4xx)\n */\nexport type Verdict = 'allowed' | 'denied' | 'redirected';\n\n/**\n * Compute the verdict label from a `RenderedResponse`.\n */\nexport function deriveVerdict(rendered: RenderedResponseLike): Verdict {\n if (rendered.status === null) return 'allowed';\n if (rendered.status === 302) return 'redirected';\n return 'denied';\n}\n\n/**\n * Build the `__checkpoint_verdict` cookie value Sites-1's Sonner toast\n * reads. Byte-format pinned by tests in both `checkpoint-nextjs` and\n * `checkpoint-express`:\n *\n * - allowed: `{\"verdict\":\"allowed\"}`\n * - denied: `{\"verdict\":\"denied\",\"reason\":\"<r>\"}`\n * - redirected: `{\"verdict\":\"redirected\"}`\n *\n * Returns raw JSON; the host's cookie-write call URL-encodes.\n */\nexport function encodeVerdictCookie(rendered: RenderedResponseLike): string {\n const verdict = deriveVerdict(rendered);\n const reason = rendered.headers['X-Checkpoint-Reason'];\n const value = reason ? { verdict, reason } : { verdict };\n return JSON.stringify(value);\n}\n","/**\n * Content negotiation — framework-agnostic Accept-header parsing for\n * host adapters.\n *\n * The engine's `RenderedResponse` doesn't make HTML-vs-JSON branching\n * decisions; the host wrapper does that based on what the client\n * accepts. Both Next.js (NextRequest) and Express (Request) carry the\n * Accept header in different shapes — `req.headers.get('accept')` vs\n * `req.get('Accept')` vs `req.headers.accept` — so we accept any\n * Headers-like input and do the parsing here.\n */\n\n/**\n * `true` when the client signaled it accepts HTML or XHTML. Used by\n * host adapters to choose between an HTML `/blocked` rewrite (browsers)\n * and a JSON 4xx response (curl, fetch-from-a-tool, ChatGPT-User).\n *\n * Loose match — q-values, parameters, and additional MIME types are\n * allowed. The spec's q-value precedence (RFC 9110 § 12.5.1) doesn't\n * matter here; we only care whether HTML is present at all.\n *\n * Accepts:\n * - a `Headers` instance (Web Fetch API; Next.js, Hono, Cloudflare)\n * - a plain `Record<string, string>` (Express, Connect, Fastify)\n * - a single string (caller already extracted the Accept value)\n * - `undefined` (treated as no-HTML)\n */\nexport function acceptsHtml(\n input: Headers | Record<string, string | string[] | undefined> | string | undefined\n): boolean {\n const accept = extractAccept(input);\n if (!accept) return false;\n return accept.includes('text/html') || accept.includes('application/xhtml+xml');\n}\n\nfunction extractAccept(\n input: Headers | Record<string, string | string[] | undefined> | string | undefined\n): string | undefined {\n if (!input) return undefined;\n if (typeof input === 'string') return input;\n if (typeof (input as Headers).get === 'function') {\n return (input as Headers).get('accept') ?? undefined;\n }\n // Record path — HTTP header names are case-insensitive (RFC 9110 § 5.1);\n // try both common casings. Express lowercases by default; Next.js\n // header objects also lowercase.\n const rec = input as Record<string, string | string[] | undefined>;\n const value = rec.accept ?? rec.Accept;\n if (Array.isArray(value)) return value.join(',');\n return value;\n}\n","/**\n * Decision mapping — framework-agnostic classification of\n * `RenderedResponse` shapes that drive host-adapter branching.\n *\n * Phase D's `checkpoint-nextjs/src/adapt.ts` open-coded these four\n * branches (pass-through / redirect / HTML-block / JSON-block). Phase E\n * extracted them so the Express adapter — and any future host — can\n * share the classifier. The actual response construction stays\n * framework-specific (NextResponse.next() vs Express res.status().json()).\n */\n\nimport type { RenderedResponseLike } from './verdict-cookie';\n\n/**\n * Path the `/blocked` dashboard route lives at. HTML clients that hit\n * a 4xx verdict get rewritten here at status 200 so the page renders\n * with the verdict cookie set and Sonner can pick up the toast.\n *\n * Hard-coded by convention; if a customer ever needs a custom path,\n * pass it through `CheckpointConfig.blockedPath` and override in the\n * host adapter (not in this lookup).\n */\nexport const BLOCKED_PATH = '/blocked';\n\n/**\n * The four mutually-exclusive shapes a `RenderedResponse` can take,\n * driving the host adapter's branching. The host renders each shape\n * with its framework-native primitives.\n */\nexport type ResponseShape =\n /** Permit (status null) OR Observe-mode any-verdict — pass through with cookie + headers. */\n | 'pass-through'\n /** Decision::Redirect → 302 + Location header. */\n | 'redirect'\n /** 4xx + HTML-accepting client → rewrite to `/blocked` at status 200 for Sonner. */\n | 'html-block'\n /** 4xx + non-HTML client (or 5xx) → JSON body at the orchestrator's status. */\n | 'json-block';\n\n/**\n * Classify a `RenderedResponse` into one of the four host-adapter\n * branches. `clientAcceptsHtml` comes from `acceptsHtml()` in\n * `content-negotiation.ts`.\n */\nexport function classifyResponseShape(\n rendered: RenderedResponseLike,\n clientAcceptsHtml: boolean\n): ResponseShape {\n if (rendered.status === null) return 'pass-through';\n if (rendered.status === 302 && rendered.headers.Location) return 'redirect';\n if (clientAcceptsHtml && rendered.status >= 400 && rendered.status < 500) return 'html-block';\n return 'json-block';\n}\n","/**\n * Dual-envelope selection predicate (draft-kya-http-02 §8.1 fetcher-200).\n *\n * AI-agent fetchers (Claude-User WebFetch, ChatGPT) collapse 4xx/5xx\n * responses and never surface the body to the LLM, so the §8.1 step-up\n * challenge served at 401 is invisible. The fix is a dual envelope: keep\n * the spec 401 for capable/discovery clients, and serve a body-readable\n * HTTP 200 (no `WWW-Authenticate`) for cooperative, self-identifying\n * agents so they can read the body + relay the consent link.\n *\n * `serveBodyReadable200` is the shared selection predicate every TS PEP\n * (checkpoint-nextjs, checkpoint-express / wasm-runtime) consults when its\n * challenge-emission mode is `negotiated`. Centralising it here — rather\n * than re-implementing per PEP — makes drift structurally impossible; the\n * fetcher-200 fixture freezes envelope BYTES, this function freezes the\n * SELECTION.\n *\n * **This is a cooperative-UX bridge, NOT an access control.** A spoofer\n * that hides its identity and does not opt in simply receives the spec\n * 401 (and the original body-drop). Access is still gated entirely by the\n * unchanged detection + delegation verification — never by which envelope\n * is selected.\n */\n\nimport { normalizeDetectionClassEnum } from '../utils/detection-class';\n\n/**\n * Header inputs the predicate accepts — a WHATWG `Headers`, a plain\n * header record (Express/Next.js style), or absent. Mirrors the input\n * union `acceptsHtml` accepts so callers pass their native headers\n * unchanged.\n */\nexport type FetcherHeaderInput =\n | Headers\n | Record<string, string | string[] | undefined>\n | undefined;\n\n/**\n * Durable opt-in header — the primary, framework-agnostic signal that a\n * caller is a cooperative agent able to handle the 200 fetcher envelope.\n * Any non-empty value counts as opt-in (value semantics are reconciled\n * with mcp-i-cloudflare's `KYA-Accept-Challenge: delegation` in the spec).\n */\nexport const ACCEPT_CHALLENGE_HEADER = 'kya-accept-challenge';\n\nfunction readHeader(input: FetcherHeaderInput, name: string): string | undefined {\n if (!input) return undefined;\n if (typeof (input as Headers).get === 'function') {\n return (input as Headers).get(name) ?? undefined;\n }\n // Record path — HTTP header names are case-insensitive (RFC 9110 §5.1).\n const rec = input as Record<string, string | string[] | undefined>;\n const lower = name.toLowerCase();\n for (const key of Object.keys(rec)) {\n if (key.toLowerCase() === lower) {\n const v = rec[key];\n return Array.isArray(v) ? v[0] : (v ?? undefined);\n }\n }\n return undefined;\n}\n\n/**\n * Decide whether a `negotiated`-mode PEP should serve the body-readable\n * HTTP 200 fetcher envelope (`true`) or the spec 401 (`false`).\n *\n * Serve 200 when EITHER:\n * 1. the caller opts in via a non-empty `KYA-Accept-Challenge` header\n * (the durable, primary signal), OR\n * 2. detection classifies the caller as an AI agent — BOTH `isAgent` and\n * `detectionClass === 'ai_agent'` must agree (a transitional UA heuristic,\n * retired as frameworks adopt the header).\n *\n * Otherwise serve the 401 — spoofers, silent, discovery, and OAuth\n * clients all land here, which is acceptable because this is UX, not a\n * security boundary.\n *\n * Requiring both `isAgent` AND the `ai_agent` class to fire the heuristic\n * mirrors .NET `IsInteractiveAiAgent` (`IsAgent && DetectionClass.Type ==\n * AiAgent`) and the gateway worker, so the cross-PEP selection cannot drift on\n * the pathological case where the two signals disagree (class says agent,\n * `isAgent` says no): that caller is treated as non-cooperative (spec 401),\n * never demoted past it. In normal engine output the two signals agree, so\n * who-gets-200 is unchanged for real traffic.\n *\n * @param headers request headers (for the opt-in signal)\n * @param detectionClass the caller's detection class in any representation\n * the engine produces (a `DetectionClass` object, the\n * `ai_agent` wire string, or absent)\n * @param isAgent the engine's `isAgent` verdict — gates the `ai_agent`\n * heuristic so a class/`isAgent` disagreement gets the 401\n */\nexport function serveBodyReadable200(\n headers: FetcherHeaderInput,\n detectionClass: unknown,\n isAgent: boolean\n): boolean {\n // 1. Durable, primary signal: explicit opt-in header (independent of isAgent).\n const optIn = readHeader(headers, ACCEPT_CHALLENGE_HEADER);\n if (optIn && optIn.trim().length > 0) return true;\n\n // 2. Transitional UA heuristic: a detected AI agent — both signals must agree.\n if (isAgent && detectionClass !== undefined && detectionClass !== null) {\n if (normalizeDetectionClassEnum(detectionClass) === 'ai_agent') return true;\n }\n\n // 3. Spec 401 path (non-cooperative / silent / discovery / signals-disagree).\n return false;\n}\n\n/**\n * Per-PEP challenge-emission mode (mirrors mcp-i-cloudflare's `mode` and\n * the .NET `DelegationChallengeMode`). The TS engine PEPs (express / nextjs)\n * default to `negotiated`; the gateway worker reads its default from\n * `KYA_HTTP_CHALLENGE_MODE` (negotiated in dev, unset → spec-401 until the\n * prod flip, #3321).\n *\n * - `spec-401` — always the spec 401.\n * - `negotiated` — 200 for cooperative agents (per `serveBodyReadable200`),\n * 401 otherwise.\n * - `always-200` — 200 for everyone (fetcher-first hosts / escape hatch).\n */\nexport type ChallengeEnvelopeMode = 'spec-401' | 'negotiated' | 'always-200';\n\n/**\n * Resolve the challenge-emission mode + request signals into the single\n * boolean each PEP needs: serve the body-readable 200 (`true`) or the spec\n * 401 (`false`). Centralising the mode gate here — not just the predicate —\n * keeps the rollout switch identical across every TS PEP.\n */\nexport function selectBodyReadable200(\n mode: ChallengeEnvelopeMode,\n headers: FetcherHeaderInput,\n detectionClass: unknown,\n isAgent: boolean\n): boolean {\n if (mode === 'always-200') return true;\n if (mode === 'negotiated') return serveBodyReadable200(headers, detectionClass, isAgent);\n return false;\n}\n","/**\n * KYA-HTTP error code registry — draft-kya-http-02 §9 / H1.2 (#3245).\n *\n * The `kyaos/*` strings are wire constants returned in the `error` field of a\n * KYA-HTTP failure response (and mapped to an HTTP status). Emitters MUST use\n * these EXACT bytes; consumers MAY additionally accept the legacy `kya/*`\n * spellings for one transition cycle.\n *\n * The single source of truth is the golden fixture\n * `packages/checkpoint-shared/fixtures/kya-http/error-codes.json`; the parity\n * test in `__tests__/kya-http-error-codes.test.ts` reads that JSON via `fs` and\n * asserts this map is byte-exact against it (no drift, no omissions).\n *\n * `as const satisfies Record<string, \\`kyaos/${string}\\`>` keeps the narrow\n * literal value types (so consumers get autocomplete and a compile error on a\n * typo'd code) while still proving every value is a well-formed `kyaos/…` string.\n */\nexport const KYA_HTTP_ERROR = {\n // ── 401 (identity / signature) ──────────────────────────────────────────\n MISSING_SIGNATURE: 'kyaos/missing-signature',\n INVALID_SIGNATURE: 'kyaos/invalid-signature',\n EXPIRED: 'kyaos/expired',\n REPLAY: 'kyaos/replay',\n DID_UNRESOLVABLE: 'kyaos/did-unresolvable',\n AUTHORIZATION_REQUIRED: 'kyaos/authorization-required',\n\n // ── 403 (delegation / profile) ──────────────────────────────────────────\n PROFILE_VIOLATION: 'kyaos/profile-violation',\n DELEGATION_REVOKED: 'kyaos/delegation-revoked',\n SCOPE_INSUFFICIENT: 'kyaos/scope-insufficient',\n CHAIN_BROKEN: 'kyaos/chain-broken',\n HOLDER_MISMATCH: 'kyaos/holder-mismatch',\n AUDIENCE_MISMATCH: 'kyaos/audience-mismatch',\n SESSION_MISMATCH: 'kyaos/session-mismatch',\n PICKUP_PINNED: 'kyaos/pickup-pinned',\n // Credential verified but its achieved assurance tier is below the\n // determining policy's opt-in `@min_assurance` floor (trust-gap G3) — a\n // bearer credential (attested-bearer, no proof-of-possession) cannot satisfy\n // a key-bound+ floor. Recovery: a key-bound signed request, not a new\n // credential.\n ASSURANCE_INSUFFICIENT: 'kyaos/assurance-insufficient',\n\n // ── 503 (revocation status unverifiable — RETRYABLE) ─────────────────────\n // Emitted when a credential DECLARES a `credentialStatus` but its status list\n // was not supplied / could not be fetched (cold cache, past the 300s status\n // cap). Fail-closed but retryable: a warmed list may yet verify (#3345 / #3446).\n STATUS_PENDING: 'kyaos/status-pending',\n AUTHORIZATION_HOST_UNAVAILABLE: 'kyaos/authorization-host-unavailable',\n REPLAY_STATE_UNAVAILABLE: 'kyaos/replay-state-unavailable',\n\n // Live replay entries are retained when admission capacity is exhausted.\n REPLAY_CAPACITY: 'kyaos/replay-capacity',\n\n // ── pickup flow (404 / 410) ─────────────────────────────────────────────\n INVALID_SESSION: 'kyaos/invalid-session',\n PICKUP_EXPIRED: 'kyaos/pickup-expired',\n} as const satisfies Record<string, `kyaos/${string}`>;\n\n/** A `kyaos/*` registry code (the value side of {@link KYA_HTTP_ERROR}). */\nexport type KyaHttpErrorCode = (typeof KYA_HTTP_ERROR)[keyof typeof KYA_HTTP_ERROR];\n","/**\n * Canonical fixture-pinned KYA HTTP challenge-wire builder.\n *\n * The builder is transport-neutral and Edge-safe. Hosts must register the\n * challenge and resolve every URI before calling it; this module validates and\n * serializes those trusted values without network, database, or request access.\n */\n\nimport { KYA_HTTP_ERROR } from '../mcpi/kya-http-error-codes';\nimport type { AssuranceTier } from '../policy/schemas';\n\nconst PROTECTED_RESOURCE_METADATA_PATH = '/.well-known/oauth-protected-resource';\nconst DEFAULT_POLL_INTERVAL_S = 3;\n// eslint-disable-next-line no-control-regex -- deliberate: reject RFC 9110 quoted-string-unsafe control characters, not a stray literal.\nconst INVALID_QUOTED_VALUE = /[\\u0000-\\u001f\\u007f\"\\\\]/;\nconst SCOPE_TOKEN = /^[\\x21\\x23-\\x5b\\x5d-\\x7e]+$/;\nconst SID = /^kya-[0-9a-f]{16,}$/;\nconst ASSURANCE_TIERS = new Set<string>([\n 'anonymous',\n 'attested-bearer',\n 'key-bound',\n 'registered',\n 'delegated',\n]);\n\n/** Ordered HTTP header pair. Names may repeat. */\nexport type HeaderEntry = readonly [name: string, value: string];\n\nexport type ChallengeWireKind = 'delegation' | 'approval_quorum';\n\ninterface ChallengeWireInputBase {\n /** Protected-resource host, optionally including a port. */\n realm: string;\n /** Registered challenge/session identifier. */\n sid: string;\n /** Authorization-Host consent URL returned by registration. */\n consentUri: string;\n /** Authorization-Host pickup URL returned or resolved by registration. */\n pickupUri: string;\n /** Scopes demanded by policy. Empty means omit the optional scope parameter. */\n requiredScopes?: readonly string[];\n /** Optional poll cadence; omission retains the server default without an auth-param. */\n pollIntervalS?: number;\n /** Registered, signed proof. Opaque to the renderer. */\n challengeProof: unknown;\n /** Optional assurance floor demanded by policy. */\n minAssurance?: AssuranceTier;\n}\n\n/** Complete registered context for an OAuth-compatible delegation step-up. */\nexport interface DelegationChallengeWireInput extends ChallengeWireInputBase {\n kind?: 'delegation';\n /** Exact RFC 9728 discovery URI configured for the protected resource. */\n resourceMetadataUri: string;\n}\n\n/** Complete registered context for an N-of-M approval step-up. */\nexport interface ApprovalQuorumChallengeWireInput extends ChallengeWireInputBase {\n kind: 'approval_quorum';\n quorum: number;\n actionNonce: string;\n}\n\nexport type ChallengeWireInput = DelegationChallengeWireInput | ApprovalQuorumChallengeWireInput;\n\ninterface CommonChallengeKyaos {\n sid: string;\n consent_uri: string;\n pickup_uri: string;\n required_scopes?: string[];\n min_assurance?: AssuranceTier;\n poll_interval_s: number;\n challenge_proof: unknown;\n}\n\ninterface DelegationChallengeKyaos extends CommonChallengeKyaos {\n action: {\n type: 'delegation';\n consent_uri: string;\n pickup_uri: string;\n poll_interval_s: number;\n pin: { header: 'X-KYA-Pickup-Token' };\n retry: { header: 'Authorization'; scheme: 'Bearer'; value_from: 'delegation' };\n };\n}\n\ninterface ApprovalQuorumChallengeKyaos extends CommonChallengeKyaos {\n kind: 'approval_quorum';\n quorum: number;\n action_nonce: string;\n}\n\n/** Canonical body shared by the 401 and body-readable 200 envelopes. */\nexport interface DelegationChallengeBody {\n error: typeof KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED;\n kyaos: DelegationChallengeKyaos | ApprovalQuorumChallengeKyaos;\n instructions: string;\n}\n\nexport interface DelegationChallengeEnvelope {\n status: 401 | 200;\n headers: HeaderEntry[];\n body: DelegationChallengeBody;\n}\n\nexport type DelegationChallengeEnvelopeMode = 'spec-401' | 'fetcher-200';\n\nexport type ChallengeWireErrorCode =\n | 'invalid-realm'\n | 'invalid-sid'\n | 'invalid-uri'\n | 'invalid-scope'\n | 'invalid-assurance'\n | 'invalid-interval'\n | 'invalid-proof'\n | 'invalid-kind'\n | 'invalid-quorum'\n | 'invalid-action-nonce'\n | 'unsupported-envelope';\n\n/** Typed validation failure raised before any response is materialized. */\nexport class ChallengeWireError extends TypeError {\n readonly code: ChallengeWireErrorCode;\n\n constructor(code: ChallengeWireErrorCode, message: string) {\n super(message);\n this.name = 'ChallengeWireError';\n this.code = code;\n }\n}\n\n/** Generate a 128-bit, lower-case hexadecimal challenge id. */\nexport function generateDelegationSid(): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n let hex = '';\n for (const byte of bytes) hex += byte.toString(16).padStart(2, '0');\n return `kya-${hex}`;\n}\n\n/** Derive pickup from the registered consent origin, never request Host. */\nexport function deriveDelegationPickupUri(consentUri: string, sid: string): string {\n const consent = parseHttpsUrl('consentUri', consentUri);\n assertQuotedValue('sid', sid, 'invalid-sid');\n return `${consent.origin}/api/delegation/pickup/${sid}`;\n}\n\n/** Build the byte-pinned Delegation authentication field value. */\nexport function buildDelegationChallengeHeader(input: ChallengeWireInput): string {\n const normalized = validateInput(input);\n const params: Array<readonly [string, string]> = [\n ['realm', normalized.realm],\n ['sid', normalized.sid],\n ['consent_uri', normalized.consentUri],\n ['pickup_uri', normalized.pickupUri],\n ];\n if (normalized.requiredScopes.length > 0) {\n params.push(['scope', normalized.requiredScopes.join(' ')]);\n }\n if (normalized.minAssurance) {\n params.push(['min_assurance', normalized.minAssurance]);\n }\n if (input.pollIntervalS !== undefined) {\n params.push(['interval', String(normalized.pollIntervalS)]);\n }\n params.push(['kind', normalized.kind]);\n\n return `Delegation ${params.map(([name, value]) => `${name}=\"${value}\"`).join(', ')}`;\n}\n\n/** Build RFC 9728 Bearer discovery for a protected-resource realm. */\nexport function buildDelegationBearerHeader(realm: string): string {\n assertRealm(realm);\n return `Bearer resource_metadata=\"https://${realm}${PROTECTED_RESOURCE_METADATA_PATH}\"`;\n}\n\n/** Build the four required machine-followable delegation instruction elements. */\nexport function buildDelegationInstructions(\n consentUri: string,\n pickupUri: string,\n pollIntervalS: number\n): string {\n return (\n `This action requires human authorization. First establish your pickup binding at ${pickupUri}. ` +\n `If you can sign HTTP requests, sign each poll with an ephemeral did:key; otherwise generate one random 32-byte token encoded as unpadded base64url and send it as X-KYA-Pickup-Token on EVERY poll. ` +\n `After receiving 202 pending, show your user this link and ask them to approve: ${consentUri}. ` +\n `Continue polling ${pickupUri} every ${pollIntervalS} seconds with the same binding. ` +\n `When the response status is 200, take the 'delegation' value and retry your original request with header 'Authorization: Bearer <delegation>'.`\n );\n}\n\n/** Build the proof-bound body shared byte-for-byte by both HTTP envelopes. */\nexport function buildDelegationChallengeBody(input: ChallengeWireInput): DelegationChallengeBody {\n const normalized = validateInput(input);\n const common: CommonChallengeKyaos = {\n sid: normalized.sid,\n consent_uri: normalized.consentUri,\n pickup_uri: normalized.pickupUri,\n ...(normalized.requiredScopes.length > 0\n ? { required_scopes: [...normalized.requiredScopes] }\n : {}),\n ...(normalized.minAssurance ? { min_assurance: normalized.minAssurance } : {}),\n poll_interval_s: normalized.pollIntervalS,\n challenge_proof: input.challengeProof,\n };\n\n if (normalized.kind === 'approval_quorum') {\n return {\n error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,\n kyaos: {\n sid: common.sid,\n kind: 'approval_quorum',\n quorum: normalized.quorum!,\n action_nonce: normalized.actionNonce!,\n consent_uri: common.consent_uri,\n pickup_uri: common.pickup_uri,\n ...(common.required_scopes ? { required_scopes: common.required_scopes } : {}),\n ...(common.min_assurance ? { min_assurance: common.min_assurance } : {}),\n poll_interval_s: common.poll_interval_s,\n challenge_proof: common.challenge_proof,\n },\n instructions: buildApprovalQuorumInstructions(normalized),\n };\n }\n\n return {\n error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,\n kyaos: {\n ...common,\n action: {\n type: 'delegation',\n consent_uri: normalized.consentUri,\n pickup_uri: normalized.pickupUri,\n poll_interval_s: normalized.pollIntervalS,\n pin: { header: 'X-KYA-Pickup-Token' },\n retry: { header: 'Authorization', scheme: 'Bearer', value_from: 'delegation' },\n },\n },\n instructions: buildDelegationInstructions(\n normalized.consentUri,\n normalized.pickupUri,\n normalized.pollIntervalS\n ),\n };\n}\n\n/** Build either the canonical 401 or its body-identical fetcher-200 envelope. */\nexport function buildDelegationChallengeEnvelope(\n input: ChallengeWireInput,\n mode: DelegationChallengeEnvelopeMode = 'spec-401'\n): DelegationChallengeEnvelope {\n const normalized = validateInput(input);\n if (normalized.kind === 'approval_quorum' && mode === 'fetcher-200') {\n throw new ChallengeWireError(\n 'unsupported-envelope',\n 'fetcher-200 is not fixture-defined for approval_quorum'\n );\n }\n\n const body = buildDelegationChallengeBody(input);\n if (normalized.kind === 'approval_quorum') {\n return {\n status: 401,\n headers: [\n ['WWW-Authenticate', buildDelegationChallengeHeader(input)],\n ['Retry-After', String(normalized.pollIntervalS)],\n ['Content-Type', 'application/json'],\n ['Cache-Control', 'no-store'],\n ],\n body,\n };\n }\n\n const hintHeaders: HeaderEntry[] = [\n ['Content-Type', 'application/json'],\n ['Cache-Control', 'no-store'],\n ['KYA-Auth-Required', 'true'],\n ['KYA-Auth-Url', normalized.consentUri],\n ['Link', `<${normalized.consentUri}>; rel=\"kya-authorize\"`],\n ['KYA-Action', 'challenge'],\n ];\n if (mode === 'fetcher-200') {\n return { status: 200, headers: hintHeaders, body };\n }\n\n return {\n status: 401,\n headers: [\n ['WWW-Authenticate', buildDelegationChallengeHeader(input)],\n ['WWW-Authenticate', `Bearer resource_metadata=\"${normalized.resourceMetadataUri}\"`],\n ['Retry-After', String(normalized.pollIntervalS)],\n ...hintHeaders,\n ],\n body,\n };\n}\n\n/** Preferred generic name; the legacy export remains for host compatibility. */\nexport const buildChallengeWire = buildDelegationChallengeEnvelope;\n\ninterface ValidatedInput {\n realm: string;\n sid: string;\n consentUri: string;\n pickupUri: string;\n resourceMetadataUri?: string;\n requiredScopes: readonly string[];\n pollIntervalS: number;\n minAssurance?: AssuranceTier;\n kind: ChallengeWireKind;\n quorum?: number;\n actionNonce?: string;\n}\n\nfunction validateInput(input: ChallengeWireInput): ValidatedInput {\n assertRealm(input.realm);\n assertQuotedValue('sid', input.sid, 'invalid-sid');\n if (!SID.test(input.sid)) {\n throw new ChallengeWireError(\n 'invalid-sid',\n 'sid must start with kya- and contain at least 64 bits of lower-case hexadecimal entropy'\n );\n }\n\n const consent = parseHttpsUrl('consentUri', input.consentUri);\n const pickup = parseHttpsUrl('pickupUri', input.pickupUri);\n const expectedPickup = `${consent.origin}/api/delegation/pickup/${input.sid}`;\n if (pickup.href !== expectedPickup) {\n throw new ChallengeWireError(\n 'invalid-uri',\n 'pickupUri must use the registered consent origin and sid'\n );\n }\n\n const pollIntervalS = input.pollIntervalS ?? DEFAULT_POLL_INTERVAL_S;\n if (!Number.isInteger(pollIntervalS) || pollIntervalS < 1 || pollIntervalS > 999) {\n throw new ChallengeWireError(\n 'invalid-interval',\n 'pollIntervalS must be an integer from 1 through 999'\n );\n }\n if (input.challengeProof === undefined || input.challengeProof === null) {\n throw new ChallengeWireError('invalid-proof', 'challengeProof is required');\n }\n const requiredScopes = input.requiredScopes ?? [];\n for (const scope of requiredScopes) {\n if (!SCOPE_TOKEN.test(scope)) {\n throw new ChallengeWireError('invalid-scope', `invalid required scope: ${scope}`);\n }\n }\n if (input.minAssurance && !ASSURANCE_TIERS.has(input.minAssurance)) {\n throw new ChallengeWireError(\n 'invalid-assurance',\n `invalid minAssurance: ${input.minAssurance}`\n );\n }\n\n const kind = input.kind ?? 'delegation';\n if (kind !== 'delegation' && kind !== 'approval_quorum') {\n throw new ChallengeWireError('invalid-kind', `unsupported challenge kind: ${String(kind)}`);\n }\n\n let resourceMetadataUri: string | undefined;\n let quorum: number | undefined;\n let actionNonce: string | undefined;\n if (kind === 'delegation') {\n resourceMetadataUri = parseHttpsUrl(\n 'resourceMetadataUri',\n (input as DelegationChallengeWireInput).resourceMetadataUri\n ).href;\n const expectedMetadata = `https://${input.realm}${PROTECTED_RESOURCE_METADATA_PATH}`;\n if (resourceMetadataUri !== expectedMetadata) {\n throw new ChallengeWireError(\n 'invalid-uri',\n 'resourceMetadataUri must be the protected resource RFC 9728 metadata URL'\n );\n }\n } else {\n const approval = input as ApprovalQuorumChallengeWireInput;\n quorum = approval.quorum;\n actionNonce = approval.actionNonce;\n if (!Number.isInteger(quorum) || quorum < 1) {\n throw new ChallengeWireError('invalid-quorum', 'quorum must be a positive integer');\n }\n assertQuotedValue('actionNonce', actionNonce, 'invalid-action-nonce');\n }\n\n return {\n realm: input.realm,\n sid: input.sid,\n consentUri: consent.href,\n pickupUri: pickup.href,\n resourceMetadataUri,\n requiredScopes,\n pollIntervalS,\n minAssurance: input.minAssurance,\n kind,\n quorum,\n actionNonce,\n };\n}\n\nfunction buildApprovalQuorumInstructions(input: ValidatedInput): string {\n return (\n `This action requires approval from ${input.quorum} human approvers. ` +\n `Show your user this link to begin the approval process: ${input.consentUri}. ` +\n `Then poll ${input.pickupUri} every ${input.pollIntervalS} seconds (sign polls with an ephemeral did:key, or send one random 32-byte X-KYA-Pickup-Token on EVERY poll). ` +\n `When the response status is 200, retry your original request presenting the returned grants in the KYA-Approvals header.`\n );\n}\n\nfunction assertRealm(realm: string): void {\n assertQuotedValue('realm', realm, 'invalid-realm');\n if (realm.includes('/') || realm.includes('@') || realm.includes('?') || realm.includes('#')) {\n throw new ChallengeWireError('invalid-realm', 'realm must be a host with an optional port');\n }\n try {\n const parsed = new URL(`https://${realm}`);\n if (parsed.host !== realm) throw new Error('invalid authority');\n } catch {\n throw new ChallengeWireError(\n 'invalid-realm',\n 'realm must be a valid host with an optional port'\n );\n }\n}\n\nfunction assertQuotedValue(name: string, value: string, code: ChallengeWireErrorCode): void {\n if (typeof value !== 'string' || value.length === 0 || INVALID_QUOTED_VALUE.test(value)) {\n throw new ChallengeWireError(\n code,\n `${name} contains characters unsafe for an HTTP quoted-string`\n );\n }\n}\n\nfunction parseHttpsUrl(name: string, value: string): URL {\n assertQuotedValue(name, value, 'invalid-uri');\n let parsed: URL;\n try {\n parsed = new URL(value);\n } catch {\n throw new ChallengeWireError('invalid-uri', `${name} must be an absolute HTTPS URL`);\n }\n if (parsed.protocol !== 'https:' || parsed.username || parsed.password) {\n throw new ChallengeWireError(\n 'invalid-uri',\n `${name} must be an absolute HTTPS URL without credentials`\n );\n }\n return parsed;\n}\n","import { buildChallengeWire, type ChallengeWireInput } from './challenge-wire';\n\nexport const DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = 3000;\n\nexport type ChallengeContextFailure = 'timeout' | 'resolver-error' | 'invalid-context';\n\nexport interface ChallengeContextFailureEvent {\n reason: ChallengeContextFailure;\n message: string;\n}\n\nexport interface ResolveChallengeContextOptions {\n timeoutMs?: number;\n onFailure?: (event: ChallengeContextFailureEvent) => void;\n}\n\n/**\n * Resolve and validate registered challenge context at the async host boundary.\n * Resolver failures become an absent context so the renderer can emit the\n * canonical retryable status-pending response; secrets and proof values are\n * never included in failure events.\n */\nexport async function resolveChallengeContext<TContext>(\n resolver:\n | ((\n context: TContext\n ) => ChallengeWireInput | undefined | Promise<ChallengeWireInput | undefined>)\n | undefined,\n context: TContext,\n options: ResolveChallengeContextOptions = {}\n): Promise<ChallengeWireInput | undefined> {\n if (!resolver) return undefined;\n\n const timeoutMs = options.timeoutMs ?? DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS;\n if (!Number.isInteger(timeoutMs) || timeoutMs < 1) {\n throw new TypeError('challenge context timeout must be a positive integer');\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n const value = await Promise.race([\n Promise.resolve(resolver(context)),\n new Promise<never>((_resolve, reject) => {\n timeoutId = setTimeout(\n () => reject(new ChallengeContextTimeoutError(timeoutMs)),\n timeoutMs\n );\n }),\n ]);\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n if (!value) return undefined;\n\n try {\n buildChallengeWire(value, 'spec-401');\n return value;\n } catch (error) {\n options.onFailure?.({\n reason: 'invalid-context',\n message: (error as Error).message,\n });\n return undefined;\n }\n } catch (error) {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n options.onFailure?.({\n reason: error instanceof ChallengeContextTimeoutError ? 'timeout' : 'resolver-error',\n message:\n error instanceof ChallengeContextTimeoutError\n ? error.message\n : 'challenge context resolver failed',\n });\n return undefined;\n }\n}\n\nclass ChallengeContextTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`challenge context resolution exceeded ${timeoutMs}ms`);\n this.name = 'ChallengeContextTimeoutError';\n }\n}\n","/**\n * Wire contract for the gateway ↔ vault bridge on Vercel (#1532,\n * #2025, #2029).\n *\n * Route: `POST /api/v1/gateway/vault/:projectId/resolve`\n *\n * The Fly gateway posts a signed Ed25519 assertion; the Vercel\n * route resolves per-user credentials and returns them. The two\n * sides used to keep independent TypeScript types for the envelope,\n * which let the success shape drift unnoticed when Vercel wrapped\n * the body in the standard `{ success, data }` envelope but Fly\n * kept reading `body.secrets` at the root. Both sides now import\n * and validate through these schemas, so shape drift becomes a\n * typecheck / runtime validation error instead of a silent bug.\n *\n * The schemas are exhaustive for their path — no `.passthrough()`,\n * no optional fields that aren't actually optional. If the live\n * wire format grows a field, land the schema change in the same\n * commit as the code that writes/reads it.\n */\n\nimport { z } from 'zod';\n\n// ---------------------------------------------------------------------------\n// Success body — 200 response from /api/v1/gateway/vault/:projectId/resolve\n// ---------------------------------------------------------------------------\n\n/**\n * Optional metadata attached to the 200 response when the vault side\n * has the org / upstream slug context. The gateway uses these to\n * build deep-link `actionUrl`s when the secrets map is empty\n * (CREDENTIALS_NOT_CONFIGURED path).\n */\nexport const vaultResolveMetaSchema = z\n .object({\n orgSlug: z.string().optional(),\n upstreamSlug: z.string().optional(),\n })\n .strict();\n\n/**\n * The inner `data` payload on a 200 response.\n *\n * `secrets` is always an object keyed by `envVarName`. Empty object\n * is valid and distinct from missing — an empty map signals \"user\n * hasn't connected this upstream yet\" while a missing field would\n * be a broken response. Values are always strings per §3.4 of the\n * #1532 wire contract; no nested secret types.\n */\nexport const vaultResolveDataSchema = z\n .object({\n secrets: z.record(z.string(), z.string()),\n _meta: vaultResolveMetaSchema.optional(),\n })\n .strict();\n\n/**\n * Canonical envelope for every successful vault resolve. Every\n * 200 response on this path MUST match this schema exactly. The\n * `.strict()` on the outer object catches stray top-level fields\n * — if a new claim needs to land on the envelope, it gets a\n * schema update in the same PR.\n */\nexport const vaultResolveSuccessSchema = z\n .object({\n success: z.literal(true),\n data: vaultResolveDataSchema,\n })\n .strict();\n\nexport type VaultResolveSuccess = z.infer<typeof vaultResolveSuccessSchema>;\nexport type VaultResolveData = z.infer<typeof vaultResolveDataSchema>;\nexport type VaultResolveMeta = z.infer<typeof vaultResolveMetaSchema>;\n\n// ---------------------------------------------------------------------------\n// Error body — 4xx/5xx responses from the same route\n// ---------------------------------------------------------------------------\n\n/**\n * Every error response uses the nested `error: { code, message, data }`\n * envelope established in #1532 step 4 (commit 95994b751). The\n * `code` is a machine-readable string (`NOT_FOUND`, `INVALID_SIGNATURE`,\n * `GONE`, etc.) — see `vault-response-mapping.ts` on the gateway\n * side for the full list of recognized codes.\n */\nexport const vaultResolveErrorSchema = z\n .object({\n success: z.literal(false),\n error: z\n .object({\n code: z.string(),\n message: z.string(),\n data: z\n .object({\n orgSlug: z.string().optional(),\n upstreamSlug: z.string().optional(),\n retryAfter: z.number().optional(),\n })\n .passthrough()\n .optional(),\n })\n .strict(),\n })\n .strict();\n\nexport type VaultResolveError = z.infer<typeof vaultResolveErrorSchema>;\n\n/**\n * Discriminated union over the two shapes. Callers that receive a\n * parsed body can branch on `success` without a separate status\n * check.\n */\nexport const vaultResolveResponseSchema = z.discriminatedUnion('success', [\n vaultResolveSuccessSchema,\n vaultResolveErrorSchema,\n]);\n\nexport type VaultResolveResponse = z.infer<typeof vaultResolveResponseSchema>;\n","/**\n * Canonical KYA-OS per-organization did:web derivation.\n *\n * The org slug becomes a single path segment in\n * `https://kya.vouched.id/orgs/<slug>/did.json`, so validation here is a\n * security boundary shared by issuers and verifiers.\n */\n\n/** did:web host for org issuer DIDs. */\nexport const MCPI_ORG_DID_HOST = 'kya.vouched.id';\n\nconst ORG_SLUG_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\n/**\n * True when `slug` is a valid `did:web` org path segment — i.e. it can be fed\n * to {@link deriveMcpiOrgDid} without throwing. Callers that accept a\n * user-supplied slug MUST gate on this before persisting it, since the org DID\n * is derived from the slug at every mint/publish/verify site; an invalid slug\n * bricks credential issuance for that org.\n */\nexport function isValidMcpiOrgSlug(slug: string): boolean {\n return ORG_SLUG_PATTERN.test(slug);\n}\n\n/** Build the org's `did:web` issuer DID from its slug. Throws on invalid slugs. */\nexport function deriveMcpiOrgDid(slug: string): string {\n if (!ORG_SLUG_PATTERN.test(slug)) {\n throw new Error(`Invalid org slug for did:web derivation: ${JSON.stringify(slug)}`);\n }\n return `did:web:${MCPI_ORG_DID_HOST}:orgs:${slug}`;\n}\n\n/** The verification-method id / JWT `kid` for an org's active signing key. */\nexport function deriveMcpiOrgKid(slug: string): string {\n return `${deriveMcpiOrgDid(slug)}#key-1`;\n}\n\n/**\n * The delegation root DIDs an org trusts — the value the policies route resolves\n * SERVER-SIDE and returns on the policy payload, which each surface forwards into\n * the engine's `ContextSpec.trustedDelegationRoots` allow-list.\n *\n * Option 1 (first-party): an org trusts ONLY delegations rooted at its own DID.\n * This is the single place trust-root composition lives — called server-side in\n * the policies route, never on a surface. Option 2 (configurable partner issuer\n * DIDs) and the #3020 `resolveOrgDid(org)` multi-host generalization extend ONLY\n * this function; the engine, wire format, orchestrator threading, and every\n * surface stay unchanged.\n *\n * Throws on an invalid slug (same boundary as {@link deriveMcpiOrgDid}) rather\n * than returning `[]`: an empty list re-enables the engine's fail-open\n * \"trust every root\" default, so an org with a broken slug is a configuration\n * error to surface loudly server-side, not a reason to trust everything.\n */\nexport function resolveTrustedDelegationRoots(org: { slug: string }): string[] {\n return [deriveMcpiOrgDid(org.slug)];\n}\n\nconst USER_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\n/**\n * Build a user's `did:web` DID under the org's DID tree. Resolves to\n * `https://kya.vouched.id/orgs/<slug>/users/<userId>/did.json`.\n *\n * Standard requires `did:web` or `did:key` for any DID we emit (no ad-hoc\n * methods); this extends the org-scoped did:web tree rather than introducing\n * a new method. The per-user did.json route is not served yet — verifiers\n * resolving this DID get a 404 today. Acceptable while there are no external\n * verifiers; the route lands alongside E5.3 (HTTP intent verification).\n *\n * Throws on invalid slug or userId so the bad shape never reaches the wire.\n */\nexport function deriveMcpiUserDid(slug: string, userId: string): string {\n if (!USER_ID_PATTERN.test(userId)) {\n throw new Error(`Invalid user id for did:web derivation: ${JSON.stringify(userId)}`);\n }\n return `${deriveMcpiOrgDid(slug)}:users:${userId}`;\n}\n","/**\n * Delegation-proof request detection (P2 / DR-1).\n *\n * The engine's L2 delegation-root pinning (`ContextSpec.trustedDelegationRoots`)\n * is only consulted when a request actually carries a delegation credential.\n * Every consumer surface — the Cloudflare gateway worker, the published SDK\n * middleware (Next.js / Express), and the Next.js detector route — uses this one\n * check to decide whether to resolve + inject the org's trusted roots, so the\n * human / no-delegation hot path stays a precise no-op.\n *\n * Keeping the header set here (rather than re-listing the literals at each site)\n * is the whole point: a new delegation transport header is added in one place\n * and every verifier surface agrees.\n */\n\n/**\n * Lowercased delegation-proof header names. `kya-os-delegation-credential` is the\n * canonical KYA-OS transport; `kya-delegation` is the legacy envelope form still\n * accepted via `legacyEnvelopeFallback`.\n */\nexport const DELEGATION_PROOF_HEADERS = ['kya-os-delegation-credential', 'kya-delegation'] as const;\n\n/** A header value is \"present\" when it is a non-empty string (or non-empty list). */\nfunction isPresent(value: unknown): boolean {\n if (Array.isArray(value)) return value.length > 0;\n return typeof value === 'string' && value.length > 0;\n}\n\n/**\n * Does the request carry a KYA-OS delegation-proof header?\n *\n * Accepts either a `Headers` instance (Next.js / fetch — case-insensitive\n * lookup) or a plain header record (raw Node/Express headers, gateway worker's\n * lowercased map). Record keys are matched case-insensitively, so callers do not\n * need to pre-normalize. Returns `false` for `null`/`undefined`.\n */\nexport function requestCarriesDelegationProof(\n headers: Headers | Record<string, unknown> | null | undefined\n): boolean {\n if (!headers) return false;\n\n if (typeof (headers as Headers).get === 'function') {\n const h = headers as Headers;\n return DELEGATION_PROOF_HEADERS.some((name) => isPresent(h.get(name)));\n }\n\n const record = headers as Record<string, unknown>;\n const lowerKeyed = new Map<string, unknown>();\n for (const key of Object.keys(record)) {\n lowerKeyed.set(key.toLowerCase(), record[key]);\n }\n return DELEGATION_PROOF_HEADERS.some((name) => isPresent(lowerKeyed.get(name)));\n}\n","/**\n * Canonical principals + MCP client DID derivation.\n *\n * Standard requires `did:web` or `did:key` for any DID we emit — no\n * ad-hoc methods. This module defines:\n *\n * - {@link ANONYMOUS_PRINCIPAL_DID}: a known anonymous-principal `did:web`\n * used as the sentinel when the gateway cannot determine the subject\n * (replaces the pre-#3022 `did:kya:anonymous` ad-hoc form).\n * - {@link deriveMcpClientDid}: derives an MCP client's canonical `did:web`\n * from its client id (replaces the pre-#3022 `did:client:<id>` shape).\n *\n * The anonymous principal resolves to a minimal stub DID document at\n * `https://kya.vouched.id/principals/anonymous/did.json` (no verification\n * methods — the principal can't sign anything, it's a sentinel).\n *\n * The client DID resolves to `https://knowthat.ai/clients/<id>/did.json`.\n * Known first-party clients (Cursor, Claude Desktop, etc.) have docs served\n * by the KTA registry; unknown clients use the same shape and may 404 on\n * resolution today.\n *\n * `deriveMcpClientDid` also accepts a CIMD `client_id` (an OAuth Client ID\n * Metadata Document URL, SEP-991 / draft-ietf-oauth-client-id-metadata-\n * document). This is NOT the ratified `did:web` <-> HTTPS bijection from\n * SPEC-ENTITY-CARD.md §7.1 (`didFromClientId` in `@kya-os/mcp`'s\n * `src/card/cimd.ts`) — applying that bijection to a third-party CIMD URL\n * (e.g. `https://claude.ai/...`) would mint a `did:web:claude.ai:...`, a\n * different host than `knowthat.ai`, which this module's callers require\n * and which would 404 (Anthropic doesn't serve a DID document there). So a\n * CIMD URL is instead mapped onto the SAME `knowthat.ai:clients:<slug>`\n * shape every other client id already produces — see `CIMD_CLIENT_SLUGS`.\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\n\n/** Canonical did:web for the anonymous-principal sentinel. */\nexport const ANONYMOUS_PRINCIPAL_DID = 'did:web:kya.vouched.id:principals:anonymous';\n\n/** did:web host for MCP client DIDs (KnowThatAi registry). */\nexport const MCP_CLIENT_DID_HOST = 'knowthat.ai';\n\nconst CLIENT_ID_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,253}[A-Za-z0-9])?$/;\n\n/** Deterministic-fallback slug prefix for a CIMD URL with no known mapping below. */\nconst CIMD_FALLBACK_PREFIX = 'cimd-';\n\n/**\n * Known CIMD `client_id` URLs mapped onto the SAME slug `KNOWN_CLIENTS`\n * already uses in `apps/web/lib/gateway/mcp-client-did.ts` — resolving one\n * of these produces the EXACT DID string that id already resolves to today\n * (no migration). Keyed on the full, exact `client_id` string, never the\n * host: `claude.ai` alone serves distinct CIMD documents for Claude Code vs.\n * Claude Desktop/web/Cowork, and host-only keying would merge slugs\n * `KNOWN_CLIENTS` deliberately keeps separate.\n *\n * `https://claude.ai/oauth/mcp-oauth-client-metadata` (Claude Desktop, the\n * claude.ai web app, mobile, and Cowork) is deliberately left OUT: that one\n * client_id is shared by four distinct surfaces, and mapping it to a single\n * `claude-desktop` slug would over-claim a precision the id doesn't carry.\n * It falls through to the deterministic `cimd-<hash>` slug below instead.\n * Revisit if/when KTA adds a broader registry entry for it.\n */\nconst CIMD_CLIENT_SLUGS: Readonly<Record<string, string>> = {\n 'https://claude.ai/oauth/claude-code-client-metadata': 'claude-code',\n 'https://vscode.dev/oauth/client-metadata.json': 'vscode',\n};\n\n/**\n * The slugs `CIMD_CLIENT_SLUGS` maps CIMD URLs onto — reserved so an\n * OPAQUE (non-URL) client id can never collide with one. Without this, an\n * opaque `client_id: 'claude-code'` would mint the exact same\n * `did:web:knowthat.ai:clients:claude-code` a domain-verified CIMD\n * resolution produces, distinguishable only by the caller's separately-\n * tracked provenance (`oauth_client_derived` vs `oauth_client_cimd`) —\n * any downstream consumer that keys off `agentDid` alone can't tell them\n * apart. `isCimdClientId` already rejects non-URL strings before this\n * function's CIMD branch ever runs, so the only way to reach a reserved\n * slug through the opaque path is by supplying the bare slug text itself.\n */\nconst RESERVED_CIMD_SLUGS = new Set(Object.values(CIMD_CLIENT_SLUGS));\n\n/**\n * Build an MCP client's `did:web` from its client id. Throws on invalid ids.\n *\n * Accepts two client id shapes:\n * - An opaque, pattern-valid id (e.g. a DCR-issued UUID or a known slug)\n * — unchanged behavior, byte-identical output to before CIMD support.\n * - A CIMD `client_id` URL — must be `https:` with a non-empty path.\n * A known KYA-OS-issued URL (`CIMD_CLIENT_SLUGS`) resolves to its\n * existing slug; an unknown one gets a deterministic `cimd-<sha256\n * prefix>` slug, stable for the life of that client_id. Either way the\n * DID keeps the exact same `did:web:knowthat.ai:clients:<slug>` shape,\n * so no migration is required.\n *\n * The resulting DID resolves to `https://knowthat.ai/clients/<id>/did.json`.\n */\nexport function deriveMcpClientDid(clientId: string): string {\n const cimdUrl = tryParseUrl(clientId);\n const slug = cimdUrl ? slugForCimdUrl(cimdUrl, clientId) : clientId;\n\n if (!CLIENT_ID_PATTERN.test(slug)) {\n throw new Error(`Invalid client id for did:web derivation: ${JSON.stringify(clientId)}`);\n }\n // Reject an opaque client id that collides with a slug CIMD_CLIENT_SLUGS\n // reserves for domain-verified resolution — see RESERVED_CIMD_SLUGS.\n if (!cimdUrl && RESERVED_CIMD_SLUGS.has(slug)) {\n throw new Error(`Reserved CIMD client slug, cannot use as an opaque client id: ${slug}`);\n }\n return `did:web:${MCP_CLIENT_DID_HOST}:clients:${slug}`;\n}\n\n/** Parse `value` as a URL, or null if it isn't URL-shaped (an opaque client id). */\nfunction tryParseUrl(value: string): URL | null {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a CIMD `client_id` URL to its did:web slug. CIMD requires `https`\n * and a path component; a non-https scheme or a bare origin throws rather\n * than silently falling back to the opaque-id path.\n */\nfunction slugForCimdUrl(url: URL, originalClientId: string): string {\n if (url.protocol !== 'https:' || url.pathname === '' || url.pathname === '/') {\n throw new Error(\n `Invalid client id for did:web derivation: ${JSON.stringify(originalClientId)}`\n );\n }\n const known = CIMD_CLIENT_SLUGS[originalClientId];\n if (known) return known;\n const digest = bytesToHex(sha256(new TextEncoder().encode(originalClientId)));\n return `${CIMD_FALLBACK_PREFIX}${digest.slice(0, 32)}`;\n}\n","/**\n * Reported identity — the wire block a KYA-OS-aware enforcement point (a\n * \"verifier\", e.g. the in-process `@kya-os/id/mcp` reporter the Hobbsidian\n * reference customer runs) sends to Checkpoint's `/api/v1/log-detection` to\n * describe WHO acted and on WHOSE behalf.\n *\n * This is the M1 hinge contract of `docs/architecture/agent-identity-taxonomy.md`\n * (§5.1) — the shape both Checkpoint ingest and every KYA-OS reporter converge\n * on, and the draft of the proposed \"Verifier Reporting Profile\" (§10). Field\n * names track KYA-OS / draft-kya-http vocabulary (issuer / audience / capability\n * / jti) so the block can graduate into a non-normative DIF companion without a\n * rename.\n *\n * THREE deliberate properties:\n *\n * 1. **Asserted vs verified is explicit.** `agent` and `principal` are\n * identities the reporter ASSERTS; only `delegation.result` carries a\n * verification OUTCOME, and `delegation.verifiedBy` says who did the\n * cryptography. Checkpoint derives an *assurance* tier\n * ({@link AssuranceTier}) from these server-side — the reporter does not\n * get to assert its own assurance.\n *\n * 2. **agent ≠ principal, structurally.** The bug that motivated this block\n * (a reporter sending a *user* DID under a generic `signals[{kind:\n * \"agent_did\"}]` entry, rendering \"on behalf of: unattributed\") is\n * impossible to express here: the principal's DID lives on `principal.did`,\n * the agent's on `agent.did`. They are separate objects.\n *\n * 3. **`clientInfoName` is a DECLARED hint, never identity.** MCP `initialize`\n * `clientInfo.name` and User-Agent are unauthenticated; a verifier MUST NOT\n * treat them as agent identity (this is the spec security-considerations\n * posture, §10.2). They are recorded as declared metadata at most — the\n * resolution ladder caps their assurance at `attested-bearer`.\n *\n * Additive-optional, mirroring every prior `log-detection` evolution\n * (enforcement #2446, engine Phase-0.1, sdk #3076, engineSteps #3164): the whole\n * block is optional, and objects are non-strict (unknown keys strip) so a newer\n * reporter field never 400s an older Checkpoint. The reporter may emit this\n * block immediately — pre-M1 ingest silently strips it (see §5.3 dual-emit pin).\n *\n * NOT carried here: the full delegation JWS/VC body. `delegations` /\n * `bouncer_proofs` remain the credential stores; this block carries the\n * *reference* (`jti`) and the *outcome*, not the proof.\n */\n\nimport { z } from 'zod';\n\n/**\n * A W3C DID string. Required form per the KYA-OS standard: `did:web` or\n * `did:key` (no ad-hoc methods). We validate only the `did:` scheme prefix here\n * — method-specific structure is the resolver's concern — but the prefix alone\n * is enough to reject the junk that an untyped signals array used to admit (a\n * bare userId, an email, a UA string).\n */\nconst DidStringSchema = z\n .string()\n .trim()\n .min(1)\n .regex(/^did:/, 'must be a DID (did:web / did:key)');\n\n/** A non-empty, trimmed free string (rejects whitespace-only values). */\nconst NonEmptyTrimmed = z.string().trim().min(1);\n\n/**\n * The acting agent's asserted identity. Every field is optional — a reporter\n * fills in what it actually knows: an enterprise A2A agent has a `did`; a\n * generic OAuth MCP client has only an `oauthClientId` (Checkpoint derives its\n * `did:web` server-side via `deriveMcpClientDid`); an unauthenticated client\n * offers only the declared `clientInfoName`.\n */\nexport const ReportedAgentSchema = z\n .object({\n /** The agent's own DID, when it has one (enterprise A2A / provisioned). */\n did: DidStringSchema.optional(),\n /**\n * OAuth `client_id` of an authenticated MCP client. Checkpoint derives the\n * canonical `did:web` from this (DR-9 `deriveMcpClientDid`); the reporter\n * sends the raw id, not the derived DID.\n */\n oauthClientId: NonEmptyTrimmed.optional(),\n /**\n * MCP `initialize` `clientInfo.name` (e.g. `claude-ai`, `cursor`). DECLARED,\n * unauthenticated — recorded as a hint, never resolved as identity above\n * `attested-bearer` assurance.\n */\n clientInfoName: NonEmptyTrimmed.optional(),\n /** MCP `initialize` `clientInfo.version`. Declared. */\n clientInfoVersion: NonEmptyTrimmed.optional(),\n })\n .describe('Asserted identity of the acting agent');\nexport type ReportedAgent = z.infer<typeof ReportedAgentSchema>;\n\n/**\n * The human (or upstream) principal the agent acted on behalf of — the \"on\n * behalf of\" attribution. `did` is preferred (e.g.\n * `did:web:h0bb5.dev:u:<userId>`); `sub` is the issuer-local subject when no\n * DID is minted; `email` is an optional display identity only.\n */\nexport const ReportedPrincipalSchema = z\n .object({\n /** The principal's DID (the delegation issuer, typically). */\n did: DidStringSchema.optional(),\n /** Issuer-local subject identifier, when the principal has no DID. */\n sub: NonEmptyTrimmed.optional(),\n /** Optional display email. Never the identity key — `did`/`sub` are. */\n email: NonEmptyTrimmed.email().optional(),\n })\n .describe('Asserted identity of the principal the agent acted for');\nexport type ReportedPrincipal = z.infer<typeof ReportedPrincipalSchema>;\n\n/**\n * Outcome of presenting a delegation. `verified` = the signed delegation\n * checked out; `failed` = presented but rejected; `not_presented` = none on the\n * request. Required whenever a `delegation` block is sent — an outcome-less\n * delegation block is meaningless.\n */\nexport const DelegationResultSchema = z.enum(['verified', 'failed', 'not_presented']);\nexport type DelegationResult = z.infer<typeof DelegationResultSchema>;\n\n/**\n * Who performed the delegation cryptography — the trust provenance of\n * `result`. `reporter` = the customer's own in-process verifier checked it\n * (same trust class as all SDK self-reporting, bounded by the API key's project\n * scope); `gateway` = a Checkpoint gateway verified it in-path; `checkpoint` =\n * the ingest plane re-verified. Persisted so a future in-path mode can rank\n * above self-reported without a schema change.\n */\nexport const DelegationVerifiedBySchema = z.enum(['reporter', 'gateway', 'checkpoint']);\nexport type DelegationVerifiedBy = z.infer<typeof DelegationVerifiedBySchema>;\n\n/**\n * Max length of a registered session anchor (`sid`) accepted on the wire and\n * enforced again at the customer route. The join partner\n * `bouncer_sessions.id` is `varchar(100)`; `detections.registered_sid` stays\n * `text` (converting a live column to `varchar` would take an ACCESS EXCLUSIVE\n * rewrite of the hottest table), so this constant is the width contract\n * instead of the column type.\n */\nexport const REGISTERED_SID_MAX_LENGTH = 100;\n\n/**\n * The one delegation result that may attribute a `sid` to a session timeline.\n * A rejected presentation carries no engine-emitted sid, and a sid on a\n * `failed` / `not_presented` report is attacker-shaped, so ingest stamps\n * `registered_sid` only for this result and nulls it otherwise (D4 / D15).\n * One member on purpose: Section 13 of the plan records how an explicitly\n * unverified-labeled `failed` could join it later.\n */\nexport const SID_ATTRIBUTABLE_RESULT = 'verified' as const;\n\n/**\n * The delegation the agent presented (a reference + outcome, not the proof).\n * `result` and `verifiedBy` are required; the JWT claims (`jti` / `iss` / `aud`\n * / `capabilities` / `exp`) are optional because `not_presented` carries none.\n */\nexport const ReportedDelegationSchema = z\n .object({\n /** Delegation credential id — the join key into `delegations`. */\n jti: NonEmptyTrimmed.optional(),\n /**\n * The registered session anchor: the draft-kya-http-02 `sid` claim of the\n * presented credential (the top-level VC-JWT `sid` minted in\n * `mint-vc-jwt.ts`), distinct from any gateway or MCP session id. Optional,\n * and attributed to a session timeline only when `result` is `verified`\n * ({@link SID_ATTRIBUTABLE_RESULT}); ingest nulls it for any other result.\n * No refine here: the identity block must never fail a request.\n */\n sid: NonEmptyTrimmed.max(REGISTERED_SID_MAX_LENGTH).optional(),\n /** Issuer DID (usually the principal). */\n iss: DidStringSchema.optional(),\n /** Audience DID (the intended verifier / resource). */\n aud: DidStringSchema.optional(),\n /** Granted capabilities, e.g. `['vault:read']`. */\n capabilities: z.array(NonEmptyTrimmed).optional(),\n /** Expiry, unix seconds. */\n exp: z.number().int().positive().optional(),\n /** Verification outcome — required. */\n result: DelegationResultSchema,\n /** Who verified — required. */\n verifiedBy: DelegationVerifiedBySchema,\n })\n .describe('Presented delegation: reference + verification outcome');\nexport type ReportedDelegation = z.infer<typeof ReportedDelegationSchema>;\n\n/**\n * The full reported-identity block. All three sub-blocks are optional so a\n * reporter sends only what it has; an empty `{}` is valid (a reporter that\n * carries no identity at all). Checkpoint resolves the agent against its\n * catalog, attributes the principal, and derives the assurance tier from this\n * block plus the engine verdict.\n */\nexport const ReportedIdentitySchema = z\n .object({\n agent: ReportedAgentSchema.optional(),\n principal: ReportedPrincipalSchema.optional(),\n delegation: ReportedDelegationSchema.optional(),\n })\n .describe('KYA-OS reported identity (verifier → observability plane)');\nexport type ReportedIdentity = z.infer<typeof ReportedIdentitySchema>;\n","/**\n * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).\n *\n * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`\n * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase\n * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,\n * so the decoded multikey is always 34 bytes and the did:key always begins\n * `z6Mk` (a fixed consequence of the `0xed01` prefix).\n *\n * This is a PURE-JS port of the base58btc decoder in\n * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division\n * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS\n * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with\n * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare\n * Workers, and the browser). The encoder is the inverse, for tests and any\n * caller that emits a `did:key` from raw key bytes.\n */\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: Record<string, number> = (() => {\n const idx: Record<string, number> = {};\n for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;\n return idx;\n})();\n\nconst DID_KEY_PREFIX = 'did:key:';\nconst ED25519_MULTICODEC = [0xed, 0x01] as const; // ed25519-pub\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Decode a base58btc string to bytes using the repeated-division algorithm.\n * Returns null if the string contains a character outside the base58btc\n * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`\n * (kept algorithm-identical to avoid cross-runtime drift).\n */\nexport function base58btcDecode(str: string): Uint8Array | null {\n if (str.length === 0) return new Uint8Array(0);\n\n let zeros = 0;\n while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;\n\n // Sentinel-seeded little-endian byte accumulator.\n const bytes: number[] = [0];\n for (let i = 0; i < str.length; i++) {\n const value = BASE58_INDEX[str[i]];\n if (value === undefined) return null;\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Drop the trailing zero sentinel(s).\n let high = bytes.length;\n while (high > 0 && bytes[high - 1] === 0) high--;\n\n const out = new Uint8Array(zeros + high);\n for (let i = 0; i < high; i++) {\n out[zeros + high - 1 - i] = bytes[i];\n }\n return out;\n}\n\n/**\n * Encode bytes to a base58btc string — the exact inverse of\n * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value\n * is accumulated as little-endian base58 digits (×256 + byte) and emitted\n * big-endian. The high-order zero sentinel is dropped the same way the decoder\n * drops its trailing zeros, so a single `0x00` byte encodes to `\"1\"`, not `\"11\"`.\n */\nexport function base58btcEncode(bytes: Uint8Array): string {\n if (bytes.length === 0) return '';\n\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\n const digits: number[] = [0];\n for (let i = 0; i < bytes.length; i++) {\n let carry = bytes[i];\n for (let j = 0; j < digits.length; j++) {\n carry += digits[j] * 256;\n digits[j] = carry % 58;\n carry = Math.floor(carry / 58);\n }\n while (carry > 0) {\n digits.push(carry % 58);\n carry = Math.floor(carry / 58);\n }\n }\n\n // Drop the high-order zero sentinel(s); leading zero bytes become '1's.\n let high = digits.length;\n while (high > 0 && digits[high - 1] === 0) high--;\n\n let out = BASE58_ALPHABET[0].repeat(zeros);\n for (let i = high - 1; i >= 0; i--) {\n out += BASE58_ALPHABET[digits[i]];\n }\n return out;\n}\n\n/**\n * Recover the raw 32-byte Ed25519 public key from a `did:key:z6Mk…` string.\n * Returns null for any malformed input: wrong method, wrong multibase, invalid\n * base58, wrong decoded length, or a non-Ed25519 multicodec. Never throws —\n * callers treat null as \"not a verifiable Ed25519 did:key\".\n */\nexport function decodeDidKeyEd25519(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(DID_KEY_PREFIX)) return null;\n\n const suffix = did.slice(DID_KEY_PREFIX.length);\n if (!suffix.startsWith('z')) return null; // base58btc multibase prefix\n\n // A legit Ed25519 did:key body is fixed at 47 base58 chars. Cap the length\n // BEFORE the O(n^2) repeated-division decode: this keyid arrives from an\n // attacker-controlled Signature-Input header on the public pickup endpoint, so\n // an over-long body (which the 34-byte length check would reject anyway) must\n // not be allowed to burn quadratic event-loop CPU first.\n const body = suffix.slice(1);\n if (body.length > 64) return null;\n\n const decoded = base58btcDecode(body);\n if (!decoded || decoded.length !== ED25519_MULTIKEY_LENGTH) return null;\n if (decoded[0] !== ED25519_MULTICODEC[0] || decoded[1] !== ED25519_MULTICODEC[1]) return null;\n\n return decoded.slice(ED25519_MULTICODEC.length);\n}\n\n/** Recover the compressed SEC1 point from the HTTP profile's p256-pub\n * multicodec (0x1200). This runtime-independent codec validates carriage only;\n * the cryptographic consumer MUST validate that the point lies on P-256 before\n * trusting it or deriving a confirmation thumbprint. */\nexport function decodeDidKeyP256(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(`${DID_KEY_PREFIX}z`)) return null;\n const body = did.slice(DID_KEY_PREFIX.length + 1);\n // Bound the quadratic base58 decoder before processing untrusted keyids.\n if (body.length > 64) return null;\n const decoded = base58btcDecode(body);\n if (\n !decoded ||\n decoded.length !== 35 ||\n decoded[0] !== 0x80 ||\n decoded[1] !== 0x24 ||\n (decoded[2] !== 2 && decoded[2] !== 3)\n )\n return null;\n return decoded.slice(2);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a `did:key:z6Mk…` string. Throws\n * if the key is not exactly 32 bytes — an emitter handing in the wrong length\n * is a programming error, not untrusted input (unlike {@link decodeDidKeyEd25519}).\n */\nexport function encodeDidKeyEd25519(publicKey: Uint8Array): string {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `encodeDidKeyEd25519: expected a ${ED25519_PUBKEY_LENGTH}-byte Ed25519 public key, got ${\n publicKey instanceof Uint8Array ? `${publicKey.length} bytes` : typeof publicKey\n }`\n );\n }\n\n const multikey = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n multikey[0] = ED25519_MULTICODEC[0];\n multikey[1] = ED25519_MULTICODEC[1];\n multikey.set(publicKey, ED25519_MULTICODEC.length);\n\n return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;\n}\n","/**\n * Tolerant + canonical multibase codec for Ed25519 public keys used across\n * checkpoint's mcp-i auth surfaces (org DID docs, approver keys, worker\n * signed-agent verification).\n *\n * Lifts two previously-divergent decoders into one shared implementation:\n * - apps/gateway/src/lib/multibase.ts's `decodeEd25519PublicKeyMultibase`\n * accepted ONLY `z` (base58btc) + exactly 34 bytes (multicodec), throwing\n * on anything else.\n * - apps/web/workers/gateway/src/detection/did-verifier.ts's local\n * `decodeMultibase` accepted `z` and `m` (read as base64url, which\n * deviates from the multibase spec where `m` = standard base64, but\n * matches what knowthat.ai's DID generator actually emits), plus 32-byte\n * raw or 34-byte multicodec bodies.\n *\n * Neither accepted `u`, the actual multibase-spec prefix for base64url.\n * `decodeEd25519PublicKeyMultibaseTolerant` accepts z/m/u and both body\n * shapes, and — unlike the strict gateway decoder — never throws; callers\n * treat `null` as \"not a decodable Ed25519 key\" and route it into their\n * existing fail-closed paths.\n *\n * Reuses the base58btc codec from `./did-key` rather than adding a third\n * copy (a THIRD near-identical implementation was the state before this\n * module existed).\n */\n\nimport { base58btcDecode, base58btcEncode } from './did-key';\n\nconst ED25519_PUB_MULTICODEC = [0xed, 0x01] as const;\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_PUB_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Length ceiling applied BEFORE decoding. The longest legitimate body is a\n * 34-byte multicodec key: 47 chars in base58btc, 48 in padded base64. Bodies\n * past this cap are rejected by the length check anyway — the point is to\n * reject them before `base58btcDecode`'s O(n^2) repeated division runs, since\n * `publicKeyMultibase` / `publicKeyBase58` arrive from DID documents fetched\n * over the network and a hostile document could otherwise burn seconds of\n * event-loop (gateway) or isolate (worker) CPU per key. Mirrors the same guard\n * on `decodeDidKeyEd25519` in ./did-key.\n */\nexport const MAX_ED25519_KEY_BODY_LENGTH = 64;\n\n/**\n * Decode a base64 body to bytes, accepting both the url-safe (`-`, `_`) and\n * standard (`+`, `/`) alphabets and tolerating the presence or absence of\n * `=` padding. Returns null on any malformed input — never throws.\n */\nfunction base64AnyToBytes(body: string): Uint8Array | null {\n if (body.length === 0) return null;\n let normalized = body.replace(/-/g, '+').replace(/_/g, '/');\n const remainder = normalized.length % 4;\n if (remainder === 1) return null; // no valid base64 encoding has this length\n if (remainder === 2) normalized += '==';\n else if (remainder === 3) normalized += '=';\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(normalized)) return null;\n\n try {\n const bin = atob(normalized);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n } catch {\n return null;\n }\n}\n\n/** Strip the ed25519-pub multicodec prefix if present; validate the length either way. */\nfunction toRawEd25519Key(decoded: Uint8Array): Uint8Array | null {\n if (decoded.length === ED25519_PUBKEY_LENGTH) return decoded;\n if (\n decoded.length === ED25519_MULTIKEY_LENGTH &&\n decoded[0] === ED25519_PUB_MULTICODEC[0] &&\n decoded[1] === ED25519_PUB_MULTICODEC[1]\n ) {\n return decoded.slice(ED25519_PUB_MULTICODEC.length);\n }\n return null;\n}\n\n/**\n * Decode a `publicKeyMultibase` value to a raw 32-byte Ed25519 public key.\n * Accepts multibase prefixes `z` (base58btc), `m` (base64url — the value\n * checkpoint's own DID documents emit, though not per the multibase spec),\n * and `u` (base64url per the multibase spec). The decoded body may be 32\n * raw key bytes or 34 bytes prefixed with the ed25519-pub multicodec\n * (`0xed 0x01`), which is stripped. Returns null for any other prefix,\n * length, or invalid encoding — never throws.\n */\nexport function decodeEd25519PublicKeyMultibaseTolerant(mb: string): Uint8Array | null {\n if (typeof mb !== 'string' || mb.length < 2) return null;\n\n const prefix = mb[0];\n const body = mb.slice(1);\n if (body.length > MAX_ED25519_KEY_BODY_LENGTH) return null;\n\n let decoded: Uint8Array | null;\n if (prefix === 'z') {\n decoded = base58btcDecode(body);\n } else if (prefix === 'm' || prefix === 'u') {\n decoded = base64AnyToBytes(body);\n } else {\n return null;\n }\n if (!decoded) return null;\n\n return toRawEd25519Key(decoded);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a canonical `z`-prefixed,\n * ed25519-pub-multicodec multibase string. Throws if the key is not\n * exactly 32 bytes — an emitter handing in the wrong length is a\n * programming error, not untrusted input (unlike the tolerant decoder).\n */\nexport function encodeEd25519PublicKeyMultibase(rawPubKey: Uint8Array): string {\n if (rawPubKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `Ed25519 public key must be ${ED25519_PUBKEY_LENGTH} bytes, got ${rawPubKey.length}`\n );\n }\n const prefixed = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n prefixed[0] = ED25519_PUB_MULTICODEC[0];\n prefixed[1] = ED25519_PUB_MULTICODEC[1];\n prefixed.set(rawPubKey, ED25519_PUB_MULTICODEC.length);\n return 'z' + base58btcEncode(prefixed);\n}\n\n// Re-exported so a single subpath import also covers: (1) the legacy\n// `Ed25519VerificationKey2018` `publicKeyBase58` form (raw base58btc, no\n// multibase prefix, no multicodec) the worker needs, and (2) constructing\n// non-canonical-but-valid multibase fixtures (e.g. raw-32-byte z bodies) in\n// tests — without pulling the full package index either way.\nexport { base58btcDecode, base58btcEncode };\n","/**\n * Common delegation-verdict shape (verifier/engine unification series).\n *\n * The `delegation` cross-runtime-parity track\n * (`tests/cross-runtime-parity/delegation/`) checks multiple independent\n * delegation-verify implementations — the Fly gateway (`apps/gateway/src/lib/\n * mcpi-auth-resolver.ts` + `dashboard-delegation-verifier.ts`, both engine-\n * backed as of PR6/PR7) and `rust/crates/kya-os-engine`'s `verify_delegation`\n * — against one canonical vector set. Every emitter normalizes its runtime's\n * result to this shape before writing `runtime-outputs/<name>.json`. Lives\n * under the package's main entrypoint (not `test-fixtures`) because the\n * parity-harness test imports it as production infrastructure;\n * `test-fixtures/delegation-verdict.ts` re-exports it for the existing\n * parity-harness imports.\n *\n * Deliberately verdict-only (`kind` + coarse `reason.kind`), not the full\n * delegation record: the gateway's audit extractions (`delegationId`,\n * `clientDid`, `orgId`, `accountableAdminDid`) are deterministic claim reads,\n * not verification decisions, so they don't belong in a cross-implementation\n * agreement check — their correctness is covered by the gateway's own unit\n * tests (`mcpi-auth-resolver.test.ts`, `dashboard-delegation-verifier.test.ts`),\n * which is their natural home. Keeping this shape to exactly what\n * `scripts/assert-cross-runtime-parity.ts` already matches on (`kind`,\n * `reason.kind`, `reason.kindStartsWith`, `oneOf`) means that script needs no\n * per-track special-casing.\n *\n * `reason.kind` is deliberately coarse — a structural reason CLASS, not a\n * fine-grained cause. Each runtime's native vocabulary is many-to-one mapped\n * onto this fixed set via `toCoarseReasonKind`:\n *\n * - `signature` — bad/absent cryptographic signature\n * - `claim` — any issuer / audience / subject / orgId / other claim or\n * authorization mismatch (including \"no identity material\n * presented at all\")\n * - `time` — expired OR not-yet-valid\n * - `revocation` — revoked, or status-unavailable (fail-closed)\n * - `scope` — delegation doesn't grant the requested scope\n * - `resolve` — DID / context could not be resolved\n *\n * This is the coarsest granularity both the gateway (whose own top-level\n * verifier already folds iss/aud/orgId/sub into one `claim_invalid` /\n * `claim_mismatch`) and the engine (whose `BlockReason` has no\n * audience/issuer/not-yet-valid-specific variants) can already express\n * without changing either side's production reason taxonomy. Fine-grained\n * reason parity is an observability nice-to-have, not a security property —\n * the gate's job is to catch security-relevant WHY-drift (a different\n * structural reason class, or accept-vs-reject), not whether both sides spell\n * a claim rejection the same way. If per-cause parity is ever wanted, extend\n * each runtime's own reason vocabulary deliberately on its own timeline —\n * never bundle it with this track's blocking gate.\n */\n\nexport type DelegationVerdictKind = 'Permit' | 'Block';\n\nexport type CoarseReasonKind = 'signature' | 'claim' | 'time' | 'revocation' | 'scope' | 'resolve';\n\nexport interface DelegationVerdictReason {\n kind: CoarseReasonKind;\n}\n\nexport interface DelegationVerdict {\n kind: DelegationVerdictKind;\n reason: DelegationVerdictReason | null;\n}\n\n/**\n * Every raw reason discriminator either runtime can natively emit for the\n * delegation path, mapped onto the coarse taxonomy above.\n *\n * Gateway (`McpiAuthErrorReason` in `mcpi-auth-resolver.ts`,\n * `DashboardVerifyFailure['reason']` in `dashboard-delegation-verifier.ts`):\n * snake_case. Engine (`BlockReason` in `rust/crates/kya-os-engine/src/types.rs`):\n * PascalCase variant names. Unrecognized input is a harness bug (an emitter\n * started producing a reason string neither side has ever emitted before) —\n * `toCoarseReasonKind` throws rather than silently defaulting, so a new raw\n * reason gets a deliberate classification instead of landing in the wrong\n * bucket unnoticed.\n */\nconst REASON_KIND_MAP: Record<string, CoarseReasonKind> = {\n // --- gateway: apps/gateway/src/lib/mcpi-auth-resolver.ts ---\n missing_bearer_token: 'claim',\n parse_error: 'claim',\n did_resolve_failed: 'resolve',\n signature_invalid: 'signature',\n audience_mismatch: 'claim',\n expired: 'time',\n not_yet_valid: 'time',\n revoked: 'revocation',\n delegation_inactive: 'revocation',\n missing_claim: 'claim',\n claim_invalid: 'claim',\n // --- gateway: apps/gateway/src/lib/dashboard-delegation-verifier.ts ---\n not_configured: 'claim',\n header_missing: 'claim',\n claim_mismatch: 'claim',\n malformed: 'claim',\n // --- engine-rust: rust/crates/kya-os-engine/src/types.rs BlockReason ---\n Revoked: 'revocation',\n InvalidSignature: 'signature',\n Unauthenticated: 'claim',\n Expired: 'time',\n OutOfScope: 'scope',\n};\n\n/** Map a runtime's native reason discriminator onto the coarse taxonomy. */\nexport function toCoarseReasonKind(rawReasonKind: string): CoarseReasonKind {\n const coarse = REASON_KIND_MAP[rawReasonKind];\n if (!coarse) {\n throw new Error(\n `toCoarseReasonKind: unrecognized raw reason kind ${JSON.stringify(rawReasonKind)} — ` +\n `add it to REASON_KIND_MAP in delegation-verdict.ts with a deliberate coarse classification`\n );\n }\n return coarse;\n}\n\n/** Build a `Permit` verdict. */\nexport function permitDelegationVerdict(): DelegationVerdict {\n return { kind: 'Permit', reason: null };\n}\n\n/** Build a `Block` verdict from a runtime-native reason discriminator. */\nexport function blockDelegationVerdict(rawReasonKind: string): DelegationVerdict {\n return { kind: 'Block', reason: { kind: toCoarseReasonKind(rawReasonKind) } };\n}\n","/**\n * JAFAR feed parser (TypeScript prep-side — AIVF-1).\n *\n * Single-shape parser for the IETF draft `draft-illyes-webbotauth-jafar`.\n * All 14 vendor endpoints catalogued in `AI-Vendor-IP-Feeds-1.md` §2\n * conform to the same JSON shape; differences are purely whitespace +\n * timestamp format. The Rust engine-side counterpart lands later when\n * Bench-Before-After-1 §3.8 unblocks.\n *\n * Out of scope here: CIDR membership semantics, IP arithmetic, vendor\n * cross-match. Engine consumes the parsed prefixes; this layer only\n * validates the wire shape.\n *\n * Empirical 2026-05-17 across all 14 fixtures:\n * - `creationTime`: 2 of 14 emit RFC 3339 with `Z` (Anthropic, CCBot);\n * the other 12 emit Python `datetime.isoformat()` output with\n * microsecond precision and no offset (e.g.\n * `2026-05-15T14:45:52.000000`). JavaScript's Date constructor\n * interprets ISO-like strings without offset as local time per\n * ES2019+; the parser explicitly appends `Z` when no offset is\n * present so naive Python output is treated as UTC.\n * - `prefixes`: every entry has exactly one of `ipv4Prefix` or\n * `ipv6Prefix`; never both, never neither.\n * - Top-level extension fields: CCBot's feed carries `synctoken`\n * and `notes` in addition to the two JAFAR-spec fields. The\n * top-level schema therefore uses `passthrough()` so vendor\n * extensions don't trip Postel's Law; the typed surface exposes\n * `synctoken` and `notes` since they're useful provenance for\n * the daily-refresh cron (synctoken can short-circuit no-op\n * refreshes; notes can land in the auto-PR body). Per-prefix\n * entries stay strict — no vendor adds extras there today.\n */\n\nimport { z } from 'zod';\n\nconst IPV4_CIDR_RE =\n /^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\/(?:3[0-2]|[12]?\\d)$/;\n\n// Relaxed IPv6 address recogniser. Strict semantic validation (canonical\n// form, zero-compression rules) is engine-side.\nconst IPV6_CIDR_RE = /^[0-9a-fA-F:]+\\/(?:12[0-8]|1[01]\\d|\\d{1,2})$/;\n\nconst HAS_OFFSET_RE = /[zZ]|[+-]\\d{2}:?\\d{2}$/;\n\nconst creationTimeSchema = z\n .string()\n .min(1)\n .transform((raw, ctx) => {\n const normalized = HAS_OFFSET_RE.test(raw) ? raw : `${raw}Z`;\n const ms = Date.parse(normalized);\n if (Number.isNaN(ms)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `creationTime is not a parseable ISO 8601 timestamp: ${raw}`,\n });\n return z.NEVER;\n }\n return new Date(ms);\n });\n\nconst prefixSchema = z\n .object({\n ipv4Prefix: z.string().regex(IPV4_CIDR_RE).optional(),\n ipv6Prefix: z.string().regex(IPV6_CIDR_RE).optional(),\n })\n .strict()\n .refine((p) => (p.ipv4Prefix != null) !== (p.ipv6Prefix != null), {\n message: 'prefix entry must have exactly one of ipv4Prefix or ipv6Prefix',\n });\n\nconst jafarFeedSchema = z\n .object({\n creationTime: creationTimeSchema,\n prefixes: z.array(prefixSchema),\n synctoken: z.string().optional(),\n notes: z.string().optional(),\n })\n .passthrough();\n\nexport type JafarPrefix = {\n ipv4Prefix?: string;\n ipv6Prefix?: string;\n};\n\nexport type JafarFeed = {\n creationTime: Date;\n prefixes: JafarPrefix[];\n synctoken?: string;\n notes?: string;\n};\n\nexport class JafarParseError extends Error {\n constructor(\n message: string,\n readonly cause?: unknown\n ) {\n super(message);\n this.name = 'JafarParseError';\n }\n}\n\n/**\n * Parse a JAFAR-format feed payload.\n *\n * Throws `JafarParseError` on malformed JSON or schema violation. The\n * thrown error's `cause` carries the underlying `SyntaxError` (JSON\n * parse) or `ZodError` (schema mismatch) so callers can drill in when\n * needed without leaking framework types in the happy path.\n */\nexport function parseJafarFeed(json: string): JafarFeed {\n let raw: unknown;\n try {\n raw = JSON.parse(json);\n } catch (err) {\n throw new JafarParseError('JAFAR feed is not valid JSON', err);\n }\n\n const result = jafarFeedSchema.safeParse(raw);\n if (!result.success) {\n throw new JafarParseError(\n `JAFAR feed failed schema validation: ${result.error.message}`,\n result.error\n );\n }\n return result.data;\n}\n","/**\n * @kya-os/checkpoint-shared\n *\n * Shared types, schemas, and constants for Checkpoint\n * This is the single source of truth for all TypeScript types\n */\n\n// Core types\nexport * from './core/detection';\nexport * from './core/enforcement';\nexport * from './core/agent';\nexport * from './core/confidence';\nexport * from './core/verdict-evidence';\nexport * from './core/detection-reason-codes';\nexport * from './core/detection-reason-mapping';\n\n// Configuration types\nexport * from './config/shield';\nexport * from './config/middleware';\n\n// Constants\nexport * from './constants/agents';\nexport * from './constants/bots';\nexport * from './constants/defaults';\nexport * from './constants/delegation';\nexport * from './constants/errors';\nexport * from './constants/limits';\nexport * from './constants/patterns';\nexport * from './constants/rules';\n\n// API types\nexport * from './api/request';\nexport * from './api/response';\nexport * from './api/event';\nexport * from './api/verification';\nexport * from './api/bulk';\nexport * from './api/internal';\nexport * from './api/public';\nexport * from './api/signal-exposure';\n// Export fingerprint types but rename conflicting ones\nexport {\n FingerprintAnalysisSchema,\n FingerprintDetectRequestSchema,\n FingerprintResponseSchema,\n EnhancedFingerprintResponseSchema,\n FingerprintRecordSchema,\n BotPatternSchema,\n TLSFingerprintSchema,\n NetworkTimingSchema,\n validateFingerprintRequest,\n validateClientDetection,\n isValidFingerprintResponse,\n // Rename these to avoid conflicts with pixel.ts exports\n ClientDetectionSchema as FingerprintClientDetectionSchema,\n} from './api/fingerprint';\n\nexport type {\n FingerprintAnalysis,\n FingerprintDetectRequest,\n FingerprintResponse,\n EnhancedFingerprintResponse,\n FingerprintRecord,\n BotPattern,\n TLSFingerprint,\n NetworkTiming,\n // Rename these to avoid conflicts with pixel.ts exports\n ClientDetection as FingerprintClientDetection,\n} from './api/fingerprint';\n\n// Re-export specific types that might be missed by wildcard exports\nexport type { SuccessResponse, PaginatedResponse, ApiKeyWithProject } from './api/internal';\n\n// Public API types - specific exports for clarity\nexport type {\n PublicProject,\n PublicDetection,\n PublicAnalytics,\n PublicAnalyticsSummary,\n PublicAnalyticsTimeSeriesPoint,\n PublicAnalyticsBotType,\n PaginationResponse as PublicPaginationResponse,\n PublicApiResponse,\n PublicApiQueryParams,\n PublicApiHeaders,\n} from './api/public';\n\nexport {\n PublicProjectSchema,\n PublicDetectionSchema,\n PublicAnalyticsSchema,\n PublicAnalyticsSummarySchema,\n PublicAnalyticsTimeSeriesPointSchema,\n PublicAnalyticsBotTypeSchema,\n PaginationResponseSchema as PublicPaginationResponseSchema,\n PublicApiResponseSchema,\n PublicApiQueryParamsSchema,\n PublicApiHeadersSchema,\n} from './api/public';\n\n// Organization and multi-user types\nexport * from './types/organization';\n\n// Shopify integration types\nexport * from './types/shopify';\n\n// Event types\nexport * from './events/agent-shield';\nexport * from './events/behavioral';\nexport * from './events/realtime';\nexport * from './events/deploy-progress';\n\n// All type definitions\nexport * from './types';\n\n// WASM-specific exports with utility functions\nexport {\n // Type-safe agent names\n type WasmAgentName,\n type WasmAgentNameExtended,\n WasmAgentTypeSchema,\n WasmAgentNameSchema,\n // Validation utilities\n isKnownAgentType,\n isValidWasmDetectionResult,\n isValidWasmRequestMetadata,\n parseAgentName,\n normalizeAgentName,\n getAgentDisplayName,\n} from './types/wasm';\n\n// API route types\nexport type {\n BaseRouteContext,\n AuthenticatedRouteContext,\n ProjectRouteContext,\n ApiKeyRouteContext,\n PixelRouteContext,\n OrganizationRouteContext,\n UserRouteContext,\n DetectionRouteContext,\n AnalyticsRouteContext,\n NextRouteContext,\n OptionalNextRouteContext,\n RouteParamValue,\n RouteParams,\n RouteParamsFromContext,\n RouteHandler,\n AuthenticatedRouteHandler,\n ProjectRouteHandler,\n ApiKeyRouteHandler,\n PixelRouteHandler,\n OrganizationRouteHandler,\n UserRouteHandler,\n DetectionRouteHandler,\n AnalyticsRouteHandler,\n ApiErrorCode,\n HttpStatus,\n ApiMethod,\n RouteConfig,\n ApiRouteMetadata,\n MiddlewareContext,\n PaginationParams as ApiPaginationParams,\n SearchParams,\n DateRangeParams,\n ExportParams,\n} from './types/api';\n\nexport { API_ERROR_CODES, HTTP_STATUS } from './types/api';\n\n// Standard response types\nexport type {\n SuccessResponse as SharedSuccessResponse,\n ErrorResponse as SharedErrorResponse,\n ApiResponse as SharedApiResponse,\n ResponseMeta,\n PaginationMeta,\n PaginatedResponse as SharedPaginatedResponse,\n ListResponse,\n CreatedResponse,\n UpdatedResponse,\n DeletedResponse,\n BatchResponse,\n ExportResponse as SharedExportResponse,\n ValidationErrorDetail,\n ValidationErrorResponse,\n RateLimitErrorResponse,\n} from './types/responses';\n\nexport {\n createSuccessResponse,\n createErrorResponse,\n createPaginatedResponse,\n createValidationErrorResponse,\n} from './types/responses';\n\n// All constants\nexport * from './constants';\n\n// Utility functions\nexport * from './utils/verification';\nexport * from './utils/detection-class';\nexport * from './utils/agent-runtime-label';\nexport * from './utils/client-ip';\nexport * from './utils/bot-signals';\nexport * from './utils/zod-helpers';\nexport * from './utils/bot-signals';\n\n// Isomorphic request correlation-id derivation (traceparent → x-kya-correlation-id →\n// fallback → minted UUID). One helper every detection surface uses so a request keeps a\n// single canonical 32-hex id across surfaces. Edge/Node/browser safe (globalThis.crypto).\nexport * from './utils/correlation-id';\n\n// All schemas (for runtime validation)\nexport * from './schemas';\n\n// Analytics schemas\nexport type {\n AnalyticsQuery,\n AnalyticsSessionsQuery,\n AnalyticsAgentSourcesQuery,\n AnalyticsAgentTypesQuery,\n AnalyticsExportQuery,\n AnalyticsRealtimeQuery,\n AnalyticsTimeSeries,\n AnalyticsSummary as AnalyticsSessionsSummary,\n AnalyticsChartData,\n AnalyticsSessionsResponse,\n AgentTypeDistribution as SharedAgentTypeDistribution,\n AgentSourceDistribution,\n ConfidenceDistribution as SharedConfidenceDistribution,\n} from './schemas/analytics';\n\nexport {\n AnalyticsQuerySchema,\n AnalyticsSessionsQuerySchema,\n AnalyticsAgentSourcesQuerySchema,\n AnalyticsAgentTypesQuerySchema,\n AnalyticsExportQuerySchema,\n AnalyticsRealtimeQuerySchema,\n AnalyticsTimeSeriesSchema,\n AnalyticsSummarySchema as AnalyticsSessionsSummarySchema,\n AnalyticsChartDataSchema,\n AnalyticsSessionsResponseSchema,\n AgentTypeDistributionSchema as SharedAgentTypeDistributionSchema,\n AgentSourceDistributionSchema,\n ConfidenceDistributionSchema as SharedConfidenceDistributionSchema,\n} from './schemas/analytics';\n\n// Rule system exports - Types\nexport type {\n UserAgentRule,\n IpRangeRule,\n SignatureRule,\n BehavioralThreshold,\n BehavioralPattern,\n BehavioralRules,\n HeaderRule,\n HeaderRules,\n IpRangeCollection,\n DetectionRules,\n RuleLoadOptions,\n RuleValidationResult,\n RuleUpdateEvent,\n RuleMatchResult,\n} from './types/rules';\n\n// Rule system exports - Schemas (these export both schemas and types)\nexport {\n UserAgentRuleSchema,\n IpRangeRuleSchema,\n SignatureRuleSchema,\n BehavioralThresholdSchema,\n BehavioralPatternSchema,\n BehavioralRulesSchema,\n HeaderRuleSchema,\n HeaderRulesSchema,\n IpRangeCollectionSchema,\n DetectionRulesSchema,\n RuleLoadOptionsSchema,\n RuleValidationResultSchema,\n RuleUpdateEventSchema,\n RuleMatchResultSchema,\n validateRules,\n parseRules,\n validateRulesLoose,\n} from './schemas/rules';\n\n// Rule system exports - Constants\nexport * from './constants/rules';\n\n// Rule system exports - Classes and functions\nexport { RuleLoader, loadRulesAsync } from './rules/rule-loader';\nexport { RuleParser } from './rules/rule-parser';\nexport { RuleValidator } from './rules/rule-validator';\nexport {\n assertVendorRangesFresh,\n DEFAULT_MAX_VENDOR_RANGE_AGE_MS,\n findStaleVendorRanges,\n StaleVendorRangesError,\n type StaleVendorDetail,\n type VendorFreshnessInput,\n} from './rules/vendor-range-freshness';\n\n// Policy module (shared between middleware packages)\nexport * from './policy';\n\n// Host-adapter primitives (shared between framework wrappers — checkpoint-nextjs, checkpoint-express)\nexport * from './host-adapter';\n\n// Wire-contract Zod schemas for Vercel ↔ Fly boundaries (#2029).\n// Both the Fly gateway and the Vercel routes import + validate\n// through these schemas, so shape drift becomes a validation\n// error instead of a silent runtime bug.\nexport * from './wire';\n\n// Canonical KYA-OS signer (Sign-1 / #2500) -- value exports live ONLY at\n// the dedicated `@kya-os/checkpoint-shared/canonical-signer` subpath\n// (tsup.config.ts ships it as its own bundle entry precisely so barrel\n// consumers don't drag in `canonicalize`, an ESM-only package with no\n// `require` export condition -- pulling it into this CJS-built barrel\n// broke every tsx/CJS consumer, e.g. scripts/sync-agent-types.ts, with\n// ERR_PACKAGE_PATH_NOT_EXPORTED). `export *` here defeated that\n// isolation. Only `McpIPayload` (a type, erased at compile time) is\n// consumed through the bare barrel anywhere in the repo\n// (checkpoint-wasm-runtime/src/engine/types.ts); every value-level\n// consumer (bouncer-middleware) already imports the subpath directly.\nexport type { McpIPayload } from './canonical-signer';\n\n// KYA-OS org issuer DID derivation shared by credential issuers and verifiers.\nexport * from './mcpi/org-did';\n\n// KYA-OS delegation-proof request detection (P2 / DR-1) — the single header set\n// every verifier surface uses to gate org trusted-root resolution.\nexport * from './mcpi/delegation-headers';\n\n// Canonical principals + MCP client DID derivation (#3022).\nexport * from './mcpi/principal';\n\n// Reported-identity wire block — the M1 verifier→ingest contract for\n// KYA-OS-attested tool calls (agent identity taxonomy v2 §5.1). Reporter asserts\n// agent/principal/delegation; Checkpoint derives assurance.\nexport * from './mcpi/reported-identity';\n\n// Authorization Host resolution — draft-kya-http-02 §7 PEP config discovery (H1.1 #3244).\nexport * from './mcpi/authorization-host';\n\n// did:key (Ed25519 multikey) codec — pure-JS base58btc/0xed01 decode+encode for\n// RFC 9421 keyid pinning (draft-kya-http-02 / H1.2 #3245).\nexport * from './mcpi/did-key';\n\n// Tolerant + canonical publicKeyMultibase codec (z/m/u prefixes) for Ed25519\n// DID-document verification methods — the single decoder shared by\n// apps/gateway's mcp-i auth/approver resolvers and the gateway worker.\nexport * from './mcpi/multibase-ed25519';\n\n// KYA-HTTP error code registry (draft-kya-http-02 §9) — the kyaos/* wire\n// constants, parity-guarded against fixtures/kya-http/error-codes.json.\nexport * from './mcpi/kya-http-error-codes';\n\n// Common delegation-verdict shape (verifier/engine unification PR 1) — the\n// coarse kind+reason.kind both the delegation cross-runtime-parity track and\n// the gateway's engine shadow-verify (PR 5) normalize each runtime's result\n// onto.\nexport * from './mcpi/delegation-verdict';\n\n// JAFAR vendor-feed parser (AIVF-1 prep). TS-side counterpart to the\n// engine-side Rust parser that lands when Bench-Before-After-1 unblocks.\nexport * from './parsers/jafar';\n\n// Utility types\nexport type DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];\n};\n\nexport type Nullable<T> = T | null;\n\nexport type Optional<T> = T | undefined;\n\nexport type AsyncResult<T, E = Error> = Promise<{ data: T } | { error: E }>;\n\n// Version info\nexport const VERSION = '0.1.0';\nexport const PACKAGE_NAME = '@kya-os/checkpoint-shared';\n"],"x_google_ignoreList":[0,1],"mappings":";;;;;;;;;;;AAGA,MAAa,eAAe;CACxB,cAAc;CACd,SAAS;CACT,WAAW;CACX,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,eAAe;CACf,aAAa;CACb,iBAAiB;CACjB,eAAe;CACf,QAAQ;AACZ;;AAaA,IAAW;AAER,0BAA0B,wBAAwB,CAAC;;;;ACzBtD,SAAgB,OAAO,QAAQ;CAC3B,OAAOA,eAAoBC,WAAmB,MAAM;AACxD;AACA,SAAgB,QAAQ,QAAQ;CAC5B,OAAOC,gBAAqBC,YAAoB,MAAM;AAC1D;AAIA,SAAgB,KAAK,QAAQ;CACzB,OAAOC,aAAkBC,SAAiB,MAAM;AACpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACqBA,MAAa,yBAAyB;;CAGpC,oBAAoB;;CAEpB,qBAAqB;;CAErB,gBAAgB;;CAEhB,wBAAwB;;CAExB,4BAA4B;;CAE5B,4BAA4B;;CAE5B,cAAc;;CAEd,oBAAoB;;CAIpB,kBAAkB;;CAElB,kBAAkB;;CAElB,cAAc;;CAEd,wBAAwB;;CAExB,8BAA8B;;CAE9B,uBAAuB;;CAEvB,0B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