@kya-os/checkpoint-shared 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/dist/base64url-BbVG8f-v.js +65 -0
  3. package/dist/base64url-D2MvsR20.mjs +49 -0
  4. package/dist/base64url-D2MvsR20.mjs.map +1 -0
  5. package/dist/beacon-forward-secret/index.d.mts +4 -0
  6. package/dist/beacon-forward-secret/index.d.mts.map +1 -0
  7. package/dist/beacon-forward-secret/index.d.ts +4 -0
  8. package/dist/beacon-forward-secret/index.d.ts.map +1 -0
  9. package/dist/beacon-forward-secret/index.js +15 -0
  10. package/dist/beacon-forward-secret/index.mjs +15 -0
  11. package/dist/beacon-forward-secret/index.mjs.map +1 -0
  12. package/dist/beacon-types/index.d.mts +53 -1
  13. package/dist/beacon-types/index.d.mts.map +1 -1
  14. package/dist/beacon-types/index.d.ts +53 -1
  15. package/dist/beacon-types/index.d.ts.map +1 -1
  16. package/dist/beacon-types/index.js +86 -1
  17. package/dist/beacon-types/index.mjs +77 -2
  18. package/dist/beacon-types/index.mjs.map +1 -1
  19. package/dist/{browser-posture-5fPrsxx7.d.mts → browser-posture-WPk0kl9u.d.mts} +18 -1
  20. package/dist/browser-posture-WPk0kl9u.d.mts.map +1 -0
  21. package/dist/{browser-posture-CCR1kh5e.d.ts → browser-posture-_y6BcdXw.d.ts} +18 -1
  22. package/dist/browser-posture-_y6BcdXw.d.ts.map +1 -0
  23. package/dist/browser-posture-cookie.mjs.map +1 -1
  24. package/dist/browser-posture-proof-verifier.js +136 -5
  25. package/dist/browser-posture-proof-verifier.mjs +134 -2
  26. package/dist/browser-posture-proof-verifier.mjs.map +1 -0
  27. package/dist/browser-posture-proof.d.mts +1 -1
  28. package/dist/browser-posture-proof.d.ts +1 -1
  29. package/dist/browser-posture-proof.js +1 -1
  30. package/dist/browser-posture-proof.mjs +1 -1
  31. package/dist/browser-posture-report.d.mts +17 -0
  32. package/dist/browser-posture-report.d.mts.map +1 -1
  33. package/dist/browser-posture-report.d.ts +17 -0
  34. package/dist/browser-posture-report.d.ts.map +1 -1
  35. package/dist/browser-posture.d.mts +1 -1
  36. package/dist/browser-posture.d.ts +1 -1
  37. package/dist/browser-posture.js +18 -1
  38. package/dist/browser-posture.mjs +18 -1
  39. package/dist/browser-posture.mjs.map +1 -1
  40. package/dist/browser.d.mts +10 -0
  41. package/dist/browser.d.mts.map +1 -1
  42. package/dist/browser.d.ts +10 -0
  43. package/dist/browser.d.ts.map +1 -1
  44. package/dist/browser.js +1 -1
  45. package/dist/browser.mjs +1 -1
  46. package/dist/browser.mjs.map +1 -1
  47. package/dist/canonical-signer/index.d.mts.map +1 -1
  48. package/dist/canonical-signer/index.d.ts.map +1 -1
  49. package/dist/canonical-signer/index.js +0 -4
  50. package/dist/canonical-signer/index.mjs +0 -4
  51. package/dist/canonical-signer/index.mjs.map +1 -1
  52. package/dist/{client-ip-B7w-uHfS.d.ts → client-ip-8KneiMK0.d.mts} +12 -2
  53. package/dist/{client-ip-B7w-uHfS.d.mts.map → client-ip-8KneiMK0.d.mts.map} +1 -1
  54. package/dist/{client-ip-B7w-uHfS.d.mts → client-ip-8KneiMK0.d.ts} +12 -2
  55. package/dist/{client-ip-B7w-uHfS.d.ts.map → client-ip-8KneiMK0.d.ts.map} +1 -1
  56. package/dist/{client-ip-B8wFzJ5f.js → client-ip-BEmLC4I4.js} +71 -0
  57. package/dist/{client-ip-DIJyr6px.mjs → client-ip-DlHx7GGh.mjs} +61 -2
  58. package/dist/client-ip-DlHx7GGh.mjs.map +1 -0
  59. package/dist/client-ip.d.mts +2 -2
  60. package/dist/client-ip.d.ts +2 -2
  61. package/dist/client-ip.js +3 -1
  62. package/dist/client-ip.mjs +2 -2
  63. package/dist/deploy/index.d.mts.map +1 -1
  64. package/dist/deploy/index.d.ts.map +1 -1
  65. package/dist/deploy/index.js +5 -1
  66. package/dist/deploy/index.mjs +5 -1
  67. package/dist/deploy/index.mjs.map +1 -1
  68. package/dist/{detection-reason-mapping-CQexNvR7.d.ts → detection-reason-mapping-BemDaDED.d.mts} +5 -2
  69. package/dist/detection-reason-mapping-BemDaDED.d.mts.map +1 -0
  70. package/dist/{detection-reason-mapping-CQexNvR7.d.mts → detection-reason-mapping-BemDaDED.d.ts} +5 -2
  71. package/dist/detection-reason-mapping-BemDaDED.d.ts.map +1 -0
  72. package/dist/{detection-reason-mapping-B9RSkOs8.js → detection-reason-mapping-BxYaQ8kb.js} +33 -8
  73. package/dist/{detection-reason-mapping-BGymWIPl.mjs → detection-reason-mapping-j-7bXsVb.mjs} +29 -10
  74. package/dist/detection-reason-mapping-j-7bXsVb.mjs.map +1 -0
  75. package/dist/errors/index.d.mts +4 -0
  76. package/dist/errors/index.d.mts.map +1 -1
  77. package/dist/errors/index.d.ts +4 -0
  78. package/dist/errors/index.d.ts.map +1 -1
  79. package/dist/errors/index.js +24 -8
  80. package/dist/errors/index.mjs +24 -8
  81. package/dist/errors/index.mjs.map +1 -1
  82. package/dist/{fetcher-CZfLcbRZ.d.mts → fetcher-CTKz07jg.d.mts} +12 -2
  83. package/dist/fetcher-CTKz07jg.d.mts.map +1 -0
  84. package/dist/{fetcher-CCw4Q95g.d.ts → fetcher-DCr920hx.d.ts} +12 -2
  85. package/dist/fetcher-DCr920hx.d.ts.map +1 -0
  86. package/dist/gateway-client-ip.js +1 -1
  87. package/dist/gateway-client-ip.mjs +1 -1
  88. package/dist/identity-cookie/index.d.mts +14 -0
  89. package/dist/identity-cookie/index.d.mts.map +1 -0
  90. package/dist/identity-cookie/index.d.ts +14 -0
  91. package/dist/identity-cookie/index.d.ts.map +1 -0
  92. package/dist/identity-cookie/index.js +45 -0
  93. package/dist/identity-cookie/index.mjs +43 -0
  94. package/dist/identity-cookie/index.mjs.map +1 -0
  95. package/dist/index.d.mts +598 -142
  96. package/dist/index.d.mts.map +1 -1
  97. package/dist/index.d.ts +598 -142
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +793 -198
  100. package/dist/index.mjs +743 -188
  101. package/dist/index.mjs.map +1 -1
  102. package/dist/kya-http.d.mts +2 -2
  103. package/dist/kya-http.d.ts +2 -2
  104. package/dist/kya-http.js +2 -1
  105. package/dist/kya-http.mjs +2 -2
  106. package/dist/mcpi/dashboard-config/index.mjs.map +1 -1
  107. package/dist/patterns-CdTh7LU2.d.mts +35 -0
  108. package/dist/patterns-CdTh7LU2.d.mts.map +1 -0
  109. package/dist/patterns-CdTh7LU2.d.ts +35 -0
  110. package/dist/patterns-CdTh7LU2.d.ts.map +1 -0
  111. package/dist/{patterns-CiMpbdAF.js → patterns-CnNxRnaK.js} +3 -130
  112. package/dist/{patterns-D4OAsNQY.mjs → patterns-CpRk9R3M.mjs} +5 -96
  113. package/dist/patterns-CpRk9R3M.mjs.map +1 -0
  114. package/dist/patterns.d.mts +2 -2
  115. package/dist/patterns.d.ts +2 -2
  116. package/dist/patterns.js +1 -7
  117. package/dist/patterns.mjs +2 -2
  118. package/dist/policy/fetcher.d.mts +2 -2
  119. package/dist/policy/fetcher.d.ts +2 -2
  120. package/dist/policy/fetcher.js +100 -8
  121. package/dist/policy/fetcher.mjs +99 -9
  122. package/dist/policy/fetcher.mjs.map +1 -1
  123. package/dist/proxy-assertion-mapping-BVwXVSMZ.mjs +81 -0
  124. package/dist/proxy-assertion-mapping-BVwXVSMZ.mjs.map +1 -0
  125. package/dist/proxy-assertion-mapping-BxhENrcY.d.mts +70 -0
  126. package/dist/proxy-assertion-mapping-BxhENrcY.d.mts.map +1 -0
  127. package/dist/proxy-assertion-mapping-D64AyZfG.js +85 -0
  128. package/dist/proxy-assertion-mapping-DhAynFqG.d.ts +70 -0
  129. package/dist/proxy-assertion-mapping-DhAynFqG.d.ts.map +1 -0
  130. package/dist/proxy-assertions.d.mts +2 -0
  131. package/dist/proxy-assertions.d.ts +2 -0
  132. package/dist/proxy-assertions.js +4 -0
  133. package/dist/proxy-assertions.mjs +3 -0
  134. package/dist/reason-codes.d.mts +2 -2
  135. package/dist/reason-codes.d.ts +2 -2
  136. package/dist/reason-codes.js +3 -2
  137. package/dist/reason-codes.mjs +2 -2
  138. package/dist/{registered-sid-CnWIU_l1.d.ts → registered-sid-BgDhdj2l.d.mts} +13 -2
  139. package/dist/registered-sid-BgDhdj2l.d.mts.map +1 -0
  140. package/dist/{registered-sid-CnWIU_l1.d.mts → registered-sid-BgDhdj2l.d.ts} +13 -2
  141. package/dist/registered-sid-BgDhdj2l.d.ts.map +1 -0
  142. package/dist/{registered-sid-BZfDOfXy.js → registered-sid-DG1tSSvl.js} +67 -12
  143. package/dist/{registered-sid-CS9V8nPr.mjs → registered-sid-D__xiDPu.mjs} +63 -14
  144. package/dist/registered-sid-D__xiDPu.mjs.map +1 -0
  145. package/dist/timezone-country-B6PkDyNP.d.mts +15 -0
  146. package/dist/timezone-country-B6PkDyNP.d.mts.map +1 -0
  147. package/dist/timezone-country-B6PkDyNP.d.ts +15 -0
  148. package/dist/timezone-country-B6PkDyNP.d.ts.map +1 -0
  149. package/dist/timezone-country-CROxU2Tl.js +505 -0
  150. package/dist/timezone-country-CrrnkOdy.mjs +489 -0
  151. package/dist/timezone-country-CrrnkOdy.mjs.map +1 -0
  152. package/dist/timezone-country.d.mts +2 -0
  153. package/dist/timezone-country.d.ts +2 -0
  154. package/dist/timezone-country.js +6 -0
  155. package/dist/timezone-country.mjs +3 -0
  156. package/dist/tool-protection/index.mjs.map +1 -1
  157. package/fixtures/detection/cloudflare-alias-parity.json +383 -0
  158. package/fixtures/detection/reason-codes.json +3 -1
  159. package/fixtures/detection/signal-exposure-example.json +1 -1
  160. package/fixtures/iana-tzdata/backward +375 -0
  161. package/fixtures/iana-tzdata/renamed-zones.json +21 -0
  162. package/fixtures/iana-tzdata/version +1 -0
  163. package/fixtures/iana-tzdata/zone.tab +448 -0
  164. package/fixtures/workbench/management-session.v1.json +20 -0
  165. package/fixtures/workbench/model-credentials.v1.json +8 -0
  166. package/fixtures/workbench/task-grant.v1.json +37 -0
  167. package/package.json +25 -3
  168. package/src/data/compiled/merged-rules.json +9 -7
  169. package/dist/browser-posture-5fPrsxx7.d.mts.map +0 -1
  170. package/dist/browser-posture-CCR1kh5e.d.ts.map +0 -1
  171. package/dist/browser-posture-proof-verifier-DvsOmFrM.js +0 -202
  172. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs +0 -180
  173. package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs.map +0 -1
  174. package/dist/client-ip-DIJyr6px.mjs.map +0 -1
  175. package/dist/detection-reason-mapping-BGymWIPl.mjs.map +0 -1
  176. package/dist/detection-reason-mapping-CQexNvR7.d.mts.map +0 -1
  177. package/dist/detection-reason-mapping-CQexNvR7.d.ts.map +0 -1
  178. package/dist/fetcher-CCw4Q95g.d.ts.map +0 -1
  179. package/dist/fetcher-CZfLcbRZ.d.mts.map +0 -1
  180. package/dist/patterns-Bp40cwh2.d.mts +0 -110
  181. package/dist/patterns-Bp40cwh2.d.mts.map +0 -1
  182. package/dist/patterns-Bp40cwh2.d.ts +0 -110
  183. package/dist/patterns-Bp40cwh2.d.ts.map +0 -1
  184. package/dist/patterns-D4OAsNQY.mjs.map +0 -1
  185. package/dist/registered-sid-CS9V8nPr.mjs.map +0 -1
  186. package/dist/registered-sid-CnWIU_l1.d.mts.map +0 -1
  187. package/dist/registered-sid-CnWIU_l1.d.ts.map +0 -1
package/dist/browser.mjs CHANGED
@@ -1,2 +1,2 @@
1
- function e(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function t(e){return/^(?:0|[1-9]\d{0,4})$/.test(e)&&Number(e)<=65535}function n(e){let t=e.split(`.`);if(t.length!==4)return null;let n=[];for(let e of t){if(!/^\d{1,3}$/.test(e))return null;let t=Number(e);if(t>255)return null;n.push(t)}return n}function r(e){return/^[0-9a-fA-F]{1,4}$/.test(e)?Number.parseInt(e,16):null}function i(t){if(!t||t.includes(`%`)||e(t))return null;let i=t;if(i.includes(`.`)){let e=i.lastIndexOf(`:`);if(e<0)return null;let t=n(i.slice(e+1));if(!t)return null;let r=t[0]<<8|t[1],a=t[2]<<8|t[3];i=`${i.slice(0,e+1)}${r.toString(16)}:${a.toString(16)}`}let a=i.indexOf(`::`);if(a!==i.lastIndexOf(`::`))return null;let o=e=>{if(!e)return[];let t=e.split(`:`),n=[];for(let e of t){let t=r(e);if(t===null)return null;n.push(t)}return n};if(a>=0){let e=o(i.slice(0,a)),t=o(i.slice(a+2));if(!e||!t)return null;let n=8-e.length-t.length;return n<1?null:[...e,...Array(n).fill(0),...t]}let s=o(i);return(s==null?void 0:s.length)===8?s:null}function a(e){let t=e.map(e=>e.toString(16)),n=-1,r=1,i=-1;for(let t=0;t<=e.length;t+=1){if(t<e.length&&e[t]===0){i<0&&(i=t);continue}if(i>=0){let e=t-i;e>r&&(n=i,r=e),i=-1}}if(n<0)return t.join(`:`);let a=t.slice(0,n).join(`:`),o=t.slice(n+r).join(`:`);return!a&&!o?`::`:a?o?`${a}::${o}`:`${a}::`:`::${o}`}function o(r){var o;let s=r.trim();if(!s||s.length>128||e(s))return null;let c=s;if(s.startsWith(`[`)){let e=s.indexOf(`]`);if(e<=1)return null;let n=s.slice(e+1);if(n&&(!n.startsWith(`:`)||!t(n.slice(1))))return null;c=s.slice(1,e)}else if(((o=s.match(/:/g))==null?[]:o).length===1&&s.includes(`.`)){let e=s.indexOf(`:`);if(!t(s.slice(e+1)))return null;c=s.slice(0,e)}let l=n(c);if(l)return l.join(`.`);let u=i(c);return u?a(u):null}function s(t){if(t==null||!t||t.length>4096||e(t))return null;let n=t.split(`,`);return n.length>32?null:n}function c(e){let t=s(e);if(!t)return null;for(let e of t){let t=o(e);if(t)return t}return null}function l(e,t){if(`get`in e&&typeof e.get==`function`){var n;return(n=e.get(t))==null?void 0:n}let r=Object.entries(e).filter(([e,n])=>e.toLowerCase()===t&&n!==void 0);if(r.length===0)return;if(r.length!==1)return``;let i=r[0][1];return typeof i==`string`?i:i.length===1?i[0]:``}function u(e){let t=s(e);return(t==null?void 0:t.length)===1?o(t[0]):null}function d(e){return{ip:null,observedClientAddress:null,source:`none`,trusted:!1,status:`unavailable`,reason:e}}function f(e,t,n){return{ip:e,observedClientAddress:e,source:t,trusted:!0,status:`observed`,reason:n}}function p(e,t){let n=u(e.directAddress);if(!n||!t.isTrustedPeer)return!1;try{return t.isTrustedPeer(n)===!0}catch(e){return!1}}function m(e){if(e.vercelRuntime!==!0)return d(`untrusted-peer`);let t=l(e.headers,`x-vercel-forwarded-for`),n=u(t==null?l(e.headers,`x-forwarded-for`):t);return n?f(n,t===void 0?`x-forwarded-for`:`x-vercel-forwarded-for`,`vercel-runtime`):d(`invalid-chain`)}function h(e){let t=n(e);if(t)return t;let r=i(e);return r.slice(0,5).every(e=>e===0)&&r[5]===65535?[r[6]>>8,r[6]&255,r[7]>>8,r[7]&255]:null}function g(e,t){if(!p(e,t))return d(`untrusted-peer`);let n=u(l(e.headers,`cf-connecting-ip`));if(!n)return d(`invalid-chain`);if(l(e.headers,`cf-worker`)!==void 0||n===`2a06:98c0:3600::103`)return d(`unsupported-worker`);let r=h(n);if(r&&r[0]>=240){let n=u(l(e.headers,`cf-connecting-ipv6`));return t.pseudoIpv4!==`overwrite`||!n||h(n)?d(`unsupported-synthetic`):n===`2a06:98c0:3600::103`?d(`unsupported-worker`):f(n,`cf-connecting-ipv6`,`authenticated-proxy`)}return f(n,`cf-connecting-ip`,`authenticated-proxy`)}function _(e,t){if(!p(e,t))return d(`untrusted-peer`);let n=s(l(e.headers,`x-forwarded-for`)),r=t.trustedHops;if(!n||!Number.isInteger(r)||r<0||n.length!==r+1)return d(`invalid-chain`);let i=n.map(o);return i.some(e=>e===null)?d(`invalid-chain`):f(i[i.length-r-1],`x-forwarded-for`,`authenticated-proxy`)}function v(e){if(e.explicitAddressTrusted===!0){let t=u(e.explicitAddress);if(t)return f(t,`explicit`,`authenticated-explicit`)}switch(e.policy.platform){case`vercel`:return m(e);case`cloudflare`:return g(e,e.policy);case`trusted-proxy`:return _(e,e.policy);default:return d(`untrusted-peer`);case`direct`:{let t=u(e.directAddress);if(t)return f(t,`socket`,`direct-peer`);let n=u(e.frameworkAddress);return n?f(n,`framework`,`direct-peer`):d(`missing-address`)}}}function y(e,t){if(`get`in e&&typeof e.get==`function`){var n;return(n=e.get(t))==null?void 0:n}let r=t.toLowerCase();for(let[t,n]of Object.entries(e))if(t.toLowerCase()===r&&n!==void 0)return Array.isArray(n)?n.join(`,`):n}function b(e,t,n){return e?{ip:e,source:t,trusted:n}:null}function x(e,t){return b(c(e),t,!0)}function S(e){return e.explicitAddressTrusted===!0?b(c(e.explicitAddress),`explicit`,!0):null}function C(e){var t,n;return b(c(y(e.headers,`x-vercel-forwarded-for`)),`x-vercel-forwarded-for`,!0)||b(c(y(e.headers,`x-forwarded-for`)),`x-forwarded-for`,!0)||b(c(y(e.headers,`x-real-ip`)),`x-real-ip`,!1)||((t=(n=x(e.frameworkAddress,`framework`))==null?x(e.directAddress,`socket`):n)==null?{ip:null,source:`none`,trusted:!1}:t)}function w(e){var t,n,r,i;return b(c(y(e.headers,`cf-connecting-ip`)),`cf-connecting-ip`,!0)||((t=(n=(r=(i=x(e.directAddress,`socket`))==null?x(e.frameworkAddress,`framework`):i)==null?b(c(y(e.headers,`x-forwarded-for`)),`x-forwarded-for`,!1):r)==null?b(c(y(e.headers,`x-real-ip`)),`x-real-ip`,!1):n)==null?{ip:null,source:`none`,trusted:!1}:t)}function T(e,t){var n,r,i;let a=s(y(e.headers,`x-forwarded-for`));if(a&&Number.isInteger(t)&&t>=0&&a.length>t){let e=a.map(o),n=e[a.length-t-1];if(n&&e.every(e=>e!==null))return{ip:n,source:`x-forwarded-for`,trusted:!0}}return(n=(r=(i=x(e.frameworkAddress,`framework`))==null?x(e.directAddress,`socket`):i)==null?b(c(y(e.headers,`x-real-ip`)),`x-real-ip`,!1):r)==null?{ip:null,source:`none`,trusted:!1}:n}function E(e){let t=S(e);if(t)return t;switch(e.policy.platform){case`vercel`:return C(e);case`cloudflare`:return w(e);case`trusted-proxy`:return T(e,e.policy.trustedHops);case`direct`:var n,r;return(n=(r=x(e.frameworkAddress,`framework`))==null?x(e.directAddress,`socket`):r)==null?{ip:null,source:`none`,trusted:!1}:n}}function D(e){if(!e||typeof e!=`object`)return!1;let t=e,n=t.metadata;return!!(t.type&&typeof t.type==`string`&&t.data&&typeof t.data==`object`&&n&&typeof n==`object`&&n.sessionId&&n.timestamp)}export{a as compressIpv6,c as normalizeClientIp,i as parseIpv6,E as resolveClientIp,v as resolveObservedClientAddress,D as validateBeaconEvent};
1
+ function e(t){"@babel/helpers - typeof";return e=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},e(t)}function t(t,n){if(e(t)!=`object`||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,n||`default`);if(e(i)!=`object`)return i;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(n===`string`?String:Number)(t)}function n(n){var r=t(n,`string`);return e(r)==`symbol`?r:r+``}function r(e,t,r){return(t=n(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?i(Object(n),!0).forEach(function(t){r(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function o(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function s(e){return/^(?:0|[1-9]\d{0,4})$/.test(e)&&Number(e)<=65535}function c(e){let t=e.split(`.`);if(t.length!==4)return null;let n=[];for(let e of t){if(!/^\d{1,3}$/.test(e))return null;let t=Number(e);if(t>255)return null;n.push(t)}return n}function l(e){return/^[0-9a-fA-F]{1,4}$/.test(e)?Number.parseInt(e,16):null}function u(e){if(!e||e.includes(`%`)||o(e))return null;let t=e;if(t.includes(`.`)){let e=t.lastIndexOf(`:`);if(e<0)return null;let n=c(t.slice(e+1));if(!n)return null;let r=n[0]<<8|n[1],i=n[2]<<8|n[3];t=`${t.slice(0,e+1)}${r.toString(16)}:${i.toString(16)}`}let n=t.indexOf(`::`);if(n!==t.lastIndexOf(`::`))return null;let r=e=>{if(!e)return[];let t=e.split(`:`),n=[];for(let e of t){let t=l(e);if(t===null)return null;n.push(t)}return n};if(n>=0){let e=r(t.slice(0,n)),i=r(t.slice(n+2));if(!e||!i)return null;let a=8-e.length-i.length;return a<1?null:[...e,...Array(a).fill(0),...i]}let i=r(t);return(i==null?void 0:i.length)===8?i:null}function d(e){let t=e.map(e=>e.toString(16)),n=-1,r=1,i=-1;for(let t=0;t<=e.length;t+=1){if(t<e.length&&e[t]===0){i<0&&(i=t);continue}if(i>=0){let e=t-i;e>r&&(n=i,r=e),i=-1}}if(n<0)return t.join(`:`);let a=t.slice(0,n).join(`:`),o=t.slice(n+r).join(`:`);return!a&&!o?`::`:a?o?`${a}::${o}`:`${a}::`:`::${o}`}function f(e){var t;let n=e.trim();if(!n||n.length>128||o(n))return null;let r=n;if(n.startsWith(`[`)){let e=n.indexOf(`]`);if(e<=1)return null;let t=n.slice(e+1);if(t&&(!t.startsWith(`:`)||!s(t.slice(1))))return null;r=n.slice(1,e)}else if(((t=n.match(/:/g))==null?[]:t).length===1&&n.includes(`.`)){let e=n.indexOf(`:`);if(!s(n.slice(e+1)))return null;r=n.slice(0,e)}let i=c(r);if(i)return i.join(`.`);let a=u(r);return a?d(a):null}function p(e){if(e==null||!e||e.length>4096||o(e))return null;let t=e.split(`,`);return t.length>32?null:t}function m(e){let t=p(e);if(!t)return null;for(let e of t){let t=f(e);if(t)return t}return null}function h(e,t){if(`get`in e&&typeof e.get==`function`){var n;return(n=e.get(t))==null?void 0:n}let r=Object.entries(e).filter(([e,n])=>e.toLowerCase()===t&&n!==void 0);if(r.length===0)return;if(r.length!==1)return``;let i=r[0][1];return typeof i==`string`?i:i.length===1?i[0]:``}function g(e){let t=p(e);return(t==null?void 0:t.length)===1?f(t[0]):null}function _(e){return{ip:null,observedClientAddress:null,source:`none`,trusted:!1,status:`unavailable`,reason:e}}function v(e,t,n){return{ip:e,observedClientAddress:e,source:t,trusted:!0,status:`observed`,reason:n}}function y(e,t){let n=g(e.directAddress);if(!n||!t.isTrustedPeer)return!1;try{return t.isTrustedPeer(n)===!0}catch(e){return!1}}function b(e){if(e.vercelRuntime!==!0)return _(`untrusted-peer`);let t=h(e.headers,`x-vercel-forwarded-for`),n=g(t==null?h(e.headers,`x-forwarded-for`):t);return n?v(n,t===void 0?`x-forwarded-for`:`x-vercel-forwarded-for`,`vercel-runtime`):_(`invalid-chain`)}function x(e){let t=c(e);if(t)return t;let n=u(e);return n.slice(0,5).every(e=>e===0)&&n[5]===65535?[n[6]>>8,n[6]&255,n[7]>>8,n[7]&255]:null}function S(e,t){if(!y(e,t))return _(`untrusted-peer`);let n=g(h(e.headers,`cf-connecting-ip`));if(!n)return _(`invalid-chain`);if(h(e.headers,`cf-worker`)!==void 0||n===`2a06:98c0:3600::103`)return _(`unsupported-worker`);let r=x(n);if(r&&r[0]>=240){let n=g(h(e.headers,`cf-connecting-ipv6`));return t.pseudoIpv4!==`overwrite`||!n||x(n)?_(`unsupported-synthetic`):n===`2a06:98c0:3600::103`?_(`unsupported-worker`):v(n,`cf-connecting-ipv6`,`authenticated-proxy`)}return v(n,`cf-connecting-ip`,`authenticated-proxy`)}function C(e,t){if(!y(e,t))return _(`untrusted-peer`);let n=p(h(e.headers,`x-forwarded-for`)),r=t.trustedHops;if(!n||!Number.isInteger(r)||r<0||n.length!==r+1)return _(`invalid-chain`);let i=n.map(f);return i.some(e=>e===null)?_(`invalid-chain`):v(i[i.length-r-1],`x-forwarded-for`,`authenticated-proxy`)}function w(e){if(e.explicitAddressTrusted===!0){let t=g(e.explicitAddress);if(t)return v(t,`explicit`,`authenticated-explicit`)}switch(e.policy.platform){case`vercel`:return b(e);case`cloudflare`:return S(e,e.policy);case`trusted-proxy`:return C(e,e.policy);default:return _(`untrusted-peer`);case`direct`:{let t=g(e.directAddress);if(t)return v(t,`socket`,`direct-peer`);let n=g(e.frameworkAddress);return n?v(n,`framework`,`direct-peer`):_(`missing-address`)}}}function T(e){let t=e.policy;if(t.platform!==`trusted-proxy`)return w(e);if(e.explicitAddressTrusted===!0){let t=g(e.explicitAddress);if(t)return v(t,`explicit`,`authenticated-explicit`)}if(!y(e,t))return _(`untrusted-peer`);let n=p(h(e.headers,`x-forwarded-for`)),r=t.trustedHops;if(!n||!Number.isInteger(r)||r<0||n.length<r+1)return _(`invalid-chain`);let i=n.slice(n.length-r-1).map(f);return i.some(e=>e===null)?_(`invalid-chain`):v(i[0],`x-forwarded-for`,`authenticated-proxy`)}function E(e,t){let n=e.policy;if(n.platform!==`trusted-proxy`)return;let r=t.reason!==`untrusted-peer`,i=T(a(a({},e),{},{policy:a(a({},n),{},{isTrustedPeer:()=>r})})),o=t.ip,s=h(e.headers,`x-forwarded-for`),c=n.trustedHops;return{agree:i.ip===o,host:o===null?`none`:`ip`,shadow:i.ip===null?`none`:`ip`,chainLength:s?Math.min(s.split(`,`).length,33):0,trustedHops:Number.isInteger(c)&&c>=0?c:-1,reason:i.reason}}function D(e,t){if(`get`in e&&typeof e.get==`function`){var n;return(n=e.get(t))==null?void 0:n}let r=t.toLowerCase();for(let[t,n]of Object.entries(e))if(t.toLowerCase()===r&&n!==void 0)return Array.isArray(n)?n.join(`,`):n}function O(e,t,n){return e?{ip:e,source:t,trusted:n}:null}function k(e,t){return O(m(e),t,!0)}function A(e){return e.explicitAddressTrusted===!0?O(m(e.explicitAddress),`explicit`,!0):null}function j(e){var t,n;return O(m(D(e.headers,`x-vercel-forwarded-for`)),`x-vercel-forwarded-for`,!0)||O(m(D(e.headers,`x-forwarded-for`)),`x-forwarded-for`,!0)||O(m(D(e.headers,`x-real-ip`)),`x-real-ip`,!1)||((t=(n=k(e.frameworkAddress,`framework`))==null?k(e.directAddress,`socket`):n)==null?{ip:null,source:`none`,trusted:!1}:t)}function M(e){var t,n,r,i;return O(m(D(e.headers,`cf-connecting-ip`)),`cf-connecting-ip`,!0)||((t=(n=(r=(i=k(e.directAddress,`socket`))==null?k(e.frameworkAddress,`framework`):i)==null?O(m(D(e.headers,`x-forwarded-for`)),`x-forwarded-for`,!1):r)==null?O(m(D(e.headers,`x-real-ip`)),`x-real-ip`,!1):n)==null?{ip:null,source:`none`,trusted:!1}:t)}function N(e,t){var n,r,i;let a=p(D(e.headers,`x-forwarded-for`));if(a&&Number.isInteger(t)&&t>=0&&a.length>t){let e=a.map(f),n=e[a.length-t-1];if(n&&e.every(e=>e!==null))return{ip:n,source:`x-forwarded-for`,trusted:!0}}return(n=(r=(i=k(e.frameworkAddress,`framework`))==null?k(e.directAddress,`socket`):i)==null?O(m(D(e.headers,`x-real-ip`)),`x-real-ip`,!1):r)==null?{ip:null,source:`none`,trusted:!1}:n}function P(e){let t=A(e);if(t)return t;switch(e.policy.platform){case`vercel`:return j(e);case`cloudflare`:return M(e);case`trusted-proxy`:return N(e,e.policy.trustedHops);case`direct`:var n,r;return(n=(r=k(e.frameworkAddress,`framework`))==null?k(e.directAddress,`socket`):r)==null?{ip:null,source:`none`,trusted:!1}:n}}function F(e){if(!e||typeof e!=`object`)return!1;let t=e,n=t.metadata;return!!(t.type&&typeof t.type==`string`&&t.data&&typeof t.data==`object`&&n&&typeof n==`object`&&n.sessionId&&n.timestamp)}export{E as compareForwardedChainShadow,d as compressIpv6,m as normalizeClientIp,u as parseIpv6,P as resolveClientIp,T as resolveForwardedChainShadow,w as resolveObservedClientAddress,F as validateBeaconEvent};
2
2
  //# sourceMappingURL=browser.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser.mjs","names":[],"sources":["../src/utils/client-ip.ts","../src/browser.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","/**\n * The `./browser` entry: exports that load no Zod and no Node built-in, so a\n * browser bundle or a Worker can import them without the root entry.\n */\n\n// Client-IP normalization is dependency-free and safe for Workers/browser\n// consumers. Keeping it on this entrypoint prevents adapters from importing\n// the server-heavy shared barrel just to resolve request provenance.\nexport * from './utils/client-ip';\n\n// ============================================================================\n// BEACON TYPES\n// ============================================================================\n\nexport type BeaconEventType =\n | 'pageview'\n | 'pageunload'\n | 'heartbeat'\n | 'evidence'\n | 'custom'\n | 'error'\n | 'performance';\n\nexport interface BeaconEvent {\n type: BeaconEventType;\n data: BeaconCollectorData;\n metadata: BeaconMetadata;\n}\n\nexport interface BeaconMetadata {\n sessionId: string;\n timestamp: number;\n eventName?: string;\n [key: string]: unknown;\n}\n\nexport interface BeaconCollectorData {\n // Browser collector data\n userAgent?: string;\n language?: string;\n platform?: string;\n screenResolution?: string;\n viewport?: string;\n cookiesEnabled?: boolean;\n doNotTrack?: boolean;\n timezone?: string;\n referrer?: string;\n url?: string;\n title?: string;\n vendor?: string;\n\n // Performance collector data\n pageLoadTime?: number;\n domContentLoadedTime?: number;\n firstPaintTime?: number;\n firstContentfulPaintTime?: number;\n connectionType?: string;\n\n // Session data\n sessionId?: string;\n timestamp?: number;\n\n // Allow additional properties\n [key: string]: unknown;\n}\n\n// ============================================================================\n// SIMPLE VALIDATORS (Lightweight replacements for Zod)\n// ============================================================================\n\n/**\n * Validates a beacon event\n */\nexport function validateBeaconEvent(event: unknown): event is BeaconEvent {\n if (!event || typeof event !== 'object') return false;\n const e = event as Record<string, unknown>;\n const metadata = e.metadata as Record<string, unknown> | undefined;\n return !!(\n e.type &&\n typeof e.type === 'string' &&\n e.data &&\n typeof e.data === 'object' &&\n metadata &&\n typeof metadata === 'object' &&\n metadata.sessionId &&\n metadata.timestamp\n );\n}\n"],"mappings":"AA+EA,SAAS,EAAoB,EAAwB,CACnD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,IAAK,CACrC,IAAM,EAAO,EAAM,WAAW,CAAC,EAC/B,GAAI,GAAQ,IAAQ,IAAS,IAAM,MAAO,EAC5C,CACA,MAAO,EACT,CAEA,SAAS,EAAU,EAAwB,CACzC,MAAO,uBAAuB,KAAK,CAAK,GAAK,OAAO,CAAK,GAAK,KAChE,CAEA,SAAS,EAAU,EAAgC,CACjD,IAAM,EAAQ,EAAM,MAAM,GAAG,EAC7B,GAAI,EAAM,SAAW,EAAG,OAAO,KAE/B,IAAM,EAAmB,CAAC,EAC1B,IAAK,IAAM,KAAQ,EAAO,CACxB,GAAI,CAAC,YAAY,KAAK,CAAI,EAAG,OAAO,KACpC,IAAM,EAAQ,OAAO,CAAI,EACzB,GAAI,EAAQ,IAAK,OAAO,KACxB,EAAO,KAAK,CAAK,CACnB,CACA,OAAO,CACT,CAEA,SAAS,EAAc,EAA8B,CAEnD,MADK,qBAAqB,KAAK,CAAK,EAC7B,OAAO,SAAS,EAAO,EAAE,EADc,IAEhD,CAG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,CAAK,EACtC,IAAK,gBACH,OAAO,EAA0B,EAAO,EAAM,OAAO,WAAW,EAClE,IAAK,iBACH,OAAA,GAAA,EACE,EAAe,EAAM,iBAAkB,WAAW,IAAA,KAClD,EAAe,EAAM,cAAe,QAAQ,EADM,IACN,KAAK,CAC/C,GAAI,KACJ,OAAQ,OACR,QAAS,EACX,EAJ4C,CAMlD,CACF,CC9aA,SAAgB,EAAoB,EAAsC,CACxE,GAAI,CAAC,GAAS,OAAO,GAAU,SAAU,MAAO,GAChD,IAAM,EAAI,EACJ,EAAW,EAAE,SACnB,MAAO,CAAC,EACN,EAAE,MACF,OAAO,EAAE,MAAS,UAClB,EAAE,MACF,OAAO,EAAE,MAAS,UAClB,GACA,OAAO,GAAa,UACpB,EAAS,WACT,EAAS,UAEb"}
1
+ {"version":3,"file":"browser.mjs","names":[],"sources":["../src/utils/client-ip.ts","../src/browser.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\n/**\n * SHADOW ONLY: the trusted-proxy rule decided on 2026-10-28, measured beside\n * {@link resolveObservedClientAddress} and never used as the client address.\n * It is deleted when the engine's client address resolver lands; that\n * resolver, and the .NET and Java shadows, must pass the same cases in\n * `tests/cross-runtime-parity/client-ip-shadow/vectors.json`.\n *\n * Behind an authenticated socket peer, the client is the entry `trustedHops`\n * places left of the right end of X-Forwarded-For. Unlike the exact rule, a\n * longer chain (entries a client prepended) is read from the right, up to the\n * 32-entry cap. Every entry from the client's to the right end must parse; a\n * chain shorter than `trustedHops + 1` gives no address. Every other profile\n * resolves exactly as {@link resolveObservedClientAddress}.\n */\nexport function resolveForwardedChainShadow(\n input: ResolveClientIpInput\n): ObservedClientAddressResolution {\n const policy = input.policy;\n if (policy.platform !== 'trusted-proxy') return resolveObservedClientAddress(input);\n if (input.explicitAddressTrusted === true) {\n const explicit = singleAddress(input.explicitAddress);\n if (explicit) return observed(explicit, 'explicit', 'authenticated-explicit');\n }\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 if (!tokens || !Number.isInteger(hops) || hops < 0 || tokens.length < hops + 1)\n return unavailable('invalid-chain');\n const trusted = tokens.slice(tokens.length - hops - 1).map(normalizeToken);\n if (trusted.some((token) => token === null)) return unavailable('invalid-chain');\n return observed(trusted[0]!, 'x-forwarded-for', 'authenticated-proxy');\n}\n\n/** How the shadow rule compared with the host's answer for one request: shapes only, never an address. */\nexport interface ClientAddressShadow {\n /** The shadow rule and the host resolved the same address, or both resolved none. */\n agree: boolean;\n host: 'ip' | 'none';\n shadow: 'ip' | 'none';\n /** X-Forwarded-For entries, 0 when absent, 33 for any chain over the 32-entry cap. */\n chainLength: number;\n /** The host's configured trustedHops, or -1 when it is not a non-negative integer. */\n trustedHops: number;\n reason: 'authenticated-explicit' | 'authenticated-proxy' | 'untrusted-peer' | 'invalid-chain';\n}\n\n/**\n * SHADOW ONLY, deleted with {@link resolveForwardedChainShadow}: compares that\n * rule with the host's own resolution of the same input for a trusted-proxy\n * deployment. It reuses the host's peer verdict instead of asking the\n * deployment's `isTrustedPeer` again. Undefined for every other profile,\n * whose rule does not change.\n */\nexport function compareForwardedChainShadow(\n input: ResolveClientIpInput,\n hostResolution: ObservedClientAddressResolution\n): ClientAddressShadow | undefined {\n const policy = input.policy;\n if (policy.platform !== 'trusted-proxy') return undefined;\n const peerTrusted = hostResolution.reason !== 'untrusted-peer';\n const shadow = resolveForwardedChainShadow({\n ...input,\n policy: { ...policy, isTrustedPeer: () => peerTrusted },\n });\n const host = hostResolution.ip;\n const raw = getObservedHeader(input.headers, 'x-forwarded-for');\n const hops = policy.trustedHops;\n return {\n agree: shadow.ip === host,\n host: host === null ? 'none' : 'ip',\n shadow: shadow.ip === null ? 'none' : 'ip',\n chainLength: raw ? Math.min(raw.split(',').length, MAX_FORWARDED_HOPS + 1) : 0,\n trustedHops: Number.isInteger(hops) && hops >= 0 ? hops : -1,\n reason: shadow.reason as ClientAddressShadow['reason'],\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","/**\n * The `./browser` entry: exports that load no Zod and no Node built-in, so a\n * browser bundle or a Worker can import them without the root entry.\n */\n\n// Client-IP normalization is dependency-free and safe for Workers/browser\n// consumers. Keeping it on this entrypoint prevents adapters from importing\n// the server-heavy shared barrel just to resolve request provenance.\nexport * from './utils/client-ip';\n\n// ============================================================================\n// BEACON TYPES\n// ============================================================================\n\nexport type BeaconEventType =\n | 'pageview'\n | 'pageunload'\n | 'heartbeat'\n | 'evidence'\n | 'custom'\n | 'error'\n | 'performance';\n\nexport interface BeaconEvent {\n type: BeaconEventType;\n data: BeaconCollectorData;\n metadata: BeaconMetadata;\n}\n\nexport interface BeaconMetadata {\n sessionId: string;\n timestamp: number;\n eventName?: string;\n [key: string]: unknown;\n}\n\nexport interface BeaconCollectorData {\n // Browser collector data\n userAgent?: string;\n language?: string;\n platform?: string;\n screenResolution?: string;\n viewport?: string;\n cookiesEnabled?: boolean;\n doNotTrack?: boolean;\n timezone?: string;\n referrer?: string;\n url?: string;\n title?: string;\n vendor?: string;\n\n // Performance collector data\n pageLoadTime?: number;\n domContentLoadedTime?: number;\n firstPaintTime?: number;\n firstContentfulPaintTime?: number;\n connectionType?: string;\n\n // Session data\n sessionId?: string;\n timestamp?: number;\n\n // Allow additional properties\n [key: string]: unknown;\n}\n\n// ============================================================================\n// SIMPLE VALIDATORS (Lightweight replacements for Zod)\n// ============================================================================\n\n/**\n * Validates a beacon event\n */\nexport function validateBeaconEvent(event: unknown): event is BeaconEvent {\n if (!event || typeof event !== 'object') return false;\n const e = event as Record<string, unknown>;\n const metadata = e.metadata as Record<string, unknown> | undefined;\n return !!(\n e.type &&\n typeof e.type === 'string' &&\n e.data &&\n typeof e.data === 'object' &&\n metadata &&\n typeof metadata === 'object' &&\n metadata.sessionId &&\n metadata.timestamp\n );\n}\n"],"mappings":"6uCA+EA,SAAS,EAAoB,EAAwB,CACnD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,IAAK,CACrC,IAAM,EAAO,EAAM,WAAW,CAAC,EAC/B,GAAI,GAAQ,IAAQ,IAAS,IAAM,MAAO,EAC5C,CACA,MAAO,EACT,CAEA,SAAS,EAAU,EAAwB,CACzC,MAAO,uBAAuB,KAAK,CAAK,GAAK,OAAO,CAAK,GAAK,KAChE,CAEA,SAAS,EAAU,EAAgC,CACjD,IAAM,EAAQ,EAAM,MAAM,GAAG,EAC7B,GAAI,EAAM,SAAW,EAAG,OAAO,KAE/B,IAAM,EAAmB,CAAC,EAC1B,IAAK,IAAM,KAAQ,EAAO,CACxB,GAAI,CAAC,YAAY,KAAK,CAAI,EAAG,OAAO,KACpC,IAAM,EAAQ,OAAO,CAAI,EACzB,GAAI,EAAQ,IAAK,OAAO,KACxB,EAAO,KAAK,CAAK,CACnB,CACA,OAAO,CACT,CAEA,SAAS,EAAc,EAA8B,CAEnD,MADK,qBAAqB,KAAK,CAAK,EAC7B,OAAO,SAAS,EAAO,EAAE,EADc,IAEhD,CAGA,SAAgB,EAAU,EAAgC,CACxD,GAAI,CAAC,GAAS,EAAM,SAAS,GAAG,GAAK,EAAoB,CAAK,EAAG,OAAO,KAExE,IAAI,EAAU,EACd,GAAI,EAAQ,SAAS,GAAG,EAAG,CACzB,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AA,EACE,EAAe,EAAM,iBAAkB,WAAW,IAAA,KAClD,EAAe,EAAM,cAAe,QAAQ,EADM,IACN,KAAK,CAC/C,GAAI,KACJ,OAAQ,OACR,QAAS,EACX,EAJ4C,CAMlD,CACF,CC3fA,SAAgB,EAAoB,EAAsC,CACxE,GAAI,CAAC,GAAS,OAAO,GAAU,SAAU,MAAO,GAChD,IAAM,EAAI,EACJ,EAAW,EAAE,SACnB,MAAO,CAAC,EACN,EAAE,MACF,OAAO,EAAE,MAAS,UAClB,EAAE,MACF,OAAO,EAAE,MAAS,UAClB,GACA,OAAO,GAAa,UACpB,EAAS,WACT,EAAS,UAEb"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/canonical-signer/key.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"mappings":";UA+BiB;EAEf;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;;wBAsBc,wBAAwB,SAAS,cAAc;wBAmD/C,oBAAoB,iBAAiB;;;UC7EpC;EAEf,YAAY;EAEZ,WAAW;EAEX;EAMA;;wBAmBoB,gBAAgB,MAAM,aAAa,QAAQ;;;wBCrC3C,iBAAiB,SAAS,aAAa,KAAK,cAAc;;;UCE/D;EAEf;IACE;IAIA;IAGA;;EAGF,SAAS;EAET,gBAAgB;EAMhB,cAAc;;qBAQH,sBAAsB;WAGf;EAAA,YAAA,gKAQhB;;wBAwFY,gBAAgB,cAAc"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/canonical-signer/key.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"mappings":";UA+BiB;EAEf;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;;wBAsBc,wBAAwB,SAAS,cAAc;wBAmD/C,oBAAoB,iBAAiB;;;UC7EpC;EAEf,YAAY;EAEZ,WAAW;EAEX;EAMA;;wBAmBoB,gBAAgB,MAAM,aAAa,QAAQ;;;wBCzC3C,iBAAiB,SAAS,aAAa,KAAK,cAAc;;;UCM/D;EAEf;IACE;IAIA;IAGA;;EAGF,SAAS;EAET,gBAAgB;EAMhB,cAAc;;qBAQH,sBAAsB;WAGf;EAAA,YAAA,gKAQhB;;wBAwFY,gBAAgB,cAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/canonical-signer/key.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"mappings":";UA+BiB;EAEf;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;;wBAsBc,wBAAwB,SAAS,cAAc;wBAmD/C,oBAAoB,iBAAiB;;;UC7EpC;EAEf,YAAY;EAEZ,WAAW;EAEX;EAMA;;wBAmBoB,gBAAgB,MAAM,aAAa,QAAQ;;;wBCrC3C,iBAAiB,SAAS,aAAa,KAAK,cAAc;;;UCE/D;EAEf;IACE;IAIA;IAGA;;EAGF,SAAS;EAET,gBAAgB;EAMhB,cAAc;;qBAQH,sBAAsB;WAGf;EAAA,YAAA,gKAQhB;;wBAwFY,gBAAgB,cAAc"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/canonical-signer/key.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"mappings":";UA+BiB;EAEf;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;;wBAsBc,wBAAwB,SAAS,cAAc;wBAmD/C,oBAAoB,iBAAiB;;;UC7EpC;EAEf,YAAY;EAEZ,WAAW;EAEX;EAMA;;wBAmBoB,gBAAgB,MAAM,aAAa,QAAQ;;;wBCzC3C,iBAAiB,SAAS,aAAa,KAAK,cAAc;;;UCM/D;EAEf;IACE;IAIA;IAGA;;EAGF,SAAS;EAET,gBAAgB;EAMhB,cAAc;;qBAQH,sBAAsB;WAGf;EAAA,YAAA,gKAQhB;;wBAwFY,gBAAgB,cAAc"}
@@ -297,10 +297,6 @@ function bytesToBase64Url(bytes) {
297
297
  * the payload is the JCS-canonicalized `McpIPayload`, and the signature is
298
298
  * Ed25519 over `BASE64URL(header) || '.' || BASE64URL(payload)` per
299
299
  * RFC 7515 § 5.1.
300
- *
301
- * Sign-1 (#2500). Output of this function is what every TS producer in the
302
- * org emits — bouncer middleware (Envelope-1), Sites-1/2 e2e helpers, future
303
- * Sites-4 parity drivers, the Adobe trial.
304
300
  */
305
301
  /**
306
302
  * Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop
@@ -296,10 +296,6 @@ function bytesToBase64Url(bytes) {
296
296
  * the payload is the JCS-canonicalized `McpIPayload`, and the signature is
297
297
  * Ed25519 over `BASE64URL(header) || '.' || BASE64URL(payload)` per
298
298
  * RFC 7515 § 5.1.
299
- *
300
- * Sign-1 (#2500). Output of this function is what every TS producer in the
301
- * org emits — bouncer middleware (Envelope-1), Sites-1/2 e2e helpers, future
302
- * Sites-4 parity drivers, the Adobe trial.
303
299
  */
304
300
  /**
305
301
  * Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../node_modules/.pnpm/canonicalize@3.0.0/node_modules/canonicalize/lib/canonicalize.js","../../src/canonical-signer/payload.ts","../../src/mcpi/did-key.ts","../../src/canonical-signer/key.ts","../../src/utils/base64url.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"sourcesContent":["export default function canonicalize (object, seen = new Set()) {\n if (typeof object === 'number' && isNaN(object)) {\n throw new Error('NaN is not allowed');\n }\n\n if (typeof object === 'number' && !isFinite(object)) {\n throw new Error('Infinity is not allowed');\n }\n\n if (object === null || typeof object !== 'object') {\n return JSON.stringify(object);\n }\n\n if (typeof object.toJSON === 'function') {\n if (seen.has(object)) {\n throw new Error('Circular reference detected');\n }\n seen.add(object);\n const result = canonicalize(object.toJSON(), seen);\n seen.delete(object);\n return result;\n }\n\n if (seen.has(object)) {\n throw new Error('Circular reference detected');\n }\n seen.add(object);\n\n let result;\n if (Array.isArray(object)) {\n const values = object.map((cv) => {\n const value = cv === undefined || typeof cv === 'symbol' ? null : cv;\n return canonicalize(value, seen);\n });\n result = `[${values.join(',')}]`;\n } else {\n const parts = [];\n for (const key of Object.keys(object).sort()) {\n if (object[key] === undefined || typeof object[key] === 'symbol') {\n continue;\n }\n parts.push(`${canonicalize(key)}:${canonicalize(object[key], seen)}`);\n }\n result = `{${parts.join(',')}}`;\n }\n\n seen.delete(object);\n return result;\n}\n","/**\n * Canonical KYA-OS signing payload (RFC 8785 / JCS).\n *\n * TS half of the cross-runtime parity contract pinned in\n * `rust/crates/kya-os-engine/src/signing.rs`. Same `McpIPayload` struct,\n * same JCS canonicalization, byte-identical output. The Rust engine's\n * `signing_payload` golden vector at `tests/fixtures/reference_payload.jcs`\n * is the firewall this module asserts against — if these bytes diverge,\n * every downstream signature verification claim is suspect.\n *\n * Field set is locked to KYA-OS spec § 7.4 (eight required claims) +\n * § 7.2 (ProofMeta). Wire format is camelCase per the KYA-OS JSON schema.\n *\n * Sign-1 (#2500). Do NOT extend without ratification through\n * mcp-i-core → D-design → here.\n *\n * @see rust/crates/kya-os-engine/src/signing.rs — Rust struct + JCS function\n * @see rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs — golden vector\n */\n\nimport canonicalize from 'canonicalize';\n\n/**\n * Structured KYA-OS payload signed by an Ed25519 key.\n *\n * Mirrors `kya_os_engine::signing::McpIPayload` field-for-field. Wire\n * format uses camelCase (matches Rust's `#[serde(rename_all = \"camelCase\")]`).\n *\n * Lexicographic key order on the wire (the JCS member-ordering rule):\n * `aud, iss, nonce, requestHash, responseHash, sessionId, sub, ts`\n */\nexport interface McpIPayload {\n /** Audience — the intended recipient DID or URL. */\n aud: string;\n /** Issuer — the signing principal's DID. */\n iss: string;\n /** Subject — the principal this proof is about (often equal to `iss`). */\n sub: string;\n /** Session nonce — binds the proof to the handshake that established the session. */\n nonce: string;\n /** Session identifier from the handshake response. */\n sessionId: string;\n /** Unix epoch seconds when the proof was generated. */\n ts: number;\n /** SHA-256 hash of the JCS-canonicalized request, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n requestHash: string;\n /** SHA-256 hash of the JCS-canonicalized response, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n responseHash: string;\n}\n\n/**\n * Canonicalize an `McpIPayload` into the byte sequence the Ed25519\n * signature is computed over.\n *\n * **Determinism contract.** Same input MUST produce byte-identical\n * output, every time, every runtime. This function is the cross-runtime\n * parity contract — TS, .NET, Go, Python, and Rust runtimes all\n * implement it independently and MUST agree on the golden vector\n * pinned at `rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs`.\n *\n * The output is RFC 8785 (JCS) canonical JSON: keys sorted\n * lexicographically by UTF-16 code units, integers serialized without\n * a decimal point, strings escaped only as required, no whitespace.\n *\n * Implementation note: `canonicalize` (npm) is Erdtman's RFC 8785\n * reference implementation. If a future TS host reaches for a\n * different library, the parity firewall test (`canonical-signer.parity.test.ts`)\n * will catch the byte drift before it reaches production.\n */\nexport function canonicalSigningPayload(payload: McpIPayload): Uint8Array {\n const json = canonicalize(payload);\n if (json === undefined) {\n // canonicalize returns undefined for non-serializable inputs\n // (functions, symbols, etc.). McpIPayload's typed fields preclude\n // this, but the runtime check guards against `as McpIPayload` casts\n // at consumer call-sites that bypass the type contract.\n throw new Error('canonicalSigningPayload: payload contains non-serializable values');\n }\n return new TextEncoder().encode(json);\n}\n\n/**\n * Field set that MUST be present for an `McpIPayload` to be valid.\n *\n * Source of truth for `validateMcpIPayload`. The list mirrors the TS\n * `McpIPayload` interface — adding a field there without adding it\n * here is a hidden bypass for the runtime contract. New required\n * fields land in lockstep; new optional fields (post-Scope-1) get\n * a sibling list with a `typeof === 'undefined' || ...` predicate.\n */\nconst REQUIRED_STRING_FIELDS = [\n 'aud',\n 'iss',\n 'sub',\n 'nonce',\n 'sessionId',\n 'requestHash',\n 'responseHash',\n] as const;\n\n/**\n * Runtime type guard: confirms a `JSON.parse` output actually matches\n * `McpIPayload`. Required because `JSON.parse` returns `unknown`, and\n * casting `as McpIPayload` is a *compile-time* assertion that the\n * runtime can't honor — a payload missing required fields silently\n * surfaces as `undefined` at consumer call-sites and bypasses field-\n * presence checks (e.g., the bouncer's replay-window comparison\n * `meta.ts < now - 300` evaluates `false` for `undefined`, skipping\n * the timestamp defense entirely).\n *\n * Throws on the FIRST missing or wrong-typed field — no error\n * accumulation, since one missing claim is enough to reject the\n * envelope and producers should re-issue the entire proof rather than\n * patch field-by-field.\n *\n * @throws Error with a descriptive message identifying the offending\n * field. `parseJwsCompact` translates this into a structured\n * `JwsParseError('InvalidPayloadShape', ...)` for consumers branching\n * on the discriminant.\n */\nexport function validateMcpIPayload(value: unknown): McpIPayload {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n for (const field of REQUIRED_STRING_FIELDS) {\n if (typeof obj[field] !== 'string') {\n throw new Error(`missing or non-string required field \"${field}\" (got ${typeof obj[field]})`);\n }\n }\n\n // ts is the load-bearing exception — number, not string. The bug\n // cursor-bot caught on PR #2546 (replay-window check silently\n // skipped on missing ts) lived on this exact field check.\n if (typeof obj.ts !== 'number' || !Number.isFinite(obj.ts)) {\n throw new Error(`missing or non-finite-number required field \"ts\" (got ${typeof obj.ts})`);\n }\n\n // Validated above: every required field is present and well-typed.\n // The double cast through `unknown` is the standard TS idiom for\n // returning a narrowed type from a `Record<string, unknown>` after\n // runtime checks — necessary because TS doesn't infer narrowing\n // across a for-of loop with dynamic keys.\n return obj as unknown as McpIPayload;\n}\n","/**\n * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).\n *\n * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`\n * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase\n * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,\n * so the decoded multikey is always 34 bytes and the did:key always begins\n * `z6Mk` (a fixed consequence of the `0xed01` prefix).\n *\n * This is a PURE-JS port of the base58btc decoder in\n * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division\n * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS\n * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with\n * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare\n * Workers, and the browser). The encoder is the inverse, for tests and any\n * caller that emits a `did:key` from raw key bytes.\n */\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: Record<string, number> = (() => {\n const idx: Record<string, number> = {};\n for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;\n return idx;\n})();\n\nconst DID_KEY_PREFIX = 'did:key:';\nconst ED25519_MULTICODEC = [0xed, 0x01] as const; // ed25519-pub\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Decode a base58btc string to bytes using the repeated-division algorithm.\n * Returns null if the string contains a character outside the base58btc\n * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`\n * (kept algorithm-identical to avoid cross-runtime drift).\n */\nexport function base58btcDecode(str: string): Uint8Array | null {\n if (str.length === 0) return new Uint8Array(0);\n\n let zeros = 0;\n while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;\n\n // Sentinel-seeded little-endian byte accumulator.\n const bytes: number[] = [0];\n for (let i = 0; i < str.length; i++) {\n const value = BASE58_INDEX[str[i]];\n if (value === undefined) return null;\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Drop the trailing zero sentinel(s).\n let high = bytes.length;\n while (high > 0 && bytes[high - 1] === 0) high--;\n\n const out = new Uint8Array(zeros + high);\n for (let i = 0; i < high; i++) {\n out[zeros + high - 1 - i] = bytes[i];\n }\n return out;\n}\n\n/**\n * Encode bytes to a base58btc string — the exact inverse of\n * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value\n * is accumulated as little-endian base58 digits (×256 + byte) and emitted\n * big-endian. The high-order zero sentinel is dropped the same way the decoder\n * drops its trailing zeros, so a single `0x00` byte encodes to `\"1\"`, not `\"11\"`.\n */\nexport function base58btcEncode(bytes: Uint8Array): string {\n if (bytes.length === 0) return '';\n\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\n const digits: number[] = [0];\n for (let i = 0; i < bytes.length; i++) {\n let carry = bytes[i];\n for (let j = 0; j < digits.length; j++) {\n carry += digits[j] * 256;\n digits[j] = carry % 58;\n carry = Math.floor(carry / 58);\n }\n while (carry > 0) {\n digits.push(carry % 58);\n carry = Math.floor(carry / 58);\n }\n }\n\n // Drop the high-order zero sentinel(s); leading zero bytes become '1's.\n let high = digits.length;\n while (high > 0 && digits[high - 1] === 0) high--;\n\n let out = BASE58_ALPHABET[0].repeat(zeros);\n for (let i = high - 1; i >= 0; i--) {\n out += BASE58_ALPHABET[digits[i]];\n }\n return out;\n}\n\n/**\n * Recover the raw 32-byte Ed25519 public key from a `did:key:z6Mk…` string.\n * Returns null for any malformed input: wrong method, wrong multibase, invalid\n * base58, wrong decoded length, or a non-Ed25519 multicodec. Never throws —\n * callers treat null as \"not a verifiable Ed25519 did:key\".\n */\nexport function decodeDidKeyEd25519(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(DID_KEY_PREFIX)) return null;\n\n const suffix = did.slice(DID_KEY_PREFIX.length);\n if (!suffix.startsWith('z')) return null; // base58btc multibase prefix\n\n // A legit Ed25519 did:key body is fixed at 47 base58 chars. Cap the length\n // BEFORE the O(n^2) repeated-division decode: this keyid arrives from an\n // attacker-controlled Signature-Input header on the public pickup endpoint, so\n // an over-long body (which the 34-byte length check would reject anyway) must\n // not be allowed to burn quadratic event-loop CPU first.\n const body = suffix.slice(1);\n if (body.length > 64) return null;\n\n const decoded = base58btcDecode(body);\n if (!decoded || decoded.length !== ED25519_MULTIKEY_LENGTH) return null;\n if (decoded[0] !== ED25519_MULTICODEC[0] || decoded[1] !== ED25519_MULTICODEC[1]) return null;\n\n return decoded.slice(ED25519_MULTICODEC.length);\n}\n\n/** Recover the compressed SEC1 point from the HTTP profile's p256-pub\n * multicodec (0x1200). This runtime-independent codec validates carriage only;\n * the cryptographic consumer MUST validate that the point lies on P-256 before\n * trusting it or deriving a confirmation thumbprint. */\nexport function decodeDidKeyP256(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(`${DID_KEY_PREFIX}z`)) return null;\n const body = did.slice(DID_KEY_PREFIX.length + 1);\n // Bound the quadratic base58 decoder before processing untrusted keyids.\n if (body.length > 64) return null;\n const decoded = base58btcDecode(body);\n if (\n !decoded ||\n decoded.length !== 35 ||\n decoded[0] !== 0x80 ||\n decoded[1] !== 0x24 ||\n (decoded[2] !== 2 && decoded[2] !== 3)\n )\n return null;\n return decoded.slice(2);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a `did:key:z6Mk…` string. Throws\n * if the key is not exactly 32 bytes — an emitter handing in the wrong length\n * is a programming error, not untrusted input (unlike {@link decodeDidKeyEd25519}).\n */\nexport function encodeDidKeyEd25519(publicKey: Uint8Array): string {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `encodeDidKeyEd25519: expected a ${ED25519_PUBKEY_LENGTH}-byte Ed25519 public key, got ${\n publicKey instanceof Uint8Array ? `${publicKey.length} bytes` : typeof publicKey\n }`\n );\n }\n\n const multikey = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n multikey[0] = ED25519_MULTICODEC[0];\n multikey[1] = ED25519_MULTICODEC[1];\n multikey.set(publicKey, ED25519_MULTICODEC.length);\n\n return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;\n}\n","/**\n * Ed25519 keypair derivation for KYA-OS detached proofs.\n *\n * Derives a `KeyMaterial` bundle (signing key, public key, did:key, kid)\n * from a 32-byte seed. The derivation MUST agree byte-for-byte with\n * Rust's `ed25519_dalek::SigningKey::from_bytes` + did:key formatter so\n * H-1's committed test fixtures (`signer.seed` + `signer.public_key`)\n * derive identically across runtimes.\n *\n * `kid` form follows mcp-i-core PR #16 (multibase-as-fragment):\n * `did:key:z6Mk...#z6Mk...`. NOT `#keys-1`. NOT `#1`. The H-1\n * `stage2_did_key_fragment_resolution` test pins this on the verifier\n * side; this module pins it on the producer side.\n *\n * Sign-1 (#2500).\n */\n\nimport { getPublicKeyAsync } from '@noble/ed25519';\n// Pure-JS base58btc encode (not multiformats' `bases/base58` subpath):\n// that subpath's package.json `exports` map ships an `import` condition\n// only, no `require` — reaching it from this subpath's own CJS build\n// crashes with ERR_PACKAGE_PATH_NOT_EXPORTED before any application code\n// runs. `base58btcEncode` is the same dependency-free codec did:key\n// verification already uses elsewhere in this package.\nimport { base58btcEncode } from '../mcpi/did-key';\n\n/**\n * Multicodec prefix for Ed25519 verifying keys per the W3C did:key spec\n * (`0xed01` varint). Prepended to the 32-byte public key, base58btc-\n * encoded with the `z` multibase prefix to produce the did:key suffix.\n */\nconst ED25519_MULTICODEC_PREFIX = new Uint8Array([0xed, 0x01]);\n\n/**\n * Bundle of derived key material. Carries the signing key, the public\n * key, the canonical did:key DID, and the verification-method `kid`\n * (multibase-as-fragment per mcp-i-core PR #16).\n *\n * `signingKey` is a **copy** of the input seed, not a reference — see\n * `parseSigningKey` for the rationale. Treat the bundle as the owning\n * holder of the key material; the caller's original seed buffer is\n * safe to zero out after `parseSigningKey` returns.\n */\nexport interface KeyMaterial {\n /** The 32-byte Ed25519 secret seed (defensive copy of the input). */\n signingKey: Uint8Array;\n /** The 32-byte Ed25519 public verifying key. */\n publicKey: Uint8Array;\n /** The canonical did:key DID — `did:key:z6Mk...`. */\n did: string;\n /**\n * The verification-method id for this DID — multibase as fragment per\n * mcp-i-core PR #16 (`did:key:z6Mk...#z6Mk...`). Goes into the JWS\n * header `kid` field.\n */\n kid: string;\n}\n\n/**\n * Derive a `KeyMaterial` bundle from a 32-byte Ed25519 seed.\n *\n * The seed IS the signing key (per RFC 8032 § 5.1.5 — Ed25519 secret\n * keys are 32-byte seeds; the expanded scalar is computed at sign time).\n * Same seed → same `(publicKey, did, kid)` deterministically across\n * any RFC 8032 implementation.\n *\n * The input seed is **defensively copied** into the returned\n * `KeyMaterial.signingKey`. Subsequent mutations of the caller's\n * buffer (zeroization, key rotation, fixture reuse) do NOT affect\n * the key bundle. Callers that own the seed are free to scrub it\n * after this function returns.\n *\n * @throws if the seed is not exactly 32 bytes.\n */\nexport async function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial> {\n if (seed.length !== 32) {\n throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);\n }\n\n const publicKey = await getPublicKeyAsync(seed);\n\n // did:key z-encoded multibase per W3C spec: 0xed01 || pubkey, then\n // base58btc-encoded. The 'z' prefix is part of base58btc's multibase\n // alphabet; encode() returns it already prepended.\n const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);\n multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);\n multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);\n const multibase = `z${base58btcEncode(multibaseBytes)}`;\n const did = `did:key:${multibase}`;\n\n return {\n // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1\n // tests assert that mutating the input seed after this call does NOT\n // mutate the held key material.\n signingKey: Uint8Array.from(seed),\n publicKey,\n did,\n // mcp-i-core PR #16: the verification-method id is the multibase value\n // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's\n // stage2_did_key_fragment_resolution.\n kid: `${did}#${multibase}`,\n };\n}\n","/**\n * Base64url (RFC 4648 § 5) built on `atob` and `btoa` rather than Node's\n * buffer API, so it runs on every runtime the SDKs support, Cloudflare Workers\n * without `nodejs_compat` included.\n */\n\nconst BASE64URL_UNPADDED = /^[A-Za-z0-9_-]*$/;\nconst PADDING = 61; // '='\n\n/**\n * `text` without its trailing `=` padding. A backward scan, not\n * `replace(/=+$/, '')`: that regex retries from every `=` in a long run that\n * does not reach the end, which is quadratic on hostile input.\n */\nfunction withoutPadding(text: string): string {\n let end = text.length;\n while (end > 0 && text.charCodeAt(end - 1) === PADDING) end -= 1;\n return text.slice(0, end);\n}\n\n/**\n * Decode base64url, with or without `=` padding.\n *\n * Strict where Node's buffer decoder is lenient: a character outside the\n * alphabet, or a length no encoder produces (one character past a multiple of\n * four), throws a `TypeError` instead of being skipped or truncated. This\n * matches the engine's decoder.\n */\nexport function base64UrlToBytes(text: string): Uint8Array<ArrayBuffer> {\n const unpadded = withoutPadding(text);\n if (!BASE64URL_UNPADDED.test(unpadded) || unpadded.length % 4 === 1) {\n throw new TypeError('not valid base64url (RFC 4648 § 5)');\n }\n const base64 = unpadded.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/** Decode base64url to a string as UTF-8, replacing invalid sequences with U+FFFD. */\nexport function base64UrlToString(text: string): string {\n return new TextDecoder().decode(base64UrlToBytes(text));\n}\n\n/** Encode bytes as base64url without padding. */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return withoutPadding(btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_'));\n}\n","/**\n * JWS-compact envelope construction for KYA-OS detached proofs.\n *\n * Produces wire bytes the engine's H-1 parser (#2486) accepts:\n *\n * BASE64URL(header) \".\" BASE64URL(payload) \".\" BASE64URL(signature)\n *\n * where the header is `{ \"alg\": \"EdDSA\", \"kid\": \"<verification-method-id>\" }`,\n * the payload is the JCS-canonicalized `McpIPayload`, and the signature is\n * Ed25519 over `BASE64URL(header) || '.' || BASE64URL(payload)` per\n * RFC 7515 § 5.1.\n *\n * Sign-1 (#2500). Output of this function is what every TS producer in the\n * org emits — bouncer middleware (Envelope-1), Sites-1/2 e2e helpers, future\n * Sites-4 parity drivers, the Adobe trial.\n */\n\nimport { signAsync } from '@noble/ed25519';\nimport { canonicalSigningPayload, type McpIPayload } from './payload';\nimport type { KeyMaterial } from './key';\nimport { bytesToBase64Url } from '../utils/base64url';\n\n/**\n * Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop\n * into `_meta.proof.jws` of the request body per KYA-OS spec § 7.4.\n *\n * The signing input is `BASE64URL(header) || '.' || BASE64URL(payload)`,\n * NOT the canonical-JSON bytes. The canonicalization happens *inside* the\n * payload base64url segment; the Ed25519 signature happens *over* the dot-\n * separated structure. This is the RFC 7515 § 5.1 contract that H-1's\n * `verify_strict` checks against.\n *\n * @param payload — the structured KYA-OS claims (eight required fields).\n * @param key — derived via `parseSigningKey(seed)`. The header `kid` is\n * set from `key.kid` (multibase-as-fragment per mcp-i-core PR #16).\n * @returns the compact-JWS string `<headerB64>.<payloadB64>.<signatureB64>`.\n */\nexport async function signMcpiEnvelope(payload: McpIPayload, key: KeyMaterial): Promise<string> {\n const header = { alg: 'EdDSA', kid: key.kid };\n const headerJson = JSON.stringify(header);\n const headerB64 = bytesToBase64Url(new TextEncoder().encode(headerJson));\n\n const payloadB64 = bytesToBase64Url(canonicalSigningPayload(payload));\n\n // RFC 7515 § 5.1: signing input is the ASCII bytes of the dot-separated\n // header and payload. `TextEncoder` produces UTF-8, which is identical to\n // ASCII for the base64url alphabet (`A-Za-z0-9-_`) and the literal '.'.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n const signature = await signAsync(signingInput, key.signingKey);\n const signatureB64 = bytesToBase64Url(signature);\n\n return `${headerB64}.${payloadB64}.${signatureB64}`;\n}\n","/**\n * Compact-JWS parser for KYA-OS detached proofs.\n *\n * Producer-side counterpart to Sign-1's `signMcpiEnvelope`: takes the\n * wire string the engine's H-1 parser would consume and decomposes it\n * into the same logical pieces (header, payload, signature, signing\n * input). Lives in `checkpoint-shared/canonical-signer/` so producer\n * AND consumer share one wire-format implementation — the JCS / base64\n * subtleties are handled in one place, not three.\n *\n * Consumed by:\n * - `@kya-os/bouncer-middleware` (Envelope-1 / #2537)\n * - any future TS host that needs to introspect a JWS without going\n * through the WASM bridge\n *\n * The Rust engine's `jws::parse_jws_compact` is the structural mirror\n * (`rust/crates/kya-os-engine/src/jws.rs`); this module produces the\n * same logical decomposition. Cross-runtime parity here is implicit:\n * if both parsers consume the same JWS string and disagree on what's\n * inside, the H-1 fixtures would catch it.\n *\n * Sign-1 (#2500). Anti-pattern: don't write a parallel parser\n * elsewhere in the org — import from here.\n */\n\nimport { base64UrlToBytes, base64UrlToString } from '../utils/base64url';\nimport type { McpIPayload } from './payload';\nimport { validateMcpIPayload } from './payload';\n\n/**\n * The decomposed compact-JWS envelope.\n *\n * `signingInput` is stored separately so callers don't have to re-encode\n * the header + payload to verify the signature — re-encoding through a\n * different base64url implementation is a known source of \"should-be-\n * identical bytes drift differently\" canonicalization bugs (the same\n * class of risk that Sign-1's JCS parity firewall guards against on the\n * payload side).\n */\nexport interface ParsedJws {\n /** Decoded JWS Protected Header. Phase 1 only supports `alg: \"EdDSA\"`. */\n header: {\n alg: 'EdDSA';\n /** Verification-method id — multibase-as-fragment for did:key per\n * mcp-i-core PR #16 (`did:key:z...#z...`); whatever the DID\n * document declares for did:web (typically `#key-1`). */\n kid: string;\n /** Optional `typ` per RFC 7515. Bouncer ignores; preserved for\n * forward-compat with future header extensions. */\n typ?: string;\n };\n /** Decoded KYA-OS payload — the eight-field signing struct. */\n payload: McpIPayload;\n /** Raw 64-byte ed25519 signature segment. */\n signatureBytes: Uint8Array;\n /**\n * `header_b64 + \".\" + payload_b64` as ASCII bytes — the signing\n * input ed25519 verifies against per RFC 7515 § 5.1. Stored\n * verbatim from the input string (no re-encode round-trip).\n */\n signingInput: Uint8Array;\n}\n\n/**\n * Discriminated error type so consumers can map parse failures to\n * appropriate response codes (400 for malformed shape, 422 for\n * unsupported alg) without string-matching error messages.\n */\nexport class JwsParseError extends Error {\n constructor(\n /** Machine-readable failure category. */\n public readonly code:\n | 'WrongSegmentCount'\n | 'InvalidBase64'\n | 'InvalidJson'\n | 'InvalidHeaderShape'\n | 'InvalidPayloadShape'\n | 'UnsupportedAlgorithm'\n | 'InvalidSignatureLength',\n message: string\n ) {\n super(message);\n this.name = 'JwsParseError';\n }\n}\n\n/**\n * Wider intermediate shape returned by `validateJwsHeader`.\n *\n * Deliberately keeps `alg` as `string` (not `'EdDSA'`) — the validator\n * only proves it's a non-empty string, not that it's the supported\n * algorithm. Narrowing to the literal type happens at the alg-check\n * site in `parseJwsCompact`, where the failure can be surfaced under\n * the correct discriminant (`UnsupportedAlgorithm`, not\n * `InvalidHeaderShape`).\n *\n * Cursor-bot review on PR #2551: the previous version returned the\n * narrowed `ParsedJws['header']` via a double cast, which lied about\n * the runtime guarantee. Strict linters (`@typescript-eslint/no-\n * unnecessary-condition`) would have flagged the downstream\n * `header.alg !== 'EdDSA'` check as always-false and suggested\n * removing it — silently letting non-EdDSA algorithms through.\n */\ninterface ValidatedJwsHeaderShape {\n alg: string;\n kid: string;\n typ?: string;\n}\n\n/**\n * Runtime type guard for the JWS Protected Header (RFC 7515 § 4).\n *\n * Mirror of `validateMcpIPayload` for the header side of the envelope.\n * Cursor-bot review on PR #2546 caught two classes of bug the unguarded\n * `JSON.parse → cast` flow let through:\n *\n * 1. **Missing `kid`** — header parses, `header.kid === undefined`\n * typed as string, propagates into the bouncer's sidecar and gets\n * dropped by JSON.stringify → malformed payload at the remote.\n * 2. **Null JSON header** (`bnVsbA` base64url) — `JSON.parse` returns\n * `null`, `header.alg` access throws TypeError, escapes the\n * bouncer's `instanceof JwsParseError` guard → leaks as 500. Easy\n * DoS/probe vector.\n *\n * Both go away by validating before any property access. Throws plain\n * Error; `parseJwsCompact` translates into `JwsParseError('InvalidHeaderShape', …)`.\n *\n * Returns `ValidatedJwsHeaderShape` with `alg: string` (not `'EdDSA'`).\n * The literal-type narrowing is the caller's responsibility — keeping\n * the failure-category boundary clean: shape failures from this\n * validator surface as `InvalidHeaderShape`; algorithm-support failures\n * surface separately as `UnsupportedAlgorithm`.\n */\nfunction validateJwsHeader(value: unknown): ValidatedJwsHeaderShape {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n if (typeof obj.alg !== 'string' || obj.alg.length === 0) {\n throw new Error(`missing or non-string required field \"alg\" (got ${typeof obj.alg})`);\n }\n if (typeof obj.kid !== 'string' || obj.kid.length === 0) {\n throw new Error(`missing or non-string required field \"kid\" (got ${typeof obj.kid})`);\n }\n if (obj.typ !== undefined && typeof obj.typ !== 'string') {\n throw new Error(`optional field \"typ\" must be a string when present (got ${typeof obj.typ})`);\n }\n\n return obj as unknown as ValidatedJwsHeaderShape;\n}\n\n/**\n * Parse a compact-JWS string per RFC 7515 § 3.1 + § 5.1.\n *\n * Three segments separated by `.`, each base64url-encoded\n * (`A-Za-z0-9-_`, no padding). Header is JSON with at minimum\n * `alg: \"EdDSA\"` + `kid`. Payload is the JCS-canonicalized\n * `McpIPayload`. Signature segment decodes to exactly 64 bytes\n * (Ed25519 fixed-length per RFC 8032 § 5.1.6).\n *\n * @throws {@link JwsParseError} with a structured `code` for malformed\n * shape, invalid base64url, invalid JSON, unsupported algorithm, or\n * wrong signature length. Cryptographic verification is OUT of scope\n * — the engine (or `@noble/ed25519` round-trip) does that against\n * `signatureBytes` over `signingInput`.\n */\nexport function parseJwsCompact(jws: string): ParsedJws {\n const parts = jws.split('.');\n if (parts.length !== 3) {\n throw new JwsParseError(\n 'WrongSegmentCount',\n `Expected 3 dot-separated segments per RFC 7515 § 3.1; got ${parts.length}`\n );\n }\n const [headerB64, payloadB64, signatureB64] = parts;\n\n let headerJson: unknown;\n try {\n headerJson = JSON.parse(base64UrlToString(headerB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS header is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation for the header. Two cursor-bot findings on\n // PR #2546 motivate this:\n //\n // 1. A header with `{\"alg\":\"EdDSA\"}` (no `kid`) parsed successfully\n // and surfaced `header.kid === undefined` typed as string. The\n // bouncer's sidecar synthesis copied that into `meta.kid`, which\n // JSON.stringify silently drops, producing a malformed `{jws,\n // meta}` payload at the remote endpoint.\n //\n // 2. A header that decodes to JSON literal `null` (base64url of\n // `\"null\"` → `bnVsbA`) made `JSON.parse` succeed and assign\n // `null` to `header`. The subsequent `header.alg` access threw\n // a TypeError, which the bouncer's `instanceof JwsParseError`\n // guard let through — a 500 API_ERROR instead of a clean 401.\n // Trivially exploitable by an attacker.\n //\n // Both classes go away by validating the shape before any property\n // access. Same pattern as `validateMcpIPayload`.\n //\n // `validatedHeader` holds the wider `ValidatedJwsHeaderShape` (alg as\n // string) so the algorithm-support check below isn't redundant from\n // TS's perspective. After the check passes, we narrow to the final\n // `ParsedJws['header']` (alg as the 'EdDSA' literal). Cursor-bot\n // review on PR #2551: returning the narrowed type from the validator\n // would lie about the runtime guarantee and let strict linters\n // remove the alg check as \"always-false.\"\n let validatedHeader: ValidatedJwsHeaderShape;\n try {\n validatedHeader = validateJwsHeader(headerJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidHeaderShape',\n `JWS header does not match expected shape: ${(cause as Error).message}`\n );\n }\n if (validatedHeader.alg !== 'EdDSA') {\n throw new JwsParseError(\n 'UnsupportedAlgorithm',\n `Unsupported JWS alg \"${validatedHeader.alg}\"; Phase 1 only supports EdDSA`\n );\n }\n // Safe narrowing: alg has been runtime-checked === 'EdDSA' above.\n const header: ParsedJws['header'] = {\n alg: 'EdDSA',\n kid: validatedHeader.kid,\n ...(validatedHeader.typ !== undefined ? { typ: validatedHeader.typ } : {}),\n };\n\n let payloadJson: unknown;\n try {\n payloadJson = JSON.parse(base64UrlToString(payloadB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS payload is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation. Cursor-bot review on PR #2546: parsing\n // and casting `as McpIPayload` is a TS-only assertion the runtime\n // can't honor. A crafted JWS missing required fields (notably `ts`)\n // would surface as `undefined` at consumer call-sites and silently\n // skip field-presence checks (e.g., the bouncer's replay-window\n // comparison evaluates `false` on an undefined operand). Validating\n // here means every consumer of `parseJwsCompact` gets a payload\n // whose runtime guarantee matches its TypeScript guarantee.\n let payload: McpIPayload;\n try {\n payload = validateMcpIPayload(payloadJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidPayloadShape',\n `JWS payload does not match McpIPayload shape: ${(cause as Error).message}`\n );\n }\n\n // A signature segment that is not base64url is `InvalidBase64`, never\n // `InvalidSignatureLength`: consumers map the codes to HTTP statuses.\n // The header/payload segments are covered by the JSON.parse step that\n // follows their decode, so they report `InvalidJson`.\n if (!BASE64URL_ALPHABET.test(signatureB64)) {\n throw new JwsParseError(\n 'InvalidBase64',\n `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 § 5)`\n );\n }\n let signatureBytes: Uint8Array;\n try {\n signatureBytes = base64UrlToBytes(signatureB64);\n } catch {\n // In the alphabet but a length no encoder produces (one character past\n // a multiple of four). The engine's decoder rejects it the same way.\n throw new JwsParseError(\n 'InvalidBase64',\n `JWS signature segment is not a valid base64url length (RFC 4648 § 5)`\n );\n }\n if (signatureBytes.length !== 64) {\n throw new JwsParseError(\n 'InvalidSignatureLength',\n `Ed25519 signatures are 64 bytes (RFC 8032 § 5.1.6); got ${signatureBytes.length}`\n );\n }\n\n // Signing input is the ASCII bytes of the dot-separated header + payload.\n // Stored verbatim from the input string so callers don't have to re-encode\n // through a (potentially-different) base64url implementation to verify.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n\n return { header, payload, signatureBytes, signingInput };\n}\n\n/**\n * Strict base64url alphabet check (RFC 4648 § 5): `A-Za-z0-9-_` plus optional\n * `=` padding. The empty string fails it on purpose: an empty signature\n * segment is reported as `InvalidBase64` too.\n */\nconst BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;\n"],"x_google_ignoreList":[0],"mappings":";;;AAAA,SAAwB,aAAc,QAAQ,uBAAO,IAAI,IAAI,GAAG;CAC9D,IAAI,OAAO,WAAW,YAAY,MAAM,MAAM,GAC5C,MAAM,IAAI,MAAM,oBAAoB;CAGtC,IAAI,OAAO,WAAW,YAAY,CAAC,SAAS,MAAM,GAChD,MAAM,IAAI,MAAM,yBAAyB;CAG3C,IAAI,WAAW,QAAQ,OAAO,WAAW,UACvC,OAAO,KAAK,UAAU,MAAM;CAG9B,IAAI,OAAO,OAAO,WAAW,YAAY;EACvC,IAAI,KAAK,IAAI,MAAM,GACjB,MAAM,IAAI,MAAM,6BAA6B;EAE/C,KAAK,IAAI,MAAM;EACf,MAAM,SAAS,aAAa,OAAO,OAAO,GAAG,IAAI;EACjD,KAAK,OAAO,MAAM;EAClB,OAAO;CACT;CAEA,IAAI,KAAK,IAAI,MAAM,GACjB,MAAM,IAAI,MAAM,6BAA6B;CAE/C,KAAK,IAAI,MAAM;CAEf,IAAI;CACJ,IAAI,MAAM,QAAQ,MAAM,GAKtB,SAAS,IAJM,OAAO,KAAK,OAAO;EAEhC,OAAO,aADO,OAAO,UAAa,OAAO,OAAO,WAAW,OAAO,IACvC,IAAI;CACjC,CACkB,CAAC,CAAC,KAAK,GAAG,EAAE;MACzB;EACL,MAAM,QAAQ,CAAC;EACf,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK,GAAG;GAC5C,IAAI,OAAO,SAAS,UAAa,OAAO,OAAO,SAAS,UACtD;GAEF,MAAM,KAAK,GAAG,aA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iC,OAAO,KAAK,GAAG;CACzF;CA4BA,IAAI;CACJ,IAAI;EACF,kBAAkB,kBAAkB,UAAU;CAChD,SAAS,OAAO;EACd,MAAM,IAAI,cACR,sBACA,6CAA8C,MAAgB,SAChE;CACF;CACA,IAAI,gBAAgB,QAAQ,SAC1B,MAAM,IAAI,cACR,wBACA,wBAAwB,gBAAgB,IAAI,+BAC9C;CAGF,MAAM,SAA8B;EAClC,KAAK;EACL,KAAK,gBAAgB;EACrB,GAAI,gBAAgB,QAAQ,SAAY,EAAE,KAAK,gBAAgB,IAAI,IAAI,CAAC;CAC1E;CAEA,IAAI;CACJ,IAAI;EACF,cAAc,KAAK,MAAM,kBAAkB,UAAU,CAAC;CACxD,SAAS,OAAO;EACd,MAAM,IAAI,cAAc,eAAe,kCAAkC,OAAO,KAAK,GAAG;CAC1F;CAUA,IAAI;CACJ,IAAI;EACF,UAAU,oBAAoB,WAAW;CAC3C,SAAS,OAAO;EACd,MAAM,IAAI,cACR,uBACA,iDAAkD,MAAgB,SACpE;CACF;CAMA,IAAI,CAAC,mBAAmB,KAAK,YAAY,GACvC,MAAM,IAAI,cACR,iBACA,yFACF;CAEF,IAAI;CACJ,IAAI;EACF,iBAAiB,iBAAiB,YAAY;CAChD,QAAQ;EAGN,MAAM,IAAI,cACR,iBACA,sEACF;CACF;CACA,IAAI,eAAe,WAAW,IAC5B,MAAM,IAAI,cACR,0BACA,2DAA2D,eAAe,QAC5E;CAMF,MAAM,eAAe,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG,UAAU,GAAG,YAAY;CAE1E,OAAO;EAAE;EAAQ;EAAS;EAAgB;CAAa;AACzD;;;;;;AAOA,MAAM,qBAAqB"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../node_modules/.pnpm/canonicalize@3.0.0/node_modules/canonicalize/lib/canonicalize.js","../../src/canonical-signer/payload.ts","../../src/mcpi/did-key.ts","../../src/canonical-signer/key.ts","../../src/utils/base64url.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"sourcesContent":["export default function canonicalize (object, seen = new Set()) {\n if (typeof object === 'number' && isNaN(object)) {\n throw new Error('NaN is not allowed');\n }\n\n if (typeof object === 'number' && !isFinite(object)) {\n throw new Error('Infinity is not allowed');\n }\n\n if (object === null || typeof object !== 'object') {\n return JSON.stringify(object);\n }\n\n if (typeof object.toJSON === 'function') {\n if (seen.has(object)) {\n throw new Error('Circular reference detected');\n }\n seen.add(object);\n const result = canonicalize(object.toJSON(), seen);\n seen.delete(object);\n return result;\n }\n\n if (seen.has(object)) {\n throw new Error('Circular reference detected');\n }\n seen.add(object);\n\n let result;\n if (Array.isArray(object)) {\n const values = object.map((cv) => {\n const value = cv === undefined || typeof cv === 'symbol' ? null : cv;\n return canonicalize(value, seen);\n });\n result = `[${values.join(',')}]`;\n } else {\n const parts = [];\n for (const key of Object.keys(object).sort()) {\n if (object[key] === undefined || typeof object[key] === 'symbol') {\n continue;\n }\n parts.push(`${canonicalize(key)}:${canonicalize(object[key], seen)}`);\n }\n result = `{${parts.join(',')}}`;\n }\n\n seen.delete(object);\n return result;\n}\n","/**\n * Canonical KYA-OS signing payload (RFC 8785 / JCS).\n *\n * TS half of the cross-runtime parity contract pinned in\n * `rust/crates/kya-os-engine/src/signing.rs`. Same `McpIPayload` struct,\n * same JCS canonicalization, byte-identical output. The Rust engine's\n * `signing_payload` golden vector at `tests/fixtures/reference_payload.jcs`\n * is the firewall this module asserts against — if these bytes diverge,\n * every downstream signature verification claim is suspect.\n *\n * Field set is locked to KYA-OS spec § 7.4 (eight required claims) +\n * § 7.2 (ProofMeta). Wire format is camelCase per the KYA-OS JSON schema.\n *\n * Sign-1 (#2500). Do NOT extend without ratification through\n * mcp-i-core → D-design → here.\n *\n * @see rust/crates/kya-os-engine/src/signing.rs — Rust struct + JCS function\n * @see rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs — golden vector\n */\n\nimport canonicalize from 'canonicalize';\n\n/**\n * Structured KYA-OS payload signed by an Ed25519 key.\n *\n * Mirrors `kya_os_engine::signing::McpIPayload` field-for-field. Wire\n * format uses camelCase (matches Rust's `#[serde(rename_all = \"camelCase\")]`).\n *\n * Lexicographic key order on the wire (the JCS member-ordering rule):\n * `aud, iss, nonce, requestHash, responseHash, sessionId, sub, ts`\n */\nexport interface McpIPayload {\n /** Audience — the intended recipient DID or URL. */\n aud: string;\n /** Issuer — the signing principal's DID. */\n iss: string;\n /** Subject — the principal this proof is about (often equal to `iss`). */\n sub: string;\n /** Session nonce — binds the proof to the handshake that established the session. */\n nonce: string;\n /** Session identifier from the handshake response. */\n sessionId: string;\n /** Unix epoch seconds when the proof was generated. */\n ts: number;\n /** SHA-256 hash of the JCS-canonicalized request, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n requestHash: string;\n /** SHA-256 hash of the JCS-canonicalized response, formatted as `\"sha256:<64-lowercase-hex>\"`. */\n responseHash: string;\n}\n\n/**\n * Canonicalize an `McpIPayload` into the byte sequence the Ed25519\n * signature is computed over.\n *\n * **Determinism contract.** Same input MUST produce byte-identical\n * output, every time, every runtime. This function is the cross-runtime\n * parity contract — TS, .NET, Go, Python, and Rust runtimes all\n * implement it independently and MUST agree on the golden vector\n * pinned at `rust/crates/kya-os-engine/tests/fixtures/reference_payload.jcs`.\n *\n * The output is RFC 8785 (JCS) canonical JSON: keys sorted\n * lexicographically by UTF-16 code units, integers serialized without\n * a decimal point, strings escaped only as required, no whitespace.\n *\n * Implementation note: `canonicalize` (npm) is Erdtman's RFC 8785\n * reference implementation. If a future TS host reaches for a\n * different library, the parity firewall test (`canonical-signer.parity.test.ts`)\n * will catch the byte drift before it reaches production.\n */\nexport function canonicalSigningPayload(payload: McpIPayload): Uint8Array {\n const json = canonicalize(payload);\n if (json === undefined) {\n // canonicalize returns undefined for non-serializable inputs\n // (functions, symbols, etc.). McpIPayload's typed fields preclude\n // this, but the runtime check guards against `as McpIPayload` casts\n // at consumer call-sites that bypass the type contract.\n throw new Error('canonicalSigningPayload: payload contains non-serializable values');\n }\n return new TextEncoder().encode(json);\n}\n\n/**\n * Field set that MUST be present for an `McpIPayload` to be valid.\n *\n * Source of truth for `validateMcpIPayload`. The list mirrors the TS\n * `McpIPayload` interface — adding a field there without adding it\n * here is a hidden bypass for the runtime contract. New required\n * fields land in lockstep; new optional fields (post-Scope-1) get\n * a sibling list with a `typeof === 'undefined' || ...` predicate.\n */\nconst REQUIRED_STRING_FIELDS = [\n 'aud',\n 'iss',\n 'sub',\n 'nonce',\n 'sessionId',\n 'requestHash',\n 'responseHash',\n] as const;\n\n/**\n * Runtime type guard: confirms a `JSON.parse` output actually matches\n * `McpIPayload`. Required because `JSON.parse` returns `unknown`, and\n * casting `as McpIPayload` is a *compile-time* assertion that the\n * runtime can't honor — a payload missing required fields silently\n * surfaces as `undefined` at consumer call-sites and bypasses field-\n * presence checks (e.g., the bouncer's replay-window comparison\n * `meta.ts < now - 300` evaluates `false` for `undefined`, skipping\n * the timestamp defense entirely).\n *\n * Throws on the FIRST missing or wrong-typed field — no error\n * accumulation, since one missing claim is enough to reject the\n * envelope and producers should re-issue the entire proof rather than\n * patch field-by-field.\n *\n * @throws Error with a descriptive message identifying the offending\n * field. `parseJwsCompact` translates this into a structured\n * `JwsParseError('InvalidPayloadShape', ...)` for consumers branching\n * on the discriminant.\n */\nexport function validateMcpIPayload(value: unknown): McpIPayload {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n for (const field of REQUIRED_STRING_FIELDS) {\n if (typeof obj[field] !== 'string') {\n throw new Error(`missing or non-string required field \"${field}\" (got ${typeof obj[field]})`);\n }\n }\n\n // ts is the load-bearing exception — number, not string. The bug\n // cursor-bot caught on PR #2546 (replay-window check silently\n // skipped on missing ts) lived on this exact field check.\n if (typeof obj.ts !== 'number' || !Number.isFinite(obj.ts)) {\n throw new Error(`missing or non-finite-number required field \"ts\" (got ${typeof obj.ts})`);\n }\n\n // Validated above: every required field is present and well-typed.\n // The double cast through `unknown` is the standard TS idiom for\n // returning a narrowed type from a `Record<string, unknown>` after\n // runtime checks — necessary because TS doesn't infer narrowing\n // across a for-of loop with dynamic keys.\n return obj as unknown as McpIPayload;\n}\n","/**\n * did:key (Ed25519 multikey) codec — draft-kya-http-02 / H1.2 (#3245).\n *\n * Format: `did:key:z<base58btc(0xed 0x01 || pubkey32)>`\n * The multicodec prefix `0xed 0x01` identifies `ed25519-pub`; the multibase\n * prefix `z` identifies base58btc. An Ed25519 public key is always 32 bytes,\n * so the decoded multikey is always 34 bytes and the did:key always begins\n * `z6Mk` (a fixed consequence of the `0xed01` prefix).\n *\n * This is a PURE-JS port of the base58btc decoder in\n * `apps/web/workers/gateway/src/detection/did-verifier.ts` (repeated-division\n * algorithm), lifted here so the H1.2 pickup endpoint — and future H2.x TS\n * PEPs — can recover the raw key for `node:crypto` Ed25519 verification with\n * zero crypto/runtime dependencies (it runs identically in Node, Cloudflare\n * Workers, and the browser). The encoder is the inverse, for tests and any\n * caller that emits a `did:key` from raw key bytes.\n */\n\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nconst BASE58_INDEX: Record<string, number> = (() => {\n const idx: Record<string, number> = {};\n for (let i = 0; i < BASE58_ALPHABET.length; i++) idx[BASE58_ALPHABET[i]] = i;\n return idx;\n})();\n\nconst DID_KEY_PREFIX = 'did:key:';\nconst ED25519_MULTICODEC = [0xed, 0x01] as const; // ed25519-pub\nconst ED25519_PUBKEY_LENGTH = 32;\nconst ED25519_MULTIKEY_LENGTH = ED25519_MULTICODEC.length + ED25519_PUBKEY_LENGTH; // 34\n\n/**\n * Decode a base58btc string to bytes using the repeated-division algorithm.\n * Returns null if the string contains a character outside the base58btc\n * alphabet. Ported verbatim from the gateway worker's `did-verifier.ts`\n * (kept algorithm-identical to avoid cross-runtime drift).\n */\nexport function base58btcDecode(str: string): Uint8Array | null {\n if (str.length === 0) return new Uint8Array(0);\n\n let zeros = 0;\n while (zeros < str.length && str[zeros] === BASE58_ALPHABET[0]) zeros++;\n\n // Sentinel-seeded little-endian byte accumulator.\n const bytes: number[] = [0];\n for (let i = 0; i < str.length; i++) {\n const value = BASE58_INDEX[str[i]];\n if (value === undefined) return null;\n let carry = value;\n for (let j = 0; j < bytes.length; j++) {\n carry += bytes[j] * 58;\n bytes[j] = carry & 0xff;\n carry >>= 8;\n }\n while (carry > 0) {\n bytes.push(carry & 0xff);\n carry >>= 8;\n }\n }\n\n // Drop the trailing zero sentinel(s).\n let high = bytes.length;\n while (high > 0 && bytes[high - 1] === 0) high--;\n\n const out = new Uint8Array(zeros + high);\n for (let i = 0; i < high; i++) {\n out[zeros + high - 1 - i] = bytes[i];\n }\n return out;\n}\n\n/**\n * Encode bytes to a base58btc string — the exact inverse of\n * {@link base58btcDecode}. Leading zero bytes map to leading `1`s; the value\n * is accumulated as little-endian base58 digits (×256 + byte) and emitted\n * big-endian. The high-order zero sentinel is dropped the same way the decoder\n * drops its trailing zeros, so a single `0x00` byte encodes to `\"1\"`, not `\"11\"`.\n */\nexport function base58btcEncode(bytes: Uint8Array): string {\n if (bytes.length === 0) return '';\n\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n\n const digits: number[] = [0];\n for (let i = 0; i < bytes.length; i++) {\n let carry = bytes[i];\n for (let j = 0; j < digits.length; j++) {\n carry += digits[j] * 256;\n digits[j] = carry % 58;\n carry = Math.floor(carry / 58);\n }\n while (carry > 0) {\n digits.push(carry % 58);\n carry = Math.floor(carry / 58);\n }\n }\n\n // Drop the high-order zero sentinel(s); leading zero bytes become '1's.\n let high = digits.length;\n while (high > 0 && digits[high - 1] === 0) high--;\n\n let out = BASE58_ALPHABET[0].repeat(zeros);\n for (let i = high - 1; i >= 0; i--) {\n out += BASE58_ALPHABET[digits[i]];\n }\n return out;\n}\n\n/**\n * Recover the raw 32-byte Ed25519 public key from a `did:key:z6Mk…` string.\n * Returns null for any malformed input: wrong method, wrong multibase, invalid\n * base58, wrong decoded length, or a non-Ed25519 multicodec. Never throws —\n * callers treat null as \"not a verifiable Ed25519 did:key\".\n */\nexport function decodeDidKeyEd25519(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(DID_KEY_PREFIX)) return null;\n\n const suffix = did.slice(DID_KEY_PREFIX.length);\n if (!suffix.startsWith('z')) return null; // base58btc multibase prefix\n\n // A legit Ed25519 did:key body is fixed at 47 base58 chars. Cap the length\n // BEFORE the O(n^2) repeated-division decode: this keyid arrives from an\n // attacker-controlled Signature-Input header on the public pickup endpoint, so\n // an over-long body (which the 34-byte length check would reject anyway) must\n // not be allowed to burn quadratic event-loop CPU first.\n const body = suffix.slice(1);\n if (body.length > 64) return null;\n\n const decoded = base58btcDecode(body);\n if (!decoded || decoded.length !== ED25519_MULTIKEY_LENGTH) return null;\n if (decoded[0] !== ED25519_MULTICODEC[0] || decoded[1] !== ED25519_MULTICODEC[1]) return null;\n\n return decoded.slice(ED25519_MULTICODEC.length);\n}\n\n/** Recover the compressed SEC1 point from the HTTP profile's p256-pub\n * multicodec (0x1200). This runtime-independent codec validates carriage only;\n * the cryptographic consumer MUST validate that the point lies on P-256 before\n * trusting it or deriving a confirmation thumbprint. */\nexport function decodeDidKeyP256(did: string): Uint8Array | null {\n if (typeof did !== 'string' || !did.startsWith(`${DID_KEY_PREFIX}z`)) return null;\n const body = did.slice(DID_KEY_PREFIX.length + 1);\n // Bound the quadratic base58 decoder before processing untrusted keyids.\n if (body.length > 64) return null;\n const decoded = base58btcDecode(body);\n if (\n !decoded ||\n decoded.length !== 35 ||\n decoded[0] !== 0x80 ||\n decoded[1] !== 0x24 ||\n (decoded[2] !== 2 && decoded[2] !== 3)\n )\n return null;\n return decoded.slice(2);\n}\n\n/**\n * Encode a raw 32-byte Ed25519 public key as a `did:key:z6Mk…` string. Throws\n * if the key is not exactly 32 bytes — an emitter handing in the wrong length\n * is a programming error, not untrusted input (unlike {@link decodeDidKeyEd25519}).\n */\nexport function encodeDidKeyEd25519(publicKey: Uint8Array): string {\n if (!(publicKey instanceof Uint8Array) || publicKey.length !== ED25519_PUBKEY_LENGTH) {\n throw new Error(\n `encodeDidKeyEd25519: expected a ${ED25519_PUBKEY_LENGTH}-byte Ed25519 public key, got ${\n publicKey instanceof Uint8Array ? `${publicKey.length} bytes` : typeof publicKey\n }`\n );\n }\n\n const multikey = new Uint8Array(ED25519_MULTIKEY_LENGTH);\n multikey[0] = ED25519_MULTICODEC[0];\n multikey[1] = ED25519_MULTICODEC[1];\n multikey.set(publicKey, ED25519_MULTICODEC.length);\n\n return `${DID_KEY_PREFIX}z${base58btcEncode(multikey)}`;\n}\n","/**\n * Ed25519 keypair derivation for KYA-OS detached proofs.\n *\n * Derives a `KeyMaterial` bundle (signing key, public key, did:key, kid)\n * from a 32-byte seed. The derivation MUST agree byte-for-byte with\n * Rust's `ed25519_dalek::SigningKey::from_bytes` + did:key formatter so\n * H-1's committed test fixtures (`signer.seed` + `signer.public_key`)\n * derive identically across runtimes.\n *\n * `kid` form follows mcp-i-core PR #16 (multibase-as-fragment):\n * `did:key:z6Mk...#z6Mk...`. NOT `#keys-1`. NOT `#1`. The H-1\n * `stage2_did_key_fragment_resolution` test pins this on the verifier\n * side; this module pins it on the producer side.\n *\n * Sign-1 (#2500).\n */\n\nimport { getPublicKeyAsync } from '@noble/ed25519';\n// Pure-JS base58btc encode (not multiformats' `bases/base58` subpath):\n// that subpath's package.json `exports` map ships an `import` condition\n// only, no `require` — reaching it from this subpath's own CJS build\n// crashes with ERR_PACKAGE_PATH_NOT_EXPORTED before any application code\n// runs. `base58btcEncode` is the same dependency-free codec did:key\n// verification already uses elsewhere in this package.\nimport { base58btcEncode } from '../mcpi/did-key';\n\n/**\n * Multicodec prefix for Ed25519 verifying keys per the W3C did:key spec\n * (`0xed01` varint). Prepended to the 32-byte public key, base58btc-\n * encoded with the `z` multibase prefix to produce the did:key suffix.\n */\nconst ED25519_MULTICODEC_PREFIX = new Uint8Array([0xed, 0x01]);\n\n/**\n * Bundle of derived key material. Carries the signing key, the public\n * key, the canonical did:key DID, and the verification-method `kid`\n * (multibase-as-fragment per mcp-i-core PR #16).\n *\n * `signingKey` is a **copy** of the input seed, not a reference — see\n * `parseSigningKey` for the rationale. Treat the bundle as the owning\n * holder of the key material; the caller's original seed buffer is\n * safe to zero out after `parseSigningKey` returns.\n */\nexport interface KeyMaterial {\n /** The 32-byte Ed25519 secret seed (defensive copy of the input). */\n signingKey: Uint8Array;\n /** The 32-byte Ed25519 public verifying key. */\n publicKey: Uint8Array;\n /** The canonical did:key DID — `did:key:z6Mk...`. */\n did: string;\n /**\n * The verification-method id for this DID — multibase as fragment per\n * mcp-i-core PR #16 (`did:key:z6Mk...#z6Mk...`). Goes into the JWS\n * header `kid` field.\n */\n kid: string;\n}\n\n/**\n * Derive a `KeyMaterial` bundle from a 32-byte Ed25519 seed.\n *\n * The seed IS the signing key (per RFC 8032 § 5.1.5 — Ed25519 secret\n * keys are 32-byte seeds; the expanded scalar is computed at sign time).\n * Same seed → same `(publicKey, did, kid)` deterministically across\n * any RFC 8032 implementation.\n *\n * The input seed is **defensively copied** into the returned\n * `KeyMaterial.signingKey`. Subsequent mutations of the caller's\n * buffer (zeroization, key rotation, fixture reuse) do NOT affect\n * the key bundle. Callers that own the seed are free to scrub it\n * after this function returns.\n *\n * @throws if the seed is not exactly 32 bytes.\n */\nexport async function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial> {\n if (seed.length !== 32) {\n throw new Error(`parseSigningKey: expected 32-byte Ed25519 seed, got ${seed.length} bytes`);\n }\n\n const publicKey = await getPublicKeyAsync(seed);\n\n // did:key z-encoded multibase per W3C spec: 0xed01 || pubkey, then\n // base58btc-encoded. The 'z' prefix is part of base58btc's multibase\n // alphabet; encode() returns it already prepended.\n const multibaseBytes = new Uint8Array(ED25519_MULTICODEC_PREFIX.length + publicKey.length);\n multibaseBytes.set(ED25519_MULTICODEC_PREFIX, 0);\n multibaseBytes.set(publicKey, ED25519_MULTICODEC_PREFIX.length);\n const multibase = `z${base58btcEncode(multibaseBytes)}`;\n const did = `did:key:${multibase}`;\n\n return {\n // Defensive copy — see KeyMaterial.signingKey docstring. The Sign-1\n // tests assert that mutating the input seed after this call does NOT\n // mutate the held key material.\n signingKey: Uint8Array.from(seed),\n publicKey,\n did,\n // mcp-i-core PR #16: the verification-method id is the multibase value\n // as a fragment. Anything else (`#keys-1`, `#1`, etc.) breaks H-1's\n // stage2_did_key_fragment_resolution.\n kid: `${did}#${multibase}`,\n };\n}\n","/**\n * Base64url (RFC 4648 § 5) built on `atob` and `btoa` rather than Node's\n * buffer API, so it runs on every runtime the SDKs support, Cloudflare Workers\n * without `nodejs_compat` included.\n */\n\nconst BASE64URL_UNPADDED = /^[A-Za-z0-9_-]*$/;\nconst PADDING = 61; // '='\n\n/**\n * `text` without its trailing `=` padding. A backward scan, not\n * `replace(/=+$/, '')`: that regex retries from every `=` in a long run that\n * does not reach the end, which is quadratic on hostile input.\n */\nfunction withoutPadding(text: string): string {\n let end = text.length;\n while (end > 0 && text.charCodeAt(end - 1) === PADDING) end -= 1;\n return text.slice(0, end);\n}\n\n/**\n * Decode base64url, with or without `=` padding.\n *\n * Strict where Node's buffer decoder is lenient: a character outside the\n * alphabet, or a length no encoder produces (one character past a multiple of\n * four), throws a `TypeError` instead of being skipped or truncated. This\n * matches the engine's decoder.\n */\nexport function base64UrlToBytes(text: string): Uint8Array<ArrayBuffer> {\n const unpadded = withoutPadding(text);\n if (!BASE64URL_UNPADDED.test(unpadded) || unpadded.length % 4 === 1) {\n throw new TypeError('not valid base64url (RFC 4648 § 5)');\n }\n const base64 = unpadded.replace(/-/g, '+').replace(/_/g, '/');\n const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n return bytes;\n}\n\n/** Decode base64url to a string as UTF-8, replacing invalid sequences with U+FFFD. */\nexport function base64UrlToString(text: string): string {\n return new TextDecoder().decode(base64UrlToBytes(text));\n}\n\n/** Encode bytes as base64url without padding. */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return withoutPadding(btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_'));\n}\n","/**\n * JWS-compact envelope construction for KYA-OS detached proofs.\n *\n * Produces wire bytes the engine's H-1 parser (#2486) accepts:\n *\n * BASE64URL(header) \".\" BASE64URL(payload) \".\" BASE64URL(signature)\n *\n * where the header is `{ \"alg\": \"EdDSA\", \"kid\": \"<verification-method-id>\" }`,\n * the payload is the JCS-canonicalized `McpIPayload`, and the signature is\n * Ed25519 over `BASE64URL(header) || '.' || BASE64URL(payload)` per\n * RFC 7515 § 5.1.\n */\n\nimport { signAsync } from '@noble/ed25519';\nimport { canonicalSigningPayload, type McpIPayload } from './payload';\nimport type { KeyMaterial } from './key';\nimport { bytesToBase64Url } from '../utils/base64url';\n\n/**\n * Sign an `McpIPayload` and produce a compact-JWS envelope ready to drop\n * into `_meta.proof.jws` of the request body per KYA-OS spec § 7.4.\n *\n * The signing input is `BASE64URL(header) || '.' || BASE64URL(payload)`,\n * NOT the canonical-JSON bytes. The canonicalization happens *inside* the\n * payload base64url segment; the Ed25519 signature happens *over* the dot-\n * separated structure. This is the RFC 7515 § 5.1 contract that H-1's\n * `verify_strict` checks against.\n *\n * @param payload — the structured KYA-OS claims (eight required fields).\n * @param key — derived via `parseSigningKey(seed)`. The header `kid` is\n * set from `key.kid` (multibase-as-fragment per mcp-i-core PR #16).\n * @returns the compact-JWS string `<headerB64>.<payloadB64>.<signatureB64>`.\n */\nexport async function signMcpiEnvelope(payload: McpIPayload, key: KeyMaterial): Promise<string> {\n const header = { alg: 'EdDSA', kid: key.kid };\n const headerJson = JSON.stringify(header);\n const headerB64 = bytesToBase64Url(new TextEncoder().encode(headerJson));\n\n const payloadB64 = bytesToBase64Url(canonicalSigningPayload(payload));\n\n // RFC 7515 § 5.1: signing input is the ASCII bytes of the dot-separated\n // header and payload. `TextEncoder` produces UTF-8, which is identical to\n // ASCII for the base64url alphabet (`A-Za-z0-9-_`) and the literal '.'.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n const signature = await signAsync(signingInput, key.signingKey);\n const signatureB64 = bytesToBase64Url(signature);\n\n return `${headerB64}.${payloadB64}.${signatureB64}`;\n}\n","/**\n * Compact-JWS parser for KYA-OS detached proofs.\n *\n * Producer-side counterpart to Sign-1's `signMcpiEnvelope`: takes the\n * wire string the engine's H-1 parser would consume and decomposes it\n * into the same logical pieces (header, payload, signature, signing\n * input). Lives in `checkpoint-shared/canonical-signer/` so producer\n * AND consumer share one wire-format implementation — the JCS / base64\n * subtleties are handled in one place, not three.\n *\n * Consumed by:\n * - `@kya-os/bouncer-middleware` (Envelope-1 / #2537)\n * - any future TS host that needs to introspect a JWS without going\n * through the WASM bridge\n *\n * The Rust engine's `jws::parse_jws_compact` is the structural mirror\n * (`rust/crates/kya-os-engine/src/jws.rs`); this module produces the\n * same logical decomposition. Cross-runtime parity here is implicit:\n * if both parsers consume the same JWS string and disagree on what's\n * inside, the H-1 fixtures would catch it.\n *\n * Sign-1 (#2500). Anti-pattern: don't write a parallel parser\n * elsewhere in the org — import from here.\n */\n\nimport { base64UrlToBytes, base64UrlToString } from '../utils/base64url';\nimport type { McpIPayload } from './payload';\nimport { validateMcpIPayload } from './payload';\n\n/**\n * The decomposed compact-JWS envelope.\n *\n * `signingInput` is stored separately so callers don't have to re-encode\n * the header + payload to verify the signature — re-encoding through a\n * different base64url implementation is a known source of \"should-be-\n * identical bytes drift differently\" canonicalization bugs (the same\n * class of risk that Sign-1's JCS parity firewall guards against on the\n * payload side).\n */\nexport interface ParsedJws {\n /** Decoded JWS Protected Header. Phase 1 only supports `alg: \"EdDSA\"`. */\n header: {\n alg: 'EdDSA';\n /** Verification-method id — multibase-as-fragment for did:key per\n * mcp-i-core PR #16 (`did:key:z...#z...`); whatever the DID\n * document declares for did:web (typically `#key-1`). */\n kid: string;\n /** Optional `typ` per RFC 7515. Bouncer ignores; preserved for\n * forward-compat with future header extensions. */\n typ?: string;\n };\n /** Decoded KYA-OS payload — the eight-field signing struct. */\n payload: McpIPayload;\n /** Raw 64-byte ed25519 signature segment. */\n signatureBytes: Uint8Array;\n /**\n * `header_b64 + \".\" + payload_b64` as ASCII bytes — the signing\n * input ed25519 verifies against per RFC 7515 § 5.1. Stored\n * verbatim from the input string (no re-encode round-trip).\n */\n signingInput: Uint8Array;\n}\n\n/**\n * Discriminated error type so consumers can map parse failures to\n * appropriate response codes (400 for malformed shape, 422 for\n * unsupported alg) without string-matching error messages.\n */\nexport class JwsParseError extends Error {\n constructor(\n /** Machine-readable failure category. */\n public readonly code:\n | 'WrongSegmentCount'\n | 'InvalidBase64'\n | 'InvalidJson'\n | 'InvalidHeaderShape'\n | 'InvalidPayloadShape'\n | 'UnsupportedAlgorithm'\n | 'InvalidSignatureLength',\n message: string\n ) {\n super(message);\n this.name = 'JwsParseError';\n }\n}\n\n/**\n * Wider intermediate shape returned by `validateJwsHeader`.\n *\n * Deliberately keeps `alg` as `string` (not `'EdDSA'`) — the validator\n * only proves it's a non-empty string, not that it's the supported\n * algorithm. Narrowing to the literal type happens at the alg-check\n * site in `parseJwsCompact`, where the failure can be surfaced under\n * the correct discriminant (`UnsupportedAlgorithm`, not\n * `InvalidHeaderShape`).\n *\n * Cursor-bot review on PR #2551: the previous version returned the\n * narrowed `ParsedJws['header']` via a double cast, which lied about\n * the runtime guarantee. Strict linters (`@typescript-eslint/no-\n * unnecessary-condition`) would have flagged the downstream\n * `header.alg !== 'EdDSA'` check as always-false and suggested\n * removing it — silently letting non-EdDSA algorithms through.\n */\ninterface ValidatedJwsHeaderShape {\n alg: string;\n kid: string;\n typ?: string;\n}\n\n/**\n * Runtime type guard for the JWS Protected Header (RFC 7515 § 4).\n *\n * Mirror of `validateMcpIPayload` for the header side of the envelope.\n * Cursor-bot review on PR #2546 caught two classes of bug the unguarded\n * `JSON.parse → cast` flow let through:\n *\n * 1. **Missing `kid`** — header parses, `header.kid === undefined`\n * typed as string, propagates into the bouncer's sidecar and gets\n * dropped by JSON.stringify → malformed payload at the remote.\n * 2. **Null JSON header** (`bnVsbA` base64url) — `JSON.parse` returns\n * `null`, `header.alg` access throws TypeError, escapes the\n * bouncer's `instanceof JwsParseError` guard → leaks as 500. Easy\n * DoS/probe vector.\n *\n * Both go away by validating before any property access. Throws plain\n * Error; `parseJwsCompact` translates into `JwsParseError('InvalidHeaderShape', …)`.\n *\n * Returns `ValidatedJwsHeaderShape` with `alg: string` (not `'EdDSA'`).\n * The literal-type narrowing is the caller's responsibility — keeping\n * the failure-category boundary clean: shape failures from this\n * validator surface as `InvalidHeaderShape`; algorithm-support failures\n * surface separately as `UnsupportedAlgorithm`.\n */\nfunction validateJwsHeader(value: unknown): ValidatedJwsHeaderShape {\n if (value === null || typeof value !== 'object') {\n throw new Error(`expected JSON object, got ${value === null ? 'null' : typeof value}`);\n }\n const obj = value as Record<string, unknown>;\n\n if (typeof obj.alg !== 'string' || obj.alg.length === 0) {\n throw new Error(`missing or non-string required field \"alg\" (got ${typeof obj.alg})`);\n }\n if (typeof obj.kid !== 'string' || obj.kid.length === 0) {\n throw new Error(`missing or non-string required field \"kid\" (got ${typeof obj.kid})`);\n }\n if (obj.typ !== undefined && typeof obj.typ !== 'string') {\n throw new Error(`optional field \"typ\" must be a string when present (got ${typeof obj.typ})`);\n }\n\n return obj as unknown as ValidatedJwsHeaderShape;\n}\n\n/**\n * Parse a compact-JWS string per RFC 7515 § 3.1 + § 5.1.\n *\n * Three segments separated by `.`, each base64url-encoded\n * (`A-Za-z0-9-_`, no padding). Header is JSON with at minimum\n * `alg: \"EdDSA\"` + `kid`. Payload is the JCS-canonicalized\n * `McpIPayload`. Signature segment decodes to exactly 64 bytes\n * (Ed25519 fixed-length per RFC 8032 § 5.1.6).\n *\n * @throws {@link JwsParseError} with a structured `code` for malformed\n * shape, invalid base64url, invalid JSON, unsupported algorithm, or\n * wrong signature length. Cryptographic verification is OUT of scope\n * — the engine (or `@noble/ed25519` round-trip) does that against\n * `signatureBytes` over `signingInput`.\n */\nexport function parseJwsCompact(jws: string): ParsedJws {\n const parts = jws.split('.');\n if (parts.length !== 3) {\n throw new JwsParseError(\n 'WrongSegmentCount',\n `Expected 3 dot-separated segments per RFC 7515 § 3.1; got ${parts.length}`\n );\n }\n const [headerB64, payloadB64, signatureB64] = parts;\n\n let headerJson: unknown;\n try {\n headerJson = JSON.parse(base64UrlToString(headerB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS header is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation for the header. Two cursor-bot findings on\n // PR #2546 motivate this:\n //\n // 1. A header with `{\"alg\":\"EdDSA\"}` (no `kid`) parsed successfully\n // and surfaced `header.kid === undefined` typed as string. The\n // bouncer's sidecar synthesis copied that into `meta.kid`, which\n // JSON.stringify silently drops, producing a malformed `{jws,\n // meta}` payload at the remote endpoint.\n //\n // 2. A header that decodes to JSON literal `null` (base64url of\n // `\"null\"` → `bnVsbA`) made `JSON.parse` succeed and assign\n // `null` to `header`. The subsequent `header.alg` access threw\n // a TypeError, which the bouncer's `instanceof JwsParseError`\n // guard let through — a 500 API_ERROR instead of a clean 401.\n // Trivially exploitable by an attacker.\n //\n // Both classes go away by validating the shape before any property\n // access. Same pattern as `validateMcpIPayload`.\n //\n // `validatedHeader` holds the wider `ValidatedJwsHeaderShape` (alg as\n // string) so the algorithm-support check below isn't redundant from\n // TS's perspective. After the check passes, we narrow to the final\n // `ParsedJws['header']` (alg as the 'EdDSA' literal). Cursor-bot\n // review on PR #2551: returning the narrowed type from the validator\n // would lie about the runtime guarantee and let strict linters\n // remove the alg check as \"always-false.\"\n let validatedHeader: ValidatedJwsHeaderShape;\n try {\n validatedHeader = validateJwsHeader(headerJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidHeaderShape',\n `JWS header does not match expected shape: ${(cause as Error).message}`\n );\n }\n if (validatedHeader.alg !== 'EdDSA') {\n throw new JwsParseError(\n 'UnsupportedAlgorithm',\n `Unsupported JWS alg \"${validatedHeader.alg}\"; Phase 1 only supports EdDSA`\n );\n }\n // Safe narrowing: alg has been runtime-checked === 'EdDSA' above.\n const header: ParsedJws['header'] = {\n alg: 'EdDSA',\n kid: validatedHeader.kid,\n ...(validatedHeader.typ !== undefined ? { typ: validatedHeader.typ } : {}),\n };\n\n let payloadJson: unknown;\n try {\n payloadJson = JSON.parse(base64UrlToString(payloadB64));\n } catch (cause) {\n throw new JwsParseError('InvalidJson', `JWS payload is not valid JSON: ${String(cause)}`);\n }\n\n // Runtime shape validation. Cursor-bot review on PR #2546: parsing\n // and casting `as McpIPayload` is a TS-only assertion the runtime\n // can't honor. A crafted JWS missing required fields (notably `ts`)\n // would surface as `undefined` at consumer call-sites and silently\n // skip field-presence checks (e.g., the bouncer's replay-window\n // comparison evaluates `false` on an undefined operand). Validating\n // here means every consumer of `parseJwsCompact` gets a payload\n // whose runtime guarantee matches its TypeScript guarantee.\n let payload: McpIPayload;\n try {\n payload = validateMcpIPayload(payloadJson);\n } catch (cause) {\n throw new JwsParseError(\n 'InvalidPayloadShape',\n `JWS payload does not match McpIPayload shape: ${(cause as Error).message}`\n );\n }\n\n // A signature segment that is not base64url is `InvalidBase64`, never\n // `InvalidSignatureLength`: consumers map the codes to HTTP statuses.\n // The header/payload segments are covered by the JSON.parse step that\n // follows their decode, so they report `InvalidJson`.\n if (!BASE64URL_ALPHABET.test(signatureB64)) {\n throw new JwsParseError(\n 'InvalidBase64',\n `JWS signature segment contains characters outside the base64url alphabet (RFC 4648 § 5)`\n );\n }\n let signatureBytes: Uint8Array;\n try {\n signatureBytes = base64UrlToBytes(signatureB64);\n } catch {\n // In the alphabet but a length no encoder produces (one character past\n // a multiple of four). The engine's decoder rejects it the same way.\n throw new JwsParseError(\n 'InvalidBase64',\n `JWS signature segment is not a valid base64url length (RFC 4648 § 5)`\n );\n }\n if (signatureBytes.length !== 64) {\n throw new JwsParseError(\n 'InvalidSignatureLength',\n `Ed25519 signatures are 64 bytes (RFC 8032 § 5.1.6); got ${signatureBytes.length}`\n );\n }\n\n // Signing input is the ASCII bytes of the dot-separated header + payload.\n // Stored verbatim from the input string so callers don't have to re-encode\n // through a (potentially-different) base64url implementation to verify.\n const signingInput = new TextEncoder().encode(`${headerB64}.${payloadB64}`);\n\n return { header, payload, signatureBytes, signingInput };\n}\n\n/**\n * Strict base64url alphabet check (RFC 4648 § 5): `A-Za-z0-9-_` plus optional\n * `=` padding. The empty string fails it on purpose: an empty signature\n * segment is reported as `InvalidBase64` too.\n */\nconst BASE64URL_ALPHABET = /^[A-Za-z0-9_-]+=*$/;\n"],"x_google_ignoreList":[0],"mappings":";;;AAAA,SAAwB,aAAc,QAAQ,uBAAO,IAAI,IAAI,GAAG;CAC9D,IAAI,OAAO,WAAW,YAAY,MAAM,MAAM,GAC5C,MAAM,IAAI,MAAM,oBAAoB;CAGtC,IAAI,OAAO,WAAW,YAAY,CAAC,SAAS,MAAM,GAChD,MAAM,IAAI,MAAM,yBAAyB;CAG3C,IAAI,WAAW,QAAQ,OAAO,WAAW,UACvC,OAAO,KAAK,UAAU,MAAM;CAG9B,IAAI,OAAO,OAAO,WAAW,YAAY;EACvC,IAAI,KAAK,IAAI,MAAM,GACjB,MAAM,IAAI,MAAM,6BAA6B;EAE/C,KAAK,IAAI,MAAM;EACf,MAAM,SAAS,aAAa,OAAO,OAAO,GAAG,IAAI;EACjD,KAAK,OAAO,MAAM;EAClB,OAAO;CACT;CAEA,IAAI,KAAK,IAAI,MAAM,GACjB,MAAM,IAAI,MAAM,6BAA6B;CAE/C,KAAK,IAAI,MAAM;CAEf,IAAI;CACJ,IAAI,MAAM,QAAQ,MAAM,GAKtB,SAAS,IAJM,OAAO,KAAK,OAAO;EAEhC,OAAO,aADO,OAAO,UAAa,OAAO,OAAO,WAAW,OAAO,I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CAAa;AACzD;;;;;;AAOA,MAAM,qBAAqB"}
@@ -49,7 +49,17 @@ declare function parseIpv6(value: string): number[] | null;
49
49
  declare function compressIpv6(groups: number[]): string;
50
50
  declare function normalizeClientIp(raw: string | null | undefined): string | null;
51
51
  declare function resolveObservedClientAddress(input: ResolveClientIpInput): ObservedClientAddressResolution;
52
+ declare function resolveForwardedChainShadow(input: ResolveClientIpInput): ObservedClientAddressResolution;
53
+ interface ClientAddressShadow {
54
+ agree: boolean;
55
+ host: 'ip' | 'none';
56
+ shadow: 'ip' | 'none';
57
+ chainLength: number;
58
+ trustedHops: number;
59
+ reason: 'authenticated-explicit' | 'authenticated-proxy' | 'untrusted-peer' | 'invalid-chain';
60
+ }
61
+ declare function compareForwardedChainShadow(input: ResolveClientIpInput, hostResolution: ObservedClientAddressResolution): ClientAddressShadow | undefined;
52
62
  declare function resolveClientIp(input: ResolveClientIpInput): ClientIpResolution;
53
63
  //#endregion
54
- export { ClientIpTrustPolicy as a, compressIpv6 as c, resolveClientIp as d, resolveObservedClientAddress as f, ClientIpSource as i, normalizeClientIp as l, ClientIpHeaders as n, ObservedClientAddressResolution as o, ClientIpResolution as r, ResolveClientIpInput as s, ClientIpHeaderValue as t, parseIpv6 as u };
55
- //# sourceMappingURL=client-ip-B7w-uHfS.d.ts.map
64
+ export { ClientIpSource as a, ResolveClientIpInput as c, normalizeClientIp as d, parseIpv6 as f, resolveObservedClientAddress as h, ClientIpResolution as i, compareForwardedChainShadow as l, resolveForwardedChainShadow as m, ClientIpHeaderValue as n, ClientIpTrustPolicy as o, resolveClientIp as p, ClientIpHeaders as r, ObservedClientAddressResolution as s, ClientAddressShadow as t, compressIpv6 as u };
65
+ //# sourceMappingURL=client-ip-8KneiMK0.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-ip-B7w-uHfS.d.mts","names":[],"sources":["../src/utils/client-ip.ts"],"mappings":";KAQY;UAYK;EACf;EACA,QAAQ;EACR;;KAGU;EAGN;EACA;EACA,QAAQ,QAAQ;EAChB;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;;UAQI;EAER,iBAAiB;;KAGP;EACN;;EACC;EAAwB;IAAoD;EAC5E;EAA2B;IAAwB;EACpD;;KAEM;KACA,kBAAkB,UAAU,eAAe;UAEtC;EACf,SAAS;EACT;EACA;EACA;EAEA;EACA;EACA,QAAQ;;iBAuCM,UAAU;iBA2CV,aAAa;iBA8Db,kBAAkB;iBAyHlB,6BACd,OAAO,uBACN;iBA+Ia,gBAAgB,OAAO,uBAAuB"}
1
+ {"version":3,"file":"client-ip-8KneiMK0.d.mts","names":[],"sources":["../src/utils/client-ip.ts"],"mappings":";KAQY;UAYK;EACf;EACA,QAAQ;EACR;;KAGU;EAGN;EACA;EACA,QAAQ,QAAQ;EAChB;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;;UAQI;EAER,iBAAiB;;KAGP;EACN;;EACC;EAAwB;IAAoD;EAC5E;EAA2B;IAAwB;EACpD;;KAEM;KACA,kBAAkB,UAAU,eAAe;UAEtC;EACf,SAAS;EACT;EACA;EACA;EAEA;EACA;EACA,QAAQ;;iBAuCM,UAAU;iBA2CV,aAAa;iBA8Db,kBAAkB;iBAyHlB,6BACd,OAAO,uBACN;iBAuCa,4BACd,OAAO,uBACN;UAkBc;EAEf;EACA;EACA;EAEA;EAEA;EACA;;iBAUc,4BACd,OAAO,sBACP,gBAAgB,kCACf;iBA2Ia,gBAAgB,OAAO,uBAAuB"}
@@ -49,7 +49,17 @@ declare function parseIpv6(value: string): number[] | null;
49
49
  declare function compressIpv6(groups: number[]): string;
50
50
  declare function normalizeClientIp(raw: string | null | undefined): string | null;
51
51
  declare function resolveObservedClientAddress(input: ResolveClientIpInput): ObservedClientAddressResolution;
52
+ declare function resolveForwardedChainShadow(input: ResolveClientIpInput): ObservedClientAddressResolution;
53
+ interface ClientAddressShadow {
54
+ agree: boolean;
55
+ host: 'ip' | 'none';
56
+ shadow: 'ip' | 'none';
57
+ chainLength: number;
58
+ trustedHops: number;
59
+ reason: 'authenticated-explicit' | 'authenticated-proxy' | 'untrusted-peer' | 'invalid-chain';
60
+ }
61
+ declare function compareForwardedChainShadow(input: ResolveClientIpInput, hostResolution: ObservedClientAddressResolution): ClientAddressShadow | undefined;
52
62
  declare function resolveClientIp(input: ResolveClientIpInput): ClientIpResolution;
53
63
  //#endregion
54
- export { ClientIpTrustPolicy as a, compressIpv6 as c, resolveClientIp as d, resolveObservedClientAddress as f, ClientIpSource as i, normalizeClientIp as l, ClientIpHeaders as n, ObservedClientAddressResolution as o, ClientIpResolution as r, ResolveClientIpInput as s, ClientIpHeaderValue as t, parseIpv6 as u };
55
- //# sourceMappingURL=client-ip-B7w-uHfS.d.mts.map
64
+ export { ClientIpSource as a, ResolveClientIpInput as c, normalizeClientIp as d, parseIpv6 as f, resolveObservedClientAddress as h, ClientIpResolution as i, compareForwardedChainShadow as l, resolveForwardedChainShadow as m, ClientIpHeaderValue as n, ClientIpTrustPolicy as o, resolveClientIp as p, ClientIpHeaders as r, ObservedClientAddressResolution as s, ClientAddressShadow as t, compressIpv6 as u };
65
+ //# sourceMappingURL=client-ip-8KneiMK0.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-ip-B7w-uHfS.d.ts","names":[],"sources":["../src/utils/client-ip.ts"],"mappings":";KAQY;UAYK;EACf;EACA,QAAQ;EACR;;KAGU;EAGN;EACA;EACA,QAAQ,QAAQ;EAChB;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;;UAQI;EAER,iBAAiB;;KAGP;EACN;;EACC;EAAwB;IAAoD;EAC5E;EAA2B;IAAwB;EACpD;;KAEM;KACA,kBAAkB,UAAU,eAAe;UAEtC;EACf,SAAS;EACT;EACA;EACA;EAEA;EACA;EACA,QAAQ;;iBAuCM,UAAU;iBA2CV,aAAa;iBA8Db,kBAAkB;iBAyHlB,6BACd,OAAO,uBACN;iBA+Ia,gBAAgB,OAAO,uBAAuB"}
1
+ {"version":3,"file":"client-ip-8KneiMK0.d.ts","names":[],"sources":["../src/utils/client-ip.ts"],"mappings":";KAQY;UAYK;EACf;EACA,QAAQ;EACR;;KAGU;EAGN;EACA;EACA,QAAQ,QAAQ;EAChB;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;;UAQI;EAER,iBAAiB;;KAGP;EACN;;EACC;EAAwB;IAAoD;EAC5E;EAA2B;IAAwB;EACpD;;KAEM;KACA,kBAAkB,UAAU,eAAe;UAEtC;EACf,SAAS;EACT;EACA;EACA;EAEA;EACA;EACA,QAAQ;;iBAuCM,UAAU;iBA2CV,aAAa;iBA8Db,kBAAkB;iBAyHlB,6BACd,OAAO,uBACN;iBAuCa,4BACd,OAAO,uBACN;UAkBc;EAEf;EACA;EACA;EAEA;EAEA;EACA;;iBAUc,4BACd,OAAO,sBACP,gBAAgB,kCACf;iBA2Ia,gBAAgB,OAAO,uBAAuB"}