zeno.id 0.6.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # zeno.id
2
2
 
3
- Zeno tells your server whether a login, signup or checkout came from a real browser, and whether to let it through. This package has both sides. In the browser, `zeno.id` is a small loader: `start()` imports the script itself at runtime through a route on your own site (the proxy route), so collection fixes reach every site without a release, and `identify()` answers a request ID for your server to verify. On your server, `zeno.id/server` is that proxy route, which adds your API key and passes the script's signals on to Zeno, a typed client for the Zeno API with `verify`, and the helpers for webhooks and sealed results.
3
+ Zeno tells your server whether a login, signup or checkout came from a real browser, and whether to let it through. This package has both sides. In the browser, `zeno.id` is a small loader: it imports the script itself at runtime through a route on your own site (the proxy route), so collection fixes reach every site without a release, and `identify()` answers a request ID for your server to verify. On your server, `zeno.id/server` is that proxy route, which adds your API key and passes the script's signals on to Zeno, a typed client for the Zeno API with `verify`, and the helper for webhooks.
4
4
 
5
5
  ## Install
6
6
 
@@ -8,7 +8,7 @@ Zeno tells your server whether a login, signup or checkout came from a real brow
8
8
  npm install zeno.id
9
9
  ```
10
10
 
11
- One package for the browser and the server. `zeno.id/server` holds your API key, so import it on your server only. It uses only standard web APIs, so it runs on Node 20+, Bun, Deno, Cloudflare Workers, Vercel and Netlify edge, with no compatibility flags; `zeno.id/server/node` adds `nodeHandler` for Express, Fastify and Node's http server. A browser bundle of `zeno.id` holds the loader only, none of the server code. Every entry ships ES modules, CommonJS and their types. Not JavaScript? The Zeno API is plain HTTP: the docs' server API reference has every call.
11
+ One package for the browser and the server. `zeno.id/server` holds your API key, so import it on your server only. It uses only standard web APIs, so it runs on Node 20+, Bun, Deno, Cloudflare Workers, Vercel and Netlify edge, with no compatibility flags; `zeno.id/server` adds `nodeHandler` for Express, Fastify and Node's http server. A browser bundle of `zeno.id` holds the loader only, none of the server code. Every entry ships ES modules, CommonJS and their types. Not JavaScript? The Zeno API is plain HTTP: the docs' server API reference has every call.
12
12
 
13
13
  ## How it fits together
14
14
 
@@ -18,18 +18,10 @@ One package for the browser and the server. `zeno.id/server` holds your API key,
18
18
  ZENO_API_KEY=sk_...
19
19
  ```
20
20
 
21
- 2. Make the proxy route once, with the key, and mount it on your site at a path of your choice (`/zeno` here).
22
- 3. In the browser, on a page with an action you want to identify (a login, signup or checkout), `start()` the browser SDK (`zeno.id`) with the same path when the page loads (it gathers signals; nothing is sent or billed), call `identify()` when the user takes the action, the identity check, and send its `requestId` to your server with the action's request.
21
+ 2. Add the proxy route on your site at a path of your choice (`/zeno` here): it answers each request with `createProxyResponse`, your key and the visitor's IP.
22
+ 3. In the browser, on a page with an action you want to identify (a login, signup or checkout), call the browser SDK's (`zeno.id`) `identify()` when the user takes the action, the identity check, and send its `requestId` to your server with the action's request. Optionally `preload()` it when the page loads (it gathers signals; nothing is sent or billed), so `identify()` is quick.
23
23
  4. On your server, make an API client with the same key, `verify` the request ID and allow, challenge or block.
24
24
 
25
- ```ts
26
- // zeno.ts
27
- import { createProxy } from 'zeno.id/server'
28
-
29
- // Your proxy route: the browser SDK talks to Zeno through it
30
- export const zeno = createProxy(process.env.ZENO_API_KEY)
31
- ```
32
-
33
25
  ```ts
34
26
  import { createClient } from 'zeno.id/server'
35
27
 
@@ -50,22 +42,24 @@ if (action === 'block') {
50
42
  }
51
43
  ```
52
44
 
53
- The package reads no option or secret from the environment: `createProxy(apiKey, options?)` and `createClient(apiKey, options?)` take the key from `process.env` or wherever your secrets live (`env` on Cloudflare Workers). It may be `undefined` where the route or client is made: neither fails at import or at build time, where the environment may be missing (Next.js collecting page data), and a call, or a request to the route, without it fails saying how to set it. Both know where the Zeno API is, so there's no address to set.
45
+ The package reads no option or secret from the environment: `createProxyResponse({ request, ip, apiKey })` and `createClient(apiKey)` take the key from `process.env` or wherever your secrets live (`env` on Cloudflare Workers). It may be `undefined` where the client is made: nothing fails at import or at build time, where the environment may be missing (Next.js collecting page data), and a call, or a request to the route, without it fails saying how to set it. Both know where the Zeno API is, so there's no address to set.
54
46
 
55
47
  ## In the browser
56
48
 
57
- Call `start()` on a page with an action you want to identify (a login, signup or checkout), when that page loads, not on every page, with the path of your route on your site. It loads Zeno's script and starts gathering signals in the browser; nothing is sent to Zeno and nothing is billed. Call `identify()` when the user takes the action: that's the identity check, it sends the report and gives you the request ID. Starting early only makes `identify()` quick, and one `start()` serves every `identify()` on that page. Call it in a module, not in a component (a component remounts, and each `start()` collects again). A module's top level is fine in any framework: while a page renders on the server, `start()` does nothing and its `identify()` answers the `not_in_browser` error.
49
+ Call `identify()` on a page with an action you want to identify (a login, signup or checkout), when the user takes the action: that's the identity check, it sends the report through your route and gives you the request ID. Optionally call `preload()` when that page loads, not on every page: it loads Zeno's script and starts gathering signals in the browser, so `identify()` is quick; nothing is sent to Zeno and nothing is billed. Without it, `identify()` loads the script first, within its 10-second limit. `preload()` loads once a page: calling it again for the same path does nothing, so a module's top level or a component that remounts are both fine. While a page renders on the server, `preload()` does nothing and `identify()` answers the `not_in_browser` error.
58
50
 
59
51
  ```ts
60
- import { start } from 'zeno.id'
52
+ import { identify, preload } from 'zeno.id'
61
53
 
62
- // Start as early as you can: it loads Zeno and starts reading the browser,
63
- // so identify() is quick later (your proxy route's path)
64
- const zeno = start('/zeno')
54
+ // Optional: start early so identify() is quick
55
+ preload('/zeno')
65
56
 
66
57
  // Recognise the browser the moment the user logs in
67
58
  // (never throws: requestId is undefined when nothing was identified)
68
- const { requestId } = await zeno.identify({ action: 'login' })
59
+ const { requestId } = await identify({
60
+ path: '/zeno',
61
+ action: 'login',
62
+ })
69
63
 
70
64
  const response = await fetch('/api/login', {
71
65
  method: 'POST',
@@ -85,15 +79,15 @@ if (response.ok) {
85
79
  }
86
80
  ```
87
81
 
88
- Your server then calls `client.verify(requestId)` from `zeno.id/server`, which answers `allow`, `challenge` or `block`: that's the answer to trust, never anything the browser says. A login request without a request ID gets `challenge` with `no-request-id`, so your server decides whether to let the action through or ask for more; a request ID verifies once. A project in zero trust mode answers only `requestId` (no `visitorId` or `returning`), and one with sealed results also returns `sealedResult` for your server to open with `unsealResult`.
82
+ Your server then calls `client.verify(requestId)` from `zeno.id/server`, which answers `allow`, `challenge` or `block`: that's the answer to trust, never anything the browser says. A login request without a request ID gets `challenge` with `no-request-id`, so your server decides whether to let the action through or ask for more; a request ID verifies once. `identify()` resolves only `{ requestId }`, never the visitor id, the signals or the score: your server gets the visitor id and `returning` with the event, from `verify`, `getEvent` or a webhook.
89
83
 
90
- `start()` imports the script as an ES module from that path, and the script identifies with a `POST` to the same path. Nothing else is tried: on a failure `identify()` resolves at once with its error (`script_load_failed`, `csp_block`, `network_connection`…).
84
+ The loader imports the script as an ES module from the route's path, and the script identifies with a `POST` to the same path. Nothing else is tried: on a failure `identify()` resolves at once with its error (`script_load_failed`, `csp_block`, `network_connection`…).
91
85
 
92
- The script also sends the page url and referrer as origin and path only, without the query string or `#fragment`; set `pageUrls` in the project's settings to `origin` to keep only the site, or `none` to keep neither.
86
+ The script also sends the page url and referrer as origin and path only, without the query string or `#fragment`.
93
87
 
94
88
  ### Content Security Policy
95
89
 
96
- - `script-src 'self'` for the script's code from the route, and `connect-src 'self'` for the identification and `forget()`.
90
+ - `script-src 'self'` for the script's code from the route, and `connect-src 'self'` for the identification.
97
91
  - `script-src blob:` and `worker-src blob:` for some of the script's checks (no `eval`). Without them those checks go unreported and the identification still works.
98
92
 
99
93
  ```
@@ -104,64 +98,63 @@ The script's code uses no `eval` or `new Function`, so `'unsafe-eval'` isn't nee
104
98
 
105
99
  ### Options
106
100
 
107
- `start(path)` takes your proxy route's path on this site, `/zeno` when you leave it out. It starts with `/`; a full url, a query string or a `#fragment` is refused with `invalid_options`, since the route answers the page's own origin only.
101
+ `preload(path)` and `identify({ path })` take your proxy route's path on this site, `/zeno` when you leave it out; pass both the same. It starts with `/`; a full url, a query string or a `#fragment` is refused with `invalid_options`, since the route answers the page's own origin only.
108
102
 
109
103
  | `identify()` option | |
110
104
  | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
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). |
105
+ | `path` | Your proxy route's path on this site, `/zeno` by default (above). |
106
+ | `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
107
  | `action` | What the visitor is doing, like `login`, `signup` or `checkout`, up to 1,024 characters. Returned with the event. |
113
108
  | `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
109
 
115
- The script keeps no visitor id itself. The route keeps it in the `zeno_id` cookie (`HttpOnly`, `SameSite=Lax`, `Secure` on https, 400 days from the last identification), on the route's own path, so two routes on one site, like a site's own login and a demo, keep separate ids. The script keeps a copy in the site's `localStorage` (`zeno:id:` and the route's path), used only when the cookie is gone. Zeno reuses either while it's still the same device, so the id survives browser updates. Every `identify()` identifies again.
110
+ The browser never learns the visitor id. The route keeps it, encrypted for the project as an opaque token, in the `zeno_id` cookie for the whole site (`Path=/`, `SameSite=Lax`, `Secure` on https, 400 days from the last identification), so use one route per site. It isn't `HttpOnly`, so `forget()` can delete it. The script stores nothing itself. Zeno reuses the cookie's visitor id while it's still the same device, so the visitor id survives browser updates. Every `identify()` identifies again.
116
111
 
117
- ### Stop and forget
112
+ ### Forget
118
113
 
119
- `zeno.stop()` ends identification for good, for a visitor who withdraws consent: an `identify()` in progress and every later one answer the `stopped` error, nothing more is collected or sent, and a `POST` to the route's `?forget` clears its cookie. A script still loading never starts: its module may finish downloading, but it isn't started. `forget(path)` does the same without loading or starting anything, and resolves once the route cleared the cookie (it rejects with `network_connection` or `server_error` when it couldn't, and `not_in_browser` on the server). Call `start()` again to identify once consent is back.
114
+ `forget()` is for a visitor who withdraws consent. It stops the script on the page, so nothing more is collected or sent and an `identify()` in progress answers the `stopped` error, and deletes the `zeno_id` cookie. It takes no argument, sends no request and can't fail, so it also covers a visitor who withdrew on an earlier visit; on the server it does nothing. A later `preload()` or `identify()` starts again, so call them only once consent is back.
120
115
 
121
116
  ```ts
122
- import { forget, start, type Zeno } from 'zeno.id'
123
-
124
- let zeno: Zeno | undefined
117
+ import { forget, preload } from 'zeno.id'
125
118
 
126
- consentTool.onChange(async ({ fraudPrevention }) => {
119
+ consentTool.onChange(({ fraudPrevention }) => {
127
120
  if (fraudPrevention) {
128
- zeno ??= start('/zeno')
129
- } else if (zeno) {
130
- zeno.stop()
131
- zeno = undefined
121
+ preload('/zeno')
132
122
  } else {
133
- await forget('/zeno')
123
+ forget()
134
124
  }
135
125
  })
136
126
  ```
137
127
 
138
128
  ### Errors
139
129
 
140
- `identify()` never rejects. When nothing was identified it resolves `{ requestId: undefined, error }`, with `error` a `ZenoError` whose `code` is one of these (`ZenoErrorCode`), and whose `message` says more where there's more to say. For all of them the action can go on without a request ID: your server's `verify` answers `challenge` with `no-request-id`, so it decides. `start()` itself throws a `ZenoError` for options it can't use (`invalid_options`).
130
+ `identify()` never rejects. When nothing was identified it resolves `{ requestId: undefined, error }`, with `error` a `ZenoError` whose `code` is one of these (`ZenoErrorCode`), and whose `message` says more where there's more to say. For all of them the action can go on without a request ID: your server's `verify` answers `challenge` with `no-request-id`, so it decides. `preload()` itself throws a `ZenoError` for a path it can't use (`invalid_options`).
141
131
 
142
132
  ```ts
143
133
  // Never throws: requestId is undefined when nothing was identified
144
- const { requestId, error } = await zeno.identify({ action: 'login' })
134
+ const { requestId, error } = await identify({
135
+ path: '/zeno',
136
+ action: 'login',
137
+ })
145
138
 
146
139
  if (error) {
147
140
  console.warn('Identification failed', error.code, error.message)
148
141
  }
149
142
  ```
150
143
 
151
- | Code | What happened | What to do |
152
- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
153
- | `client_timeout` | Zeno didn't answer in time. | Go on without a request ID. |
154
- | `network_connection` | The route couldn't be reached, or the request was cut off. | Go on without a request ID. |
155
- | `csp_block` | The page's Content Security Policy blocked the script's code (`script-src`) or the identification (`connect-src`). | Allow the route's origin in both (see Content Security Policy). |
156
- | `insecure_context` | The page isn't a secure context (https or localhost), which the script needs for its random ids and hashes. | Serve the page over https. |
157
- | `collection_failed` | The browser data couldn't be collected at all, as when an extension broke the browser's basics. | Go on without a request ID. |
158
- | `invalid_options` | An option `start()` or `identify()` can't use (a route path that isn't on this site, a bad external id or metadata), or one Zeno refused; the message names it. | Fix the option. |
159
- | `script_load_failed` | The script couldn't be loaded from the route: nothing answers there (your site's own 404 page), something other than the script does, or the network failed. The message names the url and the status. | Check the route answers at its path; meanwhile go on without a request ID. |
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
- | `account_closed` | Zeno closed the organization's account (as for unpaid invoices): identification is refused until it's reopened. | Contact support. |
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. |
164
- | `not_in_browser` | `identify()` ran on the server, while a page rendered. | Call it in the action's handler in the browser. |
144
+ | Code | What happened | What to do |
145
+ | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
146
+ | `client_timeout` | Zeno didn't answer in time. | Go on without a request ID. |
147
+ | `network_connection` | The route couldn't be reached, or the request was cut off. | Go on without a request ID. |
148
+ | `csp_block` | The page's Content Security Policy blocked the script's code (`script-src`) or the identification (`connect-src`). | Allow the route's origin in both (see Content Security Policy). |
149
+ | `insecure_context` | The page isn't a secure context (https or localhost), which the script needs for its random ids and hashes. | Serve the page over https. |
150
+ | `collection_failed` | The browser data couldn't be collected at all, as when an extension broke the browser's basics. | Go on without a request ID. |
151
+ | `invalid_options` | An option `preload()` or `identify()` can't use (a route path that isn't on this site, a bad external id or metadata), or one Zeno refused; the message names it. | Fix the option. |
152
+ | `script_load_failed` | The script couldn't be loaded from the route: nothing answers there (your site's own 404 page), something other than the script does, or the network failed. The message names the url and the status. | Check the route answers at its path; meanwhile go on without a request ID; the next call loads it again. |
153
+ | `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. |
154
+ | `account_closed` | Zeno closed the organization's account (as for unpaid invoices): identification is refused until it's reopened. | Contact support. |
155
+ | `stopped` | `forget()` was called during the `identify()`. | Go on without a request ID. |
156
+ | `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. |
157
+ | `not_in_browser` | `identify()` ran on the server, while a page rendered. | Call it in the action's handler in the browser. |
165
158
 
166
159
  ### What it collects
167
160
 
@@ -173,18 +166,18 @@ It reads no personal content, like names, messages or what people type, and noth
173
166
 
174
167
  ### Without a bundler
175
168
 
176
- A page without a build step can import `start` from the route itself, which serves the script as an ES module:
169
+ A page without a build step can import `preload`, `identify` and `forget` from the route itself, which serves the script as an ES module:
177
170
 
178
171
  <!-- prettier-ignore -->
179
172
  ```html
180
173
  <button id="login">Log in</button>
181
174
  <script type="module">
182
- import { start } from '/zeno' // your route's path
175
+ import { identify, preload } from '/zeno' // your route's path
183
176
 
184
- const zeno = start()
177
+ preload()
185
178
 
186
179
  document.querySelector('#login').addEventListener('click', async () => {
187
- const { requestId } = await zeno.identify({ action: 'login' })
180
+ const { requestId } = await identify({ action: 'login' })
188
181
 
189
182
  await fetch('/api/login', {
190
183
  method: 'POST',
@@ -195,24 +188,26 @@ A page without a build step can import `start` from the route itself, which serv
195
188
  </script>
196
189
  ```
197
190
 
198
- That `start()` takes the path it was imported from unless you pass another, and answers the same `identify()` and `stop()` with the same error codes. What it can't do is report a script that doesn't load: the `import` itself fails, without `script_load_failed` or `csp_block`, and there's no `forget()`. Use `zeno.id` where you can.
191
+ They work on the route they were imported from, so they take no path, and answer with the same error codes. What they can't do is report a script that doesn't load: the `import` itself fails, without `script_load_failed` or `csp_block`. Use `zeno.id` where you can.
199
192
 
200
193
  ## Proxy route
201
194
 
202
195
  The browser SDK never talks to Zeno directly. It loads its script from a route on your own site and sends its identifications there, and the route passes them on with your API key and the visitor's IP.
203
196
 
204
197
  - Ad and tracker blockers block requests to identification services. A path on your own site looks like any other request your pages make.
205
- - The route keeps the visitor id in a first-party `HttpOnly` cookie (`zeno_id`) that it sets itself, which Safari keeps for 400 days where it deletes a script's storage after 7 days without a visit; the script's `localStorage` copy covers a browser that cleared only its cookies.
206
- - Your API key stays on your server, and the route refuses a browser's cross-site request, so there's no allow list of origins to keep.
198
+ - The route keeps the visitor id, encrypted, in a first-party cookie (`zeno_id`) that it sets itself, which Safari keeps for 400 days where it deletes a script's storage after 7 days without a visit.
199
+ - Your API key stays on your server, and Zeno refuses an identification posted from another site, so there's no allow list of origins to keep.
207
200
 
208
- `createProxy(apiKey, options?)` returns the route's handler: `zeno(request, ip)` takes a standard `Request` and the IP address it came from, and returns a `Response`, using web APIs only. The browser SDK calls it with two methods on one path: `GET` loads the script (gzipped when the browser takes it; `HEAD` too), and `POST` identifies, or, as `forget()`, clears the visitor id for withdrawn consent.
201
+ `createProxyResponse({ request, ip, apiKey })` takes a standard `Request`, the IP address it came from and your API key, and returns the `Response` to answer with, using web APIs only. It passes the request on to Zeno and Zeno's answer back. The browser SDK calls the route with two methods on one path: `GET` loads the script (`HEAD` too), and `POST` identifies.
209
202
 
210
203
  ```ts
204
+ import { createProxyResponse } from 'zeno.id/server'
205
+
211
206
  // ip: the IP address the request came from, as your server gives it
212
207
  export const handle = (request: Request, ip: string) => {
213
208
  if (new URL(request.url).pathname === '/zeno') {
214
209
  // the path you chose
215
- return zeno(request, ip)
210
+ return createProxyResponse({ request, ip, apiKey: process.env.ZENO_API_KEY })
216
211
  }
217
212
 
218
213
  // …the rest of your app
@@ -220,20 +215,25 @@ export const handle = (request: Request, ip: string) => {
220
215
  ```
221
216
 
222
217
  ```ts
223
- // Express, Fastify or Node's http server
224
- import { nodeHandler } from 'zeno.id/server/node'
218
+ // Express or Node's http server
219
+ import { nodeHandler } from 'zeno.id/server'
225
220
 
226
221
  // behind a proxy: app.set('trust proxy', 1)
227
- app.all('/zeno', nodeHandler(zeno)) // the path you chose
222
+ // Before express.json(): the route forwards the body as it came
223
+ app.all('/zeno', nodeHandler({ apiKey: process.env.ZENO_API_KEY })) // the path you chose
228
224
  ```
229
225
 
230
226
  ```ts
231
227
  // app/zeno/route.ts
232
- import { zeno } from '@/lib/zeno'
228
+ import { createProxyResponse } from 'zeno.id/server'
233
229
 
234
230
  // X-Real-IP: set by Vercel, or by your own proxy (nginx: proxy_set_header X-Real-IP $remote_addr;)
235
231
  const handler = (request: Request) => {
236
- return zeno(request, request.headers.get('x-real-ip'))
232
+ return createProxyResponse({
233
+ request,
234
+ ip: request.headers.get('x-real-ip'),
235
+ apiKey: process.env.ZENO_API_KEY,
236
+ })
237
237
  }
238
238
 
239
239
  // Next.js calls the export named after the method
@@ -245,7 +245,8 @@ export const POST = handler
245
245
  // Bun.serve
246
246
  Bun.serve({
247
247
  routes: {
248
- '/zeno': (request, server) => zeno(request, server.requestIP(request)?.address),
248
+ '/zeno': (request, server) =>
249
+ createProxyResponse({ request, ip: server.requestIP(request)?.address, apiKey: process.env.ZENO_API_KEY }),
249
250
  },
250
251
  })
251
252
  ```
@@ -253,36 +254,29 @@ Bun.serve({
253
254
  ```ts
254
255
  // A Cloudflare Worker
255
256
  import { env } from 'cloudflare:workers'
256
- import { createProxy } from 'zeno.id/server'
257
-
258
- // Your proxy route: the browser SDK talks to Zeno through it
259
- const zeno = createProxy(env.ZENO_API_KEY)
257
+ import { createProxyResponse } from 'zeno.id/server'
260
258
 
261
259
  export default {
262
260
  fetch: (request: Request) =>
263
261
  new URL(request.url).pathname === '/zeno'
264
- ? zeno(request, request.headers.get('cf-connecting-ip'))
262
+ ? createProxyResponse({ request, ip: request.headers.get('cf-connecting-ip'), apiKey: env.ZENO_API_KEY })
265
263
  : fetch(request),
266
264
  }
267
265
  ```
268
266
 
269
267
  The docs' quickstart has SvelteKit, Nuxt, React Router, SolidStart, Astro and Hono too.
270
268
 
271
- | Option | |
272
- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
273
- | `cookiePath` | The path the browser calls the route on, when something in front of the handler rewrites it (the browser calls `/zeno`, a handler at `/api/proxy` answers); by default the request's. |
274
-
275
- The route forwards your visitors' headers by name only, apart from the values Zeno reads (`User-Agent`, `Origin`, `Signature-Agent`, `Signature-Input`), so your cookies and credentials never leave your server.
269
+ The route forwards your visitors' headers by name only, apart from the values Zeno reads (`User-Agent`, `Origin`, `Signature-Agent`, `Signature-Input`, `Sec-Fetch-Site`), so your cookies and credentials never leave your server.
276
270
 
277
271
  ### The visitor's IP
278
272
 
279
- Pass the IP address the request came from: your framework's client IP. Behind a proxy of your own, turn on your framework's trust-proxy setting so it's the visitor's. The route uses the IP as given and reads no header for it; without one, an identification answers `500 server_error` saying to pass it, which the browser SDK passes on. `nodeHandler` (from `zeno.id/server/node`, which alone uses Node's types) passes Express's and Fastify's `req.ip`, else the socket's address.
273
+ Pass `ip`, the IP address the request came from: your framework's client IP. Behind a proxy of your own, turn on your framework's trust-proxy setting so it's the visitor's. The route uses the IP as given and reads no header for it; without one, an identification answers `500 server_error` saying to pass it, which the browser SDK passes on. `nodeHandler` (from `zeno.id/server`, which alone uses Node's types) passes Express's and Fastify's `req.ip`, else the socket's address.
280
274
 
281
- The route checks a `POST` before it calls Zeno: a JSON body of at most 128 KB with a `browserData` object, and no `Sec-Fetch-Site: cross-site`. Anything else gets a `400 invalid_request` and costs nothing. Zeno's errors reach the browser with their status and code; a `401` (the route's API key is wrong) is logged with Zeno's message and the browser only gets the code. When Zeno can't be reached within 10 seconds, or something else answers in its place, the route logs it and answers `502`.
275
+ Zeno checks an identification before anything is identified or billed: a JSON body of at most 128 KB with a `browserData` object, posted from the site's own pages. Anything else gets a `400 invalid_request` and costs nothing. Zeno's answers and errors reach the browser with their status and code; a `401` (the route's API key is wrong) or `402` (the account was closed) is also logged on your server. When Zeno can't be reached within 10 seconds, the route logs it and answers `502`.
282
276
 
283
277
  ## Verify
284
278
 
285
- `client.verify(requestId, { ip?, externalId?, maxAge?, idempotencyKey? }?)` sends the request ID to `POST /verify`, which checks it and answers `{ action, reasons, event? }`. Each request ID verifies once. The event comes with its `velocity`, as `getEvent` has it, from before verify attached your `externalId`: `event.velocity['24h'].distinctExternalId` counts the users seen on this browser today, and `sameAction` its events with this event's action, for a site without external IDs. Identical devices can look like one browser, so treat a busy one as a lead to review.
279
+ `client.verify(requestId, { ip?, externalId?, scope?, maxAge?, idempotencyKey? }?)` sends the request ID to `POST /verify`, which checks it and answers `{ action, reasons, event? }`. Each request ID verifies once. The event comes with its `velocity`, as `getEvent` has it, from before verify attached your `externalId`: `event.velocity['24h'].distinctExternalId` counts the users seen on this browser today, and `sameAction` its events with this event's action, for a site without external IDs. Identical devices can look like one browser, so treat a busy one as a lead to review.
286
280
 
287
281
  | Answer | When |
288
282
  | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
@@ -307,11 +301,11 @@ const { action } = await client.verify(requestId, {
307
301
 
308
302
  `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
303
 
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.
304
+ 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
305
 
312
306
  ### Test keys
313
307
 
314
- For automated tests and staging, use a test key in place of your API key, in `createProxy` and `createClient`. Each answers `verify` the same every time, with a sample event; nothing is stored or billed, a test request ID can be verified again and again, and other calls refuse a test key. Without a request ID each answers `challenge` with `no-request-id`, like a real key.
308
+ For automated tests and staging, use a test key in place of your API key, in `createProxyResponse` and `createClient`. Each answers `verify` the same every time, with a sample event; nothing is stored or billed, a test request ID can be verified again and again, and other calls refuse a test key. Without a request ID each answers `challenge` with `no-request-id`, like a real key.
315
309
 
316
310
  | Test key | `verify` answers |
317
311
  | ------------------- | ----------------------- |
@@ -341,14 +335,8 @@ await client.deleteExternalId(user.id)
341
335
  // Related accounts: add what only you know
342
336
  await client.addRelation({
343
337
  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,
338
+ type: 'payment-card',
339
+ value: payment.cardFingerprint,
352
340
  })
353
341
  const { duplicate, identified } = await client.getRelatedValues(user.id)
354
342
  const { externalIds } = await client.getRelated(user.id, { depth: 2 })
@@ -360,31 +348,36 @@ const { url } = await client.createEmbed({
360
348
  })
361
349
  ```
362
350
 
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.
351
+ | Method | Call |
352
+ | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
353
+ | `verify(requestId, { ip?, externalId?, scope?, maxAge?, idempotencyKey? }?)` | `POST /verify` |
354
+ | `getEvent(requestId)` | `GET /events/{requestId}` |
355
+ | `searchEvents(filters)` | `GET /events?...` |
356
+ | `deleteVisitor(visitorId)` | `DELETE /visitors/{visitorId}` |
357
+ | `deleteExternalId(externalId, { scope? }?)` | `DELETE /external-ids?externalId=...` |
358
+ | `reportOutcome(requestId, outcome)` | `POST /outcomes`, `legitimate` or a type of fraud, the latest counts |
359
+ | `addRelation({ externalId, scope?, type, value, at? })` | `POST /related` |
360
+ | `removeRelation({ externalId, scope?, type, value })` | `DELETE /related?externalId=...&type=...`, `{ removed }`, free |
361
+ | `getRelated(externalId, { scope?, type?, depth? })` | `GET /related?externalId=...`, every type unless `type` names one |
362
+ | `getRelatedValues(externalId, { scope?, type? })` | `GET /related/values?externalId=...` |
363
+ | `lookupRelated(type, value, { scope?, limit?, cursor? })` | `GET /related/lookup?type=...&value=...`, 20 a page by default (up to 100) |
364
+ | `getRelatedGroup(externalId, { scope?, limit?, cursor? })` | `GET /related/group?externalId=...`, the user's `groupId` and its members |
365
+ | `getGroup(groupId, { limit?, cursor? })` | `GET /related/group/{groupId}`, a group by its ID, 500 members a page |
366
+ | `getRelatedWeights()` | `GET /related/weights`, every type with its weight and its Match within |
367
+ | `setRelatedType(type, { weight?, matchWithinDays? })` | `POST /related/weights`, weight 0 to 1, days 1 to 3650, `null` for a default |
368
+ | `createEmbed({ externalId, scope?, origin, ttl? })` | `POST /embeds` |
369
+
370
+ 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.
371
+
372
+ Your server can put users in scopes, like `tenant-1` (1 to 64 letters, digits, `.`, `_`, `:` or `-`): `user-1042` in `tenant-1` and in `tenant-2` are two users, never related or grouped together. Use them for an app with many tenants on one project, or to keep kinds of accounts apart. Pass the same `scope` wherever you name the user (`verify`, the relation calls, `deleteExternalId`, `createEmbed`, `searchEvents` with `externalId`); without one, a user has no scope and nothing changes. Only your server sets a scope: the browser's `identify()` can't. `getRelated` and `lookupRelated` take one scope, several (`['tenant-1', 'tenant-2']`) or `'*'`; without one they read every scope. `getRelated` starts from the external ID in each scope it reads and only crosses those scopes. `getRelatedValues` and `getRelatedGroup` read one user: the scope you pass, or without one the only scope the external ID has (a `400` when it has several); `getGroup` takes none. Answers name each user as `{ externalId, scope? }`, and an event has its `scope` beside its `externalId`.
380
373
 
381
374
  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
375
 
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).
376
+ 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
377
 
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.
378
+ 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
379
 
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).
380
+ `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
381
 
389
382
  ## Webhooks
390
383
 
@@ -405,21 +398,7 @@ export const handle = async (request: Request) => {
405
398
  }
406
399
  ```
407
400
 
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).
409
-
410
- ## Sealed results
411
-
412
- ```ts
413
- import { unsealResult } from 'zeno.id/server'
414
-
415
- const { action, reasons } = await unsealResult(sealedResult, {
416
- key: process.env.ZENO_ENCRYPTION_KEY,
417
- ip, // the same IP your proxy route got
418
- externalId: user.id,
419
- })
420
- ```
421
-
422
- A project with sealed results gives the browser an encrypted copy of the event, for a server that can't wait for an API call. A sealed result can't be forged: only Zeno can make one that decrypts with your key. But it comes from the browser, so the same one can be sent again within a few minutes. `unsealResult(sealed, { key, ip?, externalId?, maxAge? })` answers like `verify`, `{ action, reasons, event? }`: `challenge` with `no-request-id` for none, `block` with `not-found` for one that doesn't open (changed, or sealed with another key), `ip-mismatch` from another IP than `ip` (compared as `verify` does), `too-old` past `maxAge` (300 seconds by default), `external-id-mismatch` for another user's, else the event's verdict. If a repeat matters for the action, use `verify`, which allows each request ID once. While you replace the key, pass both, `key: [current, previous]`: each is tried in order. It rejects with a TypeError for a key that isn't one (missing, hex, the wrong length), and an Error for one that opens but isn't an event.
401
+ `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).
423
402
 
424
403
  ## License
425
404
 
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
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(
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 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||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=>{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()};exports.ZenoError=t,exports.forget=S,exports.identify=x,exports.preload=b;