@kya-os/checkpoint-shared 1.6.0 → 1.8.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 (222) hide show
  1. package/CHANGELOG.md +122 -9
  2. package/README.md +24 -7
  3. package/dist/beacon-nonce/index.d.mts +1 -0
  4. package/dist/beacon-nonce/index.d.mts.map +1 -1
  5. package/dist/beacon-nonce/index.d.ts +1 -0
  6. package/dist/beacon-nonce/index.d.ts.map +1 -1
  7. package/dist/beacon-nonce/index.js +9 -3
  8. package/dist/beacon-nonce/index.mjs +9 -4
  9. package/dist/beacon-nonce/index.mjs.map +1 -1
  10. package/dist/beacon-types/index.d.mts +23 -1
  11. package/dist/beacon-types/index.d.mts.map +1 -1
  12. package/dist/beacon-types/index.d.ts +23 -1
  13. package/dist/beacon-types/index.d.ts.map +1 -1
  14. package/dist/beacon-types/index.js +49 -4
  15. package/dist/beacon-types/index.mjs +47 -4
  16. package/dist/beacon-types/index.mjs.map +1 -1
  17. package/dist/{browser-posture-BuChqmH5.d.mts → browser-posture-5fPrsxx7.d.mts} +2 -2
  18. package/dist/{browser-posture-BuChqmH5.d.mts.map → browser-posture-5fPrsxx7.d.mts.map} +1 -1
  19. package/dist/{browser-posture-DIaVLuW3.d.ts → browser-posture-CCR1kh5e.d.ts} +2 -2
  20. package/dist/{browser-posture-DIaVLuW3.d.ts.map → browser-posture-CCR1kh5e.d.ts.map} +1 -1
  21. package/dist/browser-posture-cookie.js +1 -1
  22. package/dist/browser-posture-cookie.mjs +1 -1
  23. package/dist/browser-posture-cookie.mjs.map +1 -1
  24. package/dist/browser-posture-proof.d.mts +16 -2
  25. package/dist/browser-posture-proof.d.mts.map +1 -1
  26. package/dist/browser-posture-proof.d.ts +16 -2
  27. package/dist/browser-posture-proof.d.ts.map +1 -1
  28. package/dist/browser-posture-proof.js +114 -17
  29. package/dist/browser-posture-proof.mjs +112 -17
  30. package/dist/browser-posture-proof.mjs.map +1 -1
  31. package/dist/browser-posture.d.mts +1 -1
  32. package/dist/browser-posture.d.ts +1 -1
  33. package/dist/browser-posture.js +6 -5
  34. package/dist/browser-posture.mjs +4 -3
  35. package/dist/browser-posture.mjs.map +1 -1
  36. package/dist/browser.d.mts +25 -4
  37. package/dist/browser.d.mts.map +1 -1
  38. package/dist/browser.d.ts +25 -4
  39. package/dist/browser.d.ts.map +1 -1
  40. package/dist/browser.js +1 -1
  41. package/dist/browser.mjs +1 -1
  42. package/dist/browser.mjs.map +1 -1
  43. package/dist/canonical-signer/index.d.mts.map +1 -1
  44. package/dist/canonical-signer/index.d.ts.map +1 -1
  45. package/dist/canonical-signer/index.js +116 -79
  46. package/dist/canonical-signer/index.mjs +117 -52
  47. package/dist/canonical-signer/index.mjs.map +1 -1
  48. package/dist/clearance.d.mts +1 -1
  49. package/dist/clearance.d.ts +1 -1
  50. package/dist/clearance.js +2 -2
  51. package/dist/clearance.mjs +2 -2
  52. package/dist/client-ip-B7w-uHfS.d.mts +55 -0
  53. package/dist/client-ip-B7w-uHfS.d.mts.map +1 -0
  54. package/dist/client-ip-B7w-uHfS.d.ts +55 -0
  55. package/dist/client-ip-B7w-uHfS.d.ts.map +1 -0
  56. package/dist/{client-ip-CW6pRyLf.js → client-ip-B8wFzJ5f.js} +117 -7
  57. package/dist/{client-ip-B2Xeo-GK.mjs → client-ip-DIJyr6px.mjs} +113 -9
  58. package/dist/client-ip-DIJyr6px.mjs.map +1 -0
  59. package/dist/client-ip.d.mts +2 -0
  60. package/dist/client-ip.d.ts +2 -0
  61. package/dist/client-ip.js +8 -0
  62. package/dist/client-ip.mjs +3 -0
  63. package/dist/detection-reason-mapping-B9RSkOs8.js +277 -0
  64. package/dist/detection-reason-mapping-BGymWIPl.mjs +249 -0
  65. package/dist/detection-reason-mapping-BGymWIPl.mjs.map +1 -0
  66. package/dist/detection-reason-mapping-CQexNvR7.d.mts +52 -0
  67. package/dist/detection-reason-mapping-CQexNvR7.d.mts.map +1 -0
  68. package/dist/detection-reason-mapping-CQexNvR7.d.ts +52 -0
  69. package/dist/detection-reason-mapping-CQexNvR7.d.ts.map +1 -0
  70. package/dist/engine-enforcing-AYEcgNsb.js +39 -0
  71. package/dist/engine-enforcing-B5eNfCpG.mjs +29 -0
  72. package/dist/engine-enforcing-B5eNfCpG.mjs.map +1 -0
  73. package/dist/engine-enforcing-DiOclGqf.d.mts +11 -0
  74. package/dist/engine-enforcing-DiOclGqf.d.mts.map +1 -0
  75. package/dist/engine-enforcing-DiOclGqf.d.ts +11 -0
  76. package/dist/engine-enforcing-DiOclGqf.d.ts.map +1 -0
  77. package/dist/engine-info.d.mts +2 -0
  78. package/dist/engine-info.d.ts +2 -0
  79. package/dist/engine-info.js +4 -0
  80. package/dist/engine-info.mjs +3 -0
  81. package/dist/errors/index.d.mts +5 -0
  82. package/dist/errors/index.d.mts.map +1 -1
  83. package/dist/errors/index.d.ts +5 -0
  84. package/dist/errors/index.d.ts.map +1 -1
  85. package/dist/errors/index.js +23 -4
  86. package/dist/errors/index.mjs +23 -4
  87. package/dist/errors/index.mjs.map +1 -1
  88. package/dist/{external-B7WI9FyQ.d.ts → external-m3Kmafwj.d.mts} +2 -2
  89. package/dist/{external-B7WI9FyQ.d.mts.map → external-m3Kmafwj.d.mts.map} +1 -1
  90. package/dist/{external-B7WI9FyQ.d.mts → external-m3Kmafwj.d.ts} +2 -2
  91. package/dist/{external-B7WI9FyQ.d.ts.map → external-m3Kmafwj.d.ts.map} +1 -1
  92. package/dist/fetcher-CivUCbhL.d.ts +44 -0
  93. package/dist/fetcher-CivUCbhL.d.ts.map +1 -0
  94. package/dist/fetcher-cXQsbm6s.d.mts +44 -0
  95. package/dist/fetcher-cXQsbm6s.d.mts.map +1 -0
  96. package/dist/gateway-client-ip.d.mts +1 -1
  97. package/dist/gateway-client-ip.d.ts +1 -1
  98. package/dist/gateway-client-ip.js +2 -2
  99. package/dist/gateway-client-ip.mjs +2 -2
  100. package/dist/host-adapter/index.d.mts +2 -0
  101. package/dist/host-adapter/index.d.ts +2 -0
  102. package/dist/host-adapter/index.js +24 -0
  103. package/dist/host-adapter/index.mjs +3 -0
  104. package/dist/host-adapter-0F8EpbD6.js +753 -0
  105. package/dist/host-adapter-DHyISsIf.mjs +593 -0
  106. package/dist/host-adapter-DHyISsIf.mjs.map +1 -0
  107. package/dist/index-B3cHxr3O.d.mts +156 -0
  108. package/dist/index-B3cHxr3O.d.mts.map +1 -0
  109. package/dist/index-CXbOY7gB.d.ts +156 -0
  110. package/dist/index-CXbOY7gB.d.ts.map +1 -0
  111. package/dist/index.d.mts +6997 -12170
  112. package/dist/index.d.mts.map +1 -1
  113. package/dist/index.d.ts +6997 -12170
  114. package/dist/index.d.ts.map +1 -1
  115. package/dist/index.js +2510 -8893
  116. package/dist/index.mjs +2366 -8534
  117. package/dist/index.mjs.map +1 -1
  118. package/dist/kya-http-error-codes-7ewV5RuK.d.mts +29 -0
  119. package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +1 -0
  120. package/dist/kya-http-error-codes-7ewV5RuK.d.ts +29 -0
  121. package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +1 -0
  122. package/dist/kya-http-error-codes-C2JiWPsi.mjs +73 -0
  123. package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +1 -0
  124. package/dist/kya-http-error-codes-UYb1zpGM.js +83 -0
  125. package/dist/kya-http.d.mts +3 -0
  126. package/dist/kya-http.d.ts +3 -0
  127. package/dist/kya-http.js +19 -0
  128. package/dist/kya-http.mjs +5 -0
  129. package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
  130. package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
  131. package/dist/mcpi/status-list/index.d.mts +72 -0
  132. package/dist/mcpi/status-list/index.d.mts.map +1 -0
  133. package/dist/mcpi/status-list/index.d.ts +72 -0
  134. package/dist/mcpi/status-list/index.d.ts.map +1 -0
  135. package/dist/mcpi/status-list/index.js +703 -0
  136. package/dist/mcpi/status-list/index.mjs +684 -0
  137. package/dist/mcpi/status-list/index.mjs.map +1 -0
  138. package/dist/patterns-B2r7M9wR.js +243 -0
  139. package/dist/patterns-B7dQoeE3.mjs +173 -0
  140. package/dist/patterns-B7dQoeE3.mjs.map +1 -0
  141. package/dist/patterns-Bp40cwh2.d.mts +110 -0
  142. package/dist/patterns-Bp40cwh2.d.mts.map +1 -0
  143. package/dist/patterns-Bp40cwh2.d.ts +110 -0
  144. package/dist/patterns-Bp40cwh2.d.ts.map +1 -0
  145. package/dist/patterns.d.mts +2 -0
  146. package/dist/patterns.d.ts +2 -0
  147. package/dist/patterns.js +15 -0
  148. package/dist/patterns.mjs +3 -0
  149. package/dist/policy/enforcement.d.mts +3 -0
  150. package/dist/policy/enforcement.d.ts +3 -0
  151. package/dist/policy/enforcement.js +21 -0
  152. package/dist/policy/enforcement.mjs +4 -0
  153. package/dist/policy/fetcher.d.mts +2 -0
  154. package/dist/policy/fetcher.d.ts +2 -0
  155. package/dist/policy/fetcher.js +240 -0
  156. package/dist/policy/fetcher.mjs +238 -0
  157. package/dist/policy/fetcher.mjs.map +1 -0
  158. package/dist/policy/schemas.d.mts +3 -0
  159. package/dist/policy/schemas.d.ts +3 -0
  160. package/dist/policy/schemas.js +27 -0
  161. package/dist/policy/schemas.mjs +4 -0
  162. package/dist/{posture-origins-Pn-ii-Pp.mjs → posture-origins-Ci6k4Zh1.js} +24 -173
  163. package/dist/{posture-origins-LFkX80oF.js → posture-origins-DGyS4Vuk.mjs} +2 -267
  164. package/dist/posture-origins-DGyS4Vuk.mjs.map +1 -0
  165. package/dist/{project-verification-key-BccT12tQ.js → project-verification-key-B-L3D2nC.js} +1 -1
  166. package/dist/{project-verification-key-66N4edKn.mjs → project-verification-key-CWXdu3-n.mjs} +2 -2
  167. package/dist/{project-verification-key-66N4edKn.mjs.map → project-verification-key-CWXdu3-n.mjs.map} +1 -1
  168. package/dist/provider-registry.d.mts +2 -0
  169. package/dist/provider-registry.d.ts +2 -0
  170. package/dist/provider-registry.js +51 -0
  171. package/dist/provider-registry.mjs +3 -0
  172. package/dist/reason-codes.d.mts +2 -0
  173. package/dist/reason-codes.d.ts +2 -0
  174. package/dist/reason-codes.js +8 -0
  175. package/dist/reason-codes.mjs +3 -0
  176. package/dist/registered-sid-26hNxp6t.mjs +151 -0
  177. package/dist/registered-sid-26hNxp6t.mjs.map +1 -0
  178. package/dist/registered-sid-D6KCaT1E.d.mts +33 -0
  179. package/dist/registered-sid-D6KCaT1E.d.mts.map +1 -0
  180. package/dist/registered-sid-D6KCaT1E.d.ts +33 -0
  181. package/dist/registered-sid-D6KCaT1E.d.ts.map +1 -0
  182. package/dist/registered-sid-DVGTSH0L.js +185 -0
  183. package/dist/ruleset-hash-Cmv8MSO5.js +34 -0
  184. package/dist/ruleset-hash-IRN5eI9H.d.mts +5 -0
  185. package/dist/ruleset-hash-IRN5eI9H.d.mts.map +1 -0
  186. package/dist/ruleset-hash-IRN5eI9H.d.ts +5 -0
  187. package/dist/ruleset-hash-IRN5eI9H.d.ts.map +1 -0
  188. package/dist/ruleset-hash-QQIaLuPi.mjs +30 -0
  189. package/dist/ruleset-hash-QQIaLuPi.mjs.map +1 -0
  190. package/dist/schemas-02CI7jgm.d.mts +535 -0
  191. package/dist/schemas-02CI7jgm.d.mts.map +1 -0
  192. package/dist/{schemas-YhagYDx_.js → schemas-BlScS1it.js} +0 -20
  193. package/dist/schemas-C_3C72SR.d.ts +535 -0
  194. package/dist/schemas-C_3C72SR.d.ts.map +1 -0
  195. package/dist/schemas-Cm4C4Z5G.js +703 -0
  196. package/dist/schemas-DPIT8usF.mjs +525 -0
  197. package/dist/schemas-DPIT8usF.mjs.map +1 -0
  198. package/dist/{schemas-7qodsG-Z.mjs → schemas-IHAhH3gV.mjs} +2 -16
  199. package/dist/schemas-IHAhH3gV.mjs.map +1 -0
  200. package/dist/step-up-BK0oBi11.mjs +1563 -0
  201. package/dist/step-up-BK0oBi11.mjs.map +1 -0
  202. package/dist/step-up-Bp8RAQwv.js +1759 -0
  203. package/dist/step-up-Bz12gYKT.d.mts +130 -0
  204. package/dist/step-up-Bz12gYKT.d.mts.map +1 -0
  205. package/dist/step-up-Bz12gYKT.d.ts +130 -0
  206. package/dist/step-up-Bz12gYKT.d.ts.map +1 -0
  207. package/dist/test-fixtures/index.d.mts +4 -4
  208. package/dist/test-fixtures/index.d.mts.map +1 -1
  209. package/dist/test-fixtures/index.d.ts +4 -4
  210. package/dist/test-fixtures/index.d.ts.map +1 -1
  211. package/dist/test-fixtures/index.js +4 -4
  212. package/dist/test-fixtures/index.mjs +4 -4
  213. package/dist/test-fixtures/index.mjs.map +1 -1
  214. package/dist/verification-BAw9N8Pt.js +181 -0
  215. package/dist/verification-Cvvv86TT.mjs +123 -0
  216. package/dist/verification-Cvvv86TT.mjs.map +1 -0
  217. package/fixtures/client-ip-resolution.n01.json +101 -0
  218. package/fixtures/reviewer-grant-revocation.v1.json +53 -81
  219. package/package.json +59 -2
  220. package/dist/client-ip-B2Xeo-GK.mjs.map +0 -1
  221. package/dist/posture-origins-Pn-ii-Pp.mjs.map +0 -1
  222. package/dist/schemas-7qodsG-Z.mjs.map +0 -1
@@ -133,6 +133,106 @@ function normalizeClientIp(raw) {
133
133
  }
134
134
  return null;
135
135
  }
136
+ function getObservedHeader(headers, name) {
137
+ if ("get" in headers && typeof headers.get === "function") return headers.get(name) ?? void 0;
138
+ const matches = Object.entries(headers).filter(([key, value]) => key.toLowerCase() === name && value !== void 0);
139
+ if (matches.length === 0) return void 0;
140
+ if (matches.length !== 1) return "";
141
+ const value = matches[0][1];
142
+ return typeof value === "string" ? value : value.length === 1 ? value[0] : "";
143
+ }
144
+ function singleAddress(raw) {
145
+ const tokens = boundedTokens(raw);
146
+ return tokens?.length === 1 ? normalizeToken(tokens[0]) : null;
147
+ }
148
+ function unavailable(reason) {
149
+ return {
150
+ ip: null,
151
+ observedClientAddress: null,
152
+ source: "none",
153
+ trusted: false,
154
+ status: "unavailable",
155
+ reason
156
+ };
157
+ }
158
+ function observed(ip, source, reason) {
159
+ return {
160
+ ip,
161
+ observedClientAddress: ip,
162
+ source,
163
+ trusted: true,
164
+ status: "observed",
165
+ reason
166
+ };
167
+ }
168
+ function authenticatedPeer(input, policy) {
169
+ const peer = singleAddress(input.directAddress);
170
+ if (!peer || !policy.isTrustedPeer) return false;
171
+ try {
172
+ return policy.isTrustedPeer(peer) === true;
173
+ } catch {
174
+ return false;
175
+ }
176
+ }
177
+ function resolveVercel(input) {
178
+ if (input.vercelRuntime !== true) return unavailable("untrusted-peer");
179
+ const platformHeader = getObservedHeader(input.headers, "x-vercel-forwarded-for");
180
+ const ip = singleAddress(platformHeader ?? getObservedHeader(input.headers, "x-forwarded-for"));
181
+ return ip ? observed(ip, platformHeader === void 0 ? "x-forwarded-for" : "x-vercel-forwarded-for", "vercel-runtime") : unavailable("invalid-chain");
182
+ }
183
+ function ipv4Octets(ip) {
184
+ const ipv4 = parseIpv4(ip);
185
+ if (ipv4) return ipv4;
186
+ const groups = parseIpv6(ip);
187
+ return groups.slice(0, 5).every((group) => group === 0) && groups[5] === 65535 ? [
188
+ groups[6] >> 8,
189
+ groups[6] & 255,
190
+ groups[7] >> 8,
191
+ groups[7] & 255
192
+ ] : null;
193
+ }
194
+ function resolveCloudflare(input, policy) {
195
+ if (!authenticatedPeer(input, policy)) return unavailable("untrusted-peer");
196
+ const ip = singleAddress(getObservedHeader(input.headers, "cf-connecting-ip"));
197
+ if (!ip) return unavailable("invalid-chain");
198
+ if (getObservedHeader(input.headers, "cf-worker") !== void 0 || ip === "2a06:98c0:3600::103") return unavailable("unsupported-worker");
199
+ const ipv4 = ipv4Octets(ip);
200
+ if (ipv4 && ipv4[0] >= 240) {
201
+ const native = singleAddress(getObservedHeader(input.headers, "cf-connecting-ipv6"));
202
+ if (policy.pseudoIpv4 !== "overwrite" || !native || ipv4Octets(native)) return unavailable("unsupported-synthetic");
203
+ if (native === "2a06:98c0:3600::103") return unavailable("unsupported-worker");
204
+ return observed(native, "cf-connecting-ipv6", "authenticated-proxy");
205
+ }
206
+ return observed(ip, "cf-connecting-ip", "authenticated-proxy");
207
+ }
208
+ function resolveTrustedProxy(input, policy) {
209
+ if (!authenticatedPeer(input, policy)) return unavailable("untrusted-peer");
210
+ const tokens = boundedTokens(getObservedHeader(input.headers, "x-forwarded-for"));
211
+ const hops = policy.trustedHops;
212
+ if (!tokens || !Number.isInteger(hops) || hops < 0 || tokens.length !== hops + 1) return unavailable("invalid-chain");
213
+ const parsed = tokens.map(normalizeToken);
214
+ if (parsed.some((token) => token === null)) return unavailable("invalid-chain");
215
+ return observed(parsed[parsed.length - hops - 1], "x-forwarded-for", "authenticated-proxy");
216
+ }
217
+ /** Resolve the observed client address only through an authenticated deployment boundary. */
218
+ function resolveObservedClientAddress(input) {
219
+ if (input.explicitAddressTrusted === true) {
220
+ const explicit = singleAddress(input.explicitAddress);
221
+ if (explicit) return observed(explicit, "explicit", "authenticated-explicit");
222
+ }
223
+ switch (input.policy.platform) {
224
+ case "vercel": return resolveVercel(input);
225
+ case "cloudflare": return resolveCloudflare(input, input.policy);
226
+ case "trusted-proxy": return resolveTrustedProxy(input, input.policy);
227
+ default: return unavailable("untrusted-peer");
228
+ case "direct": {
229
+ const socket = singleAddress(input.directAddress);
230
+ if (socket) return observed(socket, "socket", "direct-peer");
231
+ const framework = singleAddress(input.frameworkAddress);
232
+ return framework ? observed(framework, "framework", "direct-peer") : unavailable("missing-address");
233
+ }
234
+ }
235
+ }
136
236
  function getHeader(headers, name) {
137
237
  if ("get" in headers && typeof headers.get === "function") return headers.get(name) ?? void 0;
138
238
  const wanted = name.toLowerCase();
@@ -155,7 +255,7 @@ function resolveExplicit(input) {
155
255
  if (input.explicitAddressTrusted !== true) return null;
156
256
  return result(normalizeClientIp(input.explicitAddress), "explicit", true);
157
257
  }
158
- function resolveVercel(input) {
258
+ function resolveLegacyVercel(input) {
159
259
  const platform = result(normalizeClientIp(getHeader(input.headers, "x-vercel-forwarded-for")), "x-vercel-forwarded-for", true);
160
260
  if (platform) return platform;
161
261
  const overwrittenXff = result(normalizeClientIp(getHeader(input.headers, "x-forwarded-for")), "x-forwarded-for", true);
@@ -168,7 +268,7 @@ function resolveVercel(input) {
168
268
  trusted: false
169
269
  };
170
270
  }
171
- function resolveCloudflare(input) {
271
+ function resolveLegacyCloudflare(input) {
172
272
  const cloudflare = result(normalizeClientIp(getHeader(input.headers, "cf-connecting-ip")), "cf-connecting-ip", true);
173
273
  if (cloudflare) return cloudflare;
174
274
  return resolveAddress(input.directAddress, "socket") ?? resolveAddress(input.frameworkAddress, "framework") ?? result(normalizeClientIp(getHeader(input.headers, "x-forwarded-for")), "x-forwarded-for", false) ?? result(normalizeClientIp(getHeader(input.headers, "x-real-ip")), "x-real-ip", false) ?? {
@@ -177,7 +277,7 @@ function resolveCloudflare(input) {
177
277
  trusted: false
178
278
  };
179
279
  }
180
- function resolveTrustedProxy(input, trustedHops) {
280
+ function resolveLegacyTrustedProxy(input, trustedHops) {
181
281
  const tokens = boundedTokens(getHeader(input.headers, "x-forwarded-for"));
182
282
  if (tokens && Number.isInteger(trustedHops) && trustedHops >= 0 && tokens.length > trustedHops) {
183
283
  const parsed = tokens.map(normalizeToken);
@@ -194,14 +294,18 @@ function resolveTrustedProxy(input, trustedHops) {
194
294
  trusted: false
195
295
  };
196
296
  }
197
- /** Resolve a client IP using an explicit deployment trust profile. */
297
+ /**
298
+ * Legacy platform-assumed resolver retained for existing gateway and runtime integrations.
299
+ * This API does not authenticate a nearest peer. New ingress integrations must use
300
+ * resolveObservedClientAddress and qualify their actual deployment boundary.
301
+ */
198
302
  function resolveClientIp(input) {
199
303
  const explicit = resolveExplicit(input);
200
304
  if (explicit) return explicit;
201
305
  switch (input.policy.platform) {
202
- case "vercel": return resolveVercel(input);
203
- case "cloudflare": return resolveCloudflare(input);
204
- case "trusted-proxy": return resolveTrustedProxy(input, input.policy.trustedHops);
306
+ case "vercel": return resolveLegacyVercel(input);
307
+ case "cloudflare": return resolveLegacyCloudflare(input);
308
+ case "trusted-proxy": return resolveLegacyTrustedProxy(input, input.policy.trustedHops);
205
309
  case "direct": return resolveAddress(input.frameworkAddress, "framework") ?? resolveAddress(input.directAddress, "socket") ?? {
206
310
  ip: null,
207
311
  source: "none",
@@ -211,5 +315,5 @@ function resolveClientIp(input) {
211
315
  }
212
316
 
213
317
  //#endregion
214
- export { resolveClientIp as i, normalizeClientIp as n, parseIpv6 as r, compressIpv6 as t };
215
- //# sourceMappingURL=client-ip-B2Xeo-GK.mjs.map
318
+ export { resolveObservedClientAddress as a, resolveClientIp as i, normalizeClientIp as n, parseIpv6 as r, compressIpv6 as t };
319
+ //# sourceMappingURL=client-ip-DIJyr6px.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-ip-DIJyr6px.mjs","names":[],"sources":["../src/utils/client-ip.ts"],"sourcesContent":["/**\n * Runtime-agnostic client-IP normalization and trust resolution.\n *\n * Header presence is not proof of provenance. Callers must select the\n * deployment profile that describes which infrastructure has already\n * authenticated a value before using the result for security decisions.\n */\n\nexport type ClientIpSource =\n | 'explicit'\n | 'cf-connecting-ip'\n | 'cf-connecting-ipv6'\n | 'x-vercel-forwarded-for'\n | 'x-forwarded-for'\n | 'x-real-ip'\n | 'framework'\n | 'socket'\n | 'none';\n\n/** Legacy platform-assumed result. Use ObservedClientAddressResolution for new ingress integrations. */\nexport interface ClientIpResolution {\n ip: string | null;\n source: ClientIpSource;\n trusted: boolean;\n}\n\nexport type ObservedClientAddressResolution =\n | {\n /** Compatibility alias for observedClientAddress. */\n ip: string;\n observedClientAddress: string;\n source: Exclude<ClientIpSource, 'none'>;\n trusted: true;\n status: 'observed';\n reason: 'direct-peer' | 'authenticated-explicit' | 'vercel-runtime' | 'authenticated-proxy';\n }\n | {\n ip: null;\n observedClientAddress: null;\n source: 'none';\n trusted: false;\n status: 'unavailable';\n reason:\n | 'missing-address'\n | 'untrusted-peer'\n | 'invalid-chain'\n | 'unsupported-synthetic'\n | 'unsupported-worker';\n };\n\ninterface PeerTrust {\n /** Check the transport peer against the deployment's proxy allowlist, never a request header. */\n isTrustedPeer?: (peerAddress: string) => boolean;\n}\n\nexport type ClientIpTrustPolicy =\n | { platform: 'vercel' }\n | ({ platform: 'cloudflare'; pseudoIpv4?: 'off' | 'add-header' | 'overwrite' } & PeerTrust)\n | ({ platform: 'trusted-proxy'; trustedHops: number } & PeerTrust)\n | { platform: 'direct' };\n\nexport type ClientIpHeaderValue = string | readonly string[] | undefined;\nexport type ClientIpHeaders = Headers | Record<string, ClientIpHeaderValue>;\n\nexport interface ResolveClientIpInput {\n headers: ClientIpHeaders;\n directAddress?: string | null;\n frameworkAddress?: string | null;\n explicitAddress?: string | null;\n /** True only after the caller has authenticated the explicit value. */\n explicitAddressTrusted?: boolean;\n vercelRuntime?: boolean;\n policy: ClientIpTrustPolicy;\n}\n\nconst MAX_INPUT_LENGTH = 4096;\nconst MAX_TOKEN_LENGTH = 128;\nconst MAX_FORWARDED_HOPS = 32;\n\nfunction hasControlCharacter(value: string): boolean {\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code <= 0x1f || code === 0x7f) return true;\n }\n return false;\n}\n\nfunction parsePort(value: string): boolean {\n return /^(?:0|[1-9]\\d{0,4})$/.test(value) && Number(value) <= 65535;\n}\n\nfunction parseIpv4(value: string): number[] | null {\n const parts = value.split('.');\n if (parts.length !== 4) return null;\n\n const octets: number[] = [];\n for (const part of parts) {\n if (!/^\\d{1,3}$/.test(part)) return null;\n const octet = Number(part);\n if (octet > 255) return null;\n octets.push(octet);\n }\n return octets;\n}\n\nfunction parseHexGroup(value: string): number | null {\n if (!/^[0-9a-fA-F]{1,4}$/.test(value)) return null;\n return Number.parseInt(value, 16);\n}\n\n/** Parses a bare IPv6 address into its 8 groups (`::` expanded). Exported for reuse by anything that needs to mask/truncate an address (see `anonymize-ip.ts`), not just resolve one. */\nexport function parseIpv6(value: string): number[] | null {\n if (!value || value.includes('%') || hasControlCharacter(value)) return null;\n\n let address = value;\n if (address.includes('.')) {\n const lastColon = address.lastIndexOf(':');\n if (lastColon < 0) return null;\n const ipv4 = parseIpv4(address.slice(lastColon + 1));\n if (!ipv4) return null;\n const first = (ipv4[0]! << 8) | ipv4[1]!;\n const second = (ipv4[2]! << 8) | ipv4[3]!;\n address = `${address.slice(0, lastColon + 1)}${first.toString(16)}:${second.toString(16)}`;\n }\n\n const doubleColon = address.indexOf('::');\n if (doubleColon !== address.lastIndexOf('::')) return null;\n\n const parseGroups = (part: string): number[] | null => {\n if (!part) return [];\n const groups = part.split(':');\n const parsed: number[] = [];\n for (const group of groups) {\n const number = parseHexGroup(group);\n if (number === null) return null;\n parsed.push(number);\n }\n return parsed;\n };\n\n if (doubleColon >= 0) {\n const head = parseGroups(address.slice(0, doubleColon));\n const tail = parseGroups(address.slice(doubleColon + 2));\n if (!head || !tail) return null;\n const missing = 8 - head.length - tail.length;\n if (missing < 1) return null;\n return [...head, ...Array<number>(missing).fill(0), ...tail];\n }\n\n const groups = parseGroups(address);\n return groups?.length === 8 ? groups : null;\n}\n\n/** RFC 5952 canonical `::` compression for 8 IPv6 groups. Exported alongside `parseIpv6`. */\nexport function compressIpv6(groups: number[]): string {\n const rendered = groups.map((group) => group.toString(16));\n let bestStart = -1;\n let bestLength = 1;\n let runStart = -1;\n\n for (let index = 0; index <= groups.length; index += 1) {\n if (index < groups.length && groups[index] === 0) {\n if (runStart < 0) runStart = index;\n continue;\n }\n if (runStart >= 0) {\n const runLength = index - runStart;\n if (runLength > bestLength) {\n bestStart = runStart;\n bestLength = runLength;\n }\n runStart = -1;\n }\n }\n\n if (bestStart < 0) return rendered.join(':');\n const before = rendered.slice(0, bestStart).join(':');\n const after = rendered.slice(bestStart + bestLength).join(':');\n if (!before && !after) return '::';\n if (!before) return `::${after}`;\n if (!after) return `${before}::`;\n return `${before}::${after}`;\n}\n\nfunction normalizeToken(rawToken: string): string | null {\n const token = rawToken.trim();\n if (!token || token.length > MAX_TOKEN_LENGTH || hasControlCharacter(token)) return null;\n\n let address = token;\n if (token.startsWith('[')) {\n const closing = token.indexOf(']');\n if (closing <= 1) return null;\n const suffix = token.slice(closing + 1);\n if (suffix && (!suffix.startsWith(':') || !parsePort(suffix.slice(1)))) return null;\n address = token.slice(1, closing);\n } else if ((token.match(/:/g) ?? []).length === 1 && token.includes('.')) {\n const colon = token.indexOf(':');\n if (!parsePort(token.slice(colon + 1))) return null;\n address = token.slice(0, colon);\n }\n\n const ipv4 = parseIpv4(address);\n if (ipv4) return ipv4.join('.');\n\n const ipv6 = parseIpv6(address);\n return ipv6 ? compressIpv6(ipv6) : null;\n}\n\nfunction boundedTokens(raw: string | null | undefined): string[] | null {\n if (raw == null || !raw || raw.length > MAX_INPUT_LENGTH || hasControlCharacter(raw)) return null;\n const tokens = raw.split(',');\n if (tokens.length > MAX_FORWARDED_HOPS) return null;\n return tokens;\n}\n\n/** Normalize the first valid address in a bounded header value. */\nexport function normalizeClientIp(raw: string | null | undefined): string | null {\n const tokens = boundedTokens(raw);\n if (!tokens) return null;\n for (const token of tokens) {\n const normalized = normalizeToken(token);\n if (normalized) return normalized;\n }\n return null;\n}\n\nfunction getObservedHeader(headers: ClientIpHeaders, name: string): string | undefined {\n if ('get' in headers && typeof headers.get === 'function') {\n return headers.get(name) ?? undefined;\n }\n\n const matches = Object.entries(headers).filter(\n ([key, value]) => key.toLowerCase() === name && value !== undefined\n );\n if (matches.length === 0) return undefined;\n if (matches.length !== 1) return '';\n const value = matches[0]![1] as string | readonly string[];\n return typeof value === 'string' ? value : value.length === 1 ? value[0] : '';\n}\n\nfunction singleAddress(raw: string | null | undefined): string | null {\n const tokens = boundedTokens(raw);\n return tokens?.length === 1 ? normalizeToken(tokens[0]!) : null;\n}\n\nfunction unavailable(\n reason: Extract<ObservedClientAddressResolution, { trusted: false }>['reason']\n): ObservedClientAddressResolution {\n return {\n ip: null,\n observedClientAddress: null,\n source: 'none',\n trusted: false,\n status: 'unavailable',\n reason,\n };\n}\n\nfunction observed(\n ip: string,\n source: Exclude<ClientIpSource, 'none'>,\n reason: Extract<ObservedClientAddressResolution, { trusted: true }>['reason']\n): ObservedClientAddressResolution {\n return { ip, observedClientAddress: ip, source, trusted: true, status: 'observed', reason };\n}\n\nfunction authenticatedPeer(input: ResolveClientIpInput, policy: PeerTrust): boolean {\n const peer = singleAddress(input.directAddress);\n if (!peer || !policy.isTrustedPeer) return false;\n try {\n return policy.isTrustedPeer(peer) === true;\n } catch {\n return false;\n }\n}\n\nfunction resolveVercel(input: ResolveClientIpInput): ObservedClientAddressResolution {\n // Vercel overwrites these values before invoking the managed runtime.\n if (input.vercelRuntime !== true) return unavailable('untrusted-peer');\n const platformHeader = getObservedHeader(input.headers, 'x-vercel-forwarded-for');\n const raw = platformHeader ?? getObservedHeader(input.headers, 'x-forwarded-for');\n const ip = singleAddress(raw);\n return ip\n ? observed(\n ip,\n platformHeader === undefined ? 'x-forwarded-for' : 'x-vercel-forwarded-for',\n 'vercel-runtime'\n )\n : unavailable('invalid-chain');\n}\n\nfunction ipv4Octets(ip: string): number[] | null {\n const ipv4 = parseIpv4(ip);\n if (ipv4) return ipv4;\n const groups = parseIpv6(ip)!;\n return groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff\n ? [groups[6]! >> 8, groups[6]! & 255, groups[7]! >> 8, groups[7]! & 255]\n : null;\n}\n\nfunction resolveCloudflare(\n input: ResolveClientIpInput,\n policy: Extract<ClientIpTrustPolicy, { platform: 'cloudflare' }>\n): ObservedClientAddressResolution {\n if (!authenticatedPeer(input, policy)) return unavailable('untrusted-peer');\n const ip = singleAddress(getObservedHeader(input.headers, 'cf-connecting-ip'));\n if (!ip) return unavailable('invalid-chain');\n // Worker subrequests can replace the visitor address. They need their own authenticated binding.\n if (getObservedHeader(input.headers, 'cf-worker') !== undefined || ip === '2a06:98c0:3600::103')\n return unavailable('unsupported-worker');\n const ipv4 = ipv4Octets(ip);\n if (ipv4 && ipv4[0]! >= 240) {\n const native = singleAddress(getObservedHeader(input.headers, 'cf-connecting-ipv6'));\n if (policy.pseudoIpv4 !== 'overwrite' || !native || ipv4Octets(native))\n return unavailable('unsupported-synthetic');\n if (native === '2a06:98c0:3600::103') return unavailable('unsupported-worker');\n return observed(native, 'cf-connecting-ipv6', 'authenticated-proxy');\n }\n return observed(ip, 'cf-connecting-ip', 'authenticated-proxy');\n}\n\nfunction resolveTrustedProxy(\n input: ResolveClientIpInput,\n policy: Extract<ClientIpTrustPolicy, { platform: 'trusted-proxy' }>\n): ObservedClientAddressResolution {\n if (!authenticatedPeer(input, policy)) return unavailable('untrusted-peer');\n const tokens = boundedTokens(getObservedHeader(input.headers, 'x-forwarded-for'));\n const hops = policy.trustedHops;\n // trustedHops counts addresses to the right of the client, excluding the socket peer.\n if (!tokens || !Number.isInteger(hops) || hops < 0 || tokens.length !== hops + 1)\n return unavailable('invalid-chain');\n const parsed = tokens.map(normalizeToken);\n if (parsed.some((token) => token === null)) return unavailable('invalid-chain');\n return observed(parsed[parsed.length - hops - 1]!, 'x-forwarded-for', 'authenticated-proxy');\n}\n\n/** Resolve the observed client address only through an authenticated deployment boundary. */\nexport function resolveObservedClientAddress(\n input: ResolveClientIpInput\n): ObservedClientAddressResolution {\n if (input.explicitAddressTrusted === true) {\n const explicit = singleAddress(input.explicitAddress);\n if (explicit) return observed(explicit, 'explicit', 'authenticated-explicit');\n }\n switch (input.policy.platform) {\n case 'vercel':\n return resolveVercel(input);\n case 'cloudflare':\n return resolveCloudflare(input, input.policy);\n case 'trusted-proxy':\n return resolveTrustedProxy(input, input.policy);\n default:\n return unavailable('untrusted-peer');\n case 'direct': {\n const socket = singleAddress(input.directAddress);\n if (socket) return observed(socket, 'socket', 'direct-peer');\n const framework = singleAddress(input.frameworkAddress);\n return framework\n ? observed(framework, 'framework', 'direct-peer')\n : unavailable('missing-address');\n }\n }\n}\n\nfunction getHeader(headers: ClientIpHeaders, name: string): string | undefined {\n if ('get' in headers && typeof headers.get === 'function') {\n return headers.get(name) ?? undefined;\n }\n\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() !== wanted || value === undefined) continue;\n return Array.isArray(value) ? value.join(',') : value;\n }\n return undefined;\n}\n\nfunction result(\n ip: string | null,\n source: Exclude<ClientIpSource, 'none'>,\n trusted: boolean\n): ClientIpResolution | null {\n return ip ? { ip, source, trusted } : null;\n}\n\nfunction resolveAddress(\n raw: string | null | undefined,\n source: 'framework' | 'socket'\n): ClientIpResolution | null {\n return result(normalizeClientIp(raw), source, true);\n}\n\nfunction resolveExplicit(input: ResolveClientIpInput): ClientIpResolution | null {\n if (input.explicitAddressTrusted !== true) return null;\n return result(normalizeClientIp(input.explicitAddress), 'explicit', true);\n}\n\nfunction resolveLegacyVercel(input: ResolveClientIpInput): ClientIpResolution {\n const platform = result(\n normalizeClientIp(getHeader(input.headers, 'x-vercel-forwarded-for')),\n 'x-vercel-forwarded-for',\n true\n );\n if (platform) return platform;\n\n const overwrittenXff = result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n true\n );\n if (overwrittenXff) return overwrittenXff;\n\n const realIp = result(\n normalizeClientIp(getHeader(input.headers, 'x-real-ip')),\n 'x-real-ip',\n false\n );\n if (realIp) return realIp;\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? { ip: null, source: 'none', trusted: false }\n );\n}\n\nfunction resolveLegacyCloudflare(input: ResolveClientIpInput): ClientIpResolution {\n const cloudflare = result(\n normalizeClientIp(getHeader(input.headers, 'cf-connecting-ip')),\n 'cf-connecting-ip',\n true\n );\n if (cloudflare) return cloudflare;\n\n return (\n resolveAddress(input.directAddress, 'socket') ??\n resolveAddress(input.frameworkAddress, 'framework') ??\n result(\n normalizeClientIp(getHeader(input.headers, 'x-forwarded-for')),\n 'x-forwarded-for',\n false\n ) ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\nfunction resolveLegacyTrustedProxy(\n input: ResolveClientIpInput,\n trustedHops: number\n): ClientIpResolution {\n const raw = getHeader(input.headers, 'x-forwarded-for');\n const tokens = boundedTokens(raw);\n if (tokens && Number.isInteger(trustedHops) && trustedHops >= 0 && tokens.length > trustedHops) {\n const parsed = tokens.map(normalizeToken);\n const selectedIndex = tokens.length - trustedHops - 1;\n const selected = parsed[selectedIndex];\n // Parse every token before selecting one. Otherwise an invalid token could\n // silently move the trusted boundary toward an attacker-controlled value.\n if (selected && parsed.every((token) => token !== null)) {\n return { ip: selected, source: 'x-forwarded-for', trusted: true };\n }\n }\n\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ??\n result(normalizeClientIp(getHeader(input.headers, 'x-real-ip')), 'x-real-ip', false) ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n}\n\n/**\n * Legacy platform-assumed resolver retained for existing gateway and runtime integrations.\n * This API does not authenticate a nearest peer. New ingress integrations must use\n * resolveObservedClientAddress and qualify their actual deployment boundary.\n */\nexport function resolveClientIp(input: ResolveClientIpInput): ClientIpResolution {\n const explicit = resolveExplicit(input);\n if (explicit) return explicit;\n\n switch (input.policy.platform) {\n case 'vercel':\n return resolveLegacyVercel(input);\n case 'cloudflare':\n return resolveLegacyCloudflare(input);\n case 'trusted-proxy':\n return resolveLegacyTrustedProxy(input, input.policy.trustedHops);\n case 'direct':\n return (\n resolveAddress(input.frameworkAddress, 'framework') ??\n resolveAddress(input.directAddress, 'socket') ?? {\n ip: null,\n source: 'none',\n trusted: false,\n }\n );\n }\n}\n"],"mappings":";AA2EA,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,qBAAqB;AAE3B,SAAS,oBAAoB,OAAwB;CACnD,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,OAAO,MAAM,WAAW,CAAC;EAC/B,IAAI,QAAQ,MAAQ,SAAS,KAAM,OAAO;CAC5C;CACA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,IAAI,UAAU,OAAO,UAAU,WAAW,KAAK,eAAe,KAAK,OAAO,SAAS,aAAa;EAC9F,MAAM,SAAS,OAAO,IAAI,cAAc;EAExC,MAAM,WAAW,OADK,OAAO,SAAS,cAAc;EAIpD,IAAI,YAAY,OAAO,OAAO,UAAU,UAAU,IAAI,GACpD,OAAO;GAAE,IAAI;GAAU,QAAQ;GAAmB,SAAS;EAAK;CAEpE;CAEA,OACE,eAAe,MAAM,kBAAkB,WAAW,KAClD,eAAe,MAAM,eAAe,QAAQ,KAC5C,OAAO,kBAAkB,UAAU,MAAM,SAAS,WAAW,CAAC,GAAG,aAAa,KAAK,KAAK;EACtF,IAAI;EACJ,QAAQ;EACR,SAAS;CACX;AAEJ;;;;;;AAOA,SAAgB,gBAAgB,OAAiD;CAC/E,MAAM,WAAW,gBAAgB,KAAK;CACtC,IAAI,UAAU,OAAO;CAErB,QAAQ,MAAM,OAAO,UAArB;EACE,KAAK,UACH,OAAO,oBAAoB,KAAK;EAClC,KAAK,cACH,OAAO,wBAAwB,KAAK;EACtC,KAAK,iBACH,OAAO,0BAA0B,OAAO,MAAM,OAAO,WAAW;EAClE,KAAK,UACH,OACE,eAAe,MAAM,kBAAkB,WAAW,KAClD,eAAe,MAAM,eAAe,QAAQ,KAAK;GAC/C,IAAI;GACJ,QAAQ;GACR,SAAS;EACX;CAEN;AACF"}
@@ -0,0 +1,2 @@
1
+ import { a as ClientIpTrustPolicy, c as compressIpv6, d as resolveClientIp, f as resolveObservedClientAddress, i as ClientIpSource, l as normalizeClientIp, n as ClientIpHeaders, o as ObservedClientAddressResolution, r as ClientIpResolution, s as ResolveClientIpInput, t as ClientIpHeaderValue, u as parseIpv6 } from "./client-ip-B7w-uHfS.mjs";
2
+ export { ClientIpHeaderValue, ClientIpHeaders, ClientIpResolution, ClientIpSource, ClientIpTrustPolicy, ObservedClientAddressResolution, ResolveClientIpInput, compressIpv6, normalizeClientIp, parseIpv6, resolveClientIp, resolveObservedClientAddress };
@@ -0,0 +1,2 @@
1
+ import { a as ClientIpTrustPolicy, c as compressIpv6, d as resolveClientIp, f as resolveObservedClientAddress, i as ClientIpSource, l as normalizeClientIp, n as ClientIpHeaders, o as ObservedClientAddressResolution, r as ClientIpResolution, s as ResolveClientIpInput, t as ClientIpHeaderValue, u as parseIpv6 } from "./client-ip-B7w-uHfS.js";
2
+ export { ClientIpHeaderValue, ClientIpHeaders, ClientIpResolution, ClientIpSource, ClientIpTrustPolicy, ObservedClientAddressResolution, ResolveClientIpInput, compressIpv6, normalizeClientIp, parseIpv6, resolveClientIp, resolveObservedClientAddress };
@@ -0,0 +1,8 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_client_ip = require('./client-ip-B8wFzJ5f.js');
3
+
4
+ exports.compressIpv6 = require_client_ip.compressIpv6;
5
+ exports.normalizeClientIp = require_client_ip.normalizeClientIp;
6
+ exports.parseIpv6 = require_client_ip.parseIpv6;
7
+ exports.resolveClientIp = require_client_ip.resolveClientIp;
8
+ exports.resolveObservedClientAddress = require_client_ip.resolveObservedClientAddress;
@@ -0,0 +1,3 @@
1
+ import { a as resolveObservedClientAddress, i as resolveClientIp, n as normalizeClientIp, r as parseIpv6, t as compressIpv6 } from "./client-ip-DIJyr6px.mjs";
2
+
3
+ export { compressIpv6, normalizeClientIp, parseIpv6, resolveClientIp, resolveObservedClientAddress };
@@ -0,0 +1,277 @@
1
+ const require_verification = require('./verification-BAw9N8Pt.js');
2
+
3
+ //#region src/core/detection-reason-codes.ts
4
+ /**
5
+ * Detection reason code registry — machine-readable "why" behind a
6
+ * `kya-confidence` verdict (companion to the `kya-http-error-codes.ts` /
7
+ * `bespoke-policy.ts` registries; same `as const satisfies` + namespaced
8
+ * string-literal convention).
9
+ *
10
+ * The engine already emits everything needed to derive these in structured
11
+ * form — `DetectionSignalDetail[]` (`signal_type` / `source`),
12
+ * `detection_class`, `verification_method`, and the AI-crawler flag (see
13
+ * `rust/crates/kya-os-engine/src/types.rs` + `api.rs`) — but until now the
14
+ * only wire-level "why" was `reasons[]`, free English prose, and only ever
15
+ * on a block/claim-rejection response. Downstream dashboards, alerts, and
16
+ * customer integrations were left string-matching that prose (see
17
+ * `apps/web/app/api/v1/pixel/route.ts` `validateDetectionResult`,
18
+ * `detection-cache.service.ts`, and `agent-classification.service.ts` for
19
+ * three live examples of exactly that pattern).
20
+ *
21
+ * `detection/*` codes are a PROJECTION of the engine's own fields: see
22
+ * `mapDetectionToReasonCodes` in the sibling `detection-reason-mapping.ts`,
23
+ * the single place that turns a detection's structured facts into an
24
+ * ordered list of these codes (consumed by the gateway worker via
25
+ * `apps/web/workers/gateway/src/detection/reason-codes.ts` and by the
26
+ * `/api/v1/enforce` signal exposure, KYA-1107). This registry never
27
+ * changes a verdict; it only labels one that already happened.
28
+ *
29
+ * The golden fixture `packages/checkpoint-shared/fixtures/detection/reason-codes.json`
30
+ * is the source of truth; the parity test in
31
+ * `__tests__/detection-reason-codes.test.ts` asserts this map is byte-exact
32
+ * against it (no drift, no omissions) — same guard shape as
33
+ * `kya-http-error-codes.test.ts`.
34
+ *
35
+ * `as const satisfies Record<string, \`detection/${string}\`>` keeps the
36
+ * narrow literal value types (autocomplete + a compile error on a typo'd
37
+ * code) while proving every value is a well-formed `detection/…` string.
38
+ */
39
+ const DETECTION_REASON_CODES = {
40
+ /** `verificationMethod === 'kya-http'`: a kya-http/RFC 9421 signature verified. */
41
+ SIGNATURE_VERIFIED: "detection/signature-verified",
42
+ /** `verificationMethod === 'kya-http-delegated'`: a verified delegation credential rode the request. */
43
+ DELEGATION_VERIFIED: "detection/delegation-verified",
44
+ /** `verificationMethod === 'mcp-i' | 'kya-os'` (the wire values; `isKyaOsWireMethod`): the MCP-I/KYA-OS handshake verified. */
45
+ MCP_I_VERIFIED: "detection/mcp-i-verified",
46
+ /** `verificationMethod === 'did'`: the retired `KYA-Agent-DID` header scheme verified a signature. Historical records only; the gateway no longer emits it. */
47
+ DID_SIGNATURE_VERIFIED: "detection/did-signature-verified",
48
+ /** `verificationMethod === 'signature'`: the worker's RFC 9421 signature verifier (ChatGPT et al.) verified against the DB-refreshed key directory. */
49
+ RFC9421_SIGNATURE_VERIFIED: "detection/rfc9421-signature-verified",
50
+ /** `verificationMethod` starts with `tier1_` (e.g. `tier1_rfc9421`): the engine's Tier-1 protocol attribution verified. */
51
+ TIER1_ATTRIBUTION_VERIFIED: "detection/tier1-attribution-verified",
52
+ /** `verificationMethod === 'a2a'`: an A2A Agent Card's declared security scheme (RFC 9421 keyid, or a JWT bearer against resolved JWKS) cryptographically verified. */
53
+ A2A_VERIFIED: "detection/a2a-verified",
54
+ /** `verificationMethod === 'error'`: a presented credential was demoted/rejected during verification; see the sibling `kyaErrorCode`. */
55
+ VERIFICATION_ERROR: "detection/verification-error",
56
+ /** A `signals[]` entry with `source === 'user_agent_pattern'`: the User-Agent matched a known pattern. */
57
+ UA_PATTERN_MATCH: "detection/ua-pattern-match",
58
+ /** `source === 'header_heuristic'`: a header shape/combination heuristic matched. */
59
+ HEADER_HEURISTIC: "detection/header-heuristic",
60
+ /** `source === 'ip_heuristic'`: an IP-based heuristic matched. */
61
+ IP_HEURISTIC: "detection/ip-heuristic",
62
+ /** `source === 'vendor_ip_feed'`: the request IP matched a known vendor's published IP range. */
63
+ VENDOR_IP_CORROBORATED: "detection/vendor-ip-corroborated",
64
+ /** `source === 'ip_intelligence'`: the host's IP-intelligence provider flagged the request's true IP as a proxy/VPN/Tor/anonymization exit. */
65
+ IP_INTELLIGENCE_PROXY_SIGNAL: "detection/ip-intelligence-proxy-signal",
66
+ /** `source === 'transport.ja4'`: a TLS JA4 fingerprint was observed at the terminating proxy (emit-only observation marker; it matches no list). */
67
+ JA4_FINGERPRINT_MATCH: "detection/ja4-fingerprint-match",
68
+ /** `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. */
69
+ CLIENT_INTEGRITY_FAILURE: "detection/client-integrity-failure",
70
+ /** `source === 'ua_tls_mismatch'`: the User-Agent claims a browser but the JA4 cipher-list hash (JA4_b) belongs to known non-browser tooling. */
71
+ UA_TLS_MISMATCH: "detection/ua-tls-mismatch",
72
+ /** `source === 'client.attributes'`: a pixel/beacon-reported client attribute contributed. */
73
+ CLIENT_ATTRIBUTE_SIGNAL: "detection/client-attribute-signal",
74
+ /** `source === 'behavioural.interaction'`: a behavioral/interaction signal contributed. */
75
+ BEHAVIORAL_SIGNAL: "detection/behavioral-signal",
76
+ /** `source === 'mcp_i'`: an MCP-I header was present (evidence short of a completed handshake). */
77
+ MCP_I_SIGNAL: "detection/mcp-i-signal",
78
+ /** `source === 'kya_http_binding'`: a kya-http binding was presented (evidence short of full verification). */
79
+ KYA_HTTP_BINDING_SIGNAL: "detection/kya-http-binding-signal",
80
+ /** `source === 'kya_delegation_bearer'`: a delegation bearer credential was presented. */
81
+ KYA_DELEGATION_BEARER_SIGNAL: "detection/kya-delegation-bearer-signal",
82
+ /** A `signals[]` entry with `source === 'a2a_agent_card'`: an A2A Agent Card was presented (evidence short of, or alongside, full verification). */
83
+ A2A_CARD_SIGNAL: "detection/a2a-card-signal",
84
+ /** `source === 'scanner_misclassification_hint'`: Cloudflare's bot score contradicted a zero-evidence Human verdict, overriding it to Unknown. */
85
+ SCANNER_MISCLASSIFICATION_HINT_SIGNAL: "detection/scanner-misclassification-hint-signal",
86
+ /** `source === 'client_headless_escalation'`: the beacon disclosed `navigator.webdriver`, or reported corroborating automation evidence (CDP/plugin/WebGL consistency, a distinctive property), escalating the classification. */
87
+ CLIENT_HEADLESS_ESCALATION_SIGNAL: "detection/client-headless-escalation-signal",
88
+ /** `source === 'transport.cloudflare_bot_management'`: Cloudflare's bot-management score or verified-bot determination contributed. */
89
+ CLOUDFLARE_BOT_MANAGEMENT_SIGNAL: "detection/cloudflare-bot-management-signal",
90
+ /** `source === 'session_velocity'`: the edge-computed request-velocity heuristic contributed. */
91
+ SESSION_VELOCITY_SIGNAL: "detection/session-velocity-signal",
92
+ /** A `signals[]` entry whose `source` starts with `tier1_`: raw Tier-1 protocol evidence, short of (or alongside) full verification. */
93
+ TIER1_ATTRIBUTION_SIGNAL: "detection/tier1-attribution-signal",
94
+ /** `isAiCrawler === true`: classified as an AI training crawler (GPTBot, ClaudeBot, etc.), not an interactive agent. */
95
+ AI_CRAWLER_FLAG: "detection/ai-crawler-flag",
96
+ /** `detectionClass === 'human'` with no contributing signals and no verification: the baseline "nothing matched" human path. */
97
+ ZERO_EVIDENCE_HUMAN: "detection/zero-evidence-human",
98
+ /** `detectionClass === 'incomplete_data' | 'unknown'` (or absent): the engine could not classify confidently. */
99
+ INCOMPLETE_DATA_OVERRIDE: "detection/incomplete-data-override",
100
+ /** 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. */
101
+ CLASSIFIED_WITHOUT_SIGNAL_EVIDENCE: "detection/classified-without-signal-evidence"
102
+ };
103
+
104
+ //#endregion
105
+ //#region src/core/detection-reason-mapping.ts
106
+ /**
107
+ * Detection reason-code mapping: the single pure projection of a
108
+ * detection's structured facts onto the `DETECTION_REASON_CODES` registry
109
+ * (#4874).
110
+ *
111
+ * The engine already emits structured evidence (`signals[]` with a typed
112
+ * `source`, `verificationMethod`, `detectionClass`, `isAiCrawler`) but the
113
+ * only wire-level "why" used to be `reasons[]`, free English prose. This
114
+ * module turns that structured evidence into an ordered list of stable,
115
+ * namespaced codes, most-significant-evidence first.
116
+ *
117
+ * Consumers (all invoke this SAME pure function, so their codes can never
118
+ * diverge):
119
+ * - the gateway worker's `addDetectionHeaders` (`KYA-Reason-Codes` on
120
+ * EVERY proxied response, including allow) and `log-detection.ts`
121
+ * (persisted alongside the detection row), both via the re-export in
122
+ * `apps/web/workers/gateway/src/detection/reason-codes.ts`;
123
+ * - the `/api/v1/enforce` response's signal exposure
124
+ * (KYA-1107) via `apps/web/lib/detection/signal-exposure.ts`.
125
+ *
126
+ * This module NEVER changes a verdict; it only labels one that already
127
+ * happened (same non-negotiable as the registry doc comment).
128
+ */
129
+ /**
130
+ * `verificationMethod` → the single strongest code it proves. Keys are the
131
+ * WIRE value space; the KYA-OS handshake/delegation alias pairs are handled
132
+ * as explicit branches in `mapDetectionToReasonCodes` via the shared
133
+ * `isKyaOs*Method` predicates (the SSOT for those alias pairs; Bugbot on
134
+ * PR #4874 caught this table keyed on engine values instead, silently
135
+ * missing every verified MCP-I/KYA-OS handshake) rather than hardcoding the
136
+ * alias strings a second time in this map.
137
+ */
138
+ const VERIFICATION_METHOD_CODES = {
139
+ "kya-http-delegated": DETECTION_REASON_CODES.DELEGATION_VERIFIED,
140
+ "kya-http": DETECTION_REASON_CODES.SIGNATURE_VERIFIED,
141
+ did: DETECTION_REASON_CODES.DID_SIGNATURE_VERIFIED,
142
+ signature: DETECTION_REASON_CODES.RFC9421_SIGNATURE_VERIFIED,
143
+ a2a: DETECTION_REASON_CODES.A2A_VERIFIED,
144
+ error: DETECTION_REASON_CODES.VERIFICATION_ERROR
145
+ };
146
+ /**
147
+ * A `signals[].source` value → the code naming that raw evidence.
148
+ *
149
+ * Declaration order IS the consideration order `mapDetectionToReasonCodes`
150
+ * iterates (object key insertion order is guaranteed for string keys), NOT
151
+ * the raw `signals[]` array order, which the engine assembles differently
152
+ * per detection path (mirrors `buildVerdictEvidence`'s own doc comment on
153
+ * the same nondeterminism). Roughly the engine's own construction order in
154
+ * `api.rs` (identity/delegation evidence before UA/IP heuristics). Keeping
155
+ * one map (rather than a map plus a separate priority-order array) means a
156
+ * new signal source is added in exactly one place.
157
+ */
158
+ const SIGNAL_SOURCE_CODES = {
159
+ mcp_i: DETECTION_REASON_CODES.MCP_I_SIGNAL,
160
+ kya_http_binding: DETECTION_REASON_CODES.KYA_HTTP_BINDING_SIGNAL,
161
+ kya_delegation_bearer: DETECTION_REASON_CODES.KYA_DELEGATION_BEARER_SIGNAL,
162
+ a2a_agent_card: DETECTION_REASON_CODES.A2A_CARD_SIGNAL,
163
+ user_agent_pattern: DETECTION_REASON_CODES.UA_PATTERN_MATCH,
164
+ ua_tls_mismatch: DETECTION_REASON_CODES.UA_TLS_MISMATCH,
165
+ header_heuristic: DETECTION_REASON_CODES.HEADER_HEURISTIC,
166
+ ip_heuristic: DETECTION_REASON_CODES.IP_HEURISTIC,
167
+ scanner_misclassification_hint: DETECTION_REASON_CODES.SCANNER_MISCLASSIFICATION_HINT_SIGNAL,
168
+ client_headless_escalation: DETECTION_REASON_CODES.CLIENT_HEADLESS_ESCALATION_SIGNAL,
169
+ vendor_ip_feed: DETECTION_REASON_CODES.VENDOR_IP_CORROBORATED,
170
+ ip_intelligence: DETECTION_REASON_CODES.IP_INTELLIGENCE_PROXY_SIGNAL,
171
+ "transport.ja4": DETECTION_REASON_CODES.JA4_FINGERPRINT_MATCH,
172
+ "transport.cloudflare_bot_management": DETECTION_REASON_CODES.CLOUDFLARE_BOT_MANAGEMENT_SIGNAL,
173
+ client_integrity: DETECTION_REASON_CODES.CLIENT_INTEGRITY_FAILURE,
174
+ "client.attributes": DETECTION_REASON_CODES.CLIENT_ATTRIBUTE_SIGNAL,
175
+ "behavioural.interaction": DETECTION_REASON_CODES.BEHAVIORAL_SIGNAL,
176
+ session_velocity: DETECTION_REASON_CODES.SESSION_VELOCITY_SIGNAL
177
+ };
178
+ /**
179
+ * Maps a detection's structured facts to an ordered, deduplicated list of
180
+ * `detection/*` reason codes, most-significant-evidence first:
181
+ *
182
+ * 1. Verification-method-derived (cryptographic proof, strongest).
183
+ * 2. Signal-source-derived (raw structured evidence), one code per
184
+ * distinct source actually present, deduplicated.
185
+ * 3. The AI-crawler classification flag.
186
+ * 4. A zero-evidence fallback, ONLY when nothing above matched, so this
187
+ * function never returns an empty list. An assumed verdict (e.g. the
188
+ * baseline "no known agent indicators matched" human path) deserves a
189
+ * code saying so, in the spirit of #4800, rather than silence.
190
+ *
191
+ * Pure: no I/O, no mutation of `detail`.
192
+ */
193
+ function mapDetectionToReasonCodes(detail) {
194
+ const codes = [];
195
+ const seen = /* @__PURE__ */ new Set();
196
+ const push = (code) => {
197
+ if (code && !seen.has(code)) {
198
+ seen.add(code);
199
+ codes.push(code);
200
+ }
201
+ };
202
+ const verificationMethod = detail.verificationMethod;
203
+ if (verificationMethod) {
204
+ if (verificationMethod.startsWith("tier1_")) push(DETECTION_REASON_CODES.TIER1_ATTRIBUTION_VERIFIED);
205
+ else if (require_verification.isKyaOsWireMethod(verificationMethod) || require_verification.isKyaOsHandshakeMethod(verificationMethod)) push(DETECTION_REASON_CODES.MCP_I_VERIFIED);
206
+ else push(VERIFICATION_METHOD_CODES[verificationMethod]);
207
+ }
208
+ const presentSources = /* @__PURE__ */ new Set();
209
+ let hasTier1Signal = false;
210
+ for (const signal of detail.signals ?? []) {
211
+ presentSources.add(signal.source);
212
+ if (signal.source.startsWith("tier1_")) hasTier1Signal = true;
213
+ }
214
+ for (const source of Object.keys(SIGNAL_SOURCE_CODES)) if (presentSources.has(source)) push(SIGNAL_SOURCE_CODES[source]);
215
+ if (hasTier1Signal) push(DETECTION_REASON_CODES.TIER1_ATTRIBUTION_SIGNAL);
216
+ if (detail.isAiCrawler) push(DETECTION_REASON_CODES.AI_CRAWLER_FLAG);
217
+ if (codes.length === 0) {
218
+ if (detail.detectionClass === "human") push(DETECTION_REASON_CODES.ZERO_EVIDENCE_HUMAN);
219
+ else if (detail.detectionClass === "incomplete_data" || detail.detectionClass === "unknown" || !detail.detectionClass) push(DETECTION_REASON_CODES.INCOMPLETE_DATA_OVERRIDE);
220
+ else push(DETECTION_REASON_CODES.CLASSIFIED_WITHOUT_SIGNAL_EVIDENCE);
221
+ }
222
+ return codes;
223
+ }
224
+ /** Wire cap: at most this many codes on the `KYA-Reason-Codes` header. */
225
+ const MAX_REASON_CODES_ON_WIRE = 5;
226
+ /** Wire cap: the header's serialized UTF-8 byte budget. */
227
+ const MAX_REASON_CODES_HEADER_BYTES = 256;
228
+ const HEADER_BYTES_ENCODER = new TextEncoder();
229
+ /**
230
+ * Formats an ordered reason-code list into the `KYA-Reason-Codes` header
231
+ * value: comma-separated, capped at {@link MAX_REASON_CODES_ON_WIRE} codes,
232
+ * then trimmed from the end (never mid-string) until the UTF-8 byte length
233
+ * fits {@link MAX_REASON_CODES_HEADER_BYTES}. `codes` is assumed already
234
+ * ordered most-significant-first (mapDetectionToReasonCodes's contract);
235
+ * this function only truncates, it never reorders.
236
+ */
237
+ function formatReasonCodesHeader(codes) {
238
+ const capped = codes.slice(0, 5);
239
+ while (capped.length > 0) {
240
+ const joined = capped.join(",");
241
+ if (HEADER_BYTES_ENCODER.encode(joined).byteLength <= 256) return joined;
242
+ capped.pop();
243
+ }
244
+ return "";
245
+ }
246
+
247
+ //#endregion
248
+ Object.defineProperty(exports, 'DETECTION_REASON_CODES', {
249
+ enumerable: true,
250
+ get: function () {
251
+ return DETECTION_REASON_CODES;
252
+ }
253
+ });
254
+ Object.defineProperty(exports, 'MAX_REASON_CODES_HEADER_BYTES', {
255
+ enumerable: true,
256
+ get: function () {
257
+ return MAX_REASON_CODES_HEADER_BYTES;
258
+ }
259
+ });
260
+ Object.defineProperty(exports, 'MAX_REASON_CODES_ON_WIRE', {
261
+ enumerable: true,
262
+ get: function () {
263
+ return MAX_REASON_CODES_ON_WIRE;
264
+ }
265
+ });
266
+ Object.defineProperty(exports, 'formatReasonCodesHeader', {
267
+ enumerable: true,
268
+ get: function () {
269
+ return formatReasonCodesHeader;
270
+ }
271
+ });
272
+ Object.defineProperty(exports, 'mapDetectionToReasonCodes', {
273
+ enumerable: true,
274
+ get: function () {
275
+ return mapDetectionToReasonCodes;
276
+ }
277
+ });