@kya-os/checkpoint-shared 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/dist/beacon-types/index.d.mts +441 -432
- package/dist/beacon-types/index.d.mts.map +1 -0
- package/dist/beacon-types/index.d.ts +441 -432
- package/dist/beacon-types/index.d.ts.map +1 -0
- package/dist/beacon-types/index.js +198 -182
- package/dist/beacon-types/index.mjs +197 -179
- package/dist/beacon-types/index.mjs.map +1 -0
- package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +5 -0
- package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +1 -0
- package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +5 -0
- package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +1 -0
- package/dist/browser-posture-cookie.d.mts +2 -0
- package/dist/browser-posture-cookie.d.ts +2 -0
- package/dist/browser-posture-cookie.js +1 -0
- package/dist/browser-posture-cookie.mjs +2 -0
- package/dist/browser-posture-cookie.mjs.map +1 -0
- package/dist/browser-posture-report.d.mts +48 -44
- package/dist/browser-posture-report.d.mts.map +1 -0
- package/dist/browser-posture-report.d.ts +48 -44
- package/dist/browser-posture-report.d.ts.map +1 -0
- package/dist/browser-posture-report.js +1 -1
- package/dist/browser-posture-report.mjs +2 -1
- package/dist/browser-posture-report.mjs.map +1 -0
- package/dist/browser-posture.d.mts +80 -75
- package/dist/browser-posture.d.mts.map +1 -0
- package/dist/browser-posture.d.ts +80 -75
- package/dist/browser-posture.d.ts.map +1 -0
- package/dist/browser-posture.js +159 -18993
- package/dist/browser-posture.mjs +158 -18990
- package/dist/browser-posture.mjs.map +1 -0
- package/dist/browser.d.mts +323 -316
- package/dist/browser.d.mts.map +1 -0
- package/dist/browser.d.ts +323 -316
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +2 -1
- package/dist/browser.mjs.map +1 -0
- package/dist/canonical-signer/index.d.mts +38 -33
- package/dist/canonical-signer/index.d.mts.map +1 -0
- package/dist/canonical-signer/index.d.ts +38 -33
- package/dist/canonical-signer/index.d.ts.map +1 -0
- package/dist/canonical-signer/index.js +411 -181
- package/dist/canonical-signer/index.mjs +383 -175
- package/dist/canonical-signer/index.mjs.map +1 -0
- package/dist/clearance.d.mts +30 -0
- package/dist/clearance.d.mts.map +1 -0
- package/dist/clearance.d.ts +30 -0
- package/dist/clearance.d.ts.map +1 -0
- package/dist/clearance.js +120 -0
- package/dist/clearance.mjs +112 -0
- package/dist/clearance.mjs.map +1 -0
- package/dist/client-ip-1y2iXAYW.js +237 -0
- package/dist/client-ip-HOfe6ucV.mjs +215 -0
- package/dist/client-ip-HOfe6ucV.mjs.map +1 -0
- package/dist/deploy/index.d.mts +339 -339
- package/dist/deploy/index.d.mts.map +1 -0
- package/dist/deploy/index.d.ts +339 -339
- package/dist/deploy/index.d.ts.map +1 -0
- package/dist/deploy/index.js +505 -413
- package/dist/deploy/index.mjs +504 -410
- package/dist/deploy/index.mjs.map +1 -0
- package/dist/errors/index.d.mts +101 -101
- package/dist/errors/index.d.mts.map +1 -0
- package/dist/errors/index.d.ts +101 -101
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/errors/index.js +341 -314
- package/dist/errors/index.mjs +340 -311
- package/dist/errors/index.mjs.map +1 -0
- package/dist/external-jr_S4iSS.d.mts +4187 -0
- package/dist/external-jr_S4iSS.d.mts.map +1 -0
- package/dist/external-jr_S4iSS.d.ts +4187 -0
- package/dist/external-jr_S4iSS.d.ts.map +1 -0
- package/dist/gateway/index.d.mts +138 -132
- package/dist/gateway/index.d.mts.map +1 -0
- package/dist/gateway/index.d.ts +138 -132
- package/dist/gateway/index.d.ts.map +1 -0
- package/dist/gateway/index.js +117 -81
- package/dist/gateway/index.mjs +116 -78
- package/dist/gateway/index.mjs.map +1 -0
- package/dist/gateway-client-ip.d.mts +59 -0
- package/dist/gateway-client-ip.d.mts.map +1 -0
- package/dist/gateway-client-ip.d.ts +59 -0
- package/dist/gateway-client-ip.d.ts.map +1 -0
- package/dist/gateway-client-ip.js +149 -0
- package/dist/gateway-client-ip.mjs +139 -0
- package/dist/gateway-client-ip.mjs.map +1 -0
- package/dist/index.d.mts +14895 -14240
- package/dist/index.d.mts.map +1 -0
- package/dist/index.d.ts +14895 -14240
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +15180 -31025
- package/dist/index.mjs +15065 -30942
- package/dist/index.mjs.map +1 -0
- package/dist/mcpi/agentshield-api/index.d.mts +45 -44
- package/dist/mcpi/agentshield-api/index.d.mts.map +1 -0
- package/dist/mcpi/agentshield-api/index.d.ts +45 -44
- package/dist/mcpi/agentshield-api/index.d.ts.map +1 -0
- package/dist/mcpi/agentshield-api/index.js +0 -2
- package/dist/mcpi/agentshield-api/index.mjs +1 -1
- package/dist/mcpi/approval-grant/index.d.mts +63 -61
- package/dist/mcpi/approval-grant/index.d.mts.map +1 -0
- package/dist/mcpi/approval-grant/index.d.ts +63 -61
- package/dist/mcpi/approval-grant/index.d.ts.map +1 -0
- package/dist/mcpi/approval-grant/index.js +220 -140
- package/dist/mcpi/approval-grant/index.mjs +219 -137
- package/dist/mcpi/approval-grant/index.mjs.map +1 -0
- package/dist/mcpi/dashboard-config/index.d.mts +2323 -2318
- package/dist/mcpi/dashboard-config/index.d.mts.map +1 -0
- package/dist/mcpi/dashboard-config/index.d.ts +2323 -2318
- package/dist/mcpi/dashboard-config/index.d.ts.map +1 -0
- package/dist/mcpi/dashboard-config/index.js +605 -458
- package/dist/mcpi/dashboard-config/index.mjs +604 -455
- package/dist/mcpi/dashboard-config/index.mjs.map +1 -0
- package/dist/mcpi/multibase-ed25519.d.mts +10 -8
- package/dist/mcpi/multibase-ed25519.d.mts.map +1 -0
- package/dist/mcpi/multibase-ed25519.d.ts +10 -8
- package/dist/mcpi/multibase-ed25519.d.ts.map +1 -0
- package/dist/mcpi/multibase-ed25519.js +182 -106
- package/dist/mcpi/multibase-ed25519.mjs +181 -103
- package/dist/mcpi/multibase-ed25519.mjs.map +1 -0
- package/dist/patterns-CkRVOdtV.js +243 -0
- package/dist/patterns-DzkGy_qk.mjs +173 -0
- package/dist/patterns-DzkGy_qk.mjs.map +1 -0
- package/dist/project-verification-key-C3L5rd8a.js +41 -0
- package/dist/project-verification-key-CgSVX9_m.mjs +37 -0
- package/dist/project-verification-key-CgSVX9_m.mjs.map +1 -0
- package/dist/rolldown-runtime-iY2fYEqi.mjs +19 -0
- package/dist/schemas-BmjNLAE7.js +5677 -0
- package/dist/schemas-DxY-dk9y.mjs +5511 -0
- package/dist/schemas-DxY-dk9y.mjs.map +1 -0
- package/dist/signals/index.d.mts +125 -115
- package/dist/signals/index.d.mts.map +1 -0
- package/dist/signals/index.d.ts +125 -115
- package/dist/signals/index.d.ts.map +1 -0
- package/dist/signals/index.js +1693 -1536
- package/dist/signals/index.mjs +1692 -1533
- package/dist/signals/index.mjs.map +1 -0
- package/dist/test-fixtures/index.d.mts +124 -119
- package/dist/test-fixtures/index.d.mts.map +1 -0
- package/dist/test-fixtures/index.d.ts +124 -119
- package/dist/test-fixtures/index.d.ts.map +1 -0
- package/dist/test-fixtures/index.js +460 -228
- package/dist/test-fixtures/index.mjs +459 -225
- package/dist/test-fixtures/index.mjs.map +1 -0
- package/dist/tool-protection/index.d.mts +343 -343
- package/dist/tool-protection/index.d.mts.map +1 -0
- package/dist/tool-protection/index.d.ts +343 -343
- package/dist/tool-protection/index.d.ts.map +1 -0
- package/dist/tool-protection/index.js +366 -285
- package/dist/tool-protection/index.mjs +365 -282
- package/dist/tool-protection/index.mjs.map +1 -0
- package/fixtures/bot-signal-resolution.json +142 -0
- package/fixtures/browser-posture-claims.json +421 -0
- package/fixtures/browser-posture-headers.json +46 -0
- package/fixtures/detection/reason-codes.json +10 -1
- package/fixtures/kya-http/challenge.delegation.fetcher-200.json +9 -3
- package/fixtures/kya-http/challenge.delegation.full.json +9 -3
- package/fixtures/kya-http/challenge.delegation.minimal.json +9 -3
- package/fixtures/kya-http/error-codes.json +7 -2
- package/package.json +20 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.d.ts","names":[],"sources":["../src/utils/client-ip.ts","../src/browser.ts"],"mappings":";YAQY;iBAUK;EACf;EACA,QAAQ;EACR;;YAGU;EACN;;EACA;;EACA;EAA2B;;EAC3B;;YAEM;YACA,kBAAkB,UAAU,eAAe;iBAEtC;EACf,SAAS;EACT;EACA;EACA;EAEA;EACA,QAAQ;;wBAuCM,UAAU;wBA2CV,aAAa;wBA8Db,kBAAkB;wBAyHlB,gBAAgB,OAAO,uBAAuB;;;iBC5R7C;EACf,UAAU;EACV,YAAY;EACZ,QAAQ;;YAQE;YACA;iBAEK;EACf;EACA;EACA;EACA;;YAOU;iBAQK;EACf,MAAM;EACN,MAAM;EACN,UAAU;;iBAGK;EACf;EACA;EACA;GACC;;iBAGc;EAEf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA;EACA;EACA;EAGA;EACA;GAGC;;iBAGc;EACf;EACA,QAAQ;EACR;EACA;EACA;EAKA;EAEA;EAEA;;iBAGe;EACf;EACA,OAAO;EACP;EACA;EACA;EACA;;iBAQe;EACf;;iBAGe;EACf;EACA;EACA,OAAO;EACP,WAAW;EAEX;EACA;EACA;EACA;EAGA;EACA;EAGA;EACA;EAGA;EACA;EACA;EACA;EACA;EAGA;EACA;EACA,eAAe;;iBAGA;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAOe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;YAGU;iBAEK;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;YAGU;iBAUK;EACf;EACA;EACA;EACA;EACA;;YAOU;YAEA;YAQA;YASA;iBAEK;EACf;EACA;EACA;EACA;EACA;EACA;EACA,WAAW;EACX;;YAGU;YASA;iBAEK;EACf;EACA;EACA;EACA;EACA;EACA,cAAc;EACd;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACE;IACA;IACA;IACA;;EAEF;IACE;IACA;;;iBAIa;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA,gBAAgB;EAChB;EACA;EACA;;YAGU;YAEA;iBAEK;EACf,MAAM;EACN;EACA;EACA;EACA;EACA;;iBAOe;EACf;EACA;EACA;;YAGU;iBAEK;EACf;EACA;EACA;EACA;EACA;;iBAOe;EACf;EACA,QAAQ;EACR;EACA;EACA;EACA;;wBAUc,oBAAoB,iBAAiB,SAAS;wBAmB9C,qBAAqB,kBAAkB,UAAU;wBASjD,oBAAoB,iBAAiB,SAAS;wBAkC9C,kBAAkB,iBAAiB;qBAsCtC;;;;EAKU,gBAAA,eAAU,OAAO;EAWnB,cAAA,eAAU,OAAO;EAWV,qBAAA,eAAU,OAAO;;wBAgB7B,kBAAkB,iBAAiB;wBAgBnC,mBAAmB,iBAAiB;wBAmBpC,iBAAiB,iBAAiB;wBAmBlC,wBAAwB,iBAAiB;wBA2BzC,gBAAgB,iBAAiB;wBAoBjC,qBAAqB,iBAAiB;wBAWtC,mBAAmB,iBAAiB;wBAWpC,0BAA0B,iBAAiB;wBAS3C,uBAAuB,iBAAiB;wBAiBxC,mBAAmB,iBAAiB;wBAcpC,sBAAsB,iBAAiB;wBAWvC,yBAAyB,iBAAiB;qBAiB7C;;;;;;;;qBASA;;;;;;qBAQA"}
|
package/dist/browser.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';function p(r){for(let e=0;e<r.length;e++){let n=r.charCodeAt(e);if(n<=31||n===127)return true}return false}function b(r){return /^(?:0|[1-9]\d{0,4})$/.test(r)&&Number(r)<=65535}function g(r){let e=r.split(".");if(e.length!==4)return null;let n=[];for(let t of e){if(!/^\d{1,3}$/.test(t))return null;let s=Number(t);if(s>255)return null;n.push(s);}return n}function h(r){return /^[0-9a-fA-F]{1,4}$/.test(r)?Number.parseInt(r,16):null}function I(r){if(!r||r.includes("%")||p(r))return null;let e=r;if(e.includes(".")){let o=e.lastIndexOf(":");if(o<0)return null;let a=g(e.slice(o+1));if(!a)return null;let i=a[0]<<8|a[1],c=a[2]<<8|a[3];e=`${e.slice(0,o+1)}${i.toString(16)}:${c.toString(16)}`;}let n=e.indexOf("::");if(n!==e.lastIndexOf("::"))return null;let t=o=>{if(!o)return [];let a=o.split(":"),i=[];for(let c of a){let m=h(c);if(m===null)return null;i.push(m);}return i};if(n>=0){let o=t(e.slice(0,n)),a=t(e.slice(n+2));if(!o||!a)return null;let i=8-o.length-a.length;return i<1?null:[...o,...Array(i).fill(0),...a]}let s=t(e);return (s==null?void 0:s.length)===8?s:null}function C(r){let e=r.map(i=>i.toString(16)),n=-1,t=1,s=-1;for(let i=0;i<=r.length;i+=1){if(i<r.length&&r[i]===0){s<0&&(s=i);continue}if(s>=0){let c=i-s;c>t&&(n=s,t=c),s=-1;}}if(n<0)return e.join(":");let o=e.slice(0,n).join(":"),a=e.slice(n+t).join(":");return !o&&!a?"::":o?a?`${o}::${a}`:`${o}::`:`::${a}`}function k(r){var o;let e=r.trim();if(!e||e.length>128||p(e))return null;let n=e;if(e.startsWith("[")){let a=e.indexOf("]");if(a<=1)return null;let i=e.slice(a+1);if(i&&(!i.startsWith(":")||!b(i.slice(1))))return null;n=e.slice(1,a);}else if(((o=e.match(/:/g))!=null?o:[]).length===1&&e.includes(".")){let a=e.indexOf(":");if(!b(e.slice(a+1)))return null;n=e.slice(0,a);}let t=g(n);if(t)return t.join(".");let s=I(n);return s?C(s):null}function y(r){if(r==null||!r||r.length>4096||p(r))return null;let e=r.split(",");return e.length>32?null:e}function u(r){let e=y(r);if(!e)return null;for(let n of e){let t=k(n);if(t)return t}return null}function d(r,e){var t;if("get"in r&&typeof r.get=="function")return (t=r.get(e))!=null?t:void 0;let n=e.toLowerCase();for(let[s,o]of Object.entries(r))if(!(s.toLowerCase()!==n||o===void 0))return Array.isArray(o)?o.join(","):o}function l(r,e,n){return r?{ip:r,source:e,trusted:n}:null}function f(r,e){return l(u(r),e,true)}function T(r){return r.explicitAddressTrusted!==true?null:l(u(r.explicitAddress),"explicit",true)}function v(r){var s,o;let e=l(u(d(r.headers,"x-vercel-forwarded-for")),"x-vercel-forwarded-for",true);if(e)return e;let n=l(u(d(r.headers,"x-forwarded-for")),"x-forwarded-for",true);if(n)return n;let t=l(u(d(r.headers,"x-real-ip")),"x-real-ip",false);return t||((o=(s=f(r.frameworkAddress,"framework"))!=null?s:f(r.directAddress,"socket"))!=null?o:{ip:null,source:"none",trusted:false})}function A(r){var n,t,s,o;let e=l(u(d(r.headers,"cf-connecting-ip")),"cf-connecting-ip",true);return e||((o=(s=(t=(n=f(r.directAddress,"socket"))!=null?n:f(r.frameworkAddress,"framework"))!=null?t:l(u(d(r.headers,"x-forwarded-for")),"x-forwarded-for",false))!=null?s:l(u(d(r.headers,"x-real-ip")),"x-real-ip",false))!=null?o:{ip:null,source:"none",trusted:false})}function R(r,e){var s,o,a;let n=d(r.headers,"x-forwarded-for"),t=y(n);if(t&&Number.isInteger(e)&&e>0&&t.length>e){let i=t.map(k),c=t.length-e-1,m=i[c];if(m&&i.every(x=>x!==null))return {ip:m,source:"x-forwarded-for",trusted:true}}return (a=(o=(s=f(r.frameworkAddress,"framework"))!=null?s:f(r.directAddress,"socket"))!=null?o:l(u(d(r.headers,"x-real-ip")),"x-real-ip",false))!=null?a:{ip:null,source:"none",trusted:false}}function S(r){var n,t;let e=T(r);if(e)return e;switch(r.policy.platform){case "vercel":return v(r);case "cloudflare":return A(r);case "trusted-proxy":return R(r,r.policy.trustedHops);case "direct":return (t=(n=f(r.frameworkAddress,"framework"))!=null?n:f(r.directAddress,"socket"))!=null?t:{ip:null,source:"none",trusted:false}}}function w(r){if(!r||typeof r!="object")return false;let e=r,n=e.metadata;return !!(e.type&&typeof e.type=="string"&&e.data&&typeof e.data=="object"&&n&&typeof n=="object"&&n.sessionId&&n.timestamp)}function W(r){if(!r||typeof r!="object")return false;let e=r;return !!(e.projectId&&typeof e.projectId=="string")}function B(r){if(!r||typeof r!="object")return false;let e=r;return !!(e.projectId&&typeof e.projectId=="string"&&Array.isArray(e.events)&&e.events.every(n=>w(n))&&e.sessionId&&typeof e.sessionId=="string"&&e.batchId&&e.timestamp&&typeof e.timestamp=="number")}function E(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.userId=="string"&&r.userId.length>0}function j(r){let e=r&&typeof r=="object"?r:{};if(!e.projectId||typeof e.projectId!="string")throw new Error("Project ID is required");return {projectId:e.projectId,environment:e.environment,tags:e.tags,identity:E(e.identity)?e.identity:void 0,endpoint:e.endpoint,enabled:e.enabled!==false,debug:e.debug===true,logLevel:e.logLevel||"error",respectDoNotTrack:e.respectDoNotTrack!==false,anonymizeIp:e.anonymizeIp===true,sessionTimeout:e.sessionTimeout||18e5,sessionCookieName:e.sessionCookieName||"_as_beacon_session",batchSize:e.batchSize||10,flushInterval:e.flushInterval||5e3,maxQueueSize:e.maxQueueSize||100,retryAttempts:e.retryAttempts||3,retryDelay:e.retryDelay||2e3,useWorker:e.useWorker!==false,workerUrl:e.workerUrl,workerConfig:e.workerConfig}}var U={isBeaconEvent:w,isBeaconConfig:W,isBeaconBatch:B,isWorkerMessage(r){if(!r||typeof r!="object")return false;let e=r;return !!(e.id&&e.type&&["request","response","error","heartbeat","status"].includes(e.type)&&typeof e.timestamp=="number")},isWorkerError(r){if(!r||typeof r!="object")return false;let e=r;return !!(e.type&&e.message&&typeof e.timestamp=="number"&&typeof e.recoverable=="boolean")},isWorkerCapabilities(r){if(!r||typeof r!="object")return false;let e=r;return typeof e.workerAPI=="boolean"&&typeof e.sharedArrayBuffer=="boolean"&&typeof e.transferableObjects=="boolean"&&typeof e.offscreenCanvas=="boolean"}};function M(r){let e=r&&typeof r=="object"?r:{};return {enabled:e.enabled!==false,url:e.url,heartbeatInterval:e.heartbeatInterval||5e3,maxUnhealthyCount:e.maxUnhealthyCount||3,maxRetries:e.maxRetries||3,retryDelay:e.retryDelay||1e3,messageTimeout:e.messageTimeout||3e4,compressionThreshold:e.compressionThreshold||1024,allowFallback:e.allowFallback!==false,crossOriginIsolated:e.crossOriginIsolated===true}}function O(r){let e=r;if(!e||typeof e!="object")throw new Error("Invalid worker message");return {id:e.id||crypto.randomUUID(),type:e.type||"request",action:e.action,payload:e.payload,timestamp:e.timestamp||Date.now(),compressed:e.compressed===true,priority:e.priority||"normal",correlationId:e.correlationId}}function N(r){let e=r;return !e||typeof e!="object"?{type:"unknown",message:String(r),timestamp:Date.now(),recoverable:false}:{type:e.type||"unknown",message:e.message||"Unknown error",stack:e.stack,timestamp:e.timestamp||Date.now(),recoverable:!!e.recoverable}}function _(r){let e=r&&typeof r=="object"?r:{};return {workerAPI:e.workerAPI!==false,sharedArrayBuffer:e.sharedArrayBuffer===true,transferableObjects:e.transferableObjects===true,offscreenCanvas:e.offscreenCanvas===true,webAssembly:e.webAssembly===true,atomics:e.atomics===true,bigInt:e.bigInt===true,csp:e.csp||{workerSrc:false,scriptSrc:false,blobUrls:false,inlineWorkers:false},performance:e.performance||{memory:false,measureUserAgentSpecificMemory:false}}}function z(r){let e=r;if(!e||typeof e!="object")throw new Error("Invalid worker task");return {id:e.id||crypto.randomUUID(),type:e.type||"process",data:e.data,priority:e.priority||"normal",createdAt:e.createdAt||Date.now(),startedAt:e.startedAt,completedAt:e.completedAt,error:e.error,maxRetries:e.maxRetries,retries:e.retries,timeout:e.timeout}}function P(r){let e=r&&typeof r=="object"?r:{};return {useRequestIdleCallback:e.useRequestIdleCallback!==false,idleTimeout:e.idleTimeout||1e4,chunkSize:e.chunkSize||10,throttleMs:e.throttleMs||16,maxExecutionTime:e.maxExecutionTime||50}}function L(r){let e=r&&typeof r=="object"?r:{};return {maxAttempts:e.maxAttempts||3,baseDelay:e.baseDelay||1e3,maxDelay:e.maxDelay||3e4,factor:e.factor||2,jitter:e.jitter!==false}}function H(r){let e=r&&typeof r=="object"?r:{};return {threshold:e.threshold||5,timeout:e.timeout||6e4,resetTimeout:e.resetTimeout||3e4}}function F(r){let e=r;if(!e||typeof e!="object")throw new Error("Invalid offline queue entry");return {id:e.id||`${Date.now()}_${Math.random().toString(36).substr(2,9)}`,events:Array.isArray(e.events)?e.events:[],timestamp:e.timestamp||Date.now(),expiresAt:e.expiresAt||Date.now()+864e5,retryCount:e.retryCount||0,size:e.size||0}}function $(r){let e=r&&typeof r=="object"?r:{};return {memoryUsage:e.memoryUsage||0,cpuUsage:e.cpuUsage||0,taskCount:e.taskCount||0,activeWorkers:e.activeWorkers||0,pendingTasks:e.pendingTasks||0,completedTasks:e.completedTasks||0,failedTasks:e.failedTasks||0,averageTaskDuration:e.averageTaskDuration||0}}function Q(r){let e=r&&typeof r=="object"?r:{};return {maxWorkers:e.maxWorkers||4,minWorkers:e.minWorkers||1,workerIdleTimeout:e.workerIdleTimeout||6e4,taskQueueSize:e.taskQueueSize||100,resourceLimits:e.resourceLimits||{}}}function q(r){let e=r;if(!e||typeof e!="object")throw new Error("Invalid beacon worker message");return {type:e.type||"collect",data:e.data,messageId:e.messageId||crypto.randomUUID(),timestamp:e.timestamp||Date.now()}}var G={batchSize:10,flushInterval:5e3,sessionTimeout:18e5,sessionCookieName:"_as_beacon_session",retryAttempts:3,retryDelay:2e3},X={NETWORK:"network",VALIDATION:"validation",TIMEOUT:"timeout",UNKNOWN:"unknown"},K={DEFAULT_DURATION:36e5,MAX_DURATION:864e5,MIN_DURATION:6e4,STORAGE_KEY:"agentshield_rules",TIMESTAMP_KEY:"agentshield_rules_timestamp"};exports.DEFAULT_CONFIG=G;exports.ERROR_TYPES=X;exports.Guards=U;exports.RULE_CACHE=K;exports.normalizeClientIp=u;exports.parseBeaconConfig=j;exports.parseBeaconWorkerMessage=q;exports.parseCircuitBreakerConfig=H;exports.parseFallbackOptions=P;exports.parseOfflineQueueEntry=F;exports.parseResourceUsage=$;exports.parseRetryStrategy=L;exports.parseWorkerCapabilities=_;exports.parseWorkerConfig=M;exports.parseWorkerError=N;exports.parseWorkerMessage=O;exports.parseWorkerPoolConfig=Q;exports.parseWorkerTask=z;exports.resolveClientIp=S;exports.validateBeaconBatch=B;exports.validateBeaconConfig=W;exports.validateBeaconEvent=w;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});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=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 u(e,t,n){return e?{ip:e,source:t,trusted:n}:null}function d(e,t){return u(c(e),t,!0)}function f(e){return e.explicitAddressTrusted===!0?u(c(e.explicitAddress),`explicit`,!0):null}function p(e){var t,n;return u(c(l(e.headers,`x-vercel-forwarded-for`)),`x-vercel-forwarded-for`,!0)||u(c(l(e.headers,`x-forwarded-for`)),`x-forwarded-for`,!0)||u(c(l(e.headers,`x-real-ip`)),`x-real-ip`,!1)||((t=(n=d(e.frameworkAddress,`framework`))==null?d(e.directAddress,`socket`):n)==null?{ip:null,source:`none`,trusted:!1}:t)}function m(e){var t,n,r,i;return u(c(l(e.headers,`cf-connecting-ip`)),`cf-connecting-ip`,!0)||((t=(n=(r=(i=d(e.directAddress,`socket`))==null?d(e.frameworkAddress,`framework`):i)==null?u(c(l(e.headers,`x-forwarded-for`)),`x-forwarded-for`,!1):r)==null?u(c(l(e.headers,`x-real-ip`)),`x-real-ip`,!1):n)==null?{ip:null,source:`none`,trusted:!1}:t)}function h(e,t){var n,r,i;let a=s(l(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=d(e.frameworkAddress,`framework`))==null?d(e.directAddress,`socket`):i)==null?u(c(l(e.headers,`x-real-ip`)),`x-real-ip`,!1):r)==null?{ip:null,source:`none`,trusted:!1}:n}function g(e){let t=f(e);if(t)return t;switch(e.policy.platform){case`vercel`:return p(e);case`cloudflare`:return m(e);case`trusted-proxy`:return h(e,e.policy.trustedHops);case`direct`:var n,r;return(n=(r=d(e.frameworkAddress,`framework`))==null?d(e.directAddress,`socket`):r)==null?{ip:null,source:`none`,trusted:!1}:n}}function _(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 v(e){if(!e||typeof e!=`object`)return!1;let t=e;return!!(t.projectId&&typeof t.projectId==`string`)}function y(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=>_(e))&&t.sessionId&&typeof t.sessionId==`string`&&t.batchId&&t.timestamp&&typeof t.timestamp==`number`)}function b(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.userId==`string`&&e.userId.length>0}function x(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:b(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||18e5,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 S={isBeaconEvent:_,isBeaconConfig:v,isBeaconBatch:y,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 C(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 w(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 T(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 E(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 D(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 O(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 k(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 A(e){let t=e&&typeof e==`object`?e:{};return{threshold:t.threshold||5,timeout:t.timeout||6e4,resetTimeout:t.resetTimeout||3e4}}function j(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 M(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 N(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 P(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 F={batchSize:10,flushInterval:5e3,sessionTimeout:18e5,sessionCookieName:`_as_beacon_session`,retryAttempts:3,retryDelay:2e3},I={NETWORK:`network`,VALIDATION:`validation`,TIMEOUT:`timeout`,UNKNOWN:`unknown`},L={DEFAULT_DURATION:36e5,MAX_DURATION:864e5,MIN_DURATION:6e4,STORAGE_KEY:`agentshield_rules`,TIMESTAMP_KEY:`agentshield_rules_timestamp`};exports.DEFAULT_CONFIG=F,exports.ERROR_TYPES=I,exports.Guards=S,exports.RULE_CACHE=L,exports.compressIpv6=a,exports.normalizeClientIp=c,exports.parseBeaconConfig=x,exports.parseBeaconWorkerMessage=P,exports.parseCircuitBreakerConfig=A,exports.parseFallbackOptions=O,exports.parseIpv6=i,exports.parseOfflineQueueEntry=j,exports.parseResourceUsage=M,exports.parseRetryStrategy=k,exports.parseWorkerCapabilities=E,exports.parseWorkerConfig=C,exports.parseWorkerError=T,exports.parseWorkerMessage=w,exports.parseWorkerPoolConfig=N,exports.parseWorkerTask=D,exports.resolveClientIp=g,exports.validateBeaconBatch=y,exports.validateBeaconConfig=v,exports.validateBeaconEvent=_;
|
package/dist/browser.mjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
function p(r){for(let e=0;e<r.length;e++){let n=r.charCodeAt(e);if(n<=31||n===127)return true}return false}function b(r){return /^(?:0|[1-9]\d{0,4})$/.test(r)&&Number(r)<=65535}function g(r){let e=r.split(".");if(e.length!==4)return null;let n=[];for(let t of e){if(!/^\d{1,3}$/.test(t))return null;let s=Number(t);if(s>255)return null;n.push(s);}return n}function h(r){return /^[0-9a-fA-F]{1,4}$/.test(r)?Number.parseInt(r,16):null}function I(r){if(!r||r.includes("%")||p(r))return null;let e=r;if(e.includes(".")){let o=e.lastIndexOf(":");if(o<0)return null;let a=g(e.slice(o+1));if(!a)return null;let i=a[0]<<8|a[1],c=a[2]<<8|a[3];e=`${e.slice(0,o+1)}${i.toString(16)}:${c.toString(16)}`;}let n=e.indexOf("::");if(n!==e.lastIndexOf("::"))return null;let t=o=>{if(!o)return [];let a=o.split(":"),i=[];for(let c of a){let m=h(c);if(m===null)return null;i.push(m);}return i};if(n>=0){let o=t(e.slice(0,n)),a=t(e.slice(n+2));if(!o||!a)return null;let i=8-o.length-a.length;return i<1?null:[...o,...Array(i).fill(0),...a]}let s=t(e);return (s==null?void 0:s.length)===8?s:null}function C(r){let e=r.map(i=>i.toString(16)),n=-1,t=1,s=-1;for(let i=0;i<=r.length;i+=1){if(i<r.length&&r[i]===0){s<0&&(s=i);continue}if(s>=0){let c=i-s;c>t&&(n=s,t=c),s=-1;}}if(n<0)return e.join(":");let o=e.slice(0,n).join(":"),a=e.slice(n+t).join(":");return !o&&!a?"::":o?a?`${o}::${a}`:`${o}::`:`::${a}`}function k(r){var o;let e=r.trim();if(!e||e.length>128||p(e))return null;let n=e;if(e.startsWith("[")){let a=e.indexOf("]");if(a<=1)return null;let i=e.slice(a+1);if(i&&(!i.startsWith(":")||!b(i.slice(1))))return null;n=e.slice(1,a);}else if(((o=e.match(/:/g))!=null?o:[]).length===1&&e.includes(".")){let a=e.indexOf(":");if(!b(e.slice(a+1)))return null;n=e.slice(0,a);}let t=g(n);if(t)return t.join(".");let s=I(n);return s?C(s):null}function y(r){if(r==null||!r||r.length>4096||p(r))return null;let e=r.split(",");return e.length>32?null:e}function u(r){let e=y(r);if(!e)return null;for(let n of e){let t=k(n);if(t)return t}return null}function d(r,e){var t;if("get"in r&&typeof r.get=="function")return (t=r.get(e))!=null?t:void 0;let n=e.toLowerCase();for(let[s,o]of Object.entries(r))if(!(s.toLowerCase()!==n||o===void 0))return Array.isArray(o)?o.join(","):o}function l(r,e,n){return r?{ip:r,source:e,trusted:n}:null}function f(r,e){return l(u(r),e,true)}function T(r){return r.explicitAddressTrusted!==true?null:l(u(r.explicitAddress),"explicit",true)}function v(r){var s,o;let e=l(u(d(r.headers,"x-vercel-forwarded-for")),"x-vercel-forwarded-for",true);if(e)return e;let n=l(u(d(r.headers,"x-forwarded-for")),"x-forwarded-for",true);if(n)return n;let t=l(u(d(r.headers,"x-real-ip")),"x-real-ip",false);return t||((o=(s=f(r.frameworkAddress,"framework"))!=null?s:f(r.directAddress,"socket"))!=null?o:{ip:null,source:"none",trusted:false})}function A(r){var n,t,s,o;let e=l(u(d(r.headers,"cf-connecting-ip")),"cf-connecting-ip",true);return e||((o=(s=(t=(n=f(r.directAddress,"socket"))!=null?n:f(r.frameworkAddress,"framework"))!=null?t:l(u(d(r.headers,"x-forwarded-for")),"x-forwarded-for",false))!=null?s:l(u(d(r.headers,"x-real-ip")),"x-real-ip",false))!=null?o:{ip:null,source:"none",trusted:false})}function R(r,e){var s,o,a;let n=d(r.headers,"x-forwarded-for"),t=y(n);if(t&&Number.isInteger(e)&&e>0&&t.length>e){let i=t.map(k),c=t.length-e-1,m=i[c];if(m&&i.every(x=>x!==null))return {ip:m,source:"x-forwarded-for",trusted:true}}return (a=(o=(s=f(r.frameworkAddress,"framework"))!=null?s:f(r.directAddress,"socket"))!=null?o:l(u(d(r.headers,"x-real-ip")),"x-real-ip",false))!=null?a:{ip:null,source:"none",trusted:false}}function S(r){var n,t;let e=T(r);if(e)return e;switch(r.policy.platform){case "vercel":return v(r);case "cloudflare":return A(r);case "trusted-proxy":return R(r,r.policy.trustedHops);case "direct":return (t=(n=f(r.frameworkAddress,"framework"))!=null?n:f(r.directAddress,"socket"))!=null?t:{ip:null,source:"none",trusted:false}}}function w(r){if(!r||typeof r!="object")return false;let e=r,n=e.metadata;return !!(e.type&&typeof e.type=="string"&&e.data&&typeof e.data=="object"&&n&&typeof n=="object"&&n.sessionId&&n.timestamp)}function W(r){if(!r||typeof r!="object")return false;let e=r;return !!(e.projectId&&typeof e.projectId=="string")}function B(r){if(!r||typeof r!="object")return false;let e=r;return !!(e.projectId&&typeof e.projectId=="string"&&Array.isArray(e.events)&&e.events.every(n=>w(n))&&e.sessionId&&typeof e.sessionId=="string"&&e.batchId&&e.timestamp&&typeof e.timestamp=="number")}function E(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof r.userId=="string"&&r.userId.length>0}function j(r){let e=r&&typeof r=="object"?r:{};if(!e.projectId||typeof e.projectId!="string")throw new Error("Project ID is required");return {projectId:e.projectId,environment:e.environment,tags:e.tags,identity:E(e.identity)?e.identity:void 0,endpoint:e.endpoint,enabled:e.enabled!==false,debug:e.debug===true,logLevel:e.logLevel||"error",respectDoNotTrack:e.respectDoNotTrack!==false,anonymizeIp:e.anonymizeIp===true,sessionTimeout:e.sessionTimeout||18e5,sessionCookieName:e.sessionCookieName||"_as_beacon_session",batchSize:e.batchSize||10,flushInterval:e.flushInterval||5e3,maxQueueSize:e.maxQueueSize||100,retryAttempts:e.retryAttempts||3,retryDelay:e.retryDelay||2e3,useWorker:e.useWorker!==false,workerUrl:e.workerUrl,workerConfig:e.workerConfig}}var U={isBeaconEvent:w,isBeaconConfig:W,isBeaconBatch:B,isWorkerMessage(r){if(!r||typeof r!="object")return false;let e=r;return !!(e.id&&e.type&&["request","response","error","heartbeat","status"].includes(e.type)&&typeof e.timestamp=="number")},isWorkerError(r){if(!r||typeof r!="object")return false;let e=r;return !!(e.type&&e.message&&typeof e.timestamp=="number"&&typeof e.recoverable=="boolean")},isWorkerCapabilities(r){if(!r||typeof r!="object")return false;let e=r;return typeof e.workerAPI=="boolean"&&typeof e.sharedArrayBuffer=="boolean"&&typeof e.transferableObjects=="boolean"&&typeof e.offscreenCanvas=="boolean"}};function M(r){let e=r&&typeof r=="object"?r:{};return {enabled:e.enabled!==false,url:e.url,heartbeatInterval:e.heartbeatInterval||5e3,maxUnhealthyCount:e.maxUnhealthyCount||3,maxRetries:e.maxRetries||3,retryDelay:e.retryDelay||1e3,messageTimeout:e.messageTimeout||3e4,compressionThreshold:e.compressionThreshold||1024,allowFallback:e.allowFallback!==false,crossOriginIsolated:e.crossOriginIsolated===true}}function O(r){let e=r;if(!e||typeof e!="object")throw new Error("Invalid worker message");return {id:e.id||crypto.randomUUID(),type:e.type||"request",action:e.action,payload:e.payload,timestamp:e.timestamp||Date.now(),compressed:e.compressed===true,priority:e.priority||"normal",correlationId:e.correlationId}}function N(r){let e=r;return !e||typeof e!="object"?{type:"unknown",message:String(r),timestamp:Date.now(),recoverable:false}:{type:e.type||"unknown",message:e.message||"Unknown error",stack:e.stack,timestamp:e.timestamp||Date.now(),recoverable:!!e.recoverable}}function _(r){let e=r&&typeof r=="object"?r:{};return {workerAPI:e.workerAPI!==false,sharedArrayBuffer:e.sharedArrayBuffer===true,transferableObjects:e.transferableObjects===true,offscreenCanvas:e.offscreenCanvas===true,webAssembly:e.webAssembly===true,atomics:e.atomics===true,bigInt:e.bigInt===true,csp:e.csp||{workerSrc:false,scriptSrc:false,blobUrls:false,inlineWorkers:false},performance:e.performance||{memory:false,measureUserAgentSpecificMemory:false}}}function z(r){let e=r;if(!e||typeof e!="object")throw new Error("Invalid worker task");return {id:e.id||crypto.randomUUID(),type:e.type||"process",data:e.data,priority:e.priority||"normal",createdAt:e.createdAt||Date.now(),startedAt:e.startedAt,completedAt:e.completedAt,error:e.error,maxRetries:e.maxRetries,retries:e.retries,timeout:e.timeout}}function P(r){let e=r&&typeof r=="object"?r:{};return {useRequestIdleCallback:e.useRequestIdleCallback!==false,idleTimeout:e.idleTimeout||1e4,chunkSize:e.chunkSize||10,throttleMs:e.throttleMs||16,maxExecutionTime:e.maxExecutionTime||50}}function L(r){let e=r&&typeof r=="object"?r:{};return {maxAttempts:e.maxAttempts||3,baseDelay:e.baseDelay||1e3,maxDelay:e.maxDelay||3e4,factor:e.factor||2,jitter:e.jitter!==false}}function H(r){let e=r&&typeof r=="object"?r:{};return {threshold:e.threshold||5,timeout:e.timeout||6e4,resetTimeout:e.resetTimeout||3e4}}function F(r){let e=r;if(!e||typeof e!="object")throw new Error("Invalid offline queue entry");return {id:e.id||`${Date.now()}_${Math.random().toString(36).substr(2,9)}`,events:Array.isArray(e.events)?e.events:[],timestamp:e.timestamp||Date.now(),expiresAt:e.expiresAt||Date.now()+864e5,retryCount:e.retryCount||0,size:e.size||0}}function $(r){let e=r&&typeof r=="object"?r:{};return {memoryUsage:e.memoryUsage||0,cpuUsage:e.cpuUsage||0,taskCount:e.taskCount||0,activeWorkers:e.activeWorkers||0,pendingTasks:e.pendingTasks||0,completedTasks:e.completedTasks||0,failedTasks:e.failedTasks||0,averageTaskDuration:e.averageTaskDuration||0}}function Q(r){let e=r&&typeof r=="object"?r:{};return {maxWorkers:e.maxWorkers||4,minWorkers:e.minWorkers||1,workerIdleTimeout:e.workerIdleTimeout||6e4,taskQueueSize:e.taskQueueSize||100,resourceLimits:e.resourceLimits||{}}}function q(r){let e=r;if(!e||typeof e!="object")throw new Error("Invalid beacon worker message");return {type:e.type||"collect",data:e.data,messageId:e.messageId||crypto.randomUUID(),timestamp:e.timestamp||Date.now()}}var G={batchSize:10,flushInterval:5e3,sessionTimeout:18e5,sessionCookieName:"_as_beacon_session",retryAttempts:3,retryDelay:2e3},X={NETWORK:"network",VALIDATION:"validation",TIMEOUT:"timeout",UNKNOWN:"unknown"},K={DEFAULT_DURATION:36e5,MAX_DURATION:864e5,MIN_DURATION:6e4,STORAGE_KEY:"agentshield_rules",TIMESTAMP_KEY:"agentshield_rules_timestamp"};export{G as DEFAULT_CONFIG,X as ERROR_TYPES,U as Guards,K as RULE_CACHE,u as normalizeClientIp,j as parseBeaconConfig,q as parseBeaconWorkerMessage,H as parseCircuitBreakerConfig,P as parseFallbackOptions,F as parseOfflineQueueEntry,$ as parseResourceUsage,L as parseRetryStrategy,_ as parseWorkerCapabilities,M as parseWorkerConfig,N as parseWorkerError,O as parseWorkerMessage,Q as parseWorkerPoolConfig,z as parseWorkerTask,S as resolveClientIp,B as validateBeaconBatch,W as validateBeaconConfig,w 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=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 u(e,t,n){return e?{ip:e,source:t,trusted:n}:null}function d(e,t){return u(c(e),t,!0)}function f(e){return e.explicitAddressTrusted===!0?u(c(e.explicitAddress),`explicit`,!0):null}function p(e){var t,n;return u(c(l(e.headers,`x-vercel-forwarded-for`)),`x-vercel-forwarded-for`,!0)||u(c(l(e.headers,`x-forwarded-for`)),`x-forwarded-for`,!0)||u(c(l(e.headers,`x-real-ip`)),`x-real-ip`,!1)||((t=(n=d(e.frameworkAddress,`framework`))==null?d(e.directAddress,`socket`):n)==null?{ip:null,source:`none`,trusted:!1}:t)}function m(e){var t,n,r,i;return u(c(l(e.headers,`cf-connecting-ip`)),`cf-connecting-ip`,!0)||((t=(n=(r=(i=d(e.directAddress,`socket`))==null?d(e.frameworkAddress,`framework`):i)==null?u(c(l(e.headers,`x-forwarded-for`)),`x-forwarded-for`,!1):r)==null?u(c(l(e.headers,`x-real-ip`)),`x-real-ip`,!1):n)==null?{ip:null,source:`none`,trusted:!1}:t)}function h(e,t){var n,r,i;let a=s(l(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=d(e.frameworkAddress,`framework`))==null?d(e.directAddress,`socket`):i)==null?u(c(l(e.headers,`x-real-ip`)),`x-real-ip`,!1):r)==null?{ip:null,source:`none`,trusted:!1}:n}function g(e){let t=f(e);if(t)return t;switch(e.policy.platform){case`vercel`:return p(e);case`cloudflare`:return m(e);case`trusted-proxy`:return h(e,e.policy.trustedHops);case`direct`:var n,r;return(n=(r=d(e.frameworkAddress,`framework`))==null?d(e.directAddress,`socket`):r)==null?{ip:null,source:`none`,trusted:!1}:n}}function _(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 v(e){if(!e||typeof e!=`object`)return!1;let t=e;return!!(t.projectId&&typeof t.projectId==`string`)}function y(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=>_(e))&&t.sessionId&&typeof t.sessionId==`string`&&t.batchId&&t.timestamp&&typeof t.timestamp==`number`)}function b(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.userId==`string`&&e.userId.length>0}function x(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:b(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||18e5,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 S={isBeaconEvent:_,isBeaconConfig:v,isBeaconBatch:y,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 C(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 w(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 T(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 E(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 D(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 O(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 k(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 A(e){let t=e&&typeof e==`object`?e:{};return{threshold:t.threshold||5,timeout:t.timeout||6e4,resetTimeout:t.resetTimeout||3e4}}function j(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 M(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 N(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 P(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 F={batchSize:10,flushInterval:5e3,sessionTimeout:18e5,sessionCookieName:`_as_beacon_session`,retryAttempts:3,retryDelay:2e3},I={NETWORK:`network`,VALIDATION:`validation`,TIMEOUT:`timeout`,UNKNOWN:`unknown`},L={DEFAULT_DURATION:36e5,MAX_DURATION:864e5,MIN_DURATION:6e4,STORAGE_KEY:`agentshield_rules`,TIMESTAMP_KEY:`agentshield_rules_timestamp`};export{F as DEFAULT_CONFIG,I as ERROR_TYPES,S as Guards,L as RULE_CACHE,a as compressIpv6,c as normalizeClientIp,x as parseBeaconConfig,P as parseBeaconWorkerMessage,A as parseCircuitBreakerConfig,O as parseFallbackOptions,i as parseIpv6,j as parseOfflineQueueEntry,M as parseResourceUsage,k as parseRetryStrategy,E as parseWorkerCapabilities,C as parseWorkerConfig,T as parseWorkerError,w as parseWorkerMessage,N as parseWorkerPoolConfig,D as parseWorkerTask,g as resolveClientIp,y as validateBeaconBatch,v as validateBeaconConfig,_ as validateBeaconEvent};
|
|
2
|
+
//# sourceMappingURL=browser.mjs.map
|
|
@@ -0,0 +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 | 'x-vercel-forwarded-for'\n | 'x-forwarded-for'\n | 'x-real-ip'\n | 'framework'\n | 'socket'\n | 'none';\n\nexport interface ClientIpResolution {\n ip: string | null;\n source: ClientIpSource;\n trusted: boolean;\n}\n\nexport type ClientIpTrustPolicy =\n | { platform: 'vercel' }\n | { platform: 'cloudflare' }\n | { platform: 'trusted-proxy'; trustedHops: number }\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 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 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 resolveVercel(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 resolveCloudflare(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 resolveTrustedProxy(input: ResolveClientIpInput, trustedHops: number): 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/** Resolve a client IP using an explicit deployment trust profile. */\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 resolveVercel(input);\n case 'cloudflare':\n return resolveCloudflare(input);\n case 'trusted-proxy':\n return resolveTrustedProxy(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 | '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 // Kept in step with the `beacon-types` copy of this allowlist by hand.\n // Both parsers drop any key they do not name, silently — which is how\n // `identity` first shipped inert. The check is restated rather than\n // imported because this bundle deliberately has no imports at all.\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) || 1800000, // 30 minutes\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 sessionTimeout: 1800000,\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\n// For future CDN rule loading\nexport const RULE_CACHE = {\n DEFAULT_DURATION: 3600000, // 1 hour\n MAX_DURATION: 86400000, // 24 hours\n MIN_DURATION: 60000, // 1 minute\n STORAGE_KEY: 'agentshield_rules',\n TIMESTAMP_KEY: 'agentshield_rules_timestamp',\n} as const;\n"],"mappings":"AA+CA,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,EAA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S,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,eAAgB,KAChB,kBAAmB,qBACnB,cAAe,EACf,WAAY,GACd,EAEa,EAAc,CACzB,QAAS,UACT,WAAY,aACZ,QAAS,UACT,QAAS,SACX,EAGa,EAAa,CACxB,iBAAkB,KAClB,aAAc,MACd,aAAc,IACd,YAAa,oBACb,cAAe,6BACjB"}
|
|
@@ -1,40 +1,45 @@
|
|
|
1
|
+
//#region src/canonical-signer/payload.d.ts
|
|
1
2
|
interface McpIPayload {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
aud: string;
|
|
4
|
+
iss: string;
|
|
5
|
+
sub: string;
|
|
6
|
+
nonce: string;
|
|
7
|
+
sessionId: string;
|
|
8
|
+
ts: number;
|
|
9
|
+
requestHash: string;
|
|
10
|
+
responseHash: string;
|
|
10
11
|
}
|
|
11
|
-
declare function canonicalSigningPayload(payload: McpIPayload): Uint8Array;
|
|
12
|
-
declare function validateMcpIPayload(value: unknown): McpIPayload;
|
|
13
|
-
|
|
12
|
+
export declare function canonicalSigningPayload(payload: McpIPayload): Uint8Array;
|
|
13
|
+
export declare function validateMcpIPayload(value: unknown): McpIPayload;
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/canonical-signer/key.d.ts
|
|
14
16
|
interface KeyMaterial {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
signingKey: Uint8Array;
|
|
18
|
+
publicKey: Uint8Array;
|
|
19
|
+
did: string;
|
|
20
|
+
kid: string;
|
|
19
21
|
}
|
|
20
|
-
declare function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial>;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
export declare function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial>;
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/canonical-signer/envelope.d.ts
|
|
25
|
+
export declare function signMcpiEnvelope(payload: McpIPayload, key: KeyMaterial): Promise<string>;
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/canonical-signer/parse.d.ts
|
|
24
28
|
interface ParsedJws {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
29
|
+
header: {
|
|
30
|
+
alg: 'EdDSA';
|
|
31
|
+
kid: string;
|
|
32
|
+
typ?: string;
|
|
33
|
+
};
|
|
34
|
+
payload: McpIPayload;
|
|
35
|
+
signatureBytes: Uint8Array;
|
|
36
|
+
signingInput: Uint8Array;
|
|
33
37
|
}
|
|
34
|
-
declare class JwsParseError extends Error {
|
|
35
|
-
|
|
36
|
-
|
|
38
|
+
export declare class JwsParseError extends Error {
|
|
39
|
+
readonly code: 'WrongSegmentCount' | 'InvalidBase64' | 'InvalidJson' | 'InvalidHeaderShape' | 'InvalidPayloadShape' | 'UnsupportedAlgorithm' | 'InvalidSignatureLength';
|
|
40
|
+
constructor(code: 'WrongSegmentCount' | 'InvalidBase64' | 'InvalidJson' | 'InvalidHeaderShape' | 'InvalidPayloadShape' | 'UnsupportedAlgorithm' | 'InvalidSignatureLength', message: string);
|
|
37
41
|
}
|
|
38
|
-
declare function parseJwsCompact(jws: string): ParsedJws;
|
|
39
|
-
|
|
40
|
-
export {
|
|
42
|
+
export declare function parseJwsCompact(jws: string): ParsedJws;
|
|
43
|
+
//#endregion
|
|
44
|
+
export type { KeyMaterial, McpIPayload, ParsedJws };
|
|
45
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/canonical-signer/key.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"mappings":";UA+BiB;EAEf;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;;wBAsBc,wBAAwB,SAAS,cAAc;wBAmD/C,oBAAoB,iBAAiB;;;UC7EpC;EAEf,YAAY;EAEZ,WAAW;EAEX;EAMA;;wBAmBoB,gBAAgB,MAAM,aAAa,QAAQ;;;wBCjB3C,iBAAiB,SAAS,aAAa,KAAK,cAAc;;;UCnB/D;EAEf;IACE;IAIA;IAGA;;EAGF,SAAS;EAET,gBAAgB;EAMhB,cAAc;;qBAQH,sBAAsB;WAGf;EAAA,YAAA,gKAQhB;;wBAwFY,gBAAgB,cAAc"}
|
|
@@ -1,40 +1,45 @@
|
|
|
1
|
+
//#region src/canonical-signer/payload.d.ts
|
|
1
2
|
interface McpIPayload {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
aud: string;
|
|
4
|
+
iss: string;
|
|
5
|
+
sub: string;
|
|
6
|
+
nonce: string;
|
|
7
|
+
sessionId: string;
|
|
8
|
+
ts: number;
|
|
9
|
+
requestHash: string;
|
|
10
|
+
responseHash: string;
|
|
10
11
|
}
|
|
11
|
-
declare function canonicalSigningPayload(payload: McpIPayload): Uint8Array;
|
|
12
|
-
declare function validateMcpIPayload(value: unknown): McpIPayload;
|
|
13
|
-
|
|
12
|
+
export declare function canonicalSigningPayload(payload: McpIPayload): Uint8Array;
|
|
13
|
+
export declare function validateMcpIPayload(value: unknown): McpIPayload;
|
|
14
|
+
//#endregion
|
|
15
|
+
//#region src/canonical-signer/key.d.ts
|
|
14
16
|
interface KeyMaterial {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
signingKey: Uint8Array;
|
|
18
|
+
publicKey: Uint8Array;
|
|
19
|
+
did: string;
|
|
20
|
+
kid: string;
|
|
19
21
|
}
|
|
20
|
-
declare function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial>;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
export declare function parseSigningKey(seed: Uint8Array): Promise<KeyMaterial>;
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/canonical-signer/envelope.d.ts
|
|
25
|
+
export declare function signMcpiEnvelope(payload: McpIPayload, key: KeyMaterial): Promise<string>;
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/canonical-signer/parse.d.ts
|
|
24
28
|
interface ParsedJws {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
29
|
+
header: {
|
|
30
|
+
alg: 'EdDSA';
|
|
31
|
+
kid: string;
|
|
32
|
+
typ?: string;
|
|
33
|
+
};
|
|
34
|
+
payload: McpIPayload;
|
|
35
|
+
signatureBytes: Uint8Array;
|
|
36
|
+
signingInput: Uint8Array;
|
|
33
37
|
}
|
|
34
|
-
declare class JwsParseError extends Error {
|
|
35
|
-
|
|
36
|
-
|
|
38
|
+
export declare class JwsParseError extends Error {
|
|
39
|
+
readonly code: 'WrongSegmentCount' | 'InvalidBase64' | 'InvalidJson' | 'InvalidHeaderShape' | 'InvalidPayloadShape' | 'UnsupportedAlgorithm' | 'InvalidSignatureLength';
|
|
40
|
+
constructor(code: 'WrongSegmentCount' | 'InvalidBase64' | 'InvalidJson' | 'InvalidHeaderShape' | 'InvalidPayloadShape' | 'UnsupportedAlgorithm' | 'InvalidSignatureLength', message: string);
|
|
37
41
|
}
|
|
38
|
-
declare function parseJwsCompact(jws: string): ParsedJws;
|
|
39
|
-
|
|
40
|
-
export {
|
|
42
|
+
export declare function parseJwsCompact(jws: string): ParsedJws;
|
|
43
|
+
//#endregion
|
|
44
|
+
export type { KeyMaterial, McpIPayload, ParsedJws };
|
|
45
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/canonical-signer/payload.ts","../../src/canonical-signer/key.ts","../../src/canonical-signer/envelope.ts","../../src/canonical-signer/parse.ts"],"mappings":";UA+BiB;EAEf;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;EAEA;;wBAsBc,wBAAwB,SAAS,cAAc;wBAmD/C,oBAAoB,iBAAiB;;;UC7EpC;EAEf,YAAY;EAEZ,WAAW;EAEX;EAMA;;wBAmBoB,gBAAgB,MAAM,aAAa,QAAQ;;;wBCjB3C,iBAAiB,SAAS,aAAa,KAAK,cAAc;;;UCnB/D;EAEf;IACE;IAIA;IAGA;;EAGF,SAAS;EAET,gBAAgB;EAMhB,cAAc;;qBAQH,sBAAsB;WAGf;EAAA,YAAA,gKAQhB;;wBAwFY,gBAAgB,cAAc"}
|