@kya-os/checkpoint-shared 1.8.0 → 1.10.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.
- package/CHANGELOG.md +61 -0
- package/README.md +1 -1
- package/dist/agent-catalog.d.mts +12 -0
- package/dist/agent-catalog.d.mts.map +1 -0
- package/dist/agent-catalog.d.ts +12 -0
- package/dist/agent-catalog.d.ts.map +1 -0
- package/dist/agent-catalog.js +105 -0
- package/dist/agent-catalog.mjs +105 -0
- package/dist/agent-catalog.mjs.map +1 -0
- package/dist/beacon-types/index.d.mts +18 -0
- package/dist/beacon-types/index.d.mts.map +1 -1
- package/dist/beacon-types/index.d.ts +18 -0
- package/dist/beacon-types/index.d.ts.map +1 -1
- package/dist/beacon-types/index.js +116 -12
- package/dist/beacon-types/index.mjs +105 -13
- package/dist/beacon-types/index.mjs.map +1 -1
- package/dist/browser-posture-5fPrsxx7.d.mts.map +1 -1
- package/dist/browser-posture-CCR1kh5e.d.ts.map +1 -1
- package/dist/browser-posture-cookie.js +1 -1
- package/dist/browser-posture-cookie.mjs +1 -1
- package/dist/browser-posture-cookie.mjs.map +1 -1
- package/dist/browser-posture-proof-verifier-DvsOmFrM.js +202 -0
- package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs +180 -0
- package/dist/browser-posture-proof-verifier-I0HP2Ics.mjs.map +1 -0
- package/dist/browser-posture-proof-verifier.d.mts +25 -0
- package/dist/browser-posture-proof-verifier.d.mts.map +1 -0
- package/dist/browser-posture-proof-verifier.d.ts +25 -0
- package/dist/browser-posture-proof-verifier.d.ts.map +1 -0
- package/dist/browser-posture-proof-verifier.js +7 -0
- package/dist/browser-posture-proof-verifier.mjs +3 -0
- package/dist/browser-posture-proof.d.mts +3 -18
- package/dist/browser-posture-proof.d.mts.map +1 -1
- package/dist/browser-posture-proof.d.ts +3 -18
- package/dist/browser-posture-proof.d.ts.map +1 -1
- package/dist/browser-posture-proof.js +6 -131
- package/dist/browser-posture-proof.mjs +1 -126
- package/dist/browser-posture-proof.mjs.map +1 -1
- package/dist/browser-posture.js +36 -5
- package/dist/browser-posture.mjs +36 -5
- package/dist/browser-posture.mjs.map +1 -1
- package/dist/browser.d.mts +0 -282
- package/dist/browser.d.mts.map +1 -1
- package/dist/browser.d.ts +0 -282
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/browser.mjs.map +1 -1
- package/dist/canonical-signer/index.mjs.map +1 -1
- package/dist/consent-handoff.d.mts +0 -3
- package/dist/consent-handoff.d.mts.map +1 -1
- package/dist/consent-handoff.d.ts +0 -3
- package/dist/consent-handoff.d.ts.map +1 -1
- package/dist/consent-handoff.mjs.map +1 -1
- package/dist/default-sign-in-host.d.mts +10 -0
- package/dist/default-sign-in-host.d.mts.map +1 -0
- package/dist/default-sign-in-host.d.ts +10 -0
- package/dist/default-sign-in-host.d.ts.map +1 -0
- package/dist/default-sign-in-host.js +72 -0
- package/dist/default-sign-in-host.mjs +66 -0
- package/dist/default-sign-in-host.mjs.map +1 -0
- package/dist/deploy/index.d.mts +1 -0
- package/dist/deploy/index.d.mts.map +1 -1
- package/dist/deploy/index.d.ts +1 -0
- package/dist/deploy/index.d.ts.map +1 -1
- package/dist/deploy/index.js +9 -1
- package/dist/deploy/index.mjs +9 -1
- package/dist/deploy/index.mjs.map +1 -1
- package/dist/errors/index.d.mts +1 -0
- package/dist/errors/index.d.mts.map +1 -1
- package/dist/errors/index.d.ts +1 -0
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +5 -2
- package/dist/errors/index.mjs +5 -2
- package/dist/errors/index.mjs.map +1 -1
- package/dist/{fetcher-CivUCbhL.d.ts → fetcher-CCw4Q95g.d.ts} +2 -2
- package/dist/{fetcher-CivUCbhL.d.ts.map → fetcher-CCw4Q95g.d.ts.map} +1 -1
- package/dist/{fetcher-cXQsbm6s.d.mts → fetcher-CZfLcbRZ.d.mts} +2 -2
- package/dist/{fetcher-cXQsbm6s.d.mts.map → fetcher-CZfLcbRZ.d.mts.map} +1 -1
- package/dist/gateway-client-ip.d.mts +0 -2
- package/dist/gateway-client-ip.d.mts.map +1 -1
- package/dist/gateway-client-ip.d.ts +0 -2
- package/dist/gateway-client-ip.d.ts.map +1 -1
- package/dist/gateway-client-ip.mjs.map +1 -1
- package/dist/host-adapter/index.d.mts +1 -1
- package/dist/host-adapter/index.d.ts +1 -1
- package/dist/host-adapter/index.js +1 -1
- package/dist/host-adapter/index.mjs +1 -1
- package/dist/{host-adapter-DHyISsIf.mjs → host-adapter-BKdQHwbi.mjs} +2 -2
- package/dist/{host-adapter-DHyISsIf.mjs.map → host-adapter-BKdQHwbi.mjs.map} +1 -1
- package/dist/{host-adapter-0F8EpbD6.js → host-adapter-bWftXA9T.js} +1 -1
- package/dist/{index-CXbOY7gB.d.ts → index-Cdv_FH0H.d.ts} +3 -3
- package/dist/{index-CXbOY7gB.d.ts.map → index-Cdv_FH0H.d.ts.map} +1 -1
- package/dist/{index-B3cHxr3O.d.mts → index-DL_dmQBY.d.mts} +3 -3
- package/dist/{index-B3cHxr3O.d.mts.map → index-DL_dmQBY.d.mts.map} +1 -1
- package/dist/index.d.mts +124 -463
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +124 -463
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +52 -468
- package/dist/index.mjs +40 -435
- package/dist/index.mjs.map +1 -1
- package/dist/{kya-http-error-codes-UYb1zpGM.js → kya-http-error-codes-B4rUmUEI.js} +2 -0
- package/dist/{kya-http-error-codes-7ewV5RuK.d.ts → kya-http-error-codes-C14E4gi3.d.mts} +2 -1
- package/dist/kya-http-error-codes-C14E4gi3.d.mts.map +1 -0
- package/dist/{kya-http-error-codes-7ewV5RuK.d.mts → kya-http-error-codes-C14E4gi3.d.ts} +2 -1
- package/dist/kya-http-error-codes-C14E4gi3.d.ts.map +1 -0
- package/dist/{kya-http-error-codes-C2JiWPsi.mjs → kya-http-error-codes-DSBrxNry.mjs} +3 -1
- package/dist/kya-http-error-codes-DSBrxNry.mjs.map +1 -0
- package/dist/kya-http.d.mts +3 -3
- package/dist/kya-http.d.ts +3 -3
- package/dist/kya-http.js +7 -3
- package/dist/kya-http.mjs +3 -3
- package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
- package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
- package/dist/mcpi/dashboard-config/index.mjs.map +1 -1
- package/dist/{patterns-B2r7M9wR.js → patterns-CiMpbdAF.js} +1 -1
- package/dist/{patterns-B7dQoeE3.mjs → patterns-D4OAsNQY.mjs} +2 -2
- package/dist/{patterns-B7dQoeE3.mjs.map → patterns-D4OAsNQY.mjs.map} +1 -1
- package/dist/patterns.js +1 -1
- package/dist/patterns.mjs +1 -1
- package/dist/policy/fetcher.d.mts +1 -1
- package/dist/policy/fetcher.d.ts +1 -1
- package/dist/policy/schemas.d.mts +1 -1
- package/dist/policy/schemas.d.ts +1 -1
- package/dist/{registered-sid-DVGTSH0L.js → registered-sid-BZfDOfXy.js} +107 -4
- package/dist/{registered-sid-26hNxp6t.mjs → registered-sid-CS9V8nPr.mjs} +85 -6
- package/dist/registered-sid-CS9V8nPr.mjs.map +1 -0
- package/dist/{registered-sid-D6KCaT1E.d.ts → registered-sid-CnWIU_l1.d.mts} +13 -2
- package/dist/registered-sid-CnWIU_l1.d.mts.map +1 -0
- package/dist/{registered-sid-D6KCaT1E.d.mts → registered-sid-CnWIU_l1.d.ts} +13 -2
- package/dist/registered-sid-CnWIU_l1.d.ts.map +1 -0
- package/dist/{schemas-02CI7jgm.d.mts → schemas-BhC88D1-.d.mts} +17 -17
- package/dist/{schemas-02CI7jgm.d.mts.map → schemas-BhC88D1-.d.mts.map} +1 -1
- package/dist/{schemas-C_3C72SR.d.ts → schemas-DZa1ouGs.d.ts} +17 -17
- package/dist/{schemas-C_3C72SR.d.ts.map → schemas-DZa1ouGs.d.ts.map} +1 -1
- package/dist/signals/index.d.mts.map +1 -1
- package/dist/signals/index.d.ts.map +1 -1
- package/dist/signals/index.js +4 -0
- package/dist/signals/index.mjs +4 -0
- package/dist/signals/index.mjs.map +1 -1
- package/dist/tool-protection/index.d.mts +12 -0
- package/dist/tool-protection/index.d.mts.map +1 -1
- package/dist/tool-protection/index.d.ts +12 -0
- package/dist/tool-protection/index.d.ts.map +1 -1
- package/dist/tool-protection/index.js +46 -0
- package/dist/tool-protection/index.mjs +44 -1
- package/dist/tool-protection/index.mjs.map +1 -1
- package/fixtures/kya-http/error-codes.json +2 -1
- package/package.json +19 -3
- package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +0 -1
- package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +0 -1
- package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +0 -1
- package/dist/registered-sid-26hNxp6t.mjs.map +0 -1
- package/dist/registered-sid-D6KCaT1E.d.mts.map +0 -1
- package/dist/registered-sid-D6KCaT1E.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)}function O(e){if(!e||typeof e!=`object`)return!1;let t=e;return!!(t.projectId&&typeof t.projectId==`string`)}function k(e){if(!e||typeof e!=`object`)return!1;let t=e;return!!(t.projectId&&typeof t.projectId==`string`&&Array.isArray(t.events)&&t.events.every(e=>D(e))&&t.sessionId&&typeof t.sessionId==`string`&&t.batchId&&t.timestamp&&typeof t.timestamp==`number`)}function A(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.userId==`string`&&e.userId.length>0}function j(e){let t=e&&typeof e==`object`?e:{};if(!t.projectId||typeof t.projectId!=`string`)throw Error(`Project ID is required`);return{projectId:t.projectId,environment:t.environment,tags:t.tags,identity:A(t.identity)?t.identity:void 0,endpoint:t.endpoint,enabled:t.enabled!==!1,debug:t.debug===!0,logLevel:t.logLevel||`error`,respectDoNotTrack:t.respectDoNotTrack!==!1,anonymizeIp:t.anonymizeIp===!0,sessionTimeout:t.sessionTimeout||void 0,sessionCookieName:t.sessionCookieName||`_as_beacon_session`,batchSize:t.batchSize||10,flushInterval:t.flushInterval||5e3,maxQueueSize:t.maxQueueSize||100,retryAttempts:t.retryAttempts||3,retryDelay:t.retryDelay||2e3,useWorker:t.useWorker!==!1,workerUrl:t.workerUrl,workerConfig:t.workerConfig}}const M={isBeaconEvent:D,isBeaconConfig:O,isBeaconBatch:k,isWorkerMessage(e){if(!e||typeof e!=`object`)return!1;let t=e;return!!(t.id&&t.type&&[`request`,`response`,`error`,`heartbeat`,`status`].includes(t.type)&&typeof t.timestamp==`number`)},isWorkerError(e){if(!e||typeof e!=`object`)return!1;let t=e;return!!(t.type&&t.message&&typeof t.timestamp==`number`&&typeof t.recoverable==`boolean`)},isWorkerCapabilities(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.workerAPI==`boolean`&&typeof t.sharedArrayBuffer==`boolean`&&typeof t.transferableObjects==`boolean`&&typeof t.offscreenCanvas==`boolean`}};function N(e){let t=e&&typeof e==`object`?e:{};return{enabled:t.enabled!==!1,url:t.url,heartbeatInterval:t.heartbeatInterval||5e3,maxUnhealthyCount:t.maxUnhealthyCount||3,maxRetries:t.maxRetries||3,retryDelay:t.retryDelay||1e3,messageTimeout:t.messageTimeout||3e4,compressionThreshold:t.compressionThreshold||1024,allowFallback:t.allowFallback!==!1,crossOriginIsolated:t.crossOriginIsolated===!0}}function P(e){let t=e;if(!t||typeof t!=`object`)throw Error(`Invalid worker message`);return{id:t.id||crypto.randomUUID(),type:t.type||`request`,action:t.action,payload:t.payload,timestamp:t.timestamp||Date.now(),compressed:t.compressed===!0,priority:t.priority||`normal`,correlationId:t.correlationId}}function F(e){let t=e;return!t||typeof t!=`object`?{type:`unknown`,message:String(e),timestamp:Date.now(),recoverable:!1}:{type:t.type||`unknown`,message:t.message||`Unknown error`,stack:t.stack,timestamp:t.timestamp||Date.now(),recoverable:!!t.recoverable}}function I(e){let t=e&&typeof e==`object`?e:{};return{workerAPI:t.workerAPI!==!1,sharedArrayBuffer:t.sharedArrayBuffer===!0,transferableObjects:t.transferableObjects===!0,offscreenCanvas:t.offscreenCanvas===!0,webAssembly:t.webAssembly===!0,atomics:t.atomics===!0,bigInt:t.bigInt===!0,csp:t.csp||{workerSrc:!1,scriptSrc:!1,blobUrls:!1,inlineWorkers:!1},performance:t.performance||{memory:!1,measureUserAgentSpecificMemory:!1}}}function L(e){let t=e;if(!t||typeof t!=`object`)throw Error(`Invalid worker task`);return{id:t.id||crypto.randomUUID(),type:t.type||`process`,data:t.data,priority:t.priority||`normal`,createdAt:t.createdAt||Date.now(),startedAt:t.startedAt,completedAt:t.completedAt,error:t.error,maxRetries:t.maxRetries,retries:t.retries,timeout:t.timeout}}function R(e){let t=e&&typeof e==`object`?e:{};return{useRequestIdleCallback:t.useRequestIdleCallback!==!1,idleTimeout:t.idleTimeout||1e4,chunkSize:t.chunkSize||10,throttleMs:t.throttleMs||16,maxExecutionTime:t.maxExecutionTime||50}}function z(e){let t=e&&typeof e==`object`?e:{};return{maxAttempts:t.maxAttempts||3,baseDelay:t.baseDelay||1e3,maxDelay:t.maxDelay||3e4,factor:t.factor||2,jitter:t.jitter!==!1}}function B(e){let t=e&&typeof e==`object`?e:{};return{threshold:t.threshold||5,timeout:t.timeout||6e4,resetTimeout:t.resetTimeout||3e4}}function V(e){let t=e;if(!t||typeof t!=`object`)throw Error(`Invalid offline queue entry`);return{id:t.id||`${Date.now()}_${Math.random().toString(36).substr(2,9)}`,events:Array.isArray(t.events)?t.events:[],timestamp:t.timestamp||Date.now(),expiresAt:t.expiresAt||Date.now()+864e5,retryCount:t.retryCount||0,size:t.size||0}}function H(e){let t=e&&typeof e==`object`?e:{};return{memoryUsage:t.memoryUsage||0,cpuUsage:t.cpuUsage||0,taskCount:t.taskCount||0,activeWorkers:t.activeWorkers||0,pendingTasks:t.pendingTasks||0,completedTasks:t.completedTasks||0,failedTasks:t.failedTasks||0,averageTaskDuration:t.averageTaskDuration||0}}function U(e){let t=e&&typeof e==`object`?e:{};return{maxWorkers:t.maxWorkers||4,minWorkers:t.minWorkers||1,workerIdleTimeout:t.workerIdleTimeout||6e4,taskQueueSize:t.taskQueueSize||100,resourceLimits:t.resourceLimits||{}}}function W(e){let t=e;if(!t||typeof t!=`object`)throw Error(`Invalid beacon worker message`);return{type:t.type||`collect`,data:t.data,messageId:t.messageId||crypto.randomUUID(),timestamp:t.timestamp||Date.now()}}const G={batchSize:10,flushInterval:5e3,sessionCookieName:`_as_beacon_session`,retryAttempts:3,retryDelay:2e3},K={NETWORK:`network`,VALIDATION:`validation`,TIMEOUT:`timeout`,UNKNOWN:`unknown`};export{G as DEFAULT_CONFIG,K as ERROR_TYPES,M as Guards,a as compressIpv6,c as normalizeClientIp,j as parseBeaconConfig,W as parseBeaconWorkerMessage,B as parseCircuitBreakerConfig,R as parseFallbackOptions,i as parseIpv6,V as parseOfflineQueueEntry,H as parseResourceUsage,z as parseRetryStrategy,I as parseWorkerCapabilities,N as parseWorkerConfig,F as parseWorkerError,P as parseWorkerMessage,U as parseWorkerPoolConfig,L as parseWorkerTask,E as resolveClientIp,v as resolveObservedClientAddress,k as validateBeaconBatch,O as validateBeaconConfig,D as validateBeaconEvent};
|
|
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};
|
|
2
2
|
//# sourceMappingURL=browser.mjs.map
|
package/dist/browser.mjs.map
CHANGED
|
@@ -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 * Browser-specific exports for Checkpoint\n *\n * Minimal bundle for browser/beacon usage without:\n * - Detection rules (server-side only)\n * - YAML parsing (build-time only)\n * - Zod schemas (replaced with simple validators)\n * - Server-side utilities\n *\n * Bundle target: <5KB minified\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// CORE TYPES (TypeScript interfaces only, zero runtime)\n// ============================================================================\n\nexport interface BrowserDetectionResult {\n category: AgentCategory;\n confidence: ConfidenceLevel;\n agent?: AgentInfo;\n}\n\n/**\n * @deprecated Use BrowserDetectionResult.\n */\nexport type { BrowserDetectionResult as DetectionResult };\n\nexport type AgentCategory = 'human' | 'bot' | 'agent';\nexport type ConfidenceLevel = 'low' | 'medium' | 'high' | 'very_high';\n\nexport interface AgentInfo {\n name: string;\n version?: string;\n url?: string;\n company?: string;\n}\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\nexport interface BeaconBatch {\n projectId: string;\n events: BeaconEvent[];\n sessionId: string;\n batchId: string;\n timestamp: number;\n /**\n * Carries `BeaconConfig.anonymizeIp` to the server. The server truncates\n * the persisted IP to /24 (IPv4) or /64 (IPv6) before storage when true.\n */\n anonymizeIp?: boolean;\n /** Nonce-bound ingest (build item 5): the value from the prior 202 response's `nonce`. See checkpoint-beacon's `BeaconBatch` for the full doc comment. */\n nonce?: string;\n /** Declares this client echoes nonces — see checkpoint-beacon's `BeaconBatch`. */\n nonceEcho?: boolean;\n}\n\nexport interface BatchEvent {\n id: string;\n event: BeaconEvent;\n timestamp: number;\n retryCount: number;\n hash: string;\n priority: 'low' | 'normal' | 'high' | 'critical';\n}\n\n// ============================================================================\n// CONFIG TYPES\n// ============================================================================\n\n/** Who the host site says the visitor is. Mirrors `beacon-types`' own copy — this bundle imports nothing by design, so the type is restated rather than shared. */\nexport interface BeaconIdentity {\n userId: string;\n}\n\nexport interface BeaconConfig {\n projectId: string; // Same as pixel's data-project-id\n environment?: 'development' | 'staging' | 'production' | string;\n tags?: Record<string, string | number | boolean>;\n identity?: BeaconIdentity;\n /** Where batches are POSTed. Defaults to the endpoint in NETWORK_CONTRACT.md. */\n endpoint?: string;\n enabled?: boolean;\n debug?: boolean;\n logLevel?: 'error' | 'warn' | 'info' | 'debug';\n\n // Privacy\n respectDoNotTrack?: boolean;\n anonymizeIp?: boolean;\n\n // Session\n sessionTimeout?: number;\n sessionCookieName?: string;\n\n // Transport\n batchSize?: number;\n flushInterval?: number;\n maxQueueSize?: number;\n retryAttempts?: number;\n retryDelay?: number;\n\n // Worker\n useWorker?: boolean;\n workerUrl?: string;\n workerConfig?: WorkerConfig;\n}\n\nexport interface TransportConfig {\n batchSize?: number;\n flushInterval?: number;\n maxRetries: number;\n retryDelayBase: number;\n offlineQueueSize: number;\n useCompression: boolean;\n compressionThreshold: number;\n networkAdaptation: boolean;\n dedupWindow: number;\n}\n\nexport interface WorkerConfig {\n enabled?: boolean;\n url?: string;\n heartbeatInterval?: number;\n maxUnhealthyCount?: number;\n maxRetries?: number;\n retryDelay?: number;\n restartDelay?: number;\n messageTimeout?: number;\n compressionThreshold?: number;\n allowFallback?: boolean;\n crossOriginIsolated?: boolean;\n maxRestartAttempts?: number;\n terminationTimeout?: number;\n taskTimeout?: number;\n fallbackDelay?: number;\n enableFallback?: boolean;\n}\n\n// ============================================================================\n// TRANSPORT TYPES\n// ============================================================================\n\nexport interface TransportOptions {\n immediate?: boolean;\n priority?: 'low' | 'normal' | 'high' | 'critical';\n retry?: boolean;\n timeout?: number;\n}\n\nexport interface TransportResponse {\n success: boolean;\n timestamp: number;\n batchId?: string;\n error?: string;\n}\n\nexport type TransportState = 'idle' | 'sending' | 'offline' | 'paused' | 'error';\n\nexport interface TransportMetrics {\n eventsSent: number;\n eventsFailed: number;\n eventsQueued: number;\n batchesSent: number;\n batchesFailed: number;\n bytesTransferred: number;\n compressionRatio?: number;\n averageLatency?: number;\n lastSuccessTimestamp?: number;\n lastErrorTimestamp?: number;\n}\n\nexport type ConnectionType =\n | 'bluetooth'\n | 'cellular'\n | 'ethernet'\n | 'none'\n | 'wifi'\n | 'wimax'\n | 'other'\n | 'unknown';\n\nexport interface NetworkInfo {\n type?: string;\n effectiveType?: string;\n downlink?: number;\n rtt?: number;\n saveData?: boolean;\n}\n\n// ============================================================================\n// WORKER TYPES\n// ============================================================================\n\nexport type MessagePriority = 'low' | 'normal' | 'high' | 'critical';\n\nexport type WorkerErrorType =\n | 'initialization'\n | 'runtime'\n | 'communication'\n | 'timeout'\n | 'memory'\n | 'unknown';\n\nexport type WorkerAction =\n | 'process'\n | 'init'\n | 'terminate'\n | 'pause'\n | 'resume'\n | 'status'\n | 'health';\n\nexport type WorkerMessageType = 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n\nexport interface WorkerMessage {\n id: string;\n type: 'request' | 'response' | 'error' | 'heartbeat' | 'status';\n action?: string;\n payload?: unknown;\n timestamp: number;\n compressed?: boolean;\n priority?: MessagePriority;\n correlationId?: string;\n}\n\nexport type WorkerState =\n | 'idle'\n | 'initializing'\n | 'ready'\n | 'processing'\n | 'error'\n | 'terminating'\n | 'terminated';\n\nexport type WorkerHealthStatus = 'healthy' | 'degraded' | 'unhealthy' | 'unknown';\n\nexport interface WorkerMetrics {\n tasksProcessed: number;\n tasksFailed: number;\n averageProcessingTime: number;\n memoryUsage?: number;\n cpuUsage?: number;\n healthStatus: WorkerHealthStatus;\n lastHealthCheck: number;\n restartCount: number;\n errorRate: number;\n}\n\nexport interface WorkerError {\n type: string;\n message: string;\n stack?: string;\n timestamp: number;\n recoverable: boolean;\n}\n\nexport interface WorkerCapabilities {\n workerAPI: boolean;\n sharedArrayBuffer: boolean;\n transferableObjects: boolean;\n offscreenCanvas: boolean;\n webAssembly: boolean;\n atomics: boolean;\n bigInt: boolean;\n csp: {\n workerSrc: boolean;\n scriptSrc: boolean;\n blobUrls: boolean;\n inlineWorkers: boolean;\n };\n performance: {\n memory: boolean;\n measureUserAgentSpecificMemory: boolean;\n };\n}\n\nexport interface WorkerTask {\n id: string;\n type: string;\n data: unknown;\n priority: 'low' | 'normal' | 'high' | 'critical';\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n error?: WorkerError;\n maxRetries?: number;\n retries?: number;\n timeout?: number;\n}\n\nexport interface FallbackOptions {\n useRequestIdleCallback: boolean;\n idleTimeout: number;\n chunkSize: number;\n throttleMs: number;\n maxExecutionTime: number;\n}\n\nexport interface ResourceUsage {\n memoryUsage: number;\n cpuUsage: number;\n taskCount: number;\n activeWorkers: number;\n pendingTasks: number;\n completedTasks: number;\n failedTasks: number;\n averageTaskDuration: number;\n memory?: number;\n cpu?: number;\n tasks?: number;\n}\n\nexport interface WorkerPoolConfig {\n maxWorkers: number;\n minWorkers: number;\n workerIdleTimeout: number;\n taskQueueSize: number;\n resourceLimits: Record<string, unknown>;\n autoScale?: boolean;\n scaleUpThreshold?: number;\n scaleDownThreshold?: number;\n}\n\nexport type BeaconWorkerMessageType = 'init' | 'collect' | 'flush' | 'config' | 'status' | 'error';\n\nexport type ProtocolVersion = '1.0' | '1.1' | '2.0';\n\nexport interface BeaconWorkerMessage {\n type: BeaconWorkerMessageType;\n data?: unknown;\n payload?: unknown;\n messageId: string;\n timestamp: number;\n id?: string;\n}\n\n// ============================================================================\n// CIRCUIT BREAKER & RETRY\n// ============================================================================\n\nexport interface CircuitBreakerConfig {\n threshold: number;\n timeout: number;\n resetTimeout: number;\n}\n\nexport type CircuitBreakerState = 'closed' | 'open' | 'half-open';\n\nexport interface RetryStrategy {\n maxAttempts: number;\n baseDelay: number;\n maxDelay: number;\n factor: number;\n jitter: boolean;\n}\n\n// ============================================================================\n// OFFLINE QUEUE\n// ============================================================================\n\nexport interface OfflineQueueEntry {\n id: string;\n events: BeaconEvent[];\n timestamp: number;\n expiresAt: number;\n retryCount: number;\n size: number;\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\n/**\n * Validates beacon configuration\n */\nexport function validateBeaconConfig(config: unknown): config is BeaconConfig {\n if (!config || typeof config !== 'object') return false;\n const c = config as Record<string, unknown>;\n return !!(c.projectId && typeof c.projectId === 'string');\n}\n\n/**\n * Validates a beacon batch\n */\nexport function validateBeaconBatch(batch: unknown): batch is BeaconBatch {\n if (!batch || typeof batch !== 'object') return false;\n const b = batch as Record<string, unknown>;\n return !!(\n b.projectId &&\n typeof b.projectId === 'string' &&\n Array.isArray(b.events) &&\n b.events.every((e: unknown) => validateBeaconEvent(e)) &&\n b.sessionId &&\n typeof b.sessionId === 'string' &&\n b.batchId &&\n b.timestamp &&\n typeof b.timestamp === 'number'\n );\n}\n\n/** Rejects an identity naming nobody: downstream this becomes `detections.user_id`, where an empty string reads as \"identified\" while identifying no one. */\nfunction isBrowserBeaconIdentity(value: unknown): value is BeaconIdentity {\n return (\n typeof value === 'object' &&\n value !== null &&\n // Arrays are objects and would otherwise pass. `beacon-types`' own guard\n // rejects them via `isRecord`; these two are meant to agree, and a silent\n // divergence between two allowlists is exactly what this file's comments\n // promise is not happening.\n !Array.isArray(value) &&\n typeof (value as BeaconIdentity).userId === 'string' &&\n (value as BeaconIdentity).userId.length > 0\n );\n}\n\n/**\n * Parse beacon config with defaults\n */\nexport function parseBeaconConfig(input: unknown): BeaconConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n\n if (!config.projectId || typeof config.projectId !== 'string') {\n throw new Error('Project ID is required');\n }\n\n return {\n projectId: config.projectId as string,\n environment: config.environment as string | undefined,\n tags: config.tags as Record<string, string | number | boolean> | undefined,\n identity: isBrowserBeaconIdentity(config.identity) ? config.identity : undefined,\n endpoint: config.endpoint as string | undefined,\n enabled: config.enabled !== false,\n debug: config.debug === true,\n logLevel: (config.logLevel as 'error' | 'warn' | 'info' | 'debug' | undefined) || 'error',\n respectDoNotTrack: config.respectDoNotTrack !== false,\n anonymizeIp: config.anonymizeIp === true,\n sessionTimeout: (config.sessionTimeout as number | undefined) || undefined,\n sessionCookieName: (config.sessionCookieName as string | undefined) || '_as_beacon_session',\n batchSize: (config.batchSize as number | undefined) || 10,\n flushInterval: (config.flushInterval as number | undefined) || 5000,\n maxQueueSize: (config.maxQueueSize as number | undefined) || 100,\n retryAttempts: (config.retryAttempts as number | undefined) || 3,\n retryDelay: (config.retryDelay as number | undefined) || 2000,\n useWorker: config.useWorker !== false,\n workerUrl: config.workerUrl as string | undefined,\n workerConfig: config.workerConfig as WorkerConfig | undefined,\n };\n}\n\n/**\n * Simple type guards\n */\nexport const Guards = {\n isBeaconEvent: validateBeaconEvent,\n isBeaconConfig: validateBeaconConfig,\n isBeaconBatch: validateBeaconBatch,\n\n isWorkerMessage(msg: unknown): msg is WorkerMessage {\n if (!msg || typeof msg !== 'object') return false;\n const m = msg as Record<string, unknown>;\n return !!(\n m.id &&\n m.type &&\n ['request', 'response', 'error', 'heartbeat', 'status'].includes(m.type as string) &&\n typeof m.timestamp === 'number'\n );\n },\n\n isWorkerError(err: unknown): err is WorkerError {\n if (!err || typeof err !== 'object') return false;\n const e = err as Record<string, unknown>;\n return !!(\n e.type &&\n e.message &&\n typeof e.timestamp === 'number' &&\n typeof e.recoverable === 'boolean'\n );\n },\n\n isWorkerCapabilities(cap: unknown): cap is WorkerCapabilities {\n if (!cap || typeof cap !== 'object') return false;\n const c = cap as Record<string, unknown>;\n return !!(\n typeof c.workerAPI === 'boolean' &&\n typeof c.sharedArrayBuffer === 'boolean' &&\n typeof c.transferableObjects === 'boolean' &&\n typeof c.offscreenCanvas === 'boolean'\n );\n },\n};\n\n// ============================================================================\n// PARSE FUNCTIONS (with defaults and validation)\n// ============================================================================\n\nexport function parseWorkerConfig(input: unknown): WorkerConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n enabled: config.enabled !== false,\n url: config.url as string | undefined,\n heartbeatInterval: (config.heartbeatInterval as number | undefined) || 5000,\n maxUnhealthyCount: (config.maxUnhealthyCount as number | undefined) || 3,\n maxRetries: (config.maxRetries as number | undefined) || 3,\n retryDelay: (config.retryDelay as number | undefined) || 1000,\n messageTimeout: (config.messageTimeout as number | undefined) || 30000,\n compressionThreshold: (config.compressionThreshold as number | undefined) || 1024,\n allowFallback: config.allowFallback !== false,\n crossOriginIsolated: config.crossOriginIsolated === true,\n };\n}\n\nexport function parseWorkerMessage(input: unknown): WorkerMessage {\n const msg = input as Record<string, unknown>;\n if (!msg || typeof msg !== 'object') {\n throw new Error('Invalid worker message');\n }\n return {\n id: (msg.id as string | undefined) || crypto.randomUUID(),\n type:\n (msg.type as 'request' | 'response' | 'error' | 'heartbeat' | 'status' | undefined) ||\n 'request',\n action: msg.action as string | undefined,\n payload: msg.payload,\n timestamp: (msg.timestamp as number | undefined) || Date.now(),\n compressed: msg.compressed === true,\n priority: (msg.priority as 'low' | 'normal' | 'high' | 'critical' | undefined) || 'normal',\n correlationId: msg.correlationId as string | undefined,\n };\n}\n\nexport function parseWorkerError(input: unknown): WorkerError {\n const err = input as Record<string, unknown>;\n if (!err || typeof err !== 'object') {\n return {\n type: 'unknown',\n message: String(input),\n timestamp: Date.now(),\n recoverable: false,\n };\n }\n return {\n type: (err.type as string | undefined) || 'unknown',\n message: (err.message as string | undefined) || 'Unknown error',\n stack: err.stack as string | undefined,\n timestamp: (err.timestamp as number | undefined) || Date.now(),\n recoverable: Boolean(err.recoverable),\n };\n}\n\nexport function parseWorkerCapabilities(input: unknown): WorkerCapabilities {\n const cap = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n workerAPI: cap.workerAPI !== false,\n sharedArrayBuffer: cap.sharedArrayBuffer === true,\n transferableObjects: cap.transferableObjects === true,\n offscreenCanvas: cap.offscreenCanvas === true,\n webAssembly: cap.webAssembly === true,\n atomics: cap.atomics === true,\n bigInt: cap.bigInt === true,\n csp: (cap.csp as\n | { workerSrc: boolean; scriptSrc: boolean; blobUrls: boolean; inlineWorkers: boolean }\n | undefined) || {\n workerSrc: false,\n scriptSrc: false,\n blobUrls: false,\n inlineWorkers: false,\n },\n performance: (cap.performance as\n | { memory: boolean; measureUserAgentSpecificMemory: boolean }\n | undefined) || {\n memory: false,\n measureUserAgentSpecificMemory: false,\n },\n };\n}\n\nexport function parseWorkerTask(input: unknown): WorkerTask {\n const task = input as Record<string, unknown>;\n if (!task || typeof task !== 'object') {\n throw new Error('Invalid worker task');\n }\n return {\n id: (task.id as string | undefined) || crypto.randomUUID(),\n type: (task.type as string | undefined) || 'process',\n data: task.data,\n priority: (task.priority as 'low' | 'normal' | 'high' | 'critical' | undefined) || 'normal',\n createdAt: (task.createdAt as number | undefined) || Date.now(),\n startedAt: task.startedAt as number | undefined,\n completedAt: task.completedAt as number | undefined,\n error: task.error as WorkerError | undefined,\n maxRetries: task.maxRetries as number | undefined,\n retries: task.retries as number | undefined,\n timeout: task.timeout as number | undefined,\n };\n}\n\nexport function parseFallbackOptions(input: unknown): FallbackOptions {\n const opts = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n useRequestIdleCallback: opts.useRequestIdleCallback !== false,\n idleTimeout: (opts.idleTimeout as number | undefined) || 10000,\n chunkSize: (opts.chunkSize as number | undefined) || 10,\n throttleMs: (opts.throttleMs as number | undefined) || 16,\n maxExecutionTime: (opts.maxExecutionTime as number | undefined) || 50,\n };\n}\n\nexport function parseRetryStrategy(input: unknown): RetryStrategy {\n const strategy = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n maxAttempts: (strategy.maxAttempts as number | undefined) || 3,\n baseDelay: (strategy.baseDelay as number | undefined) || 1000,\n maxDelay: (strategy.maxDelay as number | undefined) || 30000,\n factor: (strategy.factor as number | undefined) || 2,\n jitter: strategy.jitter !== false,\n };\n}\n\nexport function parseCircuitBreakerConfig(input: unknown): CircuitBreakerConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n threshold: (config.threshold as number | undefined) || 5,\n timeout: (config.timeout as number | undefined) || 60000,\n resetTimeout: (config.resetTimeout as number | undefined) || 30000,\n };\n}\n\nexport function parseOfflineQueueEntry(input: unknown): OfflineQueueEntry {\n const entry = input as Record<string, unknown>;\n if (!entry || typeof entry !== 'object') {\n throw new Error('Invalid offline queue entry');\n }\n return {\n id:\n (entry.id as string | undefined) ||\n `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,\n events: Array.isArray(entry.events) ? entry.events : [],\n timestamp: (entry.timestamp as number | undefined) || Date.now(),\n expiresAt: (entry.expiresAt as number | undefined) || Date.now() + 86400000, // 24 hours\n retryCount: (entry.retryCount as number | undefined) || 0,\n size: (entry.size as number | undefined) || 0,\n };\n}\n\nexport function parseResourceUsage(input: unknown): ResourceUsage {\n const usage = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n memoryUsage: (usage.memoryUsage as number | undefined) || 0,\n cpuUsage: (usage.cpuUsage as number | undefined) || 0,\n taskCount: (usage.taskCount as number | undefined) || 0,\n activeWorkers: (usage.activeWorkers as number | undefined) || 0,\n pendingTasks: (usage.pendingTasks as number | undefined) || 0,\n completedTasks: (usage.completedTasks as number | undefined) || 0,\n failedTasks: (usage.failedTasks as number | undefined) || 0,\n averageTaskDuration: (usage.averageTaskDuration as number | undefined) || 0,\n };\n}\n\nexport function parseWorkerPoolConfig(input: unknown): WorkerPoolConfig {\n const config = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;\n return {\n maxWorkers: (config.maxWorkers as number | undefined) || 4,\n minWorkers: (config.minWorkers as number | undefined) || 1,\n workerIdleTimeout: (config.workerIdleTimeout as number | undefined) || 60000,\n taskQueueSize: (config.taskQueueSize as number | undefined) || 100,\n resourceLimits: (config.resourceLimits as Record<string, unknown> | undefined) || {},\n };\n}\n\nexport function parseBeaconWorkerMessage(input: unknown): BeaconWorkerMessage {\n const msg = input as Record<string, unknown>;\n if (!msg || typeof msg !== 'object') {\n throw new Error('Invalid beacon worker message');\n }\n return {\n type: (msg.type as BeaconWorkerMessageType | undefined) || 'collect',\n data: msg.data,\n messageId: (msg.messageId as string | undefined) || crypto.randomUUID(),\n timestamp: (msg.timestamp as number | undefined) || Date.now(),\n };\n}\n\n// ============================================================================\n// MINIMAL CONSTANTS\n// ============================================================================\n\nexport const DEFAULT_CONFIG = {\n batchSize: 10,\n flushInterval: 5000,\n sessionCookieName: '_as_beacon_session',\n retryAttempts: 3,\n retryDelay: 2000,\n} as const;\n\nexport const ERROR_TYPES = {\n NETWORK: 'network',\n VALIDATION: 'validation',\n TIMEOUT: 'timeout',\n UNKNOWN: 'unknown',\n} as const;\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,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,IAAM,EAAY,EAAQ,YAAY,GAAG,EACzC,GAAI,EAAY,EAAG,OAAO,KAC1B,IAAM,EAAO,EAAU,EAAQ,MAAM,EAAY,CAAC,CAAC,EACnD,GAAI,CAAC,EAAM,OAAO,KAClB,IAAM,EAAS,EAAK,IAAO,EAAK,EAAK,GAC/B,EAAU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,WAAoC,KAAK,IAAI,EAC/D,UAAY,EAAM,WAAoC,KAAK,IAAI,EAAI,MACnE,WAAa,EAAM,YAAqC,EACxD,KAAO,EAAM,MAA+B,CAC9C,CACF,CAEA,SAAgB,EAAmB,EAA+B,CAChE,IAAM,EAAS,GAAS,OAAO,GAAU,SAAW,EAAQ,CAAC,EAC7D,MAAO,CACL,YAAc,EAAM,aAAsC,EAC1D,SAAW,EAAM,UAAmC,EACpD,UAAY,EAAM,WAAoC,EACtD,cAAgB,EAAM,eAAwC,EAC9D,aAAe,EAAM,cAAuC,EAC5D,eAAiB,EAAM,gBAAyC,EAChE,YAAc,EAAM,aAAsC,EAC1D,oBAAsB,EAAM,qBAA8C,CAC5E,CACF,CAEA,SAAgB,EAAsB,EAAkC,CACtE,IAAM,EAAU,GAAS,OAAO,GAAU,SAAW,EAAQ,CAAC,EAC9D,MAAO,CACL,WAAa,EAAO,YAAqC,EACzD,WAAa,EAAO,YAAqC,EACzD,kBAAoB,EAAO,mBAA4C,IACvE,cAAgB,EAAO,eAAwC,IAC/D,eAAiB,EAAO,gBAA0D,CAAC,CACrF,CACF,CAEA,SAAgB,EAAyB,EAAqC,CAC5E,IAAM,EAAM,EACZ,GAAI,CAAC,GAAO,OAAO,GAAQ,SACzB,MAAU,MAAM,+BAA+B,EAEjD,MAAO,CACL,KAAO,EAAI,MAAgD,UAC3D,KAAM,EAAI,KACV,UAAY,EAAI,WAAoC,OAAO,WAAW,EACtE,UAAY,EAAI,WAAoC,KAAK,IAAI,CAC/D,CACF,CAMA,MAAa,EAAiB,CAC5B,UAAW,GACX,cAAe,IACf,kBAAmB,qBACnB,cAAe,EACf,WAAY,GACd,EAEa,EAAc,CACzB,QAAS,UACT,WAAY,aACZ,QAAS,UACT,QAAS,SACX"}
|
|
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,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,IAAM,EAAY,EAAQ,YAAY,GAAG,EACzC,GAAI,EAAY,EAAG,O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,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 +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 {\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,oB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K,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 * 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,aAAa,GAAG,EAAE,GAAG,aAAa,OAAO,MAAM,IAAI,GAAG;EACtE;EACA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AkB,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"}
|
|
@@ -3,11 +3,8 @@ import { z } from "zod";
|
|
|
3
3
|
export declare const CONSENT_HANDOFF_SOURCES: readonly ["module", "probe"];
|
|
4
4
|
export type ConsentHandoffSource = (typeof CONSENT_HANDOFF_SOURCES)[number];
|
|
5
5
|
export declare const CONSENT_HANDOFF_REPORT_OUTCOMES: readonly ["registered", "registration_failed", "not_configured"];
|
|
6
|
-
export type ConsentHandoffReportOutcome = (typeof CONSENT_HANDOFF_REPORT_OUTCOMES)[number];
|
|
7
6
|
export declare const CONSENT_HANDOFF_MODULE_REASONS: readonly ["http_401", "http_403", "http_404", "http_4xx", "http_5xx", "http_other", "timeout", "network_error", "invalid_response", "missing_proof", "placeholder_proof", "invalid_config"];
|
|
8
|
-
export type ConsentHandoffModuleReason = (typeof CONSENT_HANDOFF_MODULE_REASONS)[number];
|
|
9
7
|
export declare const CONSENT_HANDOFF_PROBE_CODES: readonly ["challenge_missing", "challenge_proof_unsigned", "challenge_proof_invalid", "pickup_not_202", "consent_page_unreachable"];
|
|
10
|
-
export type ConsentHandoffProbeCode = (typeof CONSENT_HANDOFF_PROBE_CODES)[number];
|
|
11
8
|
export declare const CONSENT_HANDOFF_CODES: readonly ["http_401", "http_403", "http_404", "http_4xx", "http_5xx", "http_other", "timeout", "network_error", "invalid_response", "missing_proof", "placeholder_proof", "invalid_config", "challenge_missing", "challenge_proof_unsigned", "challenge_proof_invalid", "pickup_not_202", "consent_page_unreachable"];
|
|
12
9
|
export type ConsentHandoffCode = (typeof CONSENT_HANDOFF_CODES)[number];
|
|
13
10
|
export declare const CONSENT_HANDOFF_HEALTH_OUTCOMES: readonly ["ok", "failed", "not_configured"];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consent-handoff.d.mts","names":[],"sources":["../src/consent-handoff.ts"],"mappings":";;qBAgBa;YACD,+BAA+B;qBAG9B;
|
|
1
|
+
{"version":3,"file":"consent-handoff.d.mts","names":[],"sources":["../src/consent-handoff.ts"],"mappings":";;qBAgBa;YACD,+BAA+B;qBAG9B;qBAOA;qBAgBA;qBASA;YAID,6BAA6B;qBAG5B;YACD,sCAAsC;qBAMrC,0BAAwB,EAAA;qBAQxB,4BAA0B,EAAA;;;;;;;;;;;;;;;;;;;;;;GAKrC,EAAA,KAAA;YACU,uBAAuB,EAAE,aAAa"}
|
|
@@ -3,11 +3,8 @@ import { z } from "zod";
|
|
|
3
3
|
export declare const CONSENT_HANDOFF_SOURCES: readonly ["module", "probe"];
|
|
4
4
|
export type ConsentHandoffSource = (typeof CONSENT_HANDOFF_SOURCES)[number];
|
|
5
5
|
export declare const CONSENT_HANDOFF_REPORT_OUTCOMES: readonly ["registered", "registration_failed", "not_configured"];
|
|
6
|
-
export type ConsentHandoffReportOutcome = (typeof CONSENT_HANDOFF_REPORT_OUTCOMES)[number];
|
|
7
6
|
export declare const CONSENT_HANDOFF_MODULE_REASONS: readonly ["http_401", "http_403", "http_404", "http_4xx", "http_5xx", "http_other", "timeout", "network_error", "invalid_response", "missing_proof", "placeholder_proof", "invalid_config"];
|
|
8
|
-
export type ConsentHandoffModuleReason = (typeof CONSENT_HANDOFF_MODULE_REASONS)[number];
|
|
9
7
|
export declare const CONSENT_HANDOFF_PROBE_CODES: readonly ["challenge_missing", "challenge_proof_unsigned", "challenge_proof_invalid", "pickup_not_202", "consent_page_unreachable"];
|
|
10
|
-
export type ConsentHandoffProbeCode = (typeof CONSENT_HANDOFF_PROBE_CODES)[number];
|
|
11
8
|
export declare const CONSENT_HANDOFF_CODES: readonly ["http_401", "http_403", "http_404", "http_4xx", "http_5xx", "http_other", "timeout", "network_error", "invalid_response", "missing_proof", "placeholder_proof", "invalid_config", "challenge_missing", "challenge_proof_unsigned", "challenge_proof_invalid", "pickup_not_202", "consent_page_unreachable"];
|
|
12
9
|
export type ConsentHandoffCode = (typeof CONSENT_HANDOFF_CODES)[number];
|
|
13
10
|
export declare const CONSENT_HANDOFF_HEALTH_OUTCOMES: readonly ["ok", "failed", "not_configured"];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consent-handoff.d.ts","names":[],"sources":["../src/consent-handoff.ts"],"mappings":";;qBAgBa;YACD,+BAA+B;qBAG9B;
|
|
1
|
+
{"version":3,"file":"consent-handoff.d.ts","names":[],"sources":["../src/consent-handoff.ts"],"mappings":";;qBAgBa;YACD,+BAA+B;qBAG9B;qBAOA;qBAgBA;qBASA;YAID,6BAA6B;qBAG5B;YACD,sCAAsC;qBAMrC,0BAAwB,EAAA;qBAQxB,4BAA0B,EAAA;;;;;;;;;;;;;;;;;;;;;;GAKrC,EAAA,KAAA;YACU,uBAAuB,EAAE,aAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consent-handoff.mjs","names":[],"sources":["../src/consent-handoff.ts"],"sourcesContent":["import { z } from 'zod';\n\n/**\n * Consent-handoff health vocabulary: whether an agent that hits a delegation\n * challenge gets a consent link that can actually be redeemed.\n *\n * Two sources report into one health record per project:\n * - `module`: the PEP itself (the .NET module today), on its log-detection\n * report, right after it tries to register the challenge anchor.\n * - `probe`: the scheduled external check that plays an agent against the site.\n *\n * The module vocabulary is pinned by\n * `fixtures/kya-http/consent-handoff.codes.json`, which the .NET registrar also\n * asserts against.\n */\n\nexport const CONSENT_HANDOFF_SOURCES = ['module', 'probe'] as const;\nexport type ConsentHandoffSource = (typeof CONSENT_HANDOFF_SOURCES)[number];\n\n/** `consentHandoff.outcome` as a PEP reports it. */\nexport const CONSENT_HANDOFF_REPORT_OUTCOMES = [\n 'registered',\n 'registration_failed',\n 'not_configured',\n] as const;\
|
|
1
|
+
{"version":3,"file":"consent-handoff.mjs","names":[],"sources":["../src/consent-handoff.ts"],"sourcesContent":["import { z } from 'zod';\n\n/**\n * Consent-handoff health vocabulary: whether an agent that hits a delegation\n * challenge gets a consent link that can actually be redeemed.\n *\n * Two sources report into one health record per project:\n * - `module`: the PEP itself (the .NET module today), on its log-detection\n * report, right after it tries to register the challenge anchor.\n * - `probe`: the scheduled external check that plays an agent against the site.\n *\n * The module vocabulary is pinned by\n * `fixtures/kya-http/consent-handoff.codes.json`, which the .NET registrar also\n * asserts against.\n */\n\nexport const CONSENT_HANDOFF_SOURCES = ['module', 'probe'] as const;\nexport type ConsentHandoffSource = (typeof CONSENT_HANDOFF_SOURCES)[number];\n\n/** `consentHandoff.outcome` as a PEP reports it. */\nexport const CONSENT_HANDOFF_REPORT_OUTCOMES = [\n 'registered',\n 'registration_failed',\n 'not_configured',\n] as const;\n\n/** Why a PEP's anchor registration failed. Every `http_*` code carries `httpStatus`. */\nexport const CONSENT_HANDOFF_MODULE_REASONS = [\n 'http_401',\n 'http_403',\n 'http_404',\n 'http_4xx',\n 'http_5xx',\n 'http_other',\n 'timeout',\n 'network_error',\n 'invalid_response',\n 'missing_proof',\n 'placeholder_proof',\n 'invalid_config',\n] as const;\n\n/** Which stage of the handoff the external probe saw fail. */\nexport const CONSENT_HANDOFF_PROBE_CODES = [\n 'challenge_missing',\n 'challenge_proof_unsigned',\n 'challenge_proof_invalid',\n 'pickup_not_202',\n 'consent_page_unreachable',\n] as const;\n\n/** Every failure code either source can record. */\nexport const CONSENT_HANDOFF_CODES = [\n ...CONSENT_HANDOFF_MODULE_REASONS,\n ...CONSENT_HANDOFF_PROBE_CODES,\n] as const;\nexport type ConsentHandoffCode = (typeof CONSENT_HANDOFF_CODES)[number];\n\n/** A health observation: the handoff worked, failed, or is not set up on purpose. */\nexport const CONSENT_HANDOFF_HEALTH_OUTCOMES = ['ok', 'failed', 'not_configured'] as const;\nexport type ConsentHandoffHealthOutcome = (typeof CONSENT_HANDOFF_HEALTH_OUTCOMES)[number];\n\n// host[:port] only: never a path, query or userinfo.\nconst AUTHORITY_PATTERN = /^(?:[A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*|\\[[0-9A-Fa-f:.]+\\])(?::\\d{1,5})?$/;\n\n/** A strict `host[:port]`. The probe route requires it; reports only prefer it. */\nexport const ConsentHandoffHostSchema = z.string().max(261).regex(AUTHORITY_PATTERN);\n\n/**\n * The `consentHandoff` block of a log-detection report. A detail that doesn't\n * validate is dropped on its own, so the outcome and reason still count: .NET's\n * `Uri.Authority` can give a host this pattern refuses (an underscore, a Unicode\n * label, a trailing dot), and losing the host must never lose the 401 with it.\n */\nexport const ConsentHandoffReportSchema = z.object({\n outcome: z.enum(CONSENT_HANDOFF_REPORT_OUTCOMES),\n reason: z.enum(CONSENT_HANDOFF_MODULE_REASONS).optional(),\n httpStatus: z.number().int().min(100).max(599).optional().catch(undefined),\n host: ConsentHandoffHostSchema.optional().catch(undefined),\n});\nexport type ConsentHandoffReport = z.infer<typeof ConsentHandoffReportSchema>;\n"],"mappings":"wBAgBA,MAAa,EAA0B,CAAC,SAAU,OAAO,EAI5C,EAAkC,CAC7C,aACA,sBACA,gBACF,EAGa,EAAiC,CAC5C,WACA,WACA,WACA,WACA,WACA,aACA,UACA,gBACA,mBACA,gBACA,oBACA,gBACF,EAGa,EAA8B,CACzC,oBACA,2BACA,0BACA,iBACA,0BACF,EAGa,EAAwB,CACnC,GAAG,EACH,GAAG,CACL,EAIa,EAAkC,CAAC,KAAM,SAAU,gBAAgB,EAOnE,EAA2B,EAAE,OAAO,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,MAAM,yEAAiB,EAQtE,EAA6B,EAAE,OAAO,CACjD,QAAS,EAAE,KAAK,CAA+B,EAC/C,OAAQ,EAAE,KAAK,CAA8B,CAAC,CAAC,SAAS,EACxD,WAAY,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,EACzE,KAAM,EAAyB,SAAS,CAAC,CAAC,MAAM,IAAA,EAAS,CAC3D,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/default-sign-in-host.d.ts
|
|
2
|
+
export declare const AUTH_DOMAIN = "auth.knowthat.ai";
|
|
3
|
+
export declare function isDnsLabel(value: string): boolean;
|
|
4
|
+
export declare function isDefaultSignInHostLabel(label: string): boolean;
|
|
5
|
+
export declare function defaultSignInHost(label: string): string | null;
|
|
6
|
+
export declare function defaultSignInHostLabel(host: string): string | null;
|
|
7
|
+
export declare function isUnderAuthDomain(host: string): boolean;
|
|
8
|
+
export declare function withoutTrailingDots(host: string): string;
|
|
9
|
+
//#endregion
|
|
10
|
+
//# sourceMappingURL=default-sign-in-host.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"default-sign-in-host.d.mts","names":[],"sources":["../src/default-sign-in-host.ts"],"mappings":";qBAWa;wBAMG,WAAW;wBAUX,yBAAyB;wBAKzB,kBAAkB;wBAUlB,uBAAuB;wBAYvB,kBAAkB;wBAUlB,oBAAoB"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/default-sign-in-host.d.ts
|
|
2
|
+
export declare const AUTH_DOMAIN = "auth.knowthat.ai";
|
|
3
|
+
export declare function isDnsLabel(value: string): boolean;
|
|
4
|
+
export declare function isDefaultSignInHostLabel(label: string): boolean;
|
|
5
|
+
export declare function defaultSignInHost(label: string): string | null;
|
|
6
|
+
export declare function defaultSignInHostLabel(host: string): string | null;
|
|
7
|
+
export declare function isUnderAuthDomain(host: string): boolean;
|
|
8
|
+
export declare function withoutTrailingDots(host: string): string;
|
|
9
|
+
//#endregion
|
|
10
|
+
//# sourceMappingURL=default-sign-in-host.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"default-sign-in-host.d.ts","names":[],"sources":["../src/default-sign-in-host.ts"],"mappings":";qBAWa;wBAMG,WAAW;wBAUX,yBAAyB;wBAKzB,kBAAkB;wBAUlB,uBAAuB;wBAYvB,kBAAkB;wBAUlB,oBAAoB"}
|