zeno.id 0.6.0 → 0.7.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/README.md CHANGED
@@ -108,7 +108,7 @@ The script's code uses no `eval` or `new Function`, so `'unsafe-eval'` isn't nee
108
108
 
109
109
  | `identify()` option | |
110
110
  | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
111
- | `externalId` | Your id for the user behind the browser, to look visitors up by and to delete later. 1 to 256 characters (`invalid_options` otherwise). |
111
+ | `externalId` | Your id for the user behind the browser, to look visitors up by and to delete later. 1 to 256 bytes, none a control character like a tab or a line break (`invalid_options` otherwise). |
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
 
@@ -160,7 +160,7 @@ if (error) {
160
160
  | `server_error` | The route or Zeno failed, or answered something that isn't the route's JSON. The message says what: a route that wasn't given the visitor's IP says to pass it, a refused API key says to check the route's. | Read the message and the route's server log; go on without a request ID. |
161
161
  | `account_closed` | Zeno closed the organization's account (as for unpaid invoices): identification is refused until it's reopened. | Contact support. |
162
162
  | `stopped` | `stop()` was called, before or during the `identify()`. | Call `start()` again once consent is back. |
163
- | `capped` | A limit stopped the identification: a spend limit you set, the key's ceiling or the visitor ip's rate limit. Not a bot. | Go on without a request ID. |
163
+ | `capped` | A limit stopped the identification: a spend limit you set, the visitor ip's rate limit, or the month's free identifications used without billing details. The message says which. Not a bot. | Go on without a request ID. |
164
164
  | `not_in_browser` | `identify()` ran on the server, while a page rendered. | Call it in the action's handler in the browser. |
165
165
 
166
166
  ### What it collects
@@ -307,7 +307,7 @@ const { action } = await client.verify(requestId, {
307
307
 
308
308
  `ip` is optional: pass the same client IP your proxy route got, not your load balancer's, and a request ID sent from another ip blocks with `ip-mismatch`; leave it out (or pass `null` or `undefined`) and there's no ip check, as there's none between an IPv4 and an IPv6 address. `no-request-id` is a `challenge` so you decide: ask for a second factor, or let it through and flag the account; never treat it as verified. API errors throw a `ZenoError`.
309
309
 
310
- A lost answer is safe to retry. Each call sends an `idempotencyKey`, and after a network error or a `5xx` the SDK sends it again, twice at most, with the same key; a repeat with the same key within 5 minutes answers what the first call did instead of `already-used`. If your own code may send the same verify again (a retried job, a second try of your handler), pass your own `idempotencyKey`, 8 to 128 characters, like your request's ID.
310
+ A lost answer is safe to retry, and `verify` answers or throws within 10 seconds, its retries included, so your handler never waits longer. Each call sends an `idempotencyKey`, and after a network error or a `5xx` the SDK sends it again, twice at most, with the same key; a repeat with the same key within 5 minutes answers what the first call did instead of `already-used`. If your own code may send the same verify again (a retried job, a second try of your handler), pass your own `idempotencyKey`, 8 to 128 characters, like your request's ID.
311
311
 
312
312
  ### Test keys
313
313
 
@@ -341,14 +341,8 @@ await client.deleteExternalId(user.id)
341
341
  // Related accounts: add what only you know
342
342
  await client.addRelation({
343
343
  externalId: user.id,
344
- type: 'phone',
345
- value: order.phone,
346
- })
347
- await client.addRelation({
348
- externalId: user.id,
349
- type: 'referral',
350
- relatedExternalId: referrer.id,
351
- at: user.createdAt,
344
+ type: 'payment-card',
345
+ value: payment.cardFingerprint,
352
346
  })
353
347
  const { duplicate, identified } = await client.getRelatedValues(user.id)
354
348
  const { externalIds } = await client.getRelated(user.id, { depth: 2 })
@@ -360,31 +354,34 @@ const { url } = await client.createEmbed({
360
354
  })
361
355
  ```
362
356
 
363
- | Method | Call |
364
- | -------------------------------------------------------------------- | -------------------------------------------------------------------------- |
365
- | `verify(requestId, { ip?, externalId?, maxAge?, idempotencyKey? }?)` | `POST /verify` |
366
- | `getEvent(requestId)` | `GET /events/{requestId}` |
367
- | `searchEvents(filters)` | `GET /events?...` |
368
- | `getVisitor(visitorId)` | `GET /visitors/{visitorId}` |
369
- | `deleteVisitor(visitorId)` | `DELETE /visitors/{visitorId}` |
370
- | `deleteExternalId(externalId)` | `DELETE /external-ids?externalId=...` |
371
- | `reportOutcome(requestId, outcome)` | `POST /outcomes`, `fraud` or `legitimate`, the latest counts |
372
- | `addRelation({ externalId, type, value or relatedExternalId, at? })` | `POST /related` |
373
- | `removeRelation({ externalId, type, value or relatedExternalId })` | `DELETE /related?externalId=...&type=...`, `{ removed }`, free |
374
- | `getRelated(externalId, { type?, depth? })` | `GET /related?externalId=...`, every type unless `type` names one |
375
- | `getRelatedValues(externalId, { type? })` | `GET /related/values?externalId=...` |
376
- | `lookupRelated(type, value, { limit?, cursor? })` | `GET /related/lookup?type=...&value=...`, 20 a page by default (up to 100) |
377
- | `createEmbed({ externalId, origin, ttl? })` | `POST /embeds` |
378
-
379
- A list filter (`apiKeyId`, `country`, `origin`, `asn`, `browser`, `os`, `action`, `signal`, `bot`) takes an array and matches any of its values. Visitor ids and ips relate your users by themselves for events with an external id; `addRelation` adds what only you know: an ip seen elsewhere, a value of a type of your own, or a relation between two users. Make a `createEmbed` link for each view of your admin panel's page.
357
+ | Method | Call |
358
+ | -------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
359
+ | `verify(requestId, { ip?, externalId?, maxAge?, idempotencyKey? }?)` | `POST /verify` |
360
+ | `getEvent(requestId)` | `GET /events/{requestId}` |
361
+ | `searchEvents(filters)` | `GET /events?...` |
362
+ | `deleteVisitor(visitorId)` | `DELETE /visitors/{visitorId}` |
363
+ | `deleteExternalId(externalId)` | `DELETE /external-ids?externalId=...` |
364
+ | `reportOutcome(requestId, outcome)` | `POST /outcomes`, `legitimate` or a type of fraud, the latest counts |
365
+ | `addRelation({ externalId, type, value, at? })` | `POST /related` |
366
+ | `removeRelation({ externalId, type, value })` | `DELETE /related?externalId=...&type=...`, `{ removed }`, free |
367
+ | `getRelated(externalId, { type?, depth? })` | `GET /related?externalId=...`, every type unless `type` names one |
368
+ | `getRelatedValues(externalId, { type? })` | `GET /related/values?externalId=...` |
369
+ | `lookupRelated(type, value, { limit?, cursor? })` | `GET /related/lookup?type=...&value=...`, 20 a page by default (up to 100) |
370
+ | `getRelatedGroup(externalId, { limit?, cursor? })` | `GET /related/group?externalId=...`, the user's `groupId` and its members |
371
+ | `getGroup(groupId, { limit?, cursor? })` | `GET /related/group/{groupId}`, a group by its ID, 500 members a page |
372
+ | `getRelatedWeights()` | `GET /related/weights`, every type with its weight and its Match within |
373
+ | `setRelatedType(type, { weight?, matchWithinDays? })` | `POST /related/weights`, weight 0 to 1, days 1 to 3650, `null` for a default |
374
+ | `createEmbed({ externalId, origin, ttl? })` | `POST /embeds` |
375
+
376
+ A list filter (`apiKeyId`, `country`, `origin`, `asn`, `browser`, `os`, `action`, `signal`, `bot`, `outcome`) takes an array and matches any of its values. Visitor ids and ips relate your users by themselves for events with an external id; `addRelation` adds what only you know: an ip seen elsewhere or a value of a type of your own. Users who share a value are related; you never relate two users yourself. Make a `createEmbed` link for each view of your admin panel's page.
380
377
 
381
378
  A failed call throws a `ZenoError` with the `status` and the API's error `code` (`ZenoErrorCode`), like `not_found`. A call answered `429 rate_limited` or `503 search_unavailable` is sent again after the API's `Retry-After`, twice, a little later each time at random so calls limited together don't all come back at once; the error of one that stays limited has `retryAfter` in seconds. Neither was carried out, so retrying a write or a delete is safe.
382
379
 
383
- The SDK's own codes: `network_error` (status `0`) when the API can't be reached or doesn't answer within 10 seconds, retried only for `verify` (above); `invalid_request` with status `0` for an empty id (`getEvent('')`), refused before anything is sent; `request_failed` for an error answer without a code, or a success answer that isn't what the call returns (each answer is checked before it's handed back, so something between your server and Zeno that answers otherwise fails here rather than later in your code).
380
+ The SDK's own codes: `network_error` (status `0`) when the API can't be reached or doesn't answer within 10 seconds, retried only for `verify` (above, 10 seconds in all); `invalid_request` with status `0` for an empty id (`getEvent('')`), refused before anything is sent; `request_failed` for an error answer without a code, or a success answer that isn't what the call returns (each answer is checked before it's handed back, so something between your server and Zeno that answers otherwise fails here rather than later in your code).
384
381
 
385
- `addRelation` is the one billed call: each is billed like an identification and counts toward the free monthly identifications and the spend limits (reads, `createEmbed` and what events relate by themselves are free). Once a spend limit you set for the project, its organization or the key is reached it throws a `402` `spend_limit_reached` and adds nothing. Every call answers `402` `account_closed` while Zeno has closed the organization's account (for unpaid invoices); contact support to reopen it.
382
+ Every call is free, `addRelation` included: only identifications are billed, and an added relation doesn't count toward the free monthly identifications or the spend limits. Every call answers `402` `account_closed` while Zeno has closed the organization's account (for unpaid invoices); contact support to reopen it.
386
383
 
387
- `addRelation`'s `at` takes a `Date`, epoch milliseconds or an ISO string. A type's first call fixes whether it holds values or relations. The project's settings hold each type's weight (`visitor-id` 0.9, `residential-ip` 0.7, `ip` 0.25, `broad-visitor-id` 0.25, a type of your own 0.5 by default), applied when relations are read, so a change re-scores every relation. The reads answer each value's `weight` and each related user's (what the two share combined as `1 - Π(1 - weight)`, so two shared ips make 0.44 and a browser and an ip 0.93, multiplied along the path); `duplicate` means they share one value weighing 0.5 or more with another user. `createEmbed` answers `{ url, expiresAt }`: put the url in an iframe on `origin`, the only page allowed to frame it, before `expiresAt` (`ttl`, 5 to 60 minutes, 15 by default).
384
+ `addRelation`'s `at` takes a `Date`, epoch milliseconds or an ISO string. A type of your own exists from its first value. The project holds each type's weight, set in Settings or with `setRelatedType` (`visitor-id` 0.95, `residential-ip` 0.7, `ip` 0.25, `broad-visitor-id` 0.25, a type of your own 0.5 by default), applied when relations are read, so a change re-scores every relation. The reads answer each value's `weight` and each related user's (what the two share combined as `1 - Π(1 - weight)`, so two shared ips make 0.44 and a visitor ID and an ip 0.96, multiplied along the path); `duplicate` means they share one value weighing 0.75 or more with another user. `createEmbed` answers `{ url, expiresAt }`: put the url in an iframe on `origin`, the only page allowed to frame it, before `expiresAt` (`ttl`, 5 to 60 minutes, 15 by default).
388
385
 
389
386
  ## Webhooks
390
387
 
@@ -405,7 +402,7 @@ export const handle = async (request: Request) => {
405
402
  }
406
403
  ```
407
404
 
408
- `verifyWebhook` resolves to the event when the signature matched, a `WebhookEvent` (the event without its `velocity`), else to `undefined`. In Express, read the raw body with `express.text({ type: 'application/json' })`. Pass the raw body: the signature covers it byte for byte. Deliveries older than 5 minutes (`tolerance`, in seconds) are refused, so a captured one can't be replayed. The header is `t=<unix seconds>,v1=<hmac sha256 hex>`; spaces after the commas and several `v1=` signatures are accepted: for 24 hours after a secret rotation every delivery carries one signed with the new secret and one with the previous. Each delivery also has `Zeno-Delivery-Id` (the same on every retry, to drop one you handled) and `Zeno-Trigger` (`event`, `update`, `redeliver` or `test`; a test sends the project's latest event or a made up one, so don't act on it).
405
+ `verifyWebhook` resolves to the event when the signature matched, a `WebhookEvent` (the event without its `velocity`), else to `undefined`. In Express, read the raw body with `express.text({ type: 'application/json' })`. Pass the raw body: the signature covers it byte for byte, and a body a JSON parser already read rejects with a TypeError saying so. Deliveries older than 5 minutes (`tolerance`, in seconds) are refused, so a captured one can't be replayed. The header is `t=<unix seconds>,v1=<hmac sha256 hex>`; spaces after the commas and several `v1=` signatures are accepted: for 24 hours after a secret rotation every delivery carries one signed with the new secret and one with the previous. Each delivery also has `Zeno-Delivery-Id` (the same on every retry, to drop one you handled) and `Zeno-Trigger` (`event`, `update`, `redeliver` or `test`; a test sends the project's latest event or a made up one, so don't act on it).
409
406
 
410
407
  ## Sealed results
411
408
 
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=>`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;
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(()=>{})}}};exports.ZenoError=t,exports.forget=p,exports.start=x;
package/dist/index.d.cts CHANGED
@@ -10,7 +10,7 @@ declare class ZenoError extends Error {
10
10
  type Metadata = Record<string, string | number | boolean>;
11
11
  type IdentifyOptions = {
12
12
  /**
13
- * Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 characters;
13
+ * Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 bytes;
14
14
  * anything else is refused with `invalid_options` before anything is sent.
15
15
  */
16
16
  externalId?: string;
@@ -44,7 +44,8 @@ type Identification = {
44
44
  requestId?: undefined;
45
45
  /**
46
46
  * Why, by its `code`: a failure, `stopped`, `not_in_browser` on the server, or `capped` (a spend limit you
47
- * set, the key's ceiling or the visitor ip's rate limit; not a bot).
47
+ * set, the visitor ip's rate limit, or the month's free identifications used without billing details; not a
48
+ * bot).
48
49
  */
49
50
  error: ZenoError;
50
51
  visitorId?: undefined;
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ declare class ZenoError extends Error {
10
10
  type Metadata = Record<string, string | number | boolean>;
11
11
  type IdentifyOptions = {
12
12
  /**
13
- * Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 characters;
13
+ * Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 bytes;
14
14
  * anything else is refused with `invalid_options` before anything is sent.
15
15
  */
16
16
  externalId?: string;
@@ -44,7 +44,8 @@ type Identification = {
44
44
  requestId?: undefined;
45
45
  /**
46
46
  * Why, by its `code`: a failure, `stopped`, `not_in_browser` on the server, or `capped` (a spend limit you
47
- * set, the key's ceiling or the visitor ip's rate limit; not a bot).
47
+ * set, the visitor ip's rate limit, or the month's free identifications used without billing details; not a
48
+ * bot).
48
49
  */
49
50
  error: ZenoError;
50
51
  visitorId?: undefined;
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=>`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,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};
@@ -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`,`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;
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;