zeno.id 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -9,6 +9,11 @@ declare class ZenoError extends Error {
9
9
  /** Values a metadata key can hold; nothing nested. */
10
10
  type Metadata = Record<string, string | number | boolean>;
11
11
  type IdentifyOptions = {
12
+ /**
13
+ * The path on this site your proxy route answers at (`createProxyResponse`), `/zeno` by default, without a query
14
+ * string or fragment. Pass the same one to `preload()`.
15
+ */
16
+ path?: string;
12
17
  /**
13
18
  * Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 bytes;
14
19
  * anything else is refused with `invalid_options` before anything is sent.
@@ -24,17 +29,11 @@ type IdentifyOptions = {
24
29
  metadata?: Metadata;
25
30
  };
26
31
  type Identification = {
27
- /** Left out when the project runs in zero trust mode: only your backend learns the visitor. */
28
- visitorId?: string;
29
32
  /**
30
33
  * Send it to your server with the action, where `verify` from `zeno.id/server` says to allow, challenge or
31
- * block.
34
+ * block, and gives the event with its visitor ID. The browser never learns the visitor ID.
32
35
  */
33
36
  requestId: string;
34
- /** Whether the api had seen this visitor before; left out in zero trust mode. */
35
- returning?: boolean;
36
- /** The event encrypted with the project's key, when the project seals results. */
37
- sealedResult?: string;
38
37
  error?: undefined;
39
38
  } | {
40
39
  /**
@@ -48,41 +47,29 @@ type Identification = {
48
47
  * bot).
49
48
  */
50
49
  error: ZenoError;
51
- visitorId?: undefined;
52
- returning?: undefined;
53
- sealedResult?: undefined;
54
- };
55
- type Zeno = {
56
- /**
57
- * Identifies the browser: sends the report through the proxy route and answers the request ID. It never rejects:
58
- * when nothing was identified it resolves `{ requestId: undefined, error }`.
59
- */
60
- identify(options?: IdentifyOptions): Promise<Identification>;
61
- /**
62
- * Stops identifying for good, as when the visitor withdraws consent: nothing more is collected or sent, an
63
- * identify() in progress and every later one answer the `stopped` error, and the route is asked to clear its
64
- * visitor cookie. A script still loading never starts. Call start() again to identify once consent is given again.
65
- */
66
- stop(): void;
67
50
  };
68
51
  //#endregion
69
- //#region src/browser/forget.d.ts
52
+ //#region src/browser/index.d.ts
70
53
  /**
71
- * Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
72
- * page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
73
- * cleared the cookie; on the server it rejects with `not_in_browser`.
54
+ * Loads Zeno's script from your proxy route and starts gathering signals, so a later `identify()` is quick; nothing is
55
+ * sent until `identify()`. Optional, and once a page: calling it again for the same path does nothing. On the server it
56
+ * does nothing.
74
57
  *
75
- * @param path The same path on this site you pass to `start()`, `/zeno` by default.
58
+ * @param path The path on this site your proxy route answers at, like `/zeno` (the default), without a query string or
59
+ * fragment. Pass `identify()` the same one.
76
60
  */
77
- declare const forget: (path?: string) => Promise<void>;
78
- //#endregion
79
- //#region src/browser/index.d.ts
61
+ declare const preload: (path?: string) => void;
80
62
  /**
81
- * Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
82
- *
83
- * @param path The path on this site you mounted `createProxy` at, `/zeno` by default, without a query string or
84
- * fragment. The script loads from it and identifies through it.
63
+ * Identifies the browser: sends the report through your proxy route and answers the request ID, loading the script
64
+ * first when `preload()` didn't. It never rejects: when nothing was identified it resolves `{ requestId: undefined,
65
+ * error }`, with `not_in_browser` on the server.
66
+ */
67
+ declare const identify: (options?: IdentifyOptions) => Promise<Identification>;
68
+ /**
69
+ * For a visitor who withdraws consent: stops the script (an `identify()` in progress answers `stopped`) and deletes the
70
+ * visitor ID this browser keeps, the `zeno_id` cookie. A later `preload()` or `identify()` starts again. On the server
71
+ * it does nothing.
85
72
  */
86
- declare const start: (path?: string) => Zeno;
73
+ declare const forget: () => void;
87
74
  //#endregion
88
- export { type Identification, type IdentifyOptions, type Metadata, type Zeno, ZenoError, type ZenoErrorCode, forget, start };
75
+ export { type Identification, type IdentifyOptions, type Metadata, ZenoError, type ZenoErrorCode, forget, identify, preload };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
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(
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 by forget()`,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||new TextEncoder().encode(t).length>256))throw a(`externalId must be a string of 1 to 256 bytes`);if(t!==void 0&&/[\p{Cc}\p{Cs}]/u.test(t))throw a(`externalId can’t hold control 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};
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=>{let t=o(e??`/zeno`);if(!t)throw a(`The path is your proxy route's path on this site, like '/zeno'`);return t},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||new TextEncoder().encode(t).length>256))throw a(`externalId must be a string of 1 to 256 bytes`);if(t!==void 0&&/[\p{Cc}\p{Cs}]/u.test(t))throw a(`externalId can’t hold control 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=()=>{try{document.cookie=`zeno_id=; Max-Age=0; Path=/; SameSite=Lax`}catch{}},d=(e,t,n)=>{let r;return Promise.race([e,new Promise((e,i)=>{r=setTimeout(()=>i(n()),t)})]).finally(()=>clearTimeout(r))},f=e=>({requestId:void 0,error:n(e)}),p=e=>e.error?{...e,error:n(e.error)}:e,m=e=>async()=>{try{let t=await i(`${e}?challenge=${Date.now()}`);return s(t?.challengeToken)}catch{return}},h=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}},g=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 h(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:m(e)});return o(t),t}catch(e){throw n(e)}},_=/* @__PURE__ */ new Map,v=(e,n)=>{let r=!1,i,a=()=>{},o=new Promise((e,t)=>{a=t});o.catch(()=>{});let s=g(e,()=>r,e=>i=e);return s.catch(n),{identify:async e=>{let n=1e4,i=performance.now(),a=await d(Promise.race([s,o]),n,()=>new t(`client_timeout`)),c=Math.max(1,n-(performance.now()-i));if(r)throw new t(`stopped`);return p(await a.identify({...e,timeout:c}))},stop(){r=!0,a(new t(`stopped`)),i?.stop()}}},y=e=>{let t=_.get(e);if(t)return t;let n=v(e,()=>{_.get(e)===n&&_.delete(e)});return _.set(e,n),n},b=e=>{typeof document<`u`&&y(c(e))},x=async(e={})=>{try{if(typeof document>`u`)throw new t(`not_in_browser`);return l(e),await y(c(e.path)).identify(e)}catch(e){return f(e)}},S=()=>{for(let e of _.values())e.stop();_.clear(),typeof document<`u`&&u()};export{t as ZenoError,S as forget,x as identify,b as preload};
@@ -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{errorResponse:k()};if(r.status!==304&&!r.ok)return{errorResponse: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}:{errorResponse:d(`Zeno answered 304 for code this route never had`)};let o=await r.text().catch(()=>void 0);if(o===void 0)return{errorResponse: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.errorResponse)return n.errorResponse;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.errorResponse)return e.errorResponse;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 e.headers.get(`sec-fetch-site`)?.toLowerCase()===`cross-site`?u(`Cross-site requests are refused`):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 f=y(r);if(e.method===`POST`)return P(e,f,i);let p=await N(e,f);return e.method===`HEAD`?(await p.body?.cancel(),new Response(null,{status:p.status,headers:p.headers})):p}},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`];var k=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 A=(e,t)=>{if(!e)throw TypeError(t);return e},j=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},M=e=>new Promise(t=>setTimeout(t,e*1e3)),N=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new k(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},P=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,F=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>P(t[e],n))}),I=F(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),L=F(`a page of events`,{items:`array`}),ee=F(`a reported outcome`,{requestId:`string`,outcome:`string`}),te=F(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),ne=F(`an erasure`,{externalId:`string`,deletedEvents:`number`}),R=F(`a relation`,{externalId:`string`,type:`string`,created:`boolean`}),z=F(`a removal`,{removed:`boolean`}),B=F(`a user's values`,{externalId:`string`,values:`array`}),V=F(`a page of users`,{items:`array`}),H=F(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`,sharedValues:`array`,pairs:`array`,truncated:`boolean`,widelyShared:`array`,stoppedAt:`array`}),U=F(`the weights`,{items:`array`}),W=F(`a weight`,{type:`string`,weight:`number`,defaultWeight:`number`}),G=F(`a user's group`,{externalId:`string`,size:`number`,externalIds:`array`}),K=F(`a group`,{groupId:`string`,size:`number`,externalIds:`array`}),q=F(`an embed`,{url:`string`,expiresAt:`string`}),J=F(`verify's answer`,{action:`string`,reasons:`array`}),Y=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async({apiKey:e,base:t},n,r,i,o)=>{try{let s=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...o?{"content-type":`application/json`}:{}},body:o,signal:AbortSignal.timeout(i)});return{response:s,text:await s.text()}}catch(e){throw new k(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${i} 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),f=l?Date.now()+1e4:void 0,p=()=>f===void 0?1e4:Math.round(Math.min(5e3,f-Date.now())),m=e=>f===void 0||f-Date.now()-e*1e3>=1e3;for(let t=0;;t++){let n;try{n=await o(u,r,a,p(),d)}catch(e){let n=.5+Math.random()*.25;if(l&&t<2&&m(n)){await M(n);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 k(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new k(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:h,message:g}=e(f)?f:{},_=typeof h==`string`?h:void 0,v=i.status===429||_===`search_unavailable`||l&&i.status>=500,y=v?j(i.headers.get(`retry-after`)):void 0,b=(y??1)*(1+Math.random()*.5);if(v&&t<2&&m(b))await M(b);else throw new k(i.status,_??`request_failed`,typeof g==`string`?g:void 0,y)}},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`,J,{requestId:e??void 0,ip:n||void 0,externalId:r,maxAge:i,idempotencyKey:a},!0)},getEvent:async e=>s(`GET`,`/events/${N(`requestId`,e)}`,I),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}`,L)},reportOutcome:(e,t)=>s(`POST`,`/outcomes`,ee,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${N(`visitorId`,e)}`,te),deleteExternalId:e=>{let t=new URLSearchParams({externalId:e});return s(`DELETE`,`/external-ids?${t}`,ne)},addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,R,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>{let t=new URLSearchParams(e);return s(`DELETE`,`/related?${t}`,z)},getRelatedValues:(e,{type:t,...n}={})=>{let r=c(new URLSearchParams({externalId:e,...t?{type:t}:{}}),n);return s(`GET`,`/related/values?${r}`,B)},lookupRelated:(e,t,n={})=>{let r=c(new URLSearchParams({type:e,value:t}),n);return s(`GET`,`/related/lookup?${r}`,V)},getRelated:(e,{type:t,depth:n=1}={})=>{let r=new URLSearchParams({externalId:e,...t?{type:t}:{},depth:String(n)});return s(`GET`,`/related?${r}`,H)},getRelatedGroup:(e,t={})=>{let n=c(new URLSearchParams({externalId:e}),t);return s(`GET`,`/related/group?${n}`,G)},getGroup:async(e,t={})=>{let n=c(new URLSearchParams,t).toString(),r=`/related/group/${N(`groupId`,e)}`;return s(`GET`,n?`${r}?${n}`:r,K)},getRelatedWeights:()=>s(`GET`,`/related/weights`,U),setRelatedType:(e,t)=>s(`POST`,`/related/weights`,W,{type:e,...t}),createEmbed:e=>s(`POST`,`/embeds`,q,e)}},X=new TextEncoder,Z=e=>{try{return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}catch{return}},re=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),ie=(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},ae=async(e,t,n,{tolerance:r=300}={})=>{let i=A(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`);if(typeof e!=`string`)throw TypeError(`verifyWebhook needs the raw body as text, not a parsed one (in Express, express.text({ type: "application/json" }))`);let 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`,X.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=X.encode(re(await crypto.subtle.sign(`HMAC`,c,X.encode(`${o}.${e}`))));if(!s.map(e=>ie(X.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!I.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?)`,oe=e=>{let t=A(e,$).trim(),n=/^[A-Za-z0-9+/]+={0,2}$/.test(t)?Z(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},se=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{}}},ce=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(oe);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=Z(e.trim());if(!a||a.length<30||a[0]!==1)return Q();let o=await se(i,a);if(!o)return Q();let s;try{s=JSON.parse(new TextDecoder().decode(o))}catch{}if(!I.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=k,exports.createClient=Y,exports.createProxy=D,exports.unsealResult=ce,exports.verifyWebhook=ae;
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=>Array.isArray(e)&&e.every(e=>typeof e==`string`),r=e=>{let t=e.rawHeaders;return n(t)?t:void 0},i=1e4,a=[`user-agent`,`origin`,`signature-agent`,`signature-input`,`sec-fetch-site`],o=(e,t)=>new Response(JSON.stringify(t),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`}}),s=(e,t=500)=>o(t,{error:`server_error`,message:e}),c=e=>{for(let t of e.split(`;`)){let e=t.indexOf(`=`);if(e!==-1&&t.slice(0,e).trim()===`zeno_id`)return t.slice(e+1).trim()}},l=(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},u=e=>{let t={"zeno-visitor-header-names":e.map(([e])=>e.toLowerCase()).join(`, `)};for(let[n,r]of e){let e=n.toLowerCase(),i=e===`cookie`?c(r):void 0;i&&!t[`zeno-visitor-token`]&&(t[`zeno-visitor-token`]=i),a.includes(e)&&!t[`zeno-visitor-${e}`]&&(t[`zeno-visitor-${e}`]=r)}return t},d=async e=>{if(e.status===401||e.status===402){let t=await e.clone().text().catch(()=>``);console.error(`Zeno answered the proxy route ${e.status}: ${t}`)}let t=new Headers;return e.headers.forEach((e,n)=>{n.startsWith(`zeno-browser-`)&&n.length>13&&t.append(n.slice(13),e)}),new Response(e.body?await e.arrayBuffer():null,{status:e.status,headers:t})},f=async e=>{let{request:n,ip:a,apiKey:o,apiUrl:c,fetch:f=globalThis.fetch,...p}=e,m=t(`createProxyResponse`,o,c);if(m.problem!==void 0)return console.error(m.problem),s(`The proxy route isn't set up; its server log says what's missing`);let h=`${m.base}/proxy${new URL(n.url).search}`,g=n.method!==`GET`&&n.method!==`HEAD`;try{let e=await f(h,{method:n.method,headers:{"auth-api-key":m.apiKey,...a?{"zeno-visitor-ip":a}:{},...g?{"content-type":`application/json`}:{},...u(l(n,r(p)))},...g?{body:await n.arrayBuffer()}:{},signal:AbortSignal.timeout(i)});return await d(e)}catch(e){let t=e instanceof Error&&e.name===`TimeoutError`?`no answer within ${i} ms`:String(e);return console.error(`The proxy route couldn't reach Zeno at ${h}: ${t}`),s(`Zeno could not be reached`,502)}},p=1048576,m=async e=>{let t=[],n=0;for await(let r of e){let e=typeof r==`string`?new TextEncoder().encode(r):r;n+=e.byteLength,n<=p&&t.push(e)}if(n>p)return null;let r=new Uint8Array(n),i=0;for(let e of t)r.set(e,i),i+=e.byteLength;return r},h=(e,t)=>{let n=new Headers;for(let t=0;t+1<e.rawHeaders.length;t+=2){let r=e.rawHeaders[t];r.startsWith(`:`)||n.append(r,e.rawHeaders[t+1])}let r=e.socket.encrypted?`https`:`http`,i=e.originalUrl??e.url??`/`,a=new URL(i,`${r}://${e.headers.host??`localhost`}`);return new Request(a,{method:e.method,headers:n,...t?{body:t}:{}})},g=async(e,t)=>{t.statusCode=e.status,e.headers.forEach((e,n)=>{n!==`set-cookie`&&t.setHeader(n,e)});let n=e.headers.getSetCookie();n.length>0&&t.setHeader(`set-cookie`,n),t.end(e.body?new Uint8Array(await e.arrayBuffer()):void 0)},_=e=>async(t,n)=>{let r=`raw`in t?t.raw:t,i=t.ip,a=typeof i==`string`?i:r.socket.remoteAddress,o;`hijack`in n?(n.hijack(),o=n.raw):o=n;let s=(e,t,n)=>g(new Response(JSON.stringify({error:t,message:n}),{status:e,headers:{"content-type":`application/json; charset=utf-8`,"cache-control":`no-store`}}),o);try{let t=r.method!==`GET`&&r.method!==`HEAD`;if(t&&r.readableEnded){console.error(`The proxy route found its body already read: mount nodeHandler before any body parser`),await s(500,`server_error`,`The proxy route isn't set up; its server log says what's wrong`);return}let n=t?await m(r):void 0;if(n===null){await s(413,`invalid_request`,`The body is larger than 1 MB`);return}let i={...e,request:h(r,n),ip:a,rawHeaders:r.rawHeaders};await g(await f(i),o)}catch(e){console.error(`The proxy route failed: ${e instanceof Error?e.message:String(e)}`),o.headersSent||await s(500,`server_error`,`The proxy route failed; its server log says why`)}},v=[`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`];var y=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 b=(e,t)=>{if(!e)throw TypeError(t);return e},x=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},S=e=>new Promise(t=>setTimeout(t,e*1e3)),C=(e,t)=>{if(typeof t!=`string`||!t||t===`.`||t===`..`)throw new y(0,`invalid_request`,`${e} must be a non-empty string`);return encodeURIComponent(t)},w=(t,n)=>n===`array`?Array.isArray(t):n===`object`?e(t):typeof t===n,T=(t,n)=>({name:t,is:t=>e(t)&&Object.entries(n).every(([e,n])=>w(t[e],n))}),E=T(`an event`,{requestId:`string`,visitorId:`string`,ip:`object`,createdAt:`string`,riskScore:`number`,signals:`object`,verdict:`object`}),D=T(`a page of events`,{items:`array`}),O=T(`a reported outcome`,{requestId:`string`,outcome:`string`}),k=T(`an erasure`,{visitorId:`string`,deletedEvents:`number`}),A=T(`an erasure`,{externalId:`string`,deletedEvents:`number`}),j=T(`a relation`,{externalId:`string`,type:`string`,created:`boolean`}),M=T(`a removal`,{removed:`boolean`}),N=T(`a user's values`,{externalId:`string`,values:`array`}),P=T(`a page of users`,{items:`array`}),F=T(`related users`,{externalId:`string`,externalIds:`array`,connections:`array`,sharedValues:`array`,pairs:`array`,truncated:`boolean`,widelyShared:`array`,stoppedAt:`array`}),I=T(`the weights`,{items:`array`}),L=T(`a weight`,{type:`string`,weight:`number`,defaultWeight:`number`}),R=T(`a user's group`,{externalId:`string`,size:`number`,externalIds:`array`}),z=T(`a group`,{groupId:`string`,size:`number`,externalIds:`array`}),B=T(`an embed`,{url:`string`,expiresAt:`string`}),V=T(`verify's answer`,{action:`string`,reasons:`array`}),H=(n,r={})=>{let{apiUrl:i,fetch:a=globalThis.fetch}=r,o=async({apiKey:e,base:t},n,r,i,o)=>{try{let s=await a(`${t}${r}`,{method:n,headers:{"auth-api-key":e,...o?{"content-type":`application/json`}:{}},body:o,signal:AbortSignal.timeout(i)});return{response:s,text:await s.text()}}catch(e){throw new y(0,`network_error`,e instanceof Error&&e.name===`TimeoutError`?`Zeno didn't answer ${n} ${r.split(`?`)[0]} within ${i} 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),f=l?Date.now()+1e4:void 0,p=()=>f===void 0?1e4:Math.round(Math.min(5e3,f-Date.now())),m=e=>f===void 0||f-Date.now()-e*1e3>=1e3;for(let t=0;;t++){let n;try{n=await o(u,r,a,p(),d)}catch(e){let n=.5+Math.random()*.25;if(l&&t<2&&m(n)){await S(n);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 y(i.status,`request_failed`,`Zeno answered ${i.status} without JSON`);if(!s.is(f))throw new y(i.status,`request_failed`,`Zeno answered ${r} ${a.split(`?`)[0]} with something that isn't ${s.name}`);return f}let{error:h,message:g}=e(f)?f:{},_=typeof h==`string`?h:void 0,v=i.status===429||_===`search_unavailable`||l&&i.status>=500,b=v?x(i.headers.get(`retry-after`)):void 0,C=(b??1)*(1+Math.random()*.5);if(v&&t<2&&m(C))await S(C);else throw new y(i.status,_??`request_failed`,typeof g==`string`?g:void 0,b)}},c=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 t};return{verify:async(e,t={})=>{let{ip:n,externalId:r,scope:i,maxAge:a,idempotencyKey:o=crypto.randomUUID()}=t;return s(`POST`,`/verify`,V,{requestId:e??void 0,ip:n||void 0,externalId:r,scope:i,maxAge:a,idempotencyKey:o},!0)},getEvent:async e=>s(`GET`,`/events/${C(`requestId`,e)}`,E),searchEvents:(e={})=>s(`GET`,`/events?${c(e)}`,D),reportOutcome:(e,t)=>s(`POST`,`/outcomes`,O,{requestId:e,outcome:t}),deleteVisitor:async e=>s(`DELETE`,`/visitors/${C(`visitorId`,e)}`,k),deleteExternalId:(e,{scope:t}={})=>s(`DELETE`,`/external-ids?${c({externalId:e,scope:t})}`,A),addRelation:({at:e,...t})=>{let n=e instanceof Date||typeof e==`number`?new Date(e).toISOString():e;return s(`POST`,`/related`,j,{...t,...n===void 0?{}:{at:n}})},removeRelation:e=>s(`DELETE`,`/related?${c(e)}`,M),getRelatedValues:(e,{scope:t,type:n,...r}={})=>{let i=c({externalId:e,scope:t,type:n,...r});return s(`GET`,`/related/values?${i}`,N)},lookupRelated:(e,t,{scope:n,...r}={})=>{let i=c({type:e,value:t,scope:n,...r});return s(`GET`,`/related/lookup?${i}`,P)},getRelated:(e,{scope:t,type:n,depth:r=1}={})=>{let i=c({externalId:e,scope:t,type:n,depth:r});return s(`GET`,`/related?${i}`,F)},getRelatedGroup:(e,{scope:t,...n}={})=>{let r=c({externalId:e,scope:t,...n});return s(`GET`,`/related/group?${r}`,R)},getGroup:async(e,t={})=>{let n=c(t).toString(),r=`/related/group/${C(`groupId`,e)}`;return s(`GET`,n?`${r}?${n}`:r,z)},getRelatedWeights:()=>s(`GET`,`/related/weights`,I),setRelatedType:(e,t)=>s(`POST`,`/related/weights`,L,{type:e,...t}),createEmbed:e=>s(`POST`,`/embeds`,B,e)}},U=new TextEncoder,W=e=>Array.from(new Uint8Array(e),e=>e.toString(16).padStart(2,`0`)).join(``),G=(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},K=async(e,t,n,{tolerance:r=300}={})=>{let i=b(n,`verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)`);if(typeof e!=`string`)throw TypeError(`verifyWebhook needs the raw body as text, not a parsed one (in Express, express.text({ type: "application/json" }))`);let 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`,U.encode(i),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),l=U.encode(W(await crypto.subtle.sign(`HMAC`,c,U.encode(`${o}.${e}`))));if(!s.map(e=>G(U.encode(e),l)).includes(!0))return;let u;try{u=JSON.parse(e)}catch{}if(!E.is(u))throw Error(`The webhook's body is signed but isn't an event; update zeno.id/server`);return u};exports.SIGNALS=v,exports.ZenoError=y,exports.createClient=H,exports.createProxyResponse=f,exports.nodeHandler=_,exports.verifyWebhook=K;
@@ -1,4 +1,70 @@
1
- import { a as ApiOptions, i as ApiKey, n as ProxyOptions, r as createProxy, t as ProxyHandler } from "./proxy-CUZ-Jwgy.cjs";
1
+ //#region src/server/util.d.ts
2
+ /** The project's API key, `sk_...`, from your server's environment: `process.env.ZENO_API_KEY`. */
3
+ type ApiKey = string | undefined;
4
+ /** Options both createClient and createProxyResponse take. */
5
+ type ApiOptions = {
6
+ /** The Zeno API's http(s) origin, for staging or a local Zeno. Zeno's own API by default. */
7
+ apiUrl?: string | undefined;
8
+ };
9
+ //#endregion
10
+ //#region src/server/proxy.d.ts
11
+ /** What `createProxyResponse` takes: the browser's request to your route, the IP it came from and your API key. */
12
+ type ProxyRequest = ApiOptions & {
13
+ /** The browser's request to your proxy route, a web `Request`. */
14
+ request: Request;
15
+ /**
16
+ * The IP address the request came from, your framework's client IP; behind a proxy of your own, turn on your
17
+ * framework's trust-proxy setting so it's the visitor's. Zeno refuses an identification without it (`400`).
18
+ */
19
+ ip: string | null | undefined;
20
+ /** Your API key, from your server's environment: `process.env.ZENO_API_KEY`. */
21
+ apiKey: ApiKey;
22
+ };
23
+ /**
24
+ * Your proxy route's answer: a route on your own site between the browser SDK and the Zeno API. It forwards the
25
+ * browser's request to Zeno with your API key and the visitor's IP, and returns Zeno's answer: the script, or an
26
+ * identification's request ID with the visitor ID in a first-party cookie. Call it for every request on one path of
27
+ * your choice (the browser SDK's `path`, like `/zeno`); Zeno decides what each gets. The `apiKey` (undefined accepted)
28
+ * is checked on each call, so a module that reads it at load builds without the environment (as Next.js does when it
29
+ * collects page data); a request without it answers `500` and logs it. On Node's `(req, res)`, use `nodeHandler` from
30
+ * `zeno.id/server`.
31
+ */
32
+ declare const createProxyResponse: (options: ProxyRequest) => Promise<Response>;
33
+ type NodeRequest = AsyncIterable<Uint8Array | string> & {
34
+ method?: string;
35
+ url?: string;
36
+ headers: {
37
+ host?: string;
38
+ };
39
+ rawHeaders: string[];
40
+ readableEnded: boolean;
41
+ socket: {
42
+ remoteAddress?: string;
43
+ encrypted?: boolean;
44
+ };
45
+ };
46
+ type NodeResponse = {
47
+ statusCode: number;
48
+ headersSent: boolean;
49
+ setHeader(name: string, value: string | string[]): unknown;
50
+ end(body?: Uint8Array | string): unknown;
51
+ };
52
+ type FastifyRequest = {
53
+ raw: NodeRequest;
54
+ ip?: unknown;
55
+ };
56
+ type FastifyReply = {
57
+ raw: NodeResponse;
58
+ hijack(): unknown;
59
+ };
60
+ /**
61
+ * Your proxy route on Node's `(req, res)`: Express, Fastify or `http.createServer`. `app.all('/zeno', nodeHandler({
62
+ * apiKey: process.env.ZENO_API_KEY }))`. It passes `createProxyResponse` the request and the IP address it came from:
63
+ * Express's and Fastify's `req.ip` (behind a proxy of your own, set their trust proxy so it's the visitor's), else the
64
+ * socket's address. Mount it before any body parser (`express.json()`): it forwards the body as it came.
65
+ */
66
+ declare const nodeHandler: (options: Omit<ProxyRequest, 'request' | 'ip'>) => (request: NodeRequest | FastifyRequest, response: NodeResponse | FastifyReply) => Promise<void>;
67
+ //#endregion
2
68
  //#region src/server/index.d.ts
3
69
  /** Every signal an event checks, the keys of its `signals`. */
4
70
  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'];
@@ -286,6 +352,8 @@ type Event = {
286
352
  */
287
353
  returning?: boolean;
288
354
  externalId?: string;
355
+ /** The external ID's scope, when your server set one (`verify`). */
356
+ scope?: string;
289
357
  /** What the visitor was doing, as the browser's `identify({ action })` named it, like `login`. */
290
358
  action?: string;
291
359
  /** Your own key-values from the browser's `identify({ metadata })`. Not in search results. */
@@ -299,7 +367,7 @@ type Event = {
299
367
  */
300
368
  updatedAt?: string;
301
369
  origin?: string;
302
- /** The page as origin and path, or only its origin; left out when the project keeps no page urls (`pageUrls`). */
370
+ /** The page as origin and path, never its query string or fragment. */
303
371
  url?: string;
304
372
  referrer?: string;
305
373
  browser: EventBrowser;
@@ -322,25 +390,25 @@ type Event = {
322
390
  radius: number;
323
391
  confidence: number;
324
392
  };
325
- /** Only on getEvent and verify, not in webhooks or sealed results. */
393
+ /** Only on getEvent and verify, not in webhooks. */
326
394
  rawDeviceAttributes?: RawDeviceAttributes;
327
- /** Only on getEvent and verify, not in webhooks or sealed results. */
395
+ /** Only on getEvent and verify, not in webhooks. */
328
396
  velocity?: Record<'5m' | '1h' | '24h', Velocity>;
329
397
  /**
330
- * Your other users this event ties to, by external id: those sharing its `visitorId`, its residential IP
398
+ * Your other users this event ties to, by external ID and scope: those sharing its `visitorId`, its residential IP
331
399
  * (`residentialIp`), and both its `broadVisitorId` and its IP (`broadVisitorId`, as a broad visitor ID isn't strong
332
- * enough on its own). Up to 25 of each. Only on getEvent and verify, not in webhooks or sealed results.
400
+ * enough on its own). Up to 25 of each. Only on getEvent and verify, not in webhooks.
333
401
  */
334
402
  related?: {
335
- visitorId: string[];
336
- residentialIp: string[];
337
- broadVisitorId: string[];
403
+ visitorId: ExternalIdRef[];
404
+ residentialIp: ExternalIdRef[];
405
+ broadVisitorId: ExternalIdRef[];
338
406
  };
339
407
  /**
340
408
  * The group of the event's user: one ID that every user tied to it through a shared strong value answers too (a
341
409
  * visitor ID with the default weights), directly or through other users. Without an external ID, the group its
342
410
  * visitor ID ties. `null` when there is none. It can change when groups join or come apart, so key a counter on it
343
- * and keep what must last on your own user. Only on getEvent and verify, not in webhooks or sealed results.
411
+ * and keep what must last on your own user. Only on getEvent and verify, not in webhooks.
344
412
  */
345
413
  groupId?: string | null;
346
414
  } & GlobalFields;
@@ -350,6 +418,8 @@ type SearchFilters = {
350
418
  apiKeyId?: AnyOf<string>;
351
419
  visitorId?: string;
352
420
  externalId?: string;
421
+ /** The `externalId`'s scope; without one, the user without a scope. */
422
+ scope?: string;
353
423
  ip?: string;
354
424
  requestId?: string;
355
425
  country?: AnyOf<string>;
@@ -381,7 +451,7 @@ type SearchFilters = {
381
451
  * version, and its `ip` the address with the country, city, asn and company, each left out when the event has none of
382
452
  * them.
383
453
  */
384
- type SearchEvent = Pick<Event, 'requestId' | 'visitorId' | 'verdict' | 'riskScore' | 'bot' | 'outcome' | 'confidence' | 'externalId' | 'action' | 'apiKeyId' | 'createdAt' | 'origin'> & {
454
+ type SearchEvent = Pick<Event, 'requestId' | 'visitorId' | 'verdict' | 'riskScore' | 'bot' | 'outcome' | 'confidence' | 'externalId' | 'scope' | 'action' | 'apiKeyId' | 'createdAt' | 'origin'> & {
385
455
  signals: { [S in Signal]?: {
386
456
  detected: true;
387
457
  }; };
@@ -400,6 +470,19 @@ type Page<T> = {
400
470
  type SearchResult = Page<SearchEvent> & {
401
471
  found?: number;
402
472
  };
473
+ /**
474
+ * One of your users as Zeno names it in an answer: your external ID and, when you gave it one, its scope. `user-1042`
475
+ * in `tenant-1` and in `tenant-2` are two users.
476
+ */
477
+ type ExternalIdRef = {
478
+ externalId: string;
479
+ scope?: string;
480
+ };
481
+ /**
482
+ * The scopes a read covers: one, several, or `'*'` for every scope, as when it's left out. Users of two scopes are
483
+ * never related.
484
+ */
485
+ type Scopes = string | string[];
403
486
  /**
404
487
  * What relates two users: the built-in `visitor-id` (a browser), `broad-visitor-id` (its hardware), `residential-ip`
405
488
  * (an ip of an internet provider, not a VPN, proxy or mobile network), all three from events only, and `ip`, or a type
@@ -433,9 +516,11 @@ type RelatedWeight = {
433
516
  /** One of Zeno's own types (`visitor-id`, `ip`, ...), not one of yours. */
434
517
  builtIn: boolean;
435
518
  };
436
- /** A user's group: everyone tied to the user through shared strong values, directly or through other users. */
437
- type RelatedGroup = {
438
- externalId: string;
519
+ /**
520
+ * A user's group: everyone tied to the user through shared strong values, directly or through other users, all in the
521
+ * user's scope.
522
+ */
523
+ type RelatedGroup = ExternalIdRef & {
439
524
  /** The same for every user in the group. `null` for a user Zeno has no values of. */
440
525
  groupId: string | null;
441
526
  /**
@@ -444,7 +529,7 @@ type RelatedGroup = {
444
529
  */
445
530
  size: number;
446
531
  /** A page of the group's users, the asked one among them: no weights, no depth. Empty without a group ID. */
447
- externalIds: string[];
532
+ externalIds: ExternalIdRef[];
448
533
  /** Pass it back for the next page; none on the last page. */
449
534
  cursor?: string;
450
535
  };
@@ -455,7 +540,7 @@ type Group = {
455
540
  /** How many users the group has, up to 10,000: a larger group is answered as 10,000 of its users. */
456
541
  size: number;
457
542
  /** A page of the group's users: no weights, no depth. */
458
- externalIds: string[];
543
+ externalIds: ExternalIdRef[];
459
544
  /** Pass it back for the next page; none on the last page. */
460
545
  cursor?: string;
461
546
  };
@@ -463,16 +548,15 @@ type Group = {
463
548
  type RelatedValue = ValueDetails & {
464
549
  value: string;
465
550
  };
466
- type RelatedValues = {
467
- externalId: string;
551
+ type RelatedValues = ExternalIdRef & {
468
552
  /**
469
553
  * The user's group, the same on every page. `null` for a user Zeno has no values of, and for a group of more than
470
554
  * 10,000 users, which has no ID.
471
555
  */
472
556
  groupId: string | null;
473
557
  /**
474
- * Shares one value weighing 0.75 or more with another user: with the default weights a visitor id does, a
475
- * residential ip or a type of your own only once you weigh it that much. Lesser ties never add up to one.
558
+ * Shares one value weighing 0.75 or more with another user of its scope: with the default weights a visitor id
559
+ * does, a residential ip or a type of your own only once you weigh it that much. Lesser ties never add up to one.
476
560
  */
477
561
  duplicate: boolean;
478
562
  /** Was ever identified in a browser; treat a user who wasn't as unverified. */
@@ -482,9 +566,8 @@ type RelatedValues = {
482
566
  /** Pass it back for the next page; none on the last page. */
483
567
  cursor?: string;
484
568
  };
485
- /** Another user (`externalId`) who shares a `value` with the asked one. */
486
- type Connection = ValueDetails & {
487
- externalId: string;
569
+ /** Another user (`externalId` in `scope`) who shares a `value` with the asked one. */
570
+ type Connection = ValueDetails & ExternalIdRef & {
488
571
  value: string;
489
572
  };
490
573
  /** A value two or more of the users found share, with each of the users who share it and when they got it. */
@@ -493,11 +576,10 @@ type SharedValue = {
493
576
  /** The type's weight, 0 to 1. */
494
577
  weight: number;
495
578
  value: string;
496
- externalIds: {
497
- externalId: string;
579
+ externalIds: (ExternalIdRef & {
498
580
  at: string;
499
581
  createdAt: string;
500
- }[];
582
+ })[];
501
583
  };
502
584
  /**
503
585
  * Two of the related users who share values: `a` and `b` are their indexes in `externalIds` (`a` the lower), and
@@ -506,6 +588,8 @@ type SharedValue = {
506
588
  type RelatedPair = [a: number, b: number, values: number[]];
507
589
  type Related = {
508
590
  externalId: string;
591
+ /** The scopes asked for; none for every scope. */
592
+ scope?: Scopes;
509
593
  /** The type asked for; none when every type was walked. */
510
594
  type?: RelatedType;
511
595
  /**
@@ -513,10 +597,9 @@ type Related = {
513
597
  * (`1 - Π(1 - weight)`, so with the default weights two shared ips make 0.44 and a visitor id and an ip 0.96),
514
598
  * multiplied along the strongest path for a user further away.
515
599
  */
516
- externalIds: {
517
- externalId: string;
600
+ externalIds: (ExternalIdRef & {
518
601
  weight: number;
519
- }[];
602
+ })[];
520
603
  /** What the asked user shares with others: one entry per other user and shared value. */
521
604
  connections: Connection[];
522
605
  /**
@@ -546,19 +629,17 @@ type Related = {
546
629
  * one to continue the search from that user. The asked user is in the list when it has more values than one search
547
630
  * follows: pass a `type`, or page its values with `getRelatedValues`.
548
631
  */
549
- stoppedAt: string[];
632
+ stoppedAt: ExternalIdRef[];
550
633
  };
551
634
  /** One of your users who has a value, and since when. */
552
- type RelatedUser = {
553
- externalId: string;
635
+ type RelatedUser = ExternalIdRef & {
554
636
  createdAt: string;
555
637
  };
556
638
  /**
557
639
  * A relation: an ip seen by another system (`type: 'ip'`) or a value of a type of your own (`{ type: 'payment-card',
558
640
  * value }`). Its weight isn't part of it: the project holds each type's weight, applied when related users are read.
559
641
  */
560
- type RelationTarget = {
561
- externalId: string;
642
+ type RelationTarget = ExternalIdRef & {
562
643
  type: RelatedType;
563
644
  value: string;
564
645
  };
@@ -628,6 +709,11 @@ type VerifyOptions = {
628
709
  * succeeded (the password matched, the account exists), with the user's ID, so a failed login attaches nothing.
629
710
  */
630
711
  externalId?: string;
712
+ /**
713
+ * The scope the user is in, like `tenant-1`, when your users are in scopes: the same `externalId` in another scope
714
+ * is another user. Only with `externalId`.
715
+ */
716
+ scope?: string;
631
717
  /**
632
718
  * Makes sending the same verify again safe: a repeat with this key within 5 minutes answers what the first did,
633
719
  * instead of `already-used`. The SDK makes one per call and retries a lost answer with it itself; pass your own (8
@@ -644,8 +730,7 @@ type VerifyResult = {
644
730
  reasons: (VerifyCheck | VerdictReason)[];
645
731
  /**
646
732
  * The event, from `verify` with its velocity as `getEvent` has it (`event.velocity['24h'].distinctExternalId`, or
647
- * `sameAction` without external IDs), its velocity counted before verify attached your `externalId`. Only from
648
- * `verify`: `unsealResult` runs on your server and has no velocity.
733
+ * `sameAction` without external IDs), its velocity counted before verify attached your `externalId`.
649
734
  */
650
735
  event?: Event;
651
736
  };
@@ -687,16 +772,20 @@ declare const createClient: (apiKey: ApiKey, options?: ClientOptions) => {
687
772
  visitorId: string;
688
773
  deletedEvents: number;
689
774
  }>;
690
- /** Deletes everything stored for one of your users: their events, and what relates them to devices and others. */
691
- deleteExternalId: (externalId: string) => Promise<{
692
- externalId: string;
775
+ /**
776
+ * Deletes everything stored for one of your users (in its `scope`, when it has one): their events, and what
777
+ * relates them to devices and others.
778
+ */
779
+ deleteExternalId: (externalId: string, { scope }?: {
780
+ scope?: string;
781
+ }) => Promise<ExternalIdRef & {
693
782
  deletedEvents: number;
694
783
  }>;
695
784
  /**
696
- * Adds a relation to one of your users: an ip seen by another system, or a value of a type of your own (a
697
- * card's fingerprint, your own device id). Users who have the same value are related; you never relate two
698
- * users yourself. Visitor ids only come from events with an external id, so `identified` means the user was
699
- * seen in a browser.
785
+ * Adds a relation to one of your users (in its `scope`, when it has one): an ip seen by another system, or a
786
+ * value of a type of your own (a card's fingerprint, your own device id). Users who have the same value are
787
+ * related, never across scopes; you never relate two users yourself. Visitor ids only come from events with an
788
+ * external id, so `identified` means the user was seen in a browser.
700
789
  *
701
790
  * Free, like reads. `created` says whether the call added the value; sending one again only brings it up to
702
791
  * date.
@@ -712,39 +801,46 @@ declare const createClient: (apiKey: ApiKey, options?: ClientOptions) => {
712
801
  removed: boolean;
713
802
  }>;
714
803
  /**
715
- * One of your users' values, of one `type` or every type, each with its weight, whether they share one value
716
- * weighing 0.75 or more with another user (`duplicate`) and their group (`groupId`). 500 a page by default
717
- * (`limit` up to 500); pass the cursor back for the next page.
804
+ * One of your users' values (in its `scope`, when it has one), of one `type` or every type, each with its
805
+ * weight, whether they share one value weighing 0.75 or more with another user of the scope (`duplicate`) and
806
+ * their group (`groupId`). 500 a page by default (`limit` up to 500); pass the cursor back for the next page.
718
807
  */
719
- getRelatedValues: (externalId: string, { type, ...page }?: {
808
+ getRelatedValues: (externalId: string, { scope, type, ...page }?: {
809
+ scope?: string;
720
810
  type?: RelatedType;
721
811
  limit?: number;
722
812
  cursor?: string;
723
813
  }) => Promise<RelatedValues>;
724
814
  /**
725
- * Your users who have one value, like everyone who paid with one card, 20 a page by default (`limit` up to
726
- * 100); pass the cursor back for the next page.
815
+ * Your users who have one value, like everyone who paid with one card, in the `scope` you pass (several, or
816
+ * `'*'` for every scope, as without one), 20 a page by default (`limit` up to 100); pass the cursor back for
817
+ * the next page.
727
818
  */
728
- lookupRelated: (type: RelatedType, value: string, page?: {
819
+ lookupRelated: (type: RelatedType, value: string, { scope, ...page }?: {
820
+ scope?: Scopes;
729
821
  limit?: number;
730
822
  cursor?: string;
731
823
  }) => Promise<Page<RelatedUser>>;
732
824
  /**
733
825
  * Your users related to one through shared values of every type, or of one `type`, up to `depth` (1 or 2, 1 by
734
- * default) hops away, heaviest first, each with its weight. A deeper search reads more and takes longer.
826
+ * default) hops away, heaviest first, each with its weight. A deeper search reads more and takes longer. With
827
+ * `scope`, the user in that scope; with several, the user in each of them, related only to users of those
828
+ * scopes; `'*'`, or none, the user in every scope it has, related to users of any scope.
735
829
  */
736
- getRelated: (externalId: string, { type, depth }?: {
830
+ getRelated: (externalId: string, { scope, type, depth }?: {
831
+ scope?: Scopes;
737
832
  type?: RelatedType;
738
833
  depth?: number;
739
834
  }) => Promise<Related>;
740
835
  /**
741
- * One of your users' group: the ID every user tied to it through shared strong values answers (the event's
742
- * `groupId`), how many users it has (`size`) and its users, the asked one among them, 500 a page by default
743
- * (`limit` up to 500); pass the cursor back for the next page. Check a fact that must hold once per group, like
744
- * a reward, against these users in your own records. A group of more than 10,000 users is answered as the
745
- * 10,000 nearest the asked one.
836
+ * One of your users' group (in its `scope`, when it has one): the ID every user tied to it through shared
837
+ * strong values answers (the event's `groupId`), how many users it has (`size`) and its users, the asked one
838
+ * among them, 500 a page by default (`limit` up to 500); pass the cursor back for the next page. Check a fact
839
+ * that must hold once per group, like a reward, against these users in your own records. A group of more than
840
+ * 10,000 users is answered as the 10,000 nearest the asked one.
746
841
  */
747
- getRelatedGroup: (externalId: string, page?: {
842
+ getRelatedGroup: (externalId: string, { scope, ...page }?: {
843
+ scope?: string;
748
844
  limit?: number;
749
845
  cursor?: string;
750
846
  }) => Promise<RelatedGroup>;
@@ -777,12 +873,13 @@ declare const createClient: (apiKey: ApiKey, options?: ClientOptions) => {
777
873
  matchWithinDays?: number | null;
778
874
  }) => Promise<RelatedWeight>;
779
875
  /**
780
- * A link to one user's Related view (their values, related users and recent events) for your admin panel at
781
- * `origin` to frame, working for `ttl` seconds (300 to 3600, 900 by default). Make one per page view and never
782
- * hand the API key to the browser.
876
+ * A link to one user's Related view (their values, related users and recent events; in its `scope`, when it has
877
+ * one) for your admin panel at `origin` to frame, working for `ttl` seconds (300 to 3600, 900 by default). Make
878
+ * one per page view and never hand the API key to the browser.
783
879
  */
784
880
  createEmbed: (embed: {
785
881
  externalId: string;
882
+ scope?: string;
786
883
  origin: string;
787
884
  ttl?: number;
788
885
  }) => Promise<Embed>;
@@ -800,33 +897,5 @@ type WebhookEvent = Omit<Event, 'broadVisitorId' | 'proximity' | 'rawDeviceAttri
800
897
  declare const verifyWebhook: (body: string, header: string | null | undefined, secret: string | undefined, { tolerance }?: {
801
898
  tolerance?: number | undefined;
802
899
  }) => Promise<WebhookEvent | undefined>;
803
- /** What `unsealResult` takes besides the sealed result. */
804
- type UnsealOptions = {
805
- /**
806
- * The project's encryption key, base64 (32 bytes), as the dashboard shows it: `process.env.ZENO_ENCRYPTION_KEY`; or
807
- * several, tried in order, while you rotate it: `[current, previous]`.
808
- */
809
- key: string | undefined | (string | undefined)[];
810
- /**
811
- * The IP address the request came from, as you pass it to `verify`: a sealed result from another ip blocks
812
- * (`ip-mismatch`, for IPv6 another /64); left out, or of the other family than the event's, there's no ip check.
813
- */
814
- ip?: string | null | undefined;
815
- /** Your own id for the user: an event with another user's blocks (`external-id-mismatch`); one with none is fine. */
816
- externalId?: string;
817
- /** Seconds a sealed result stays good for, 5 minutes (300) by default, as with `verify`; an older one blocks. */
818
- maxAge?: number;
819
- };
820
- /**
821
- * Opens a sealed result from the browser with the project's encryption key and says what to do, in `verify`'s shape: `{
822
- * action, reasons, event? }`. No sealed result (`undefined`, `null` or empty) is a `challenge` with `no-request-id`;
823
- * one that doesn't open with any `key` (changed, sealed with another project's key, or not one at all) is a `block`
824
- * with `not-found`. An opened one from another ip than `ip` blocks with `ip-mismatch`, compared as `verify` does, one
825
- * older than `maxAge` seconds with `too-old`, another user's than `externalId` with `external-id-mismatch`; otherwise
826
- * it answers the event's verdict. It can't tell a sealed result sent twice: where a repeat matters, use `verify`, which
827
- * allows each request ID once. Rejects with a TypeError for a missing or malformed key. The format: base64(version |
828
- * iv(12) | ciphertext | tag(16)), AES-256-GCM.
829
- */
830
- declare const unsealResult: (sealedResult: string | undefined | null, options: UnsealOptions) => Promise<VerifyResult>;
831
900
  //#endregion
832
- export { AddedRelation, type ApiOptions, Bot, BotType, Client, ClientOptions, Confidence, Connection, Contradiction, Embed, Event, EventBot, EventBrowser, EventIp, ForgedPayloadIndicator, GlobalFields, Group, Metadata, NetworkOwnerType, Outcome, Page, type ProxyHandler, type ProxyOptions, RawDeviceAttributes, Related, RelatedGroup, RelatedPair, RelatedType, RelatedUser, RelatedValue, RelatedValues, RelatedWeight, Relation, RelationInput, RelationRemoval, SIGNALS, SearchEvent, SearchFilters, SearchResult, SharedValue, Signal, SignalDetails, SignalReason, SignalResult, Signals, UnsealOptions, Velocity, Verdict, VerdictAction, VerdictReason, VerifyCheck, VerifyOptions, VerifyResult, VirtualMachineIndicator, WebhookEvent, ZenoError, ZenoErrorCode, createClient, createProxy, unsealResult, verifyWebhook };
901
+ export { AddedRelation, type ApiOptions, Bot, BotType, Client, ClientOptions, Confidence, Connection, Contradiction, Embed, Event, EventBot, EventBrowser, EventIp, ExternalIdRef, ForgedPayloadIndicator, GlobalFields, Group, Metadata, NetworkOwnerType, Outcome, Page, type ProxyRequest, RawDeviceAttributes, Related, RelatedGroup, RelatedPair, RelatedType, RelatedUser, RelatedValue, RelatedValues, RelatedWeight, Relation, RelationInput, RelationRemoval, SIGNALS, Scopes, SearchEvent, SearchFilters, SearchResult, SharedValue, Signal, SignalDetails, SignalReason, SignalResult, Signals, Velocity, Verdict, VerdictAction, VerdictReason, VerifyCheck, VerifyOptions, VerifyResult, VirtualMachineIndicator, WebhookEvent, ZenoError, ZenoErrorCode, createClient, createProxyResponse, nodeHandler, verifyWebhook };