zeno.id 0.5.0 → 0.6.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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Creative Code Solutions B.V.
3
+ Copyright (c) 2026 Zeno
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -112,7 +112,7 @@ The script's code uses no `eval` or `new Function`, so `'unsafe-eval'` isn't nee
112
112
  | `action` | What the visitor is doing, like `login`, `signup` or `checkout`, up to 1,024 characters. Returned with the event. |
113
113
  | `metadata` | Your own key-values kept with the event, like `{ orderId: 'A-1042', plan: 'pro' }`: up to 20 keys of 1 to 40 letters, digits, `_`, `.` or `-`, each a string up to 256 characters, a number or a boolean, 2 KB in all. Returned with the event, never used for detection. |
114
114
 
115
- The script keeps no visitor id itself. The route keeps it in the `zeno_id` cookie (`HttpOnly`, `SameSite=Lax`, `Secure` on https, a year), on the route's own path, so two routes on one site, like a site's own login and a demo, keep separate ids. Zeno reuses it while it's still the same device, so the id survives browser updates. The script keeps nothing in the browser's storage, and every `identify()` identifies again.
115
+ The script keeps no visitor id itself. The route keeps it in the `zeno_id` cookie (`HttpOnly`, `SameSite=Lax`, `Secure` on https, 400 days from the last identification), on the route's own path, so two routes on one site, like a site's own login and a demo, keep separate ids. The script keeps a copy in the site's `localStorage` (`zeno:id:` and the route's path), used only when the cookie is gone. Zeno reuses either while it's still the same device, so the id survives browser updates. Every `identify()` identifies again.
116
116
 
117
117
  ### Stop and forget
118
118
 
@@ -202,7 +202,7 @@ That `start()` takes the path it was imported from unless you pass another, and
202
202
  The browser SDK never talks to Zeno directly. It loads its script from a route on your own site and sends its identifications there, and the route passes them on with your API key and the visitor's IP.
203
203
 
204
204
  - Ad and tracker blockers block requests to identification services. A path on your own site looks like any other request your pages make.
205
- - The route keeps the visitor id in a first-party `HttpOnly` cookie (`zeno_id`) that it sets itself, which Safari keeps for a year where it would delete a script's storage after 7 days.
205
+ - The route keeps the visitor id in a first-party `HttpOnly` cookie (`zeno_id`) that it sets itself, which Safari keeps for 400 days where it deletes a script's storage after 7 days without a visit; the script's `localStorage` copy covers a browser that cleared only its cookies.
206
206
  - Your API key stays on your server, and the route refuses a browser's cross-site request, so there's no allow list of origins to keep.
207
207
 
208
208
  `createProxy(apiKey, options?)` returns the route's handler: `zeno(request, ip)` takes a standard `Request` and the IP address it came from, and returns a `Response`, using web APIs only. The browser SDK calls it with two methods on one path: `GET` loads the script (gzipped when the browser takes it; `HEAD` too), and `POST` identifies, or, as `forget()`, clears the visitor id for withdrawn consent.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
1
  Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e={client_timeout:`Client timeout`,network_connection:`Network connection error`,csp_block:`Blocked by the Content Security Policy`,insecure_context:`Zeno needs a secure context (https)`,collection_failed:`Collecting the browser data failed`,invalid_options:`The options are invalid`,server_error:`The identification api failed`,account_closed:`The project's organization is closed; contact Zeno support to reopen it`,script_load_failed:`The script couldn't be loaded from the endpoint`,stopped:`Identification was stopped; call start() again to identify`,capped:`Nothing was identified: a spend limit or rate limit was reached`,not_in_browser:`Zeno identifies in the browser only; this ran on the server`};var t=class extends Error{code;constructor(t,n){super(n??e[t]),this.code=t,this.name=`ZenoError`}};const n=n=>{if(n instanceof t)return n;let{name:r,code:i,message:a}=typeof n==`object`&&n?n:{},o=typeof a==`string`?a:void 0;return r===`ZenoError`&&typeof i==`string`&&i in e?new t(i,o):new t(`collection_failed`,o)},r=e=>{let n=!1,r=t=>{t.blockedURI.startsWith(e)&&(n=!0)};return globalThis.document?.addEventListener(`securitypolicyviolation`,r),{errorFor:async(e,r)=>(await new Promise(e=>setTimeout(e,0)),n?new t(`csp_block`,r):e),stop:()=>globalThis.document?.removeEventListener(`securitypolicyviolation`,r)}},i=e=>import(
2
2
  /* @vite-ignore */
3
3
  /* webpackIgnore: true */
4
- e),a=e=>new t(`invalid_options`,e),o=e=>{if(typeof e==`string`&&/^\/(?![/\\])[^?#\\]*$/.test(e))try{let t=new URL(globalThis.location.href),n=new URL(e,t);return n.origin===t.origin?`${n.origin}${n.pathname}`:void 0}catch{return}},s=e=>typeof e==`string`&&e.length>0&&e.length<=200?e:void 0,c=(e,t=`start`)=>{let n=o(e??`/zeno`);if(!n)throw a(`${t}() takes your proxy route's path on this site, like ${t}('/zeno')`);return n},l=e=>{if(typeof e!=`object`||!e)throw a(`Pass the identify() options as an object: identify({ externalId, action })`);let{externalId:t,action:n,metadata:r}=e;if(t!==void 0&&(typeof t!=`string`||!t||t.length>256))throw a(`externalId must be a string of 1 to 256 characters`);if(t===`.`||t===`..`)throw a(`externalId can’t be . or ..`);if(n!==void 0&&(typeof n!=`string`||n.length>1024))throw a(`action must be a string of at most 1,024 characters`);if(r!==void 0&&(typeof r!=`object`||!r||Array.isArray(r)))throw a(`metadata must be an object of keys and values, like { orderId: 'A-1042' }`)},u=e=>fetch(`${e}?forget`,{method:`POST`,credentials:`same-origin`,keepalive:!0}),d=async e=>{if(typeof document>`u`)throw new t(`not_in_browser`);let n=c(e,`forget`),i=r(new URL(n).origin),a;try{a=await u(n)}catch{throw await i.errorFor(new t(`network_connection`))}finally{i.stop()}if(!a.ok)throw new t(`server_error`,`The route answered ${a.status} when asked to clear its cookie`)},f=(e,t,n)=>{let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(n()),t)})]).finally(()=>clearTimeout(r))},p=e=>({requestId:void 0,error:n(e)}),m=e=>e.error?{...e,error:n(e.error)}:e,h=()=>({identify:()=>Promise.resolve(p(new t(`not_in_browser`))),stop(){}}),g=e=>async()=>{try{let t=await i(`${e}?challenge=${Date.now()}`);return s(t?.challengeToken)}catch{return}},_=async e=>{let n=new t(`script_load_failed`,`The script couldn't be loaded from ${e}: check that your proxy route answers there`);try{let r=await fetch(e,{credentials:`same-origin`});if(r.ok)return await r.body?.cancel(),/javascript/i.test(r.headers.get(`content-type`)??``)?n:new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);let i=await r.json().catch(()=>void 0),a=typeof i?.error==`string`?i.error:void 0;return a===`invalid_api_key`?new t(`server_error`,`The proxy route's API key was refused: check the API key the route on your server is set up with`):a===`account_closed`?new t(`account_closed`):a||r.status>=500?new t(`server_error`,`The route at ${e} answered ${r.status}${a?` ${a}`:``} for the script`):new t(`script_load_failed`,`The route at ${e} answered ${r.status}: check that your proxy route answers there`)}catch{return n}},v=async(e,a,o)=>{let c=r(new URL(e).origin),l;try{l=await i(e)}catch{let n=await c.errorFor(new t(`script_load_failed`),`The page's Content Security Policy blocked loading the script from ${e}: allow it in script-src`);throw n.code===`csp_block`?n:await _(e)}finally{c.stop()}if(a())throw new t(`stopped`);if(typeof l?.start!=`function`)throw new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);try{let t=l.start(new URL(e).pathname,{challengeToken:s(l.challengeToken),refreshChallengeToken:g(e)});return o(t),t}catch(e){throw n(e)}},y=e=>{if(typeof document>`u`)return h();let n=c(e),r=!1,i,a=()=>{},o=new Promise((e,t)=>{a=t});o.catch(()=>{});let s=v(n,()=>r,e=>i=e);s.catch(()=>{});let d=async e=>{if(r)throw new t(`stopped`);l(e);let n=1e4,i=performance.now(),a=await f(Promise.race([s,o]),n,()=>new t(`client_timeout`)),c=Math.max(1,n-(performance.now()-i));if(r)throw new t(`stopped`);return m(await a.identify({...e,timeout:c}))};return{identify:(e={})=>d(e).catch(p),stop(){r||(r=!0,a(new t(`stopped`))),i?i.stop():u(n).catch(()=>{})}}};exports.ZenoError=t,exports.forget=d,exports.start=y;
4
+ e),a=e=>new t(`invalid_options`,e),o=e=>{if(typeof e==`string`&&/^\/(?![/\\])[^?#\\]*$/.test(e))try{let t=new URL(globalThis.location.href),n=new URL(e,t);return n.origin===t.origin?`${n.origin}${n.pathname}`:void 0}catch{return}},s=e=>typeof e==`string`&&e.length>0&&e.length<=200?e:void 0,c=(e,t=`start`)=>{let n=o(e??`/zeno`);if(!n)throw a(`${t}() takes your proxy route's path on this site, like ${t}('/zeno')`);return n},l=e=>{if(typeof e!=`object`||!e)throw a(`Pass the identify() options as an object: identify({ externalId, action })`);let{externalId:t,action:n,metadata:r}=e;if(t!==void 0&&(typeof t!=`string`||!t||t.length>256))throw a(`externalId must be a string of 1 to 256 characters`);if(t===`.`||t===`..`)throw a(`externalId can’t be . or ..`);if(n!==void 0&&(typeof n!=`string`||n.length>1024))throw a(`action must be a string of at most 1,024 characters`);if(r!==void 0&&(typeof r!=`object`||!r||Array.isArray(r)))throw a(`metadata must be an object of keys and values, like { orderId: 'A-1042' }`)},u=e=>`zeno:id:${new URL(e).pathname}`,d=()=>{try{return globalThis.localStorage??void 0}catch{return}},f=e=>{try{d()?.removeItem(u(e))}catch{}return fetch(`${e}?forget`,{method:`POST`,credentials:`same-origin`,keepalive:!0})},p=async e=>{if(typeof document>`u`)throw new t(`not_in_browser`);let n=c(e,`forget`),i=r(new URL(n).origin),a;try{a=await f(n)}catch{throw await i.errorFor(new t(`network_connection`))}finally{i.stop()}if(!a.ok)throw new t(`server_error`,`The route answered ${a.status} when asked to clear its cookie`)},m=(e,t,n)=>{let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(n()),t)})]).finally(()=>clearTimeout(r))},h=e=>({requestId:void 0,error:n(e)}),g=e=>e.error?{...e,error:n(e.error)}:e,_=()=>({identify:()=>Promise.resolve(h(new t(`not_in_browser`))),stop(){}}),v=e=>async()=>{try{let t=await i(`${e}?challenge=${Date.now()}`);return s(t?.challengeToken)}catch{return}},y=async e=>{let n=new t(`script_load_failed`,`The script couldn't be loaded from ${e}: check that your proxy route answers there`);try{let r=await fetch(e,{credentials:`same-origin`});if(r.ok)return await r.body?.cancel(),/javascript/i.test(r.headers.get(`content-type`)??``)?n:new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);let i=await r.json().catch(()=>void 0),a=typeof i?.error==`string`?i.error:void 0;return a===`invalid_api_key`?new t(`server_error`,`The proxy route's API key was refused: check the API key the route on your server is set up with`):a===`account_closed`?new t(`account_closed`):a||r.status>=500?new t(`server_error`,`The route at ${e} answered ${r.status}${a?` ${a}`:``} for the script`):new t(`script_load_failed`,`The route at ${e} answered ${r.status}: check that your proxy route answers there`)}catch{return n}},b=async(e,a,o)=>{let c=r(new URL(e).origin),l;try{l=await i(e)}catch{let n=await c.errorFor(new t(`script_load_failed`),`The page's Content Security Policy blocked loading the script from ${e}: allow it in script-src`);throw n.code===`csp_block`?n:await y(e)}finally{c.stop()}if(a())throw new t(`stopped`);if(typeof l?.start!=`function`)throw new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);try{let t=l.start(new URL(e).pathname,{challengeToken:s(l.challengeToken),refreshChallengeToken:v(e)});return o(t),t}catch(e){throw n(e)}},x=e=>{if(typeof document>`u`)return _();let n=c(e),r=!1,i,a=()=>{},o=new Promise((e,t)=>{a=t});o.catch(()=>{});let s=b(n,()=>r,e=>i=e);s.catch(()=>{});let u=async e=>{if(r)throw new t(`stopped`);l(e);let n=1e4,i=performance.now(),a=await m(Promise.race([s,o]),n,()=>new t(`client_timeout`)),c=Math.max(1,n-(performance.now()-i));if(r)throw new t(`stopped`);return g(await a.identify({...e,timeout:c}))};return{identify:(e={})=>u(e).catch(h),stop(){r||(r=!0,a(new t(`stopped`))),i?i.stop():f(n).catch(()=>{})}}};exports.ZenoError=t,exports.forget=p,exports.start=x;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  const e={client_timeout:`Client timeout`,network_connection:`Network connection error`,csp_block:`Blocked by the Content Security Policy`,insecure_context:`Zeno needs a secure context (https)`,collection_failed:`Collecting the browser data failed`,invalid_options:`The options are invalid`,server_error:`The identification api failed`,account_closed:`The project's organization is closed; contact Zeno support to reopen it`,script_load_failed:`The script couldn't be loaded from the endpoint`,stopped:`Identification was stopped; call start() again to identify`,capped:`Nothing was identified: a spend limit or rate limit was reached`,not_in_browser:`Zeno identifies in the browser only; this ran on the server`};var t=class extends Error{code;constructor(t,n){super(n??e[t]),this.code=t,this.name=`ZenoError`}};const n=n=>{if(n instanceof t)return n;let{name:r,code:i,message:a}=typeof n==`object`&&n?n:{},o=typeof a==`string`?a:void 0;return r===`ZenoError`&&typeof i==`string`&&i in e?new t(i,o):new t(`collection_failed`,o)},r=e=>{let n=!1,r=t=>{t.blockedURI.startsWith(e)&&(n=!0)};return globalThis.document?.addEventListener(`securitypolicyviolation`,r),{errorFor:async(e,r)=>(await new Promise(e=>setTimeout(e,0)),n?new t(`csp_block`,r):e),stop:()=>globalThis.document?.removeEventListener(`securitypolicyviolation`,r)}},i=e=>import(
2
2
  /* @vite-ignore */
3
3
  /* webpackIgnore: true */
4
- e),a=e=>new t(`invalid_options`,e),o=e=>{if(typeof e==`string`&&/^\/(?![/\\])[^?#\\]*$/.test(e))try{let t=new URL(globalThis.location.href),n=new URL(e,t);return n.origin===t.origin?`${n.origin}${n.pathname}`:void 0}catch{return}},s=e=>typeof e==`string`&&e.length>0&&e.length<=200?e:void 0,c=(e,t=`start`)=>{let n=o(e??`/zeno`);if(!n)throw a(`${t}() takes your proxy route's path on this site, like ${t}('/zeno')`);return n},l=e=>{if(typeof e!=`object`||!e)throw a(`Pass the identify() options as an object: identify({ externalId, action })`);let{externalId:t,action:n,metadata:r}=e;if(t!==void 0&&(typeof t!=`string`||!t||t.length>256))throw a(`externalId must be a string of 1 to 256 characters`);if(t===`.`||t===`..`)throw a(`externalId can’t be . or ..`);if(n!==void 0&&(typeof n!=`string`||n.length>1024))throw a(`action must be a string of at most 1,024 characters`);if(r!==void 0&&(typeof r!=`object`||!r||Array.isArray(r)))throw a(`metadata must be an object of keys and values, like { orderId: 'A-1042' }`)},u=e=>fetch(`${e}?forget`,{method:`POST`,credentials:`same-origin`,keepalive:!0}),d=async e=>{if(typeof document>`u`)throw new t(`not_in_browser`);let n=c(e,`forget`),i=r(new URL(n).origin),a;try{a=await u(n)}catch{throw await i.errorFor(new t(`network_connection`))}finally{i.stop()}if(!a.ok)throw new t(`server_error`,`The route answered ${a.status} when asked to clear its cookie`)},f=(e,t,n)=>{let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(n()),t)})]).finally(()=>clearTimeout(r))},p=e=>({requestId:void 0,error:n(e)}),m=e=>e.error?{...e,error:n(e.error)}:e,h=()=>({identify:()=>Promise.resolve(p(new t(`not_in_browser`))),stop(){}}),g=e=>async()=>{try{let t=await i(`${e}?challenge=${Date.now()}`);return s(t?.challengeToken)}catch{return}},_=async e=>{let n=new t(`script_load_failed`,`The script couldn't be loaded from ${e}: check that your proxy route answers there`);try{let r=await fetch(e,{credentials:`same-origin`});if(r.ok)return await r.body?.cancel(),/javascript/i.test(r.headers.get(`content-type`)??``)?n:new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);let i=await r.json().catch(()=>void 0),a=typeof i?.error==`string`?i.error:void 0;return a===`invalid_api_key`?new t(`server_error`,`The proxy route's API key was refused: check the API key the route on your server is set up with`):a===`account_closed`?new t(`account_closed`):a||r.status>=500?new t(`server_error`,`The route at ${e} answered ${r.status}${a?` ${a}`:``} for the script`):new t(`script_load_failed`,`The route at ${e} answered ${r.status}: check that your proxy route answers there`)}catch{return n}},v=async(e,a,o)=>{let c=r(new URL(e).origin),l;try{l=await i(e)}catch{let n=await c.errorFor(new t(`script_load_failed`),`The page's Content Security Policy blocked loading the script from ${e}: allow it in script-src`);throw n.code===`csp_block`?n:await _(e)}finally{c.stop()}if(a())throw new t(`stopped`);if(typeof l?.start!=`function`)throw new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);try{let t=l.start(new URL(e).pathname,{challengeToken:s(l.challengeToken),refreshChallengeToken:g(e)});return o(t),t}catch(e){throw n(e)}},y=e=>{if(typeof document>`u`)return h();let n=c(e),r=!1,i,a=()=>{},o=new Promise((e,t)=>{a=t});o.catch(()=>{});let s=v(n,()=>r,e=>i=e);s.catch(()=>{});let d=async e=>{if(r)throw new t(`stopped`);l(e);let n=1e4,i=performance.now(),a=await f(Promise.race([s,o]),n,()=>new t(`client_timeout`)),c=Math.max(1,n-(performance.now()-i));if(r)throw new t(`stopped`);return m(await a.identify({...e,timeout:c}))};return{identify:(e={})=>d(e).catch(p),stop(){r||(r=!0,a(new t(`stopped`))),i?i.stop():u(n).catch(()=>{})}}};export{t as ZenoError,d as forget,y as start};
4
+ e),a=e=>new t(`invalid_options`,e),o=e=>{if(typeof e==`string`&&/^\/(?![/\\])[^?#\\]*$/.test(e))try{let t=new URL(globalThis.location.href),n=new URL(e,t);return n.origin===t.origin?`${n.origin}${n.pathname}`:void 0}catch{return}},s=e=>typeof e==`string`&&e.length>0&&e.length<=200?e:void 0,c=(e,t=`start`)=>{let n=o(e??`/zeno`);if(!n)throw a(`${t}() takes your proxy route's path on this site, like ${t}('/zeno')`);return n},l=e=>{if(typeof e!=`object`||!e)throw a(`Pass the identify() options as an object: identify({ externalId, action })`);let{externalId:t,action:n,metadata:r}=e;if(t!==void 0&&(typeof t!=`string`||!t||t.length>256))throw a(`externalId must be a string of 1 to 256 characters`);if(t===`.`||t===`..`)throw a(`externalId can’t be . or ..`);if(n!==void 0&&(typeof n!=`string`||n.length>1024))throw a(`action must be a string of at most 1,024 characters`);if(r!==void 0&&(typeof r!=`object`||!r||Array.isArray(r)))throw a(`metadata must be an object of keys and values, like { orderId: 'A-1042' }`)},u=e=>`zeno:id:${new URL(e).pathname}`,d=()=>{try{return globalThis.localStorage??void 0}catch{return}},f=e=>{try{d()?.removeItem(u(e))}catch{}return fetch(`${e}?forget`,{method:`POST`,credentials:`same-origin`,keepalive:!0})},p=async e=>{if(typeof document>`u`)throw new t(`not_in_browser`);let n=c(e,`forget`),i=r(new URL(n).origin),a;try{a=await f(n)}catch{throw await i.errorFor(new t(`network_connection`))}finally{i.stop()}if(!a.ok)throw new t(`server_error`,`The route answered ${a.status} when asked to clear its cookie`)},m=(e,t,n)=>{let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(n()),t)})]).finally(()=>clearTimeout(r))},h=e=>({requestId:void 0,error:n(e)}),g=e=>e.error?{...e,error:n(e.error)}:e,_=()=>({identify:()=>Promise.resolve(h(new t(`not_in_browser`))),stop(){}}),v=e=>async()=>{try{let t=await i(`${e}?challenge=${Date.now()}`);return s(t?.challengeToken)}catch{return}},y=async e=>{let n=new t(`script_load_failed`,`The script couldn't be loaded from ${e}: check that your proxy route answers there`);try{let r=await fetch(e,{credentials:`same-origin`});if(r.ok)return await r.body?.cancel(),/javascript/i.test(r.headers.get(`content-type`)??``)?n:new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);let i=await r.json().catch(()=>void 0),a=typeof i?.error==`string`?i.error:void 0;return a===`invalid_api_key`?new t(`server_error`,`The proxy route's API key was refused: check the API key the route on your server is set up with`):a===`account_closed`?new t(`account_closed`):a||r.status>=500?new t(`server_error`,`The route at ${e} answered ${r.status}${a?` ${a}`:``} for the script`):new t(`script_load_failed`,`The route at ${e} answered ${r.status}: check that your proxy route answers there`)}catch{return n}},b=async(e,a,o)=>{let c=r(new URL(e).origin),l;try{l=await i(e)}catch{let n=await c.errorFor(new t(`script_load_failed`),`The page's Content Security Policy blocked loading the script from ${e}: allow it in script-src`);throw n.code===`csp_block`?n:await y(e)}finally{c.stop()}if(a())throw new t(`stopped`);if(typeof l?.start!=`function`)throw new t(`script_load_failed`,`${e} didn't answer with the script; check the endpoint`);try{let t=l.start(new URL(e).pathname,{challengeToken:s(l.challengeToken),refreshChallengeToken:v(e)});return o(t),t}catch(e){throw n(e)}},x=e=>{if(typeof document>`u`)return _();let n=c(e),r=!1,i,a=()=>{},o=new Promise((e,t)=>{a=t});o.catch(()=>{});let s=b(n,()=>r,e=>i=e);s.catch(()=>{});let u=async e=>{if(r)throw new t(`stopped`);l(e);let n=1e4,i=performance.now(),a=await m(Promise.race([s,o]),n,()=>new t(`client_timeout`)),c=Math.max(1,n-(performance.now()-i));if(r)throw new t(`stopped`);return g(await a.identify({...e,timeout:c}))};return{identify:(e={})=>u(e).catch(h),stop(){r||(r=!0,a(new t(`stopped`))),i?i.stop():f(n).catch(()=>{})}}};export{t as ZenoError,p as forget,x as start};
@@ -1,2 +1,2 @@
1
1
  Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=e=>typeof e==`object`&&!!e&&!Array.isArray(e),t=(e,t,n=`https://api.zeno.id`)=>{if(!t)return{problem:`${e}'s apiKey is missing: pass your API key (ZENO_API_KEY in your environment)`};if(!n)return{problem:`${e}'s apiUrl is missing: this copy of zeno.id/server has no default, so pass the Zeno API's origin as apiUrl`};try{if([`http:`,`https:`].includes(new URL(n).protocol))return{apiKey:t,base:n.replace(/\/+$/,``)}}catch{}return{problem:`${e}'s apiUrl must be the Zeno API's http(s) origin, like https://api.example.com, not ${JSON.stringify(n)}`}},n=e=>{if(!e.includes(`:`))return e;let t=e.match(/^(?:::|(?:0{1,4}:){5})ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);if(t)return t[1];let[n=``,r=``]=e.split(`::`),i=n?n.split(`:`):[],a=r?r.split(`:`):[],o=Math.max(0,8-i.length-a.length),s=[...i,...Array.from({length:o},()=>`0`),...a].map(e=>e.toLowerCase().replace(/^0+(?=\w)/,``));if(s.slice(0,5).every(e=>e===`0`)&&s[5]===`ffff`){let[e=0,t=0]=s.slice(6).map(e=>parseInt(e,16));return[e>>8,e&255,t>>8,t&255].join(`.`)}return s.slice(0,4).join(`:`)},r=(e,t)=>{let r=t.trim();return e.includes(`:`)===r.includes(`:`)&&n(e)!==n(r)},i=(e,t)=>{let n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r)a===`\\`?i++:a===`"`&&(r=!1);else if(a===`"`)r=!0;else if(a===`{`||a===`[`){if(++n>t)return!0}else(a===`}`||a===`]`)&&n--}return!1},a=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),o=e=>{let t=e?.rawHeaders;return a(t)?t:void 0},s=`zeno_id`,c=1e4,l=(e,t,n={})=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`,...n}}),u=e=>l(400,{error:`invalid_request`,message:e}),d=(e,t=500)=>l(t,{error:`server_error`,message:e}),f=`Pass the IP address the request came from: zeno(request, ip)`,p=async(e,t)=>{if(Number(e.headers.get(`content-length`))>t)return;if(!e.body)return``;let n=e.body.getReader(),r=[],i=0;for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.byteLength,i>t){await n.cancel();return}r.push(a)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)},m=e=>{for(let t of e.split(`;`)){let e=t.indexOf(`=`);if(e!==-1&&t.slice(0,e).trim()===s)return t.slice(e+1).trim()}},h=(e,t)=>{if(!t)return Array.from(e.headers.entries());let n=[];for(let e=0;e+1<t.length;e+=2)n.push([t[e],t[e+1]]);return n},g=/* @__PURE__ */ new Set([`user-agent`,`origin`,`signature-agent`,`signature-input`]),_=e=>e.map(([e,t])=>[e,g.has(e.toLowerCase())?t:``]),v=e=>{for(let[t,n]of e){let e=t.toLowerCase()===`cookie`?m(n):void 0;if(e!==void 0)return/^[A-Za-z0-9]{20}$/.test(e)?e:void 0}},y=e=>e?.trim().replace(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i,`$1`)||void 0,b=(e,t,n,r=e.pathname)=>{let i=[`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||e.hostname.endsWith(`.localhost`),a=e.protocol===`http:`&&i?``:`; Secure`,o=r.replace(/[;,\s]/g,encodeURIComponent);return`${s}=${t}; Max-Age=${n}; Path=${o}; HttpOnly${a}; SameSite=Lax`},x=e=>(e.headers.get(`accept-encoding`)??``).split(`,`).some(e=>{let[t=``,...n]=e.split(`;`).map(e=>e.trim().toLowerCase()),r=n.find(e=>e.startsWith(`q=`));return(t===`gzip`||t===`*`)&&!(r&&Number(r.slice(2))===0)}),S=t=>e(t)?t.capped===!0||typeof t.requestId==`string`&&[`undefined`,`string`].includes(typeof t.visitorId)&&[`undefined`,`boolean`].includes(typeof t.returning)&&[`undefined`,`string`].includes(typeof t.sealedResult):!1,C=t=>{if(!e(t))return;let{value:n,maxAge:r}=t;return typeof n==`string`&&/^[A-Za-z0-9]{1,64}$/.test(n)&&typeof r==`number`&&Number.isInteger(r)&&r>=0?{value:n,maxAge:r}:void 0},w=e=>new Response(new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`))).arrayBuffer(),T=async(e,t,n)=>{let r={"content-type":`text/javascript; charset=utf-8`,"cache-control":n,vary:`accept-encoding`},i=typeof t==`string`?t:t.code;if(!x(e)||typeof CompressionStream!=`function`)return new Response(i,{headers:r});let a=typeof t==`string`?w(i):t.gzipped??=w(i);return new Response(await a,{headers:{...r,"content-encoding":`gzip`}})},E=(e,t)=>[`const code = await import(new URL(${JSON.stringify(`?${new URLSearchParams({v:e})}`)}, import.meta.url))`,`export const challengeToken = ${t}`,`const own = new URL(import.meta.url)`,`const refreshChallengeToken = () => import(new URL("?challenge=" + Date.now(), own)).then(module => module.challengeToken, () => undefined)`,`export const start = (path = own.pathname, options) => code.start(path, { challengeToken, refreshChallengeToken, ...options })`,``].join(`
2
- `),D=(n,r={})=>{let{apiUrl:a,cookiePath:s,fetch:m=globalThis.fetch}=r,g,x=``,w=``,D=async(e,t)=>{try{return await m(`${w}${e}`,{...t,signal:AbortSignal.timeout(c)})}catch(t){let n=t instanceof Error&&t.name===`TimeoutError`?`no answer within ${c} ms`:String(t);console.error(`The proxy route couldn't reach Zeno at ${w}${e}: ${n}`);return}},O=async(t,n)=>{let r=await t.json().catch(()=>void 0),i=e(r)&&typeof r.error==`string`?r.error:void 0,a=e(r)&&typeof r.message==`string`?r.message:void 0;if(t.status===401)return console.error(`Zeno refused the proxy route's API key (401${i?` ${i}`:``}${a?`: ${a}`:``}): check createProxy's apiKey`),l(401,{error:`invalid_api_key`,message:`Zeno refused the proxy route's API key; the route's server log says more`});if(!i)return console.error(`Zeno answered the proxy route's ${n} call with ${t.status} without an error code`),d(`Zeno answered ${t.status}`,502);i===`account_closed`&&console.error(`Zeno closed this project's organization (402 account_closed): contact Zeno support`);let o=t.headers.get(`retry-after`);return l(t.status,{error:i,...a?{message:a}:{}},o?{"retry-after":o}:{})},k=()=>d(`Zeno could not be reached`,502),A=async e=>{let t=g,n=t?`/script?${new URLSearchParams({v:t.etag})}`:`/script`,r=await D(n,{headers:{"auth-api-key":x,...t?{"if-none-match":t.etag}:{},...e?{"zeno-visitor-ip":e}:{}}});if(!r)return{failed:k()};if(r.status!==304&&!r.ok)return{failed:await O(r,`/script`)};let i=r.headers.get(`zeno-challenge-token`),a=i?JSON.stringify(i):`undefined`;if(r.status===304)return t?{script:t,challengeToken:a}:{failed:d(`Zeno answered 304 for code this route never had`)};let o=await r.text().catch(()=>void 0);if(o===void 0)return{failed:k()};let s=r.headers.get(`etag`);return g=s?{etag:s,code:o}:void 0,{script:g??{code:o},challengeToken:a}},j=async(e,t)=>{let n=await A(t);if(n.failed)return n.failed;let{script:r,challengeToken:i}=n;return r.etag===void 0?T(e,`${r.code}\nexport const challengeToken = ${i}\n`,`private, max-age=60`):T(e,E(r.etag,i),`private, max-age=60`)},M=async(e,t)=>{let n=g;if(n?.etag!==t){let e=await A(void 0);if(e.failed)return e.failed;n=e.script}return T(e,n,n.etag===t?`private, max-age=31536000, immutable`:`no-store`)},N=(e,t)=>{let n=new URL(e.url).searchParams.get(`v`);return n===null?j(e,t):M(e,n)},P=async(t,n,r)=>{if(!/^application\/json\s*(;|$)/i.test(t.headers.get(`content-type`)??``))return u(`The body must be JSON`);if(t.headers.get(`sec-fetch-site`)?.toLowerCase()===`cross-site`)return u(`Cross-site requests are refused`);let a=await p(t,131072);if(a===void 0)return u(`The body is larger than 128 KB`);if(i(a,64))return u(`The body nests deeper than 64 levels`);let c;try{c=JSON.parse(a)}catch{return u(`The body is not valid JSON`)}if(!e(c)||!e(c.browserData))return u(`The body has no browserData`);if(!n)return console.error(`The proxy route got no IP address: ${f}, or nodeHandler(zeno) on Node`),d(f);let m=h(t,o(r)),g=v(m),y={...g?{visitorId:g}:{},ip:n,headers:_(m),payload:c},w=await D(`/identify`,{method:`POST`,headers:{"auth-api-key":x,"content-type":`application/json`},body:JSON.stringify(y)});if(!w)return k();if(!w.ok)return O(w,`/identify`);let T=await w.json().catch(()=>void 0);if(!e(T)||!S(T.result))return console.error(`Zeno's answer to the proxy route's identification couldn't be read`),d(`Zeno's answer couldn't be read`,502);let E=C(T.cookie);return l(200,T.result,E?{"set-cookie":b(new URL(t.url),E.value,E.maxAge,s)}:{})};return async(e,r,i)=>{let o=new URL(e.url);if(e.method===`POST`&&o.searchParams.has(`forget`))return new Response(null,{status:204,headers:{"set-cookie":b(o,``,0,s)}});if(![`GET`,`HEAD`,`POST`].includes(e.method))return l(405,{error:`method_not_allowed`,message:`Use GET or POST`},{allow:`GET, HEAD, POST`});let c=t(`createProxy`,n,a);if(c.problem!==void 0)return console.error(c.problem),d(`The proxy route isn't set up; its server log says what's missing`);x=c.apiKey,w=c.base;let u=y(r);if(e.method===`POST`)return P(e,u,i);let f=await N(e,u);return e.method===`HEAD`?(await f.body?.cancel(),new Response(null,{status:f.status,headers:f.headers})):f}},O=[`automation`,`headless`,`software-renderer`,`tampering`,`timezone-mismatch`,`privacy-settings`,`vpn`,`proxy`,`tor`,`datacenter`,`abusive-ip`,`incognito`,`virtual-machine`,`developer-tools`,`ai-agent`,`privacy-browser`,`high-activity`,`replayed`,`residential-proxy`,`private-relay`,`forged-payload`,`stored-id-rejected`],k=1e4;var A=class extends Error{status;code;retryAfter;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.retryAfter=r,this.name=`ZenoError`}};const j=(e,t)=>{if(!e)throw TypeError(t);return e},M=e=>{if(e===null)return;let t=/^\d+$/.test(e.trim())?Number(e):(Date.parse(e)-Date.now())/1e3;return Number.isFinite(t)?Math.min(Math.max(t,0),60):void 0},N=e=>new Promise(t=>setTimeout(t,e*1e3)),P=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new A(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},F=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,I=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>F(t[e],n))}),L=I(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),ee=I(`a page of events`,{items:`array`}),te=I(`a visitor`,{visitorId:`string`,externalIds:`array`,externalIdCount:`number`,recentEvents:`array`}),R=I(`a reported outcome`,{requestId:`string`,outcome:`string`}),z=I(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),B=I(`an erasure`,{externalId:`string`,deletedEvents:`number`}),V=I(`a relation`,{externalId:`string`,type:`string`,linkWrite:`boolean`}),H=I(`a removal`,{removed:`boolean`}),U=I(`a user's values`,{externalId:`string`,values:`array`,truncated:`boolean`}),W=I(`a page of users`,{items:`array`}),G=I(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`}),K=I(`an embed`,{url:`string`,expiresAt:`string`}),q=I(`verify's answer`,{action:`string`,reasons:`array`}),J=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async(e,t,n,r,i)=>{try{let o=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...i?{"content-type":`application/json`}:{}},body:i,signal:AbortSignal.timeout(k)});return{response:o,text:await o.text()}}catch(e){throw new A(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${k} ms`:`Zeno couldn't be reached at ${t}: ${e instanceof Error?e.message:String(e)}`)}},s=async(r,a,s,c,l=!1)=>{let u=t(`createClient`,n,i);if(u.problem!==void 0)throw TypeError(u.problem);let d=c&&JSON.stringify(c);for(let t=0;;t++){let n;try{n=await o(u.apiKey,u.base,r,a,d)}catch(e){if(l&&t<2){await N(1+Math.random()*.5);continue}throw e}let{response:i,text:c}=n,f;try{f=JSON.parse(c)}catch{}if(i.ok){if(f===void 0)throw new A(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new A(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:p,message:m}=e(f)?f:{},h=typeof p==`string`?p:void 0,g=i.status===429||h===`search_unavailable`||l&&i.status>=500,_=g?M(i.headers.get(`retry-after`)):void 0;if(g&&t<2){let e=_??1;await N(e+Math.random()*e*.5)}else throw new A(i.status,h??`request_failed`,typeof m==`string`?m:void 0,_)}},c=(e,t)=>{for(let[n,r]of Object.entries(t))r!==void 0&&e.set(n,String(r));return e};return{verify:async(e,t={})=>{let{ip:n,externalId:r,maxAge:i,idempotencyKey:a=crypto.randomUUID()}=t;return s(`POST`,`/verify`,q,{requestId:e??void 0,ip:n||void 0,externalId:r,maxAge:i,idempotencyKey:a},!0)},getEvent:async e=>s(`GET`,`/events/${P(`requestId`,e)}`,L),searchEvents:(e={})=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])e!==void 0&&t.append(n,e instanceof Date?e.toISOString():String(e));return s(`GET`,`/events?${t}`,ee)},getVisitor:async e=>s(`GET`,`/visitors/${P(`visitorId`,e)}`,te),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,R,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${P(`visitorId`,e)}`,z),deleteExternalId:e=>{let t=new URLSearchParams({externalId:e});return s(`DELETE`,`/external-ids?${t}`,B)},addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,V,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>{let t=new URLSearchParams(e);return s(`DELETE`,`/related?${t}`,H)},getRelatedValues:(e,{type:t}={})=>{let n=new URLSearchParams({externalId:e,...t?{type:t}:{}});return s(`GET`,`/related/values?${n}`,U)},lookupRelated:(e,t,n={})=>{let r=c(new URLSearchParams({type:e,value:t}),n);return s(`GET`,`/related/lookup?${r}`,W)},getRelated:(e,{type:t,depth:n=1}={})=>{let r=new URLSearchParams({externalId:e,...t?{type:t}:{},depth:String(n)});return s(`GET`,`/related?${r}`,G)},createEmbed:e=>s(`POST`,`/embeds`,K,e)}},Y=new TextEncoder,X=e=>{try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch{return}},Z=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),ne=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0},re=async(e,t,n,{tolerance:r=300}={})=>{let i=j(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`),a=(t??``).split(`,`).map(e=>{let[t,...n]=e.trim().split(`=`);return[t??``,n.join(`=`)]}),o=Number(a.find(([e])=>e===`t`)?.[1]),s=a.filter(([e,t])=>e===`v1`&&t).map(([,e])=>e);if(!Number.isInteger(o)||s.length===0||Math.abs(Date.now()/1e3-o)>r)return;let c=await crypto.subtle.importKey(`raw`,Y.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=Y.encode(Z(await crypto.subtle.sign(`HMAC`,c,Y.encode(`${o}.${e}`))));if(!s.map(e=>ne(Y.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!L.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u},Q=()=>({action:`block`,reasons:[`not-found`]}),$=`unsealResult needs the project's encryption key as key (is it set in the environment?)`,ie=e=>{let t=j(e,$).trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(t)?X(t):void 0;if(!n)throw TypeError(`unsealResult's key isn't base64: pass the project's encryption key as the app shows it`);if(n.length!==32)throw TypeError(/^[0-9a-f]{64}$/i.test(t)?`unsealResult's key looks like hex: pass the project's encryption key as the app shows it, in base64`:`unsealResult's key is ${n.length} bytes, not 32: pass the project's encryption key as the app shows it`);return n},ae=async(e,t)=>{for(let n of e){let e=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`decrypt`]);try{return await crypto.subtle.decrypt({name:`AES-GCM`,iv:t.subarray(1,13),tagLength:128},e,t.subarray(13))}catch{}}},oe=async(e,t)=>{let n=(Array.isArray(t?.key)?t.key:[t?.key]).filter(e=>e);if(n.length===0)throw TypeError($);let i=n.map(ie);if(!e)return{action:`challenge`,reasons:[`no-request-id`]};if(typeof e!=`string`||!/^[A-Za-z0-9+/]+={0,2}$/.test(e.trim()))return Q();let a=X(e.trim());if(!a||a.length<30||a[0]!==1)return Q();let o=await ae(i,a);if(!o)return Q();let s;try{s=JSON.parse(new TextDecoder().decode(o))}catch{}if(!L.is(s))throw Error(`The sealed result opened but isn't an event; update zeno.id/server`);let c=[],l=t.maxAge??300;return t.ip&&r(s.ip.address,t.ip)&&c.push(`ip-mismatch`),Date.now()-Date.parse(s.createdAt)>l*1e3&&c.push(`too-old`),t.externalId!==void 0&&s.externalId!==void 0&&s.externalId!==t.externalId&&c.push(`external-id-mismatch`),c.length>0?{action:`block`,reasons:c,event:s}:{action:s.verdict.action,reasons:s.verdict.reasons,event:s}};exports.SIGNALS=O,exports.ZenoError=A,exports.createClient=J,exports.createProxy=D,exports.unsealResult=oe,exports.verifyWebhook=re;
2
+ `),D=(n,r={})=>{let{apiUrl:a,cookiePath:s,fetch:m=globalThis.fetch}=r,g,x=``,w=``,D=async(e,t)=>{try{return await m(`${w}${e}`,{...t,signal:AbortSignal.timeout(c)})}catch(t){let n=t instanceof Error&&t.name===`TimeoutError`?`no answer within ${c} ms`:String(t);console.error(`The proxy route couldn't reach Zeno at ${w}${e}: ${n}`);return}},O=async(t,n)=>{let r=await t.json().catch(()=>void 0),i=e(r)&&typeof r.error==`string`?r.error:void 0,a=e(r)&&typeof r.message==`string`?r.message:void 0;if(t.status===401)return console.error(`Zeno refused the proxy route's API key (401${i?` ${i}`:``}${a?`: ${a}`:``}): check createProxy's apiKey`),l(401,{error:`invalid_api_key`,message:`Zeno refused the proxy route's API key; the route's server log says more`});if(!i)return console.error(`Zeno answered the proxy route's ${n} call with ${t.status} without an error code`),d(`Zeno answered ${t.status}`,502);i===`account_closed`&&console.error(`Zeno closed this project's organization (402 account_closed): contact Zeno support`);let o=t.headers.get(`retry-after`);return l(t.status,{error:i,...a?{message:a}:{}},o?{"retry-after":o}:{})},k=()=>d(`Zeno could not be reached`,502),A=async e=>{let t=g,n=t?`/script?${new URLSearchParams({v:t.etag})}`:`/script`,r=await D(n,{headers:{"auth-api-key":x,...t?{"if-none-match":t.etag}:{},...e?{"zeno-visitor-ip":e}:{}}});if(!r)return{failed:k()};if(r.status!==304&&!r.ok)return{failed:await O(r,`/script`)};let i=r.headers.get(`zeno-challenge-token`),a=i?JSON.stringify(i):`undefined`;if(r.status===304)return t?{script:t,challengeToken:a}:{failed:d(`Zeno answered 304 for code this route never had`)};let o=await r.text().catch(()=>void 0);if(o===void 0)return{failed:k()};let s=r.headers.get(`etag`);return g=s?{etag:s,code:o}:void 0,{script:g??{code:o},challengeToken:a}},j=async(e,t)=>{let n=await A(t);if(n.failed)return n.failed;let{script:r,challengeToken:i}=n;return r.etag===void 0?T(e,`${r.code}\nexport const challengeToken = ${i}\n`,`private, max-age=60`):T(e,E(r.etag,i),`private, max-age=60`)},M=async(e,t)=>{let n=g;if(n?.etag!==t){let e=await A(void 0);if(e.failed)return e.failed;n=e.script}return T(e,n,n.etag===t?`private, max-age=31536000, immutable`:`no-store`)},N=(e,t)=>{let n=new URL(e.url).searchParams.get(`v`);return n===null?j(e,t):M(e,n)},P=async(t,n,r)=>{if(!/^application\/json\s*(;|$)/i.test(t.headers.get(`content-type`)??``))return u(`The body must be JSON`);if(t.headers.get(`sec-fetch-site`)?.toLowerCase()===`cross-site`)return u(`Cross-site requests are refused`);let a=await p(t,131072);if(a===void 0)return u(`The body is larger than 128 KB`);if(i(a,64))return u(`The body nests deeper than 64 levels`);let c;try{c=JSON.parse(a)}catch{return u(`The body is not valid JSON`)}if(!e(c)||!e(c.browserData))return u(`The body has no browserData`);if(!n)return console.error(`The proxy route got no IP address: ${f}, or nodeHandler(zeno) on Node`),d(f);let m=h(t,o(r)),g=v(m),y={...g?{visitorId:g}:{},ip:n,headers:_(m),payload:c},w=await D(`/identify`,{method:`POST`,headers:{"auth-api-key":x,"content-type":`application/json`},body:JSON.stringify(y)});if(!w)return k();if(!w.ok)return O(w,`/identify`);let T=await w.json().catch(()=>void 0);if(!e(T)||!S(T.result))return console.error(`Zeno's answer to the proxy route's identification couldn't be read`),d(`Zeno's answer couldn't be read`,502);let E=C(T.cookie);return l(200,T.result,E?{"set-cookie":b(new URL(t.url),E.value,E.maxAge,s)}:{})};return async(e,r,i)=>{let o=new URL(e.url);if(e.method===`POST`&&o.searchParams.has(`forget`))return new Response(null,{status:204,headers:{"set-cookie":b(o,``,0,s)}});if(![`GET`,`HEAD`,`POST`].includes(e.method))return l(405,{error:`method_not_allowed`,message:`Use GET or POST`},{allow:`GET, HEAD, POST`});let c=t(`createProxy`,n,a);if(c.problem!==void 0)return console.error(c.problem),d(`The proxy route isn't set up; its server log says what's missing`);x=c.apiKey,w=c.base;let u=y(r);if(e.method===`POST`)return P(e,u,i);let f=await N(e,u);return e.method===`HEAD`?(await f.body?.cancel(),new Response(null,{status:f.status,headers:f.headers})):f}},O=[`automation`,`headless`,`software-renderer`,`tampering`,`timezone-mismatch`,`privacy-settings`,`vpn`,`proxy`,`tor`,`datacenter`,`abusive-ip`,`incognito`,`virtual-machine`,`developer-tools`,`ai-agent`,`privacy-browser`,`high-activity`,`replayed`,`residential-proxy`,`private-relay`,`forged-payload`,`stored-id-rejected`,`storage-cleared`],k=1e4;var A=class extends Error{status;code;retryAfter;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.retryAfter=r,this.name=`ZenoError`}};const j=(e,t)=>{if(!e)throw TypeError(t);return e},M=e=>{if(e===null)return;let t=/^\d+$/.test(e.trim())?Number(e):(Date.parse(e)-Date.now())/1e3;return Number.isFinite(t)?Math.min(Math.max(t,0),60):void 0},N=e=>new Promise(t=>setTimeout(t,e*1e3)),P=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new A(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},F=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,I=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>F(t[e],n))}),L=I(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),ee=I(`a page of events`,{items:`array`}),te=I(`a visitor`,{visitorId:`string`,externalIds:`array`,externalIdCount:`number`,recentEvents:`array`}),R=I(`a reported outcome`,{requestId:`string`,outcome:`string`}),z=I(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),B=I(`an erasure`,{externalId:`string`,deletedEvents:`number`}),V=I(`a relation`,{externalId:`string`,type:`string`,linkWrite:`boolean`}),H=I(`a removal`,{removed:`boolean`}),U=I(`a user's values`,{externalId:`string`,values:`array`,truncated:`boolean`}),W=I(`a page of users`,{items:`array`}),G=I(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`}),K=I(`an embed`,{url:`string`,expiresAt:`string`}),q=I(`verify's answer`,{action:`string`,reasons:`array`}),J=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async(e,t,n,r,i)=>{try{let o=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...i?{"content-type":`application/json`}:{}},body:i,signal:AbortSignal.timeout(k)});return{response:o,text:await o.text()}}catch(e){throw new A(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${k} ms`:`Zeno couldn't be reached at ${t}: ${e instanceof Error?e.message:String(e)}`)}},s=async(r,a,s,c,l=!1)=>{let u=t(`createClient`,n,i);if(u.problem!==void 0)throw TypeError(u.problem);let d=c&&JSON.stringify(c);for(let t=0;;t++){let n;try{n=await o(u.apiKey,u.base,r,a,d)}catch(e){if(l&&t<2){await N(1+Math.random()*.5);continue}throw e}let{response:i,text:c}=n,f;try{f=JSON.parse(c)}catch{}if(i.ok){if(f===void 0)throw new A(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new A(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:p,message:m}=e(f)?f:{},h=typeof p==`string`?p:void 0,g=i.status===429||h===`search_unavailable`||l&&i.status>=500,_=g?M(i.headers.get(`retry-after`)):void 0;if(g&&t<2){let e=_??1;await N(e+Math.random()*e*.5)}else throw new A(i.status,h??`request_failed`,typeof m==`string`?m:void 0,_)}},c=(e,t)=>{for(let[n,r]of Object.entries(t))r!==void 0&&e.set(n,String(r));return e};return{verify:async(e,t={})=>{let{ip:n,externalId:r,maxAge:i,idempotencyKey:a=crypto.randomUUID()}=t;return s(`POST`,`/verify`,q,{requestId:e??void 0,ip:n||void 0,externalId:r,maxAge:i,idempotencyKey:a},!0)},getEvent:async e=>s(`GET`,`/events/${P(`requestId`,e)}`,L),searchEvents:(e={})=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])e!==void 0&&t.append(n,e instanceof Date?e.toISOString():String(e));return s(`GET`,`/events?${t}`,ee)},getVisitor:async e=>s(`GET`,`/visitors/${P(`visitorId`,e)}`,te),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,R,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${P(`visitorId`,e)}`,z),deleteExternalId:e=>{let t=new URLSearchParams({externalId:e});return s(`DELETE`,`/external-ids?${t}`,B)},addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,V,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>{let t=new URLSearchParams(e);return s(`DELETE`,`/related?${t}`,H)},getRelatedValues:(e,{type:t}={})=>{let n=new URLSearchParams({externalId:e,...t?{type:t}:{}});return s(`GET`,`/related/values?${n}`,U)},lookupRelated:(e,t,n={})=>{let r=c(new URLSearchParams({type:e,value:t}),n);return s(`GET`,`/related/lookup?${r}`,W)},getRelated:(e,{type:t,depth:n=1}={})=>{let r=new URLSearchParams({externalId:e,...t?{type:t}:{},depth:String(n)});return s(`GET`,`/related?${r}`,G)},createEmbed:e=>s(`POST`,`/embeds`,K,e)}},Y=new TextEncoder,X=e=>{try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch{return}},Z=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),ne=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0},re=async(e,t,n,{tolerance:r=300}={})=>{let i=j(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`),a=(t??``).split(`,`).map(e=>{let[t,...n]=e.trim().split(`=`);return[t??``,n.join(`=`)]}),o=Number(a.find(([e])=>e===`t`)?.[1]),s=a.filter(([e,t])=>e===`v1`&&t).map(([,e])=>e);if(!Number.isInteger(o)||s.length===0||Math.abs(Date.now()/1e3-o)>r)return;let c=await crypto.subtle.importKey(`raw`,Y.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=Y.encode(Z(await crypto.subtle.sign(`HMAC`,c,Y.encode(`${o}.${e}`))));if(!s.map(e=>ne(Y.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!L.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u},Q=()=>({action:`block`,reasons:[`not-found`]}),$=`unsealResult needs the project's encryption key as key (is it set in the environment?)`,ie=e=>{let t=j(e,$).trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(t)?X(t):void 0;if(!n)throw TypeError(`unsealResult's key isn't base64: pass the project's encryption key as the app shows it`);if(n.length!==32)throw TypeError(/^[0-9a-f]{64}$/i.test(t)?`unsealResult's key looks like hex: pass the project's encryption key as the app shows it, in base64`:`unsealResult's key is ${n.length} bytes, not 32: pass the project's encryption key as the app shows it`);return n},ae=async(e,t)=>{for(let n of e){let e=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`decrypt`]);try{return await crypto.subtle.decrypt({name:`AES-GCM`,iv:t.subarray(1,13),tagLength:128},e,t.subarray(13))}catch{}}},oe=async(e,t)=>{let n=(Array.isArray(t?.key)?t.key:[t?.key]).filter(e=>e);if(n.length===0)throw TypeError($);let i=n.map(ie);if(!e)return{action:`challenge`,reasons:[`no-request-id`]};if(typeof e!=`string`||!/^[A-Za-z0-9+/]+={0,2}$/.test(e.trim()))return Q();let a=X(e.trim());if(!a||a.length<30||a[0]!==1)return Q();let o=await ae(i,a);if(!o)return Q();let s;try{s=JSON.parse(new TextDecoder().decode(o))}catch{}if(!L.is(s))throw Error(`The sealed result opened but isn't an event; update zeno.id/server`);let c=[],l=t.maxAge??300;return t.ip&&r(s.ip.address,t.ip)&&c.push(`ip-mismatch`),Date.now()-Date.parse(s.createdAt)>l*1e3&&c.push(`too-old`),t.externalId!==void 0&&s.externalId!==void 0&&s.externalId!==t.externalId&&c.push(`external-id-mismatch`),c.length>0?{action:`block`,reasons:c,event:s}:{action:s.verdict.action,reasons:s.verdict.reasons,event:s}};exports.SIGNALS=O,exports.ZenoError=A,exports.createClient=J,exports.createProxy=D,exports.unsealResult=oe,exports.verifyWebhook=re;
@@ -1,7 +1,7 @@
1
1
  import { a as ApiOptions, i as ApiKey, n as ProxyOptions, r as createProxy, t as ProxyHandler } from "./proxy-CUZ-Jwgy.cjs";
2
2
  //#region src/server/index.d.ts
3
3
  /** Every signal an event checks, the keys of its `signals`. */
4
- declare const SIGNALS: readonly ['automation', 'headless', 'software-renderer', 'tampering', 'timezone-mismatch', 'privacy-settings', 'vpn', 'proxy', 'tor', 'datacenter', 'abusive-ip', 'incognito', 'virtual-machine', 'developer-tools', 'ai-agent', 'privacy-browser', 'high-activity', 'replayed', 'residential-proxy', 'private-relay', 'forged-payload', 'stored-id-rejected'];
4
+ declare const SIGNALS: readonly ['automation', 'headless', 'software-renderer', 'tampering', 'timezone-mismatch', 'privacy-settings', 'vpn', 'proxy', 'tor', 'datacenter', 'abusive-ip', 'incognito', 'virtual-machine', 'developer-tools', 'ai-agent', 'privacy-browser', 'high-activity', 'replayed', 'residential-proxy', 'private-relay', 'forged-payload', 'stored-id-rejected', 'storage-cleared'];
5
5
  type Signal = (typeof SIGNALS)[number];
6
6
  /** The bot verdict: a known good bot (a search engine's crawler), a bad one (automation, a headless browser), or none. */
7
7
  type Bot = 'good' | 'bad' | 'not-detected';
@@ -1,7 +1,7 @@
1
1
  import { a as ApiOptions, i as ApiKey, n as ProxyOptions, r as createProxy, t as ProxyHandler } from "./proxy-CUZ-Jwgy.js";
2
2
  //#region src/server/index.d.ts
3
3
  /** Every signal an event checks, the keys of its `signals`. */
4
- declare const SIGNALS: readonly ['automation', 'headless', 'software-renderer', 'tampering', 'timezone-mismatch', 'privacy-settings', 'vpn', 'proxy', 'tor', 'datacenter', 'abusive-ip', 'incognito', 'virtual-machine', 'developer-tools', 'ai-agent', 'privacy-browser', 'high-activity', 'replayed', 'residential-proxy', 'private-relay', 'forged-payload', 'stored-id-rejected'];
4
+ declare const SIGNALS: readonly ['automation', 'headless', 'software-renderer', 'tampering', 'timezone-mismatch', 'privacy-settings', 'vpn', 'proxy', 'tor', 'datacenter', 'abusive-ip', 'incognito', 'virtual-machine', 'developer-tools', 'ai-agent', 'privacy-browser', 'high-activity', 'replayed', 'residential-proxy', 'private-relay', 'forged-payload', 'stored-id-rejected', 'storage-cleared'];
5
5
  type Signal = (typeof SIGNALS)[number];
6
6
  /** The bot verdict: a known good bot (a search engine's crawler), a bad one (automation, a headless browser), or none. */
7
7
  type Bot = 'good' | 'bad' | 'not-detected';
@@ -1,2 +1,2 @@
1
1
  const e=e=>typeof e==`object`&&!!e&&!Array.isArray(e),t=(e,t,n=`https://api.zeno.id`)=>{if(!t)return{problem:`${e}'s apiKey is missing: pass your API key (ZENO_API_KEY in your environment)`};if(!n)return{problem:`${e}'s apiUrl is missing: this copy of zeno.id/server has no default, so pass the Zeno API's origin as apiUrl`};try{if([`http:`,`https:`].includes(new URL(n).protocol))return{apiKey:t,base:n.replace(/\/+$/,``)}}catch{}return{problem:`${e}'s apiUrl must be the Zeno API's http(s) origin, like https://api.example.com, not ${JSON.stringify(n)}`}},n=e=>{if(!e.includes(`:`))return e;let t=e.match(/^(?:::|(?:0{1,4}:){5})ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);if(t)return t[1];let[n=``,r=``]=e.split(`::`),i=n?n.split(`:`):[],a=r?r.split(`:`):[],o=Math.max(0,8-i.length-a.length),s=[...i,...Array.from({length:o},()=>`0`),...a].map(e=>e.toLowerCase().replace(/^0+(?=\w)/,``));if(s.slice(0,5).every(e=>e===`0`)&&s[5]===`ffff`){let[e=0,t=0]=s.slice(6).map(e=>parseInt(e,16));return[e>>8,e&255,t>>8,t&255].join(`.`)}return s.slice(0,4).join(`:`)},r=(e,t)=>{let r=t.trim();return e.includes(`:`)===r.includes(`:`)&&n(e)!==n(r)},i=(e,t)=>{let n=0,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r)a===`\\`?i++:a===`"`&&(r=!1);else if(a===`"`)r=!0;else if(a===`{`||a===`[`){if(++n>t)return!0}else(a===`}`||a===`]`)&&n--}return!1},a=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),o=e=>{let t=e?.rawHeaders;return a(t)?t:void 0},s=`zeno_id`,c=1e4,l=(e,t,n={})=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`,...n}}),u=e=>l(400,{error:`invalid_request`,message:e}),d=(e,t=500)=>l(t,{error:`server_error`,message:e}),f=`Pass the IP address the request came from: zeno(request, ip)`,p=async(e,t)=>{if(Number(e.headers.get(`content-length`))>t)return;if(!e.body)return``;let n=e.body.getReader(),r=[],i=0;for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.byteLength,i>t){await n.cancel();return}r.push(a)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return new TextDecoder().decode(a)},m=e=>{for(let t of e.split(`;`)){let e=t.indexOf(`=`);if(e!==-1&&t.slice(0,e).trim()===s)return t.slice(e+1).trim()}},h=(e,t)=>{if(!t)return Array.from(e.headers.entries());let n=[];for(let e=0;e+1<t.length;e+=2)n.push([t[e],t[e+1]]);return n},g=/* @__PURE__ */ new Set([`user-agent`,`origin`,`signature-agent`,`signature-input`]),_=e=>e.map(([e,t])=>[e,g.has(e.toLowerCase())?t:``]),v=e=>{for(let[t,n]of e){let e=t.toLowerCase()===`cookie`?m(n):void 0;if(e!==void 0)return/^[A-Za-z0-9]{20}$/.test(e)?e:void 0}},y=e=>e?.trim().replace(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i,`$1`)||void 0,b=(e,t,n,r=e.pathname)=>{let i=[`localhost`,`127.0.0.1`,`[::1]`].includes(e.hostname)||e.hostname.endsWith(`.localhost`),a=e.protocol===`http:`&&i?``:`; Secure`,o=r.replace(/[;,\s]/g,encodeURIComponent);return`${s}=${t}; Max-Age=${n}; Path=${o}; HttpOnly${a}; SameSite=Lax`},x=e=>(e.headers.get(`accept-encoding`)??``).split(`,`).some(e=>{let[t=``,...n]=e.split(`;`).map(e=>e.trim().toLowerCase()),r=n.find(e=>e.startsWith(`q=`));return(t===`gzip`||t===`*`)&&!(r&&Number(r.slice(2))===0)}),S=t=>e(t)?t.capped===!0||typeof t.requestId==`string`&&[`undefined`,`string`].includes(typeof t.visitorId)&&[`undefined`,`boolean`].includes(typeof t.returning)&&[`undefined`,`string`].includes(typeof t.sealedResult):!1,C=t=>{if(!e(t))return;let{value:n,maxAge:r}=t;return typeof n==`string`&&/^[A-Za-z0-9]{1,64}$/.test(n)&&typeof r==`number`&&Number.isInteger(r)&&r>=0?{value:n,maxAge:r}:void 0},w=e=>new Response(new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`))).arrayBuffer(),T=async(e,t,n)=>{let r={"content-type":`text/javascript; charset=utf-8`,"cache-control":n,vary:`accept-encoding`},i=typeof t==`string`?t:t.code;if(!x(e)||typeof CompressionStream!=`function`)return new Response(i,{headers:r});let a=typeof t==`string`?w(i):t.gzipped??=w(i);return new Response(await a,{headers:{...r,"content-encoding":`gzip`}})},E=(e,t)=>[`const code = await import(new URL(${JSON.stringify(`?${new URLSearchParams({v:e})}`)}, import.meta.url))`,`export const challengeToken = ${t}`,`const own = new URL(import.meta.url)`,`const refreshChallengeToken = () => import(new URL("?challenge=" + Date.now(), own)).then(module => module.challengeToken, () => undefined)`,`export const start = (path = own.pathname, options) => code.start(path, { challengeToken, refreshChallengeToken, ...options })`,``].join(`
2
- `),D=(n,r={})=>{let{apiUrl:a,cookiePath:s,fetch:m=globalThis.fetch}=r,g,x=``,w=``,D=async(e,t)=>{try{return await m(`${w}${e}`,{...t,signal:AbortSignal.timeout(c)})}catch(t){let n=t instanceof Error&&t.name===`TimeoutError`?`no answer within ${c} ms`:String(t);console.error(`The proxy route couldn't reach Zeno at ${w}${e}: ${n}`);return}},O=async(t,n)=>{let r=await t.json().catch(()=>void 0),i=e(r)&&typeof r.error==`string`?r.error:void 0,a=e(r)&&typeof r.message==`string`?r.message:void 0;if(t.status===401)return console.error(`Zeno refused the proxy route's API key (401${i?` ${i}`:``}${a?`: ${a}`:``}): check createProxy's apiKey`),l(401,{error:`invalid_api_key`,message:`Zeno refused the proxy route's API key; the route's server log says more`});if(!i)return console.error(`Zeno answered the proxy route's ${n} call with ${t.status} without an error code`),d(`Zeno answered ${t.status}`,502);i===`account_closed`&&console.error(`Zeno closed this project's organization (402 account_closed): contact Zeno support`);let o=t.headers.get(`retry-after`);return l(t.status,{error:i,...a?{message:a}:{}},o?{"retry-after":o}:{})},k=()=>d(`Zeno could not be reached`,502),A=async e=>{let t=g,n=t?`/script?${new URLSearchParams({v:t.etag})}`:`/script`,r=await D(n,{headers:{"auth-api-key":x,...t?{"if-none-match":t.etag}:{},...e?{"zeno-visitor-ip":e}:{}}});if(!r)return{failed:k()};if(r.status!==304&&!r.ok)return{failed:await O(r,`/script`)};let i=r.headers.get(`zeno-challenge-token`),a=i?JSON.stringify(i):`undefined`;if(r.status===304)return t?{script:t,challengeToken:a}:{failed:d(`Zeno answered 304 for code this route never had`)};let o=await r.text().catch(()=>void 0);if(o===void 0)return{failed:k()};let s=r.headers.get(`etag`);return g=s?{etag:s,code:o}:void 0,{script:g??{code:o},challengeToken:a}},j=async(e,t)=>{let n=await A(t);if(n.failed)return n.failed;let{script:r,challengeToken:i}=n;return r.etag===void 0?T(e,`${r.code}\nexport const challengeToken = ${i}\n`,`private, max-age=60`):T(e,E(r.etag,i),`private, max-age=60`)},M=async(e,t)=>{let n=g;if(n?.etag!==t){let e=await A(void 0);if(e.failed)return e.failed;n=e.script}return T(e,n,n.etag===t?`private, max-age=31536000, immutable`:`no-store`)},N=(e,t)=>{let n=new URL(e.url).searchParams.get(`v`);return n===null?j(e,t):M(e,n)},P=async(t,n,r)=>{if(!/^application\/json\s*(;|$)/i.test(t.headers.get(`content-type`)??``))return u(`The body must be JSON`);if(t.headers.get(`sec-fetch-site`)?.toLowerCase()===`cross-site`)return u(`Cross-site requests are refused`);let a=await p(t,131072);if(a===void 0)return u(`The body is larger than 128 KB`);if(i(a,64))return u(`The body nests deeper than 64 levels`);let c;try{c=JSON.parse(a)}catch{return u(`The body is not valid JSON`)}if(!e(c)||!e(c.browserData))return u(`The body has no browserData`);if(!n)return console.error(`The proxy route got no IP address: ${f}, or nodeHandler(zeno) on Node`),d(f);let m=h(t,o(r)),g=v(m),y={...g?{visitorId:g}:{},ip:n,headers:_(m),payload:c},w=await D(`/identify`,{method:`POST`,headers:{"auth-api-key":x,"content-type":`application/json`},body:JSON.stringify(y)});if(!w)return k();if(!w.ok)return O(w,`/identify`);let T=await w.json().catch(()=>void 0);if(!e(T)||!S(T.result))return console.error(`Zeno's answer to the proxy route's identification couldn't be read`),d(`Zeno's answer couldn't be read`,502);let E=C(T.cookie);return l(200,T.result,E?{"set-cookie":b(new URL(t.url),E.value,E.maxAge,s)}:{})};return async(e,r,i)=>{let o=new URL(e.url);if(e.method===`POST`&&o.searchParams.has(`forget`))return new Response(null,{status:204,headers:{"set-cookie":b(o,``,0,s)}});if(![`GET`,`HEAD`,`POST`].includes(e.method))return l(405,{error:`method_not_allowed`,message:`Use GET or POST`},{allow:`GET, HEAD, POST`});let c=t(`createProxy`,n,a);if(c.problem!==void 0)return console.error(c.problem),d(`The proxy route isn't set up; its server log says what's missing`);x=c.apiKey,w=c.base;let u=y(r);if(e.method===`POST`)return P(e,u,i);let f=await N(e,u);return e.method===`HEAD`?(await f.body?.cancel(),new Response(null,{status:f.status,headers:f.headers})):f}},O=[`automation`,`headless`,`software-renderer`,`tampering`,`timezone-mismatch`,`privacy-settings`,`vpn`,`proxy`,`tor`,`datacenter`,`abusive-ip`,`incognito`,`virtual-machine`,`developer-tools`,`ai-agent`,`privacy-browser`,`high-activity`,`replayed`,`residential-proxy`,`private-relay`,`forged-payload`,`stored-id-rejected`],k=1e4;var A=class extends Error{status;code;retryAfter;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.retryAfter=r,this.name=`ZenoError`}};const j=(e,t)=>{if(!e)throw TypeError(t);return e},M=e=>{if(e===null)return;let t=/^\d+$/.test(e.trim())?Number(e):(Date.parse(e)-Date.now())/1e3;return Number.isFinite(t)?Math.min(Math.max(t,0),60):void 0},N=e=>new Promise(t=>setTimeout(t,e*1e3)),P=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new A(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},F=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,I=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>F(t[e],n))}),L=I(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),ee=I(`a page of events`,{items:`array`}),te=I(`a visitor`,{visitorId:`string`,externalIds:`array`,externalIdCount:`number`,recentEvents:`array`}),R=I(`a reported outcome`,{requestId:`string`,outcome:`string`}),z=I(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),B=I(`an erasure`,{externalId:`string`,deletedEvents:`number`}),V=I(`a relation`,{externalId:`string`,type:`string`,linkWrite:`boolean`}),H=I(`a removal`,{removed:`boolean`}),U=I(`a user's values`,{externalId:`string`,values:`array`,truncated:`boolean`}),W=I(`a page of users`,{items:`array`}),G=I(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`}),K=I(`an embed`,{url:`string`,expiresAt:`string`}),q=I(`verify's answer`,{action:`string`,reasons:`array`}),J=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async(e,t,n,r,i)=>{try{let o=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...i?{"content-type":`application/json`}:{}},body:i,signal:AbortSignal.timeout(k)});return{response:o,text:await o.text()}}catch(e){throw new A(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${k} ms`:`Zeno couldn't be reached at ${t}: ${e instanceof Error?e.message:String(e)}`)}},s=async(r,a,s,c,l=!1)=>{let u=t(`createClient`,n,i);if(u.problem!==void 0)throw TypeError(u.problem);let d=c&&JSON.stringify(c);for(let t=0;;t++){let n;try{n=await o(u.apiKey,u.base,r,a,d)}catch(e){if(l&&t<2){await N(1+Math.random()*.5);continue}throw e}let{response:i,text:c}=n,f;try{f=JSON.parse(c)}catch{}if(i.ok){if(f===void 0)throw new A(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new A(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:p,message:m}=e(f)?f:{},h=typeof p==`string`?p:void 0,g=i.status===429||h===`search_unavailable`||l&&i.status>=500,_=g?M(i.headers.get(`retry-after`)):void 0;if(g&&t<2){let e=_??1;await N(e+Math.random()*e*.5)}else throw new A(i.status,h??`request_failed`,typeof m==`string`?m:void 0,_)}},c=(e,t)=>{for(let[n,r]of Object.entries(t))r!==void 0&&e.set(n,String(r));return e};return{verify:async(e,t={})=>{let{ip:n,externalId:r,maxAge:i,idempotencyKey:a=crypto.randomUUID()}=t;return s(`POST`,`/verify`,q,{requestId:e??void 0,ip:n||void 0,externalId:r,maxAge:i,idempotencyKey:a},!0)},getEvent:async e=>s(`GET`,`/events/${P(`requestId`,e)}`,L),searchEvents:(e={})=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])e!==void 0&&t.append(n,e instanceof Date?e.toISOString():String(e));return s(`GET`,`/events?${t}`,ee)},getVisitor:async e=>s(`GET`,`/visitors/${P(`visitorId`,e)}`,te),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,R,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${P(`visitorId`,e)}`,z),deleteExternalId:e=>{let t=new URLSearchParams({externalId:e});return s(`DELETE`,`/external-ids?${t}`,B)},addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,V,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>{let t=new URLSearchParams(e);return s(`DELETE`,`/related?${t}`,H)},getRelatedValues:(e,{type:t}={})=>{let n=new URLSearchParams({externalId:e,...t?{type:t}:{}});return s(`GET`,`/related/values?${n}`,U)},lookupRelated:(e,t,n={})=>{let r=c(new URLSearchParams({type:e,value:t}),n);return s(`GET`,`/related/lookup?${r}`,W)},getRelated:(e,{type:t,depth:n=1}={})=>{let r=new URLSearchParams({externalId:e,...t?{type:t}:{},depth:String(n)});return s(`GET`,`/related?${r}`,G)},createEmbed:e=>s(`POST`,`/embeds`,K,e)}},Y=new TextEncoder,X=e=>{try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch{return}},Z=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),ne=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0},re=async(e,t,n,{tolerance:r=300}={})=>{let i=j(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`),a=(t??``).split(`,`).map(e=>{let[t,...n]=e.trim().split(`=`);return[t??``,n.join(`=`)]}),o=Number(a.find(([e])=>e===`t`)?.[1]),s=a.filter(([e,t])=>e===`v1`&&t).map(([,e])=>e);if(!Number.isInteger(o)||s.length===0||Math.abs(Date.now()/1e3-o)>r)return;let c=await crypto.subtle.importKey(`raw`,Y.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=Y.encode(Z(await crypto.subtle.sign(`HMAC`,c,Y.encode(`${o}.${e}`))));if(!s.map(e=>ne(Y.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!L.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u},Q=()=>({action:`block`,reasons:[`not-found`]}),$=`unsealResult needs the project's encryption key as key (is it set in the environment?)`,ie=e=>{let t=j(e,$).trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(t)?X(t):void 0;if(!n)throw TypeError(`unsealResult's key isn't base64: pass the project's encryption key as the app shows it`);if(n.length!==32)throw TypeError(/^[0-9a-f]{64}$/i.test(t)?`unsealResult's key looks like hex: pass the project's encryption key as the app shows it, in base64`:`unsealResult's key is ${n.length} bytes, not 32: pass the project's encryption key as the app shows it`);return n},ae=async(e,t)=>{for(let n of e){let e=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`decrypt`]);try{return await crypto.subtle.decrypt({name:`AES-GCM`,iv:t.subarray(1,13),tagLength:128},e,t.subarray(13))}catch{}}},oe=async(e,t)=>{let n=(Array.isArray(t?.key)?t.key:[t?.key]).filter(e=>e);if(n.length===0)throw TypeError($);let i=n.map(ie);if(!e)return{action:`challenge`,reasons:[`no-request-id`]};if(typeof e!=`string`||!/^[A-Za-z0-9+/]+={0,2}$/.test(e.trim()))return Q();let a=X(e.trim());if(!a||a.length<30||a[0]!==1)return Q();let o=await ae(i,a);if(!o)return Q();let s;try{s=JSON.parse(new TextDecoder().decode(o))}catch{}if(!L.is(s))throw Error(`The sealed result opened but isn't an event; update zeno.id/server`);let c=[],l=t.maxAge??300;return t.ip&&r(s.ip.address,t.ip)&&c.push(`ip-mismatch`),Date.now()-Date.parse(s.createdAt)>l*1e3&&c.push(`too-old`),t.externalId!==void 0&&s.externalId!==void 0&&s.externalId!==t.externalId&&c.push(`external-id-mismatch`),c.length>0?{action:`block`,reasons:c,event:s}:{action:s.verdict.action,reasons:s.verdict.reasons,event:s}};export{O as SIGNALS,A as ZenoError,J as createClient,D as createProxy,oe as unsealResult,re as verifyWebhook};
2
+ `),D=(n,r={})=>{let{apiUrl:a,cookiePath:s,fetch:m=globalThis.fetch}=r,g,x=``,w=``,D=async(e,t)=>{try{return await m(`${w}${e}`,{...t,signal:AbortSignal.timeout(c)})}catch(t){let n=t instanceof Error&&t.name===`TimeoutError`?`no answer within ${c} ms`:String(t);console.error(`The proxy route couldn't reach Zeno at ${w}${e}: ${n}`);return}},O=async(t,n)=>{let r=await t.json().catch(()=>void 0),i=e(r)&&typeof r.error==`string`?r.error:void 0,a=e(r)&&typeof r.message==`string`?r.message:void 0;if(t.status===401)return console.error(`Zeno refused the proxy route's API key (401${i?` ${i}`:``}${a?`: ${a}`:``}): check createProxy's apiKey`),l(401,{error:`invalid_api_key`,message:`Zeno refused the proxy route's API key; the route's server log says more`});if(!i)return console.error(`Zeno answered the proxy route's ${n} call with ${t.status} without an error code`),d(`Zeno answered ${t.status}`,502);i===`account_closed`&&console.error(`Zeno closed this project's organization (402 account_closed): contact Zeno support`);let o=t.headers.get(`retry-after`);return l(t.status,{error:i,...a?{message:a}:{}},o?{"retry-after":o}:{})},k=()=>d(`Zeno could not be reached`,502),A=async e=>{let t=g,n=t?`/script?${new URLSearchParams({v:t.etag})}`:`/script`,r=await D(n,{headers:{"auth-api-key":x,...t?{"if-none-match":t.etag}:{},...e?{"zeno-visitor-ip":e}:{}}});if(!r)return{failed:k()};if(r.status!==304&&!r.ok)return{failed:await O(r,`/script`)};let i=r.headers.get(`zeno-challenge-token`),a=i?JSON.stringify(i):`undefined`;if(r.status===304)return t?{script:t,challengeToken:a}:{failed:d(`Zeno answered 304 for code this route never had`)};let o=await r.text().catch(()=>void 0);if(o===void 0)return{failed:k()};let s=r.headers.get(`etag`);return g=s?{etag:s,code:o}:void 0,{script:g??{code:o},challengeToken:a}},j=async(e,t)=>{let n=await A(t);if(n.failed)return n.failed;let{script:r,challengeToken:i}=n;return r.etag===void 0?T(e,`${r.code}\nexport const challengeToken = ${i}\n`,`private, max-age=60`):T(e,E(r.etag,i),`private, max-age=60`)},M=async(e,t)=>{let n=g;if(n?.etag!==t){let e=await A(void 0);if(e.failed)return e.failed;n=e.script}return T(e,n,n.etag===t?`private, max-age=31536000, immutable`:`no-store`)},N=(e,t)=>{let n=new URL(e.url).searchParams.get(`v`);return n===null?j(e,t):M(e,n)},P=async(t,n,r)=>{if(!/^application\/json\s*(;|$)/i.test(t.headers.get(`content-type`)??``))return u(`The body must be JSON`);if(t.headers.get(`sec-fetch-site`)?.toLowerCase()===`cross-site`)return u(`Cross-site requests are refused`);let a=await p(t,131072);if(a===void 0)return u(`The body is larger than 128 KB`);if(i(a,64))return u(`The body nests deeper than 64 levels`);let c;try{c=JSON.parse(a)}catch{return u(`The body is not valid JSON`)}if(!e(c)||!e(c.browserData))return u(`The body has no browserData`);if(!n)return console.error(`The proxy route got no IP address: ${f}, or nodeHandler(zeno) on Node`),d(f);let m=h(t,o(r)),g=v(m),y={...g?{visitorId:g}:{},ip:n,headers:_(m),payload:c},w=await D(`/identify`,{method:`POST`,headers:{"auth-api-key":x,"content-type":`application/json`},body:JSON.stringify(y)});if(!w)return k();if(!w.ok)return O(w,`/identify`);let T=await w.json().catch(()=>void 0);if(!e(T)||!S(T.result))return console.error(`Zeno's answer to the proxy route's identification couldn't be read`),d(`Zeno's answer couldn't be read`,502);let E=C(T.cookie);return l(200,T.result,E?{"set-cookie":b(new URL(t.url),E.value,E.maxAge,s)}:{})};return async(e,r,i)=>{let o=new URL(e.url);if(e.method===`POST`&&o.searchParams.has(`forget`))return new Response(null,{status:204,headers:{"set-cookie":b(o,``,0,s)}});if(![`GET`,`HEAD`,`POST`].includes(e.method))return l(405,{error:`method_not_allowed`,message:`Use GET or POST`},{allow:`GET, HEAD, POST`});let c=t(`createProxy`,n,a);if(c.problem!==void 0)return console.error(c.problem),d(`The proxy route isn't set up; its server log says what's missing`);x=c.apiKey,w=c.base;let u=y(r);if(e.method===`POST`)return P(e,u,i);let f=await N(e,u);return e.method===`HEAD`?(await f.body?.cancel(),new Response(null,{status:f.status,headers:f.headers})):f}},O=[`automation`,`headless`,`software-renderer`,`tampering`,`timezone-mismatch`,`privacy-settings`,`vpn`,`proxy`,`tor`,`datacenter`,`abusive-ip`,`incognito`,`virtual-machine`,`developer-tools`,`ai-agent`,`privacy-browser`,`high-activity`,`replayed`,`residential-proxy`,`private-relay`,`forged-payload`,`stored-id-rejected`,`storage-cleared`],k=1e4;var A=class extends Error{status;code;retryAfter;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.retryAfter=r,this.name=`ZenoError`}};const j=(e,t)=>{if(!e)throw TypeError(t);return e},M=e=>{if(e===null)return;let t=/^\d+$/.test(e.trim())?Number(e):(Date.parse(e)-Date.now())/1e3;return Number.isFinite(t)?Math.min(Math.max(t,0),60):void 0},N=e=>new Promise(t=>setTimeout(t,e*1e3)),P=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new A(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},F=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,I=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>F(t[e],n))}),L=I(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),ee=I(`a page of events`,{items:`array`}),te=I(`a visitor`,{visitorId:`string`,externalIds:`array`,externalIdCount:`number`,recentEvents:`array`}),R=I(`a reported outcome`,{requestId:`string`,outcome:`string`}),z=I(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),B=I(`an erasure`,{externalId:`string`,deletedEvents:`number`}),V=I(`a relation`,{externalId:`string`,type:`string`,linkWrite:`boolean`}),H=I(`a removal`,{removed:`boolean`}),U=I(`a user's values`,{externalId:`string`,values:`array`,truncated:`boolean`}),W=I(`a page of users`,{items:`array`}),G=I(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`}),K=I(`an embed`,{url:`string`,expiresAt:`string`}),q=I(`verify's answer`,{action:`string`,reasons:`array`}),J=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async(e,t,n,r,i)=>{try{let o=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...i?{"content-type":`application/json`}:{}},body:i,signal:AbortSignal.timeout(k)});return{response:o,text:await o.text()}}catch(e){throw new A(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${k} ms`:`Zeno couldn't be reached at ${t}: ${e instanceof Error?e.message:String(e)}`)}},s=async(r,a,s,c,l=!1)=>{let u=t(`createClient`,n,i);if(u.problem!==void 0)throw TypeError(u.problem);let d=c&&JSON.stringify(c);for(let t=0;;t++){let n;try{n=await o(u.apiKey,u.base,r,a,d)}catch(e){if(l&&t<2){await N(1+Math.random()*.5);continue}throw e}let{response:i,text:c}=n,f;try{f=JSON.parse(c)}catch{}if(i.ok){if(f===void 0)throw new A(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new A(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:p,message:m}=e(f)?f:{},h=typeof p==`string`?p:void 0,g=i.status===429||h===`search_unavailable`||l&&i.status>=500,_=g?M(i.headers.get(`retry-after`)):void 0;if(g&&t<2){let e=_??1;await N(e+Math.random()*e*.5)}else throw new A(i.status,h??`request_failed`,typeof m==`string`?m:void 0,_)}},c=(e,t)=>{for(let[n,r]of Object.entries(t))r!==void 0&&e.set(n,String(r));return e};return{verify:async(e,t={})=>{let{ip:n,externalId:r,maxAge:i,idempotencyKey:a=crypto.randomUUID()}=t;return s(`POST`,`/verify`,q,{requestId:e??void 0,ip:n||void 0,externalId:r,maxAge:i,idempotencyKey:a},!0)},getEvent:async e=>s(`GET`,`/events/${P(`requestId`,e)}`,L),searchEvents:(e={})=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r])e!==void 0&&t.append(n,e instanceof Date?e.toISOString():String(e));return s(`GET`,`/events?${t}`,ee)},getVisitor:async e=>s(`GET`,`/visitors/${P(`visitorId`,e)}`,te),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,R,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${P(`visitorId`,e)}`,z),deleteExternalId:e=>{let t=new URLSearchParams({externalId:e});return s(`DELETE`,`/external-ids?${t}`,B)},addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,V,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>{let t=new URLSearchParams(e);return s(`DELETE`,`/related?${t}`,H)},getRelatedValues:(e,{type:t}={})=>{let n=new URLSearchParams({externalId:e,...t?{type:t}:{}});return s(`GET`,`/related/values?${n}`,U)},lookupRelated:(e,t,n={})=>{let r=c(new URLSearchParams({type:e,value:t}),n);return s(`GET`,`/related/lookup?${r}`,W)},getRelated:(e,{type:t,depth:n=1}={})=>{let r=new URLSearchParams({externalId:e,...t?{type:t}:{},depth:String(n)});return s(`GET`,`/related?${r}`,G)},createEmbed:e=>s(`POST`,`/embeds`,K,e)}},Y=new TextEncoder,X=e=>{try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch{return}},Z=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),ne=(e,t)=>{if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0},re=async(e,t,n,{tolerance:r=300}={})=>{let i=j(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`),a=(t??``).split(`,`).map(e=>{let[t,...n]=e.trim().split(`=`);return[t??``,n.join(`=`)]}),o=Number(a.find(([e])=>e===`t`)?.[1]),s=a.filter(([e,t])=>e===`v1`&&t).map(([,e])=>e);if(!Number.isInteger(o)||s.length===0||Math.abs(Date.now()/1e3-o)>r)return;let c=await crypto.subtle.importKey(`raw`,Y.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=Y.encode(Z(await crypto.subtle.sign(`HMAC`,c,Y.encode(`${o}.${e}`))));if(!s.map(e=>ne(Y.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!L.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u},Q=()=>({action:`block`,reasons:[`not-found`]}),$=`unsealResult needs the project's encryption key as key (is it set in the environment?)`,ie=e=>{let t=j(e,$).trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(t)?X(t):void 0;if(!n)throw TypeError(`unsealResult's key isn't base64: pass the project's encryption key as the app shows it`);if(n.length!==32)throw TypeError(/^[0-9a-f]{64}$/i.test(t)?`unsealResult's key looks like hex: pass the project's encryption key as the app shows it, in base64`:`unsealResult's key is ${n.length} bytes, not 32: pass the project's encryption key as the app shows it`);return n},ae=async(e,t)=>{for(let n of e){let e=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`decrypt`]);try{return await crypto.subtle.decrypt({name:`AES-GCM`,iv:t.subarray(1,13),tagLength:128},e,t.subarray(13))}catch{}}},oe=async(e,t)=>{let n=(Array.isArray(t?.key)?t.key:[t?.key]).filter(e=>e);if(n.length===0)throw TypeError($);let i=n.map(ie);if(!e)return{action:`challenge`,reasons:[`no-request-id`]};if(typeof e!=`string`||!/^[A-Za-z0-9+/]+={0,2}$/.test(e.trim()))return Q();let a=X(e.trim());if(!a||a.length<30||a[0]!==1)return Q();let o=await ae(i,a);if(!o)return Q();let s;try{s=JSON.parse(new TextDecoder().decode(o))}catch{}if(!L.is(s))throw Error(`The sealed result opened but isn't an event; update zeno.id/server`);let c=[],l=t.maxAge??300;return t.ip&&r(s.ip.address,t.ip)&&c.push(`ip-mismatch`),Date.now()-Date.parse(s.createdAt)>l*1e3&&c.push(`too-old`),t.externalId!==void 0&&s.externalId!==void 0&&s.externalId!==t.externalId&&c.push(`external-id-mismatch`),c.length>0?{action:`block`,reasons:c,event:s}:{action:s.verdict.action,reasons:s.verdict.reasons,event:s}};export{O as SIGNALS,A as ZenoError,J as createClient,D as createProxy,oe as unsealResult,re as verifyWebhook};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zeno.id",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Zeno's SDK for device identification: the browser SDK, and the proxy route and API client for your server",
5
5
  "license": "MIT",
6
6
  "files": [