zeno.id 0.1.0 → 0.3.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,43 +1,53 @@
1
1
  # zeno.id
2
2
 
3
- Zeno's browser SDK. Zeno tells your server whether a login, signup or checkout came from a real browser, and whether to let it through. This package 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. The script sends device signals to that route, the route adds your API key and passes them on to Zeno, and `identify()` answers a request ID for your server to verify.
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.
4
4
 
5
5
  ## Install
6
6
 
7
7
  ```sh
8
- npm install zeno.id @zeno.id/server
8
+ npm install zeno.id
9
9
  ```
10
10
 
11
- `zeno.id` runs in the browser; `@zeno.id/server` is the route on your server, on any JavaScript runtime with the standard `Request` and `Response` (Node 20 or later, Bun, Deno, Cloudflare Workers, Vercel and so on). Both ship ES modules, CommonJS and their types.
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.
12
12
 
13
- ## The route on your server
13
+ ## How it fits together
14
14
 
15
- The browser never talks to Zeno directly. Add a route to your own site with `createProxy` from `@zeno.id/server`, at a path of your choice (`/zeno` here, the browser SDK's default). It holds the project's API key, so it runs on your server only; pass it the key from your server's environment:
15
+ 1. Make a project and an API key in the dashboard, and put the key in your server's environment:
16
+
17
+ ```sh
18
+ ZENO_API_KEY=sk_...
19
+ ```
20
+
21
+ 2. Make the proxy route and the API client once, with the key, and mount the route 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.
23
+ 4. On your server, `verify` the request ID and allow, challenge or block.
16
24
 
17
25
  ```ts
18
- import { createProxy } from '@zeno.id/server'
26
+ // zeno.ts
27
+ import { createClient, createProxy } from 'zeno.id/server'
19
28
 
20
29
  // Your proxy route: the browser SDK talks to Zeno through it
21
- const zeno = createProxy(process.env.ZENO_API_KEY)
22
-
23
- // ip: the IP address the request came from, as your server gives it
24
- export const handle = (request: Request, ip: string) => {
25
- if (new URL(request.url).pathname === '/zeno') {
26
- // the path you chose
27
- return zeno(request, ip)
28
- }
30
+ export const zeno = createProxy(process.env.ZENO_API_KEY)
31
+ // For verify() in your server's handlers
32
+ export const client = createClient(process.env.ZENO_API_KEY)
33
+ ```
29
34
 
30
- // …the rest of your app
35
+ ```ts
36
+ // After the password matched:
37
+ const {
38
+ action, // 'allow', 'challenge' or 'block'
39
+ reasons, // why, like ['vpn', 'automation']
40
+ event, // the full event (visitor ID, IP, signals, velocity…), when found
41
+ } = await client.verify(requestId)
42
+
43
+ if (action === 'block') {
44
+ // Refuse, or hold it for review
45
+ } else if (action === 'challenge') {
46
+ // Ask for a second factor
31
47
  }
32
48
  ```
33
49
 
34
- `@zeno.id/server`'s README has Express, Next.js, Bun and Cloudflare Workers, and the docs' quickstart every other framework. The route:
35
-
36
- - answers `GET` (and `HEAD`) with the script's code, which it fetches from Zeno and caches by its ETag, gzipped when the browser takes it;
37
- - answers `POST` (an identification) by passing the script's signals on with the visitor's ip and request headers, and keeps the visitor id in an `HttpOnly` cookie of its own;
38
- - answers `POST` to `?forget` (`forget()` and `stop()`) by clearing that cookie.
39
-
40
- Which IP to pass as `zeno(request, ip)` is on the docs' proxy route page (`/docs/proxy#the-visitors-ip`).
50
+ 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.
41
51
 
42
52
  ## In the browser
43
53
 
@@ -46,10 +56,12 @@ Call `start()` on a page with an action you want to identify (a login, signup or
46
56
  ```ts
47
57
  import { start } from 'zeno.id'
48
58
 
49
- // When the login page loads:
50
- const zeno = start('/zeno') // the same path as your route
59
+ // Start as early as you can: it loads Zeno and starts reading the browser,
60
+ // so identify() is quick later (your proxy route's path)
61
+ const zeno = start('/zeno')
51
62
 
52
- // When the user logs in (never throws; requestId is undefined when it failed):
63
+ // Recognise the browser the moment the user logs in
64
+ // (never throws: requestId is undefined when nothing was identified)
53
65
  const { requestId } = await zeno.identify({ action: 'login' })
54
66
 
55
67
  const response = await fetch('/api/login', {
@@ -70,13 +82,13 @@ if (response.ok) {
70
82
  }
71
83
  ```
72
84
 
73
- 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`.
85
+ 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`.
74
86
 
75
87
  `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`…).
76
88
 
77
89
  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.
78
90
 
79
- ## Content Security Policy
91
+ ### Content Security Policy
80
92
 
81
93
  - `script-src 'self'` for the script's code from the route, and `connect-src 'self'` for the identification and `forget()`.
82
94
  - `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.
@@ -87,7 +99,7 @@ Content-Security-Policy: script-src 'self' blob:; connect-src 'self'; worker-src
87
99
 
88
100
  The script's code uses no `eval` or `new Function`, so `'unsafe-eval'` isn't needed.
89
101
 
90
- ## Options
102
+ ### Options
91
103
 
92
104
  `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.
93
105
 
@@ -99,11 +111,13 @@ The script's code uses no `eval` or `new Function`, so `'unsafe-eval'` isn't nee
99
111
 
100
112
  The script keeps no visitor id itself. The route keeps it in the `zeno_id` cookie (`HttpOnly`, `SameSite=Lax`, `Secure` on https, a year), on the route's own path, so two routes on one site, like a site's own login and a demo, keep separate ids. Zeno reuses it while it's still the same device, so the id survives browser updates. The script keeps nothing in the browser's storage, and every `identify()` identifies again.
101
113
 
102
- ## Stop and forget
114
+ ### Stop and forget
103
115
 
104
116
  `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.
105
117
 
106
118
  ```ts
119
+ import { forget, start, type Zeno } from 'zeno.id'
120
+
107
121
  let zeno: Zeno | undefined
108
122
 
109
123
  consentTool.onChange(async ({ fraudPrevention }) => {
@@ -118,7 +132,7 @@ consentTool.onChange(async ({ fraudPrevention }) => {
118
132
  })
119
133
  ```
120
134
 
121
- ## Errors
135
+ ### Errors
122
136
 
123
137
  `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`).
124
138
 
@@ -146,7 +160,7 @@ if (error) {
146
160
  | `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. |
147
161
  | `not_in_browser` | `identify()` ran on the server, while a page rendered. | Call it in the action's handler in the browser. |
148
162
 
149
- ## What it collects
163
+ ### What it collects
150
164
 
151
165
  - **The device and browser:** technical characteristics of the hardware and software, like the screen, the browser's settings, its languages and time zone.
152
166
  - **Integrity checks:** whether a script drives the browser and whether what it reports fits together.
@@ -154,7 +168,7 @@ if (error) {
154
168
 
155
169
  It reads no personal content, like names, messages or what people type, and nothing from other sites. The report is about a kilobyte.
156
170
 
157
- ## Without a bundler
171
+ ### Without a bundler
158
172
 
159
173
  A page without a build step can import `start` from the route itself, which serves the script as an ES module:
160
174
 
@@ -180,6 +194,215 @@ A page without a build step can import `start` from the route itself, which serv
180
194
 
181
195
  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.
182
196
 
197
+ ## Proxy route
198
+
199
+ 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.
200
+
201
+ - Ad and tracker blockers block requests to identification services. A path on your own site looks like any other request your pages make.
202
+ - The route keeps the visitor id in a first-party `HttpOnly` cookie (`zeno_id`) that it sets itself, which Safari keeps for a year where it would delete a script's storage after 7 days.
203
+ - 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.
204
+
205
+ `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.
206
+
207
+ ```ts
208
+ // ip: the IP address the request came from, as your server gives it
209
+ export const handle = (request: Request, ip: string) => {
210
+ if (new URL(request.url).pathname === '/zeno') {
211
+ // the path you chose
212
+ return zeno(request, ip)
213
+ }
214
+
215
+ // …the rest of your app
216
+ }
217
+ ```
218
+
219
+ ```ts
220
+ // Express, Fastify or Node's http server
221
+ import { nodeHandler } from 'zeno.id/server/node'
222
+
223
+ // behind a proxy: app.set('trust proxy', 1)
224
+ app.all('/zeno', nodeHandler(zeno)) // the path you chose
225
+ ```
226
+
227
+ ```ts
228
+ // app/zeno/route.ts
229
+ import { zeno } from '@/lib/zeno'
230
+
231
+ // X-Real-IP: set by Vercel, or by your own proxy (nginx: proxy_set_header X-Real-IP $remote_addr;)
232
+ const handler = (request: Request) => zeno(request, request.headers.get('x-real-ip'))
233
+
234
+ // Next.js calls the export named after the method
235
+ export const GET = handler
236
+ export const POST = handler
237
+ ```
238
+
239
+ ```ts
240
+ // Bun.serve
241
+ Bun.serve({
242
+ routes: {
243
+ '/zeno': (request, server) => zeno(request, server.requestIP(request)?.address),
244
+ },
245
+ })
246
+ ```
247
+
248
+ ```ts
249
+ // A Cloudflare Worker
250
+ import { env } from 'cloudflare:workers'
251
+ import { createProxy } from 'zeno.id/server'
252
+
253
+ // Your proxy route: the browser SDK talks to Zeno through it
254
+ const zeno = createProxy(env.ZENO_API_KEY)
255
+
256
+ export default {
257
+ fetch: (request: Request) =>
258
+ new URL(request.url).pathname === '/zeno'
259
+ ? zeno(request, request.headers.get('cf-connecting-ip'))
260
+ : fetch(request),
261
+ }
262
+ ```
263
+
264
+ The docs' quickstart has SvelteKit, Nuxt, React Router, SolidStart, Astro and Hono too.
265
+
266
+ | Option | |
267
+ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
268
+ | `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. |
269
+
270
+ 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.
271
+
272
+ ### The visitor's IP
273
+
274
+ 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.
275
+
276
+ 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`.
277
+
278
+ ## Verify
279
+
280
+ `client.verify(requestId, { ip?, externalId?, maxAge? }?)` 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.
281
+
282
+ | Answer | When |
283
+ | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
284
+ | `{ action: 'challenge', reasons: ['no-request-id'] }` | `requestId` is `undefined`, `null` or empty: the browser sent none (its identification failed, was blocked or capped, or a bot never ran the script). |
285
+ | `{ action: 'block', reasons: ['not-found'] }` | No such event: a forged request ID, or another project's. |
286
+ | `{ action: 'block', reasons: ['already-used'], event }` | The request ID was verified before: an action's request sent again, or a captured request ID. |
287
+ | `{ action: 'block', reasons: ['ip-mismatch'], event }` | The event came from another ip (for IPv6 another /64; IPv4 and IPv6 are never compared): a request ID captured and sent elsewhere. |
288
+ | `{ action: 'block', reasons: ['too-old'], event }` | The event is older than `maxAge` seconds, 300 (5 minutes) by default. |
289
+ | `{ action: 'block', reasons: ['external-id-mismatch'], event }` | The event has another external ID than the one you passed: another user's identification. One without an external ID is fine. |
290
+ | the event's `verdict`, with the `event` | Otherwise: `allow`, `challenge` or `block`, and the signals behind it. |
291
+
292
+ `ip-mismatch`, `too-old` and `external-id-mismatch` come together when several fail, and leave the request ID unused, so a request ID sent from elsewhere doesn't use up the visitor's own. The verdict comes from the event's risk score and bot verdict: `block` for a bad bot or a risk score of 15 or more, `challenge` from 9 to 14, else `allow`; its `reasons` are the detected signals that scored, strongest first, and `bad-bot`.
293
+
294
+ Call it after the action succeeded (the password matched, the account exists), with the user's ID as `externalId`: Zeno records it on an event that has none, so a signup needs no other call and a failed login attaches nothing. It writes nothing else but the request ID's use.
295
+
296
+ ```ts
297
+ // At a signup, once the account exists:
298
+ const { action } = await client.verify(requestId, {
299
+ externalId: account.id,
300
+ })
301
+ ```
302
+
303
+ `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`.
304
+
305
+ ## Server API
306
+
307
+ ```ts
308
+ import { client } from './zeno' // made next to your proxy route
309
+
310
+ const event = await client.getEvent(requestId)
311
+ const { items, cursor } = await client.searchEvents({
312
+ externalId: user.id,
313
+ signal: 'vpn',
314
+ })
315
+ // Several values match any of them
316
+ const risky = await client.searchEvents({
317
+ country: ['US', 'DE'],
318
+ signal: ['vpn', 'tor'],
319
+ })
320
+ await client.deleteExternalId(user.id)
321
+
322
+ // Related accounts: add what only you know
323
+ await client.addRelation({
324
+ externalId: user.id,
325
+ type: 'phone',
326
+ value: order.phone,
327
+ action: 'checkout',
328
+ })
329
+ await client.addRelation({
330
+ externalId: user.id,
331
+ type: 'referral',
332
+ relatedExternalId: referrer.id,
333
+ at: user.createdAt,
334
+ })
335
+ const { duplicate, identified } = await client.getRelatedValues(user.id)
336
+ const { externalIds } = await client.getRelated(user.id, { depth: 2 })
337
+
338
+ // For your admin panel's user page, one per view
339
+ const { url } = await client.createEmbed({
340
+ externalId: user.id,
341
+ origin: 'https://admin.example.com',
342
+ })
343
+ ```
344
+
345
+ | Method | Call |
346
+ | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
347
+ | `verify(requestId, { ip?, externalId?, maxAge? }?)` | `POST /verify` |
348
+ | `getEvent(requestId)` | `GET /events/{requestId}` |
349
+ | `searchEvents(filters)` | `GET /events?...` |
350
+ | `getVisitor(visitorId)` | `GET /visitors/{visitorId}` |
351
+ | `deleteVisitor(visitorId)` | `DELETE /visitors/{visitorId}` |
352
+ | `deleteExternalId(externalId)` | `DELETE /external-ids?externalId=...` |
353
+ | `addRelation({ externalId, type, value or relatedExternalId, action?, at? })` | `POST /related` |
354
+ | `removeRelation({ externalId, type, value or relatedExternalId })` | `DELETE /related?externalId=...&type=...`, `{ removed }`, free |
355
+ | `getRelated(externalId, { type?, depth? })` | `GET /related?externalId=...`, every type unless `type` names one |
356
+ | `getRelatedValues(externalId, { type? })` | `GET /related/values?externalId=...` |
357
+ | `lookupRelated(type, value, { limit?, cursor? })` | `GET /related/lookup?type=...&value=...`, 20 a page by default (up to 100) |
358
+ | `getSharedValues(type, { limit?, cursor? })` | `GET /related/shared?type=...` |
359
+ | `createEmbed({ externalId, origin, ttl? })` | `POST /embeds` |
360
+
361
+ 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.
362
+
363
+ 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.
364
+
365
+ The SDK's own codes: `network_error` (status `0`) when the API can't be reached or doesn't answer within 10 seconds, never retried; `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).
366
+
367
+ `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.
368
+
369
+ `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.8, `ip` 0.4, 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.64 and a browser and an ip 0.88, 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).
370
+
371
+ ## Webhooks
372
+
373
+ ```ts
374
+ import { verifyWebhook } from 'zeno.id/server'
375
+
376
+ // POST /webhooks/zeno: any runtime with web Request and Response
377
+ export const handle = async (request: Request) => {
378
+ // The raw body: the signature covers the exact bytes
379
+ const body = await request.text()
380
+ const event = await verifyWebhook(body, request.headers.get('zeno-signature'), process.env.ZENO_WEBHOOK_SECRET)
381
+
382
+ if (!event) {
383
+ return new Response(null, { status: 400 })
384
+ }
385
+
386
+ return new Response(null, { status: 204 })
387
+ }
388
+ ```
389
+
390
+ `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).
391
+
392
+ ## Sealed results
393
+
394
+ ```ts
395
+ import { unsealResult } from 'zeno.id/server'
396
+
397
+ const { action, reasons } = await unsealResult(sealedResult, {
398
+ key: process.env.ZENO_ENCRYPTION_KEY,
399
+ ip, // the same IP your proxy route got
400
+ externalId: user.id,
401
+ })
402
+ ```
403
+
404
+ 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.
405
+
183
406
  ## License
184
407
 
185
408
  MIT, see `LICENSE`.