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.
@@ -0,0 +1,787 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/server/util.ts
3
+ const isObject = (value) => {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ };
6
+ const DEFAULT_API_URL = "https://api.zeno.id";
7
+ const checkApiSettings = (name, apiKey, apiUrl = DEFAULT_API_URL) => {
8
+ if (!apiKey) return { problem: `${name}'s apiKey is missing: pass your API key (ZENO_API_KEY in your environment)` };
9
+ if (!apiUrl) return { problem: `${name}'s apiUrl is missing: this copy of zeno.id/server has no default, so pass the Zeno API's origin as apiUrl` };
10
+ try {
11
+ if (["http:", "https:"].includes(new URL(apiUrl).protocol)) return {
12
+ apiKey,
13
+ base: apiUrl.replace(/\/+$/, "")
14
+ };
15
+ } catch {}
16
+ return { problem: `${name}'s apiUrl must be the Zeno API's http(s) origin, like https://api.example.com, not ${JSON.stringify(apiUrl)}` };
17
+ };
18
+ const networkOf = (address) => {
19
+ if (!address.includes(":")) return address;
20
+ const mappedDotted = address.match(/^(?:::|(?:0{1,4}:){5})ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
21
+ if (mappedDotted) return mappedDotted[1];
22
+ const [head = "", tail = ""] = address.split("::");
23
+ const headGroups = head ? head.split(":") : [];
24
+ const tailGroups = tail ? tail.split(":") : [];
25
+ const missingCount = Math.max(0, 8 - headGroups.length - tailGroups.length);
26
+ const groups = [
27
+ ...headGroups,
28
+ ...Array.from({ length: missingCount }, () => "0"),
29
+ ...tailGroups
30
+ ].map((group) => group.toLowerCase().replace(/^0+(?=\w)/, ""));
31
+ if (groups.slice(0, 5).every((group) => group === "0") && groups[5] === "ffff") {
32
+ const [high = 0, low = 0] = groups.slice(6).map((group) => parseInt(group, 16));
33
+ return [
34
+ high >> 8,
35
+ high & 255,
36
+ low >> 8,
37
+ low & 255
38
+ ].join(".");
39
+ }
40
+ return groups.slice(0, 4).join(":");
41
+ };
42
+ const isIpMismatch = (eventIp, ip) => {
43
+ const requestIp = ip.trim();
44
+ return eventIp.includes(":") === requestIp.includes(":") && networkOf(eventIp) !== networkOf(requestIp);
45
+ };
46
+ //#endregion
47
+ //#region src/server/proxy.ts
48
+ const isStrings = (value) => {
49
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
50
+ };
51
+ const rawHeadersOf = (internal) => {
52
+ const rawHeaders = internal?.rawHeaders;
53
+ return isStrings(rawHeaders) ? rawHeaders : void 0;
54
+ };
55
+ const COOKIE = "zeno_id";
56
+ const MAX_BODY = 131072;
57
+ const TIMEOUT$1 = 1e4;
58
+ const jsonResponse = (status, body, headers = {}) => {
59
+ return new Response(JSON.stringify(body), {
60
+ status,
61
+ headers: {
62
+ "content-type": "application/json; charset=utf-8",
63
+ "cache-control": "no-store",
64
+ ...headers
65
+ }
66
+ });
67
+ };
68
+ const invalidRequest = (message) => jsonResponse(400, {
69
+ error: "invalid_request",
70
+ message
71
+ });
72
+ const serverError = (message, status = 500) => jsonResponse(status, {
73
+ error: "server_error",
74
+ message
75
+ });
76
+ const NO_IP = "Pass the IP address the request came from: zeno(request, ip)";
77
+ const readCappedBody = async (request, limit) => {
78
+ if (Number(request.headers.get("content-length")) > limit) return;
79
+ if (!request.body) return "";
80
+ const reader = request.body.getReader();
81
+ const chunks = [];
82
+ let size = 0;
83
+ for (;;) {
84
+ const { done, value } = await reader.read();
85
+ if (done) break;
86
+ size += value.byteLength;
87
+ if (size > limit) {
88
+ await reader.cancel();
89
+ return;
90
+ }
91
+ chunks.push(value);
92
+ }
93
+ const bytes = new Uint8Array(size);
94
+ let offset = 0;
95
+ for (const chunk of chunks) {
96
+ bytes.set(chunk, offset);
97
+ offset += chunk.byteLength;
98
+ }
99
+ return new TextDecoder().decode(bytes);
100
+ };
101
+ const findOwnCookie = (header) => {
102
+ for (const part of header.split(";")) {
103
+ const index = part.indexOf("=");
104
+ if (index !== -1 && part.slice(0, index).trim() === COOKIE) return part.slice(index + 1).trim();
105
+ }
106
+ };
107
+ const toHeaderPairs = (request, rawHeaders) => {
108
+ if (!rawHeaders) return Array.from(request.headers.entries());
109
+ const pairs = [];
110
+ for (let index = 0; index + 1 < rawHeaders.length; index += 2) pairs.push([rawHeaders[index], rawHeaders[index + 1]]);
111
+ return pairs;
112
+ };
113
+ const READ_HEADERS = /* @__PURE__ */ new Set([
114
+ "user-agent",
115
+ "origin",
116
+ "signature-agent",
117
+ "signature-input"
118
+ ]);
119
+ const toForwardedHeaders = (pairs) => {
120
+ return pairs.map(([name, value]) => [name, READ_HEADERS.has(name.toLowerCase()) ? value : ""]);
121
+ };
122
+ const visitorIdOf = (pairs) => {
123
+ for (const [name, value] of pairs) {
124
+ const cookieValue = name.toLowerCase() === "cookie" ? findOwnCookie(value) : void 0;
125
+ if (cookieValue !== void 0) return /^[A-Za-z0-9]{20}$/.test(cookieValue) ? cookieValue : void 0;
126
+ }
127
+ };
128
+ const toPlainAddress = (address) => {
129
+ return address?.trim().replace(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i, "$1") || void 0;
130
+ };
131
+ const toCookieHeader = (url, value, maxAge, cookiePath = url.pathname) => {
132
+ const isLocalhost = [
133
+ "localhost",
134
+ "127.0.0.1",
135
+ "[::1]"
136
+ ].includes(url.hostname) || url.hostname.endsWith(".localhost");
137
+ const secureAttribute = url.protocol === "http:" && isLocalhost ? "" : "; Secure";
138
+ const escapedPath = cookiePath.replace(/[;,\s]/g, encodeURIComponent);
139
+ return `${COOKIE}=${value}; Max-Age=${maxAge}; Path=${escapedPath}; HttpOnly${secureAttribute}; SameSite=Lax`;
140
+ };
141
+ const isGzipAccepted = (request) => {
142
+ return (request.headers.get("accept-encoding") ?? "").split(",").some((part) => {
143
+ const [name = "", ...params] = part.split(";").map((item) => item.trim().toLowerCase());
144
+ const quality = params.find((param) => param.startsWith("q="));
145
+ return (name === "gzip" || name === "*") && !(quality && Number(quality.slice(2)) === 0);
146
+ });
147
+ };
148
+ const isIdentifyResult = (value) => {
149
+ if (!isObject(value)) return false;
150
+ if (value.capped === true) return true;
151
+ return typeof value.requestId === "string" && ["undefined", "string"].includes(typeof value.visitorId) && ["undefined", "boolean"].includes(typeof value.returning) && ["undefined", "string"].includes(typeof value.sealedResult);
152
+ };
153
+ const cookieOf = (cookie) => {
154
+ if (!isObject(cookie)) return;
155
+ const { value, maxAge } = cookie;
156
+ return typeof value === "string" && /^[A-Za-z0-9]{1,64}$/.test(value) && typeof maxAge === "number" && Number.isInteger(maxAge) && maxAge >= 0 ? {
157
+ value,
158
+ maxAge
159
+ } : void 0;
160
+ };
161
+ const gzipText = (text) => {
162
+ return new Response(new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
163
+ };
164
+ const javascriptResponse = async (request, module, cacheControl) => {
165
+ const headers = {
166
+ "content-type": "text/javascript; charset=utf-8",
167
+ "cache-control": cacheControl,
168
+ vary: "accept-encoding"
169
+ };
170
+ const text = typeof module === "string" ? module : module.code;
171
+ if (!isGzipAccepted(request) || typeof CompressionStream !== "function") return new Response(text, { headers });
172
+ const bytes = typeof module === "string" ? gzipText(text) : module.gzipped ??= gzipText(text);
173
+ return new Response(await bytes, { headers: {
174
+ ...headers,
175
+ "content-encoding": "gzip"
176
+ } });
177
+ };
178
+ const buildPageCode = (etag, challengeToken) => {
179
+ return [
180
+ `const code = await import(new URL(${JSON.stringify(`?${new URLSearchParams({ v: etag })}`)}, import.meta.url))`,
181
+ `export const challengeToken = ${challengeToken}`,
182
+ "const own = new URL(import.meta.url)",
183
+ "const refreshChallengeToken = () => import(new URL(\"?challenge=\" + Date.now(), own)).then(module => module.challengeToken, () => undefined)",
184
+ "export const start = (path = own.pathname, options) => code.start(path, { challengeToken, refreshChallengeToken, ...options })",
185
+ ""
186
+ ].join("\n");
187
+ };
188
+ /**
189
+ * The proxy route: a route on your own site between the browser SDK and the Zeno API. It serves the script's code,
190
+ * forwards its identifications with your API key and the visitor's ip, and keeps the visitor id in a first-party
191
+ * HttpOnly cookie. Answer `GET` and `POST` on one path of your choice (the one the browser's `start()` takes, `/zeno`
192
+ * by default) with what it returns, `zeno(request, ip)` with the IP address the request came from (`nodeHandler(zeno)`
193
+ * from `zeno.id/server/node` on Node's `(req, res)`). The `apiKey` (from your server's environment, undefined accepted)
194
+ * is checked on each request, so a module that makes it at load builds without the environment (as Next.js does when it
195
+ * collects page data); a request without it answers `500` and logs it.
196
+ */
197
+ const createProxy = (apiKey, options = {}) => {
198
+ const { apiUrl, cookiePath, fetch = globalThis.fetch } = options;
199
+ let heldScript;
200
+ let activeApiKey = "";
201
+ let apiBase = "";
202
+ const callApi = async (path, init) => {
203
+ try {
204
+ return await fetch(`${apiBase}${path}`, {
205
+ ...init,
206
+ signal: AbortSignal.timeout(TIMEOUT$1)
207
+ });
208
+ } catch (error) {
209
+ const reason = error instanceof Error && error.name === "TimeoutError" ? `no answer within ${TIMEOUT$1} ms` : String(error);
210
+ console.error(`The proxy route couldn't reach Zeno at ${apiBase}${path}: ${reason}`);
211
+ return;
212
+ }
213
+ };
214
+ const passApiError = async (response, path) => {
215
+ const body = await response.json().catch(() => void 0);
216
+ const code = isObject(body) && typeof body.error === "string" ? body.error : void 0;
217
+ const message = isObject(body) && typeof body.message === "string" ? body.message : void 0;
218
+ if (response.status === 401) {
219
+ console.error(`Zeno refused the proxy route's API key (401${code ? ` ${code}` : ""}${message ? `: ${message}` : ""}): check createProxy's apiKey`);
220
+ return jsonResponse(401, {
221
+ error: "invalid_api_key",
222
+ message: "Zeno refused the proxy route's API key; the route's server log says more"
223
+ });
224
+ }
225
+ if (!code) {
226
+ console.error(`Zeno answered the proxy route's ${path} call with ${response.status} without an error code`);
227
+ return serverError(`Zeno answered ${response.status}`, 502);
228
+ }
229
+ if (code === "account_closed") console.error("Zeno closed this project's organization (402 account_closed): contact Zeno support");
230
+ const retryAfter = response.headers.get("retry-after");
231
+ return jsonResponse(response.status, {
232
+ error: code,
233
+ ...message ? { message } : {}
234
+ }, retryAfter ? { "retry-after": retryAfter } : {});
235
+ };
236
+ const unreachableResponse = () => serverError("Zeno could not be reached", 502);
237
+ const fetchScript = async (visitorIp) => {
238
+ const cachedScript = heldScript;
239
+ const path = cachedScript ? `/script?${new URLSearchParams({ v: cachedScript.etag })}` : "/script";
240
+ const response = await callApi(path, { headers: {
241
+ "auth-api-key": activeApiKey,
242
+ ...cachedScript ? { "if-none-match": cachedScript.etag } : {},
243
+ ...visitorIp ? { "zeno-visitor-ip": visitorIp } : {}
244
+ } });
245
+ if (!response) return { failed: unreachableResponse() };
246
+ if (response.status !== 304 && !response.ok) return { failed: await passApiError(response, "/script") };
247
+ const tokenHeader = response.headers.get("zeno-challenge-token");
248
+ const challengeToken = tokenHeader ? JSON.stringify(tokenHeader) : "undefined";
249
+ if (response.status === 304) return cachedScript ? {
250
+ script: cachedScript,
251
+ challengeToken
252
+ } : { failed: serverError("Zeno answered 304 for code this route never had") };
253
+ const code = await response.text().catch(() => void 0);
254
+ if (code === void 0) return { failed: unreachableResponse() };
255
+ const etag = response.headers.get("etag");
256
+ heldScript = etag ? {
257
+ etag,
258
+ code
259
+ } : void 0;
260
+ return {
261
+ script: heldScript ?? { code },
262
+ challengeToken
263
+ };
264
+ };
265
+ const servePageModule = async (request, ip) => {
266
+ const fetched = await fetchScript(ip);
267
+ if (fetched.failed) return fetched.failed;
268
+ const { script, challengeToken } = fetched;
269
+ if (script.etag === void 0) return javascriptResponse(request, `${script.code}\nexport const challengeToken = ${challengeToken}\n`, "private, max-age=60");
270
+ return javascriptResponse(request, buildPageCode(script.etag, challengeToken), "private, max-age=60");
271
+ };
272
+ const serveCodeModule = async (request, version) => {
273
+ let script = heldScript;
274
+ if (script?.etag !== version) {
275
+ const fetched = await fetchScript(void 0);
276
+ if (fetched.failed) return fetched.failed;
277
+ script = fetched.script;
278
+ }
279
+ return javascriptResponse(request, script, script.etag === version ? "private, max-age=31536000, immutable" : "no-store");
280
+ };
281
+ const handleGet = (request, ip) => {
282
+ const version = new URL(request.url).searchParams.get("v");
283
+ return version === null ? servePageModule(request, ip) : serveCodeModule(request, version);
284
+ };
285
+ const handlePost = async (request, ip, internal) => {
286
+ if (!/^application\/json\s*(;|$)/i.test(request.headers.get("content-type") ?? "")) return invalidRequest("The body must be JSON");
287
+ if (request.headers.get("sec-fetch-site") === "cross-site") return invalidRequest("Cross-site requests are refused");
288
+ const bodyText = await readCappedBody(request, MAX_BODY);
289
+ if (bodyText === void 0) return invalidRequest("The body is larger than 128 KB");
290
+ let payload;
291
+ try {
292
+ payload = JSON.parse(bodyText);
293
+ } catch {
294
+ return invalidRequest("The body is not valid JSON");
295
+ }
296
+ if (!isObject(payload) || !isObject(payload.browserData)) return invalidRequest("The body has no browserData");
297
+ if (!ip) {
298
+ console.error(`The proxy route got no IP address: ${NO_IP}, or nodeHandler(zeno) on Node`);
299
+ return serverError(NO_IP);
300
+ }
301
+ const pairs = toHeaderPairs(request, rawHeadersOf(internal));
302
+ const visitorId = visitorIdOf(pairs);
303
+ const envelope = {
304
+ ...visitorId ? { visitorId } : {},
305
+ ip,
306
+ headers: toForwardedHeaders(pairs),
307
+ payload
308
+ };
309
+ const response = await callApi("/identify", {
310
+ method: "POST",
311
+ headers: {
312
+ "auth-api-key": activeApiKey,
313
+ "content-type": "application/json"
314
+ },
315
+ body: JSON.stringify(envelope)
316
+ });
317
+ if (!response) return unreachableResponse();
318
+ if (!response.ok) return passApiError(response, "/identify");
319
+ const answer = await response.json().catch(() => void 0);
320
+ if (!isObject(answer) || !isIdentifyResult(answer.result)) {
321
+ console.error("Zeno's answer to the proxy route's identification couldn't be read");
322
+ return serverError("Zeno's answer couldn't be read", 502);
323
+ }
324
+ const cookie = cookieOf(answer.cookie);
325
+ return jsonResponse(200, answer.result, cookie ? { "set-cookie": toCookieHeader(new URL(request.url), cookie.value, cookie.maxAge, cookiePath) } : {});
326
+ };
327
+ const handler = async (request, givenIp, internal) => {
328
+ const url = new URL(request.url);
329
+ if (request.method === "POST" && url.searchParams.has("forget")) return new Response(null, {
330
+ status: 204,
331
+ headers: { "set-cookie": toCookieHeader(url, "", 0, cookiePath) }
332
+ });
333
+ if (![
334
+ "GET",
335
+ "HEAD",
336
+ "POST"
337
+ ].includes(request.method)) return jsonResponse(405, {
338
+ error: "method_not_allowed",
339
+ message: "Use GET or POST"
340
+ }, { allow: "GET, HEAD, POST" });
341
+ const settings = checkApiSettings("createProxy", apiKey, apiUrl);
342
+ if (settings.problem !== void 0) {
343
+ console.error(settings.problem);
344
+ return serverError("The proxy route isn't set up; its server log says what's missing");
345
+ }
346
+ activeApiKey = settings.apiKey;
347
+ apiBase = settings.base;
348
+ const ip = toPlainAddress(givenIp);
349
+ if (request.method === "POST") return handlePost(request, ip, internal);
350
+ const response = await handleGet(request, ip);
351
+ if (request.method === "HEAD") {
352
+ await response.body?.cancel();
353
+ return new Response(null, {
354
+ status: response.status,
355
+ headers: response.headers
356
+ });
357
+ }
358
+ return response;
359
+ };
360
+ return handler;
361
+ };
362
+ //#endregion
363
+ //#region src/server/index.ts
364
+ /** Every signal an event checks, the keys of its `signals`. */
365
+ const SIGNALS = [
366
+ "automation",
367
+ "headless",
368
+ "software-renderer",
369
+ "tampering",
370
+ "timezone-mismatch",
371
+ "privacy-settings",
372
+ "vpn",
373
+ "proxy",
374
+ "tor",
375
+ "datacenter",
376
+ "abusive-ip",
377
+ "incognito",
378
+ "virtual-machine",
379
+ "developer-tools",
380
+ "ai-agent",
381
+ "privacy-browser",
382
+ "rare-device",
383
+ "replayed",
384
+ "residential-proxy",
385
+ "private-relay",
386
+ "forged-payload",
387
+ "stored-id-rejected"
388
+ ];
389
+ const RETRIES = 2;
390
+ const TIMEOUT = 1e4;
391
+ /**
392
+ * An error answer of the api, with its status and error code like `not_found`, and for a `429 rate_limited` or `503
393
+ * search_unavailable` the seconds to wait from its `Retry-After`. A relation added by hand and refused because a spend
394
+ * limit you set (the project's, its organization's or the key's) is reached is a `402` `spend_limit_reached`. Any call
395
+ * while the organization's account is closed is a `402` `account_closed`: contact support to reopen it.
396
+ */
397
+ var ZenoError = class extends Error {
398
+ status;
399
+ code;
400
+ retryAfter;
401
+ constructor(status, code, message, retryAfter) {
402
+ super(message ?? code);
403
+ this.status = status;
404
+ this.code = code;
405
+ this.retryAfter = retryAfter;
406
+ this.name = "ZenoError";
407
+ }
408
+ };
409
+ const requireSecret = (value, message) => {
410
+ if (!value) throw new TypeError(message);
411
+ return value;
412
+ };
413
+ const retryAfterOf = (header) => {
414
+ if (header === null) return;
415
+ const seconds = /^\d+$/.test(header.trim()) ? Number(header) : (Date.parse(header) - Date.now()) / 1e3;
416
+ return Number.isFinite(seconds) ? Math.min(Math.max(seconds, 0), 60) : void 0;
417
+ };
418
+ const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
419
+ const toPathSegment = (name, value) => {
420
+ if (typeof value !== "string" || !value || value === "." || value === "..") throw new ZenoError(0, "invalid_request", `${name} must be a non-empty string`);
421
+ return encodeURIComponent(value);
422
+ };
423
+ const isKind = (value, kind) => {
424
+ if (kind === "array") return Array.isArray(value);
425
+ return kind === "object" ? isObject(value) : typeof value === kind;
426
+ };
427
+ const defineShape = (name, fields) => ({
428
+ name,
429
+ is: (value) => isObject(value) && Object.entries(fields).every(([field, kind]) => isKind(value[field], kind))
430
+ });
431
+ const EVENT = defineShape("an event", {
432
+ requestId: "string",
433
+ visitorId: "string",
434
+ ip: "string",
435
+ createdAt: "string",
436
+ riskScore: "number",
437
+ signals: "object",
438
+ verdict: "object"
439
+ });
440
+ const SEARCH = defineShape("a page of events", { items: "array" });
441
+ const VISITOR = defineShape("a visitor", {
442
+ visitorId: "string",
443
+ externalIds: "array",
444
+ externalIdCount: "number",
445
+ recentEvents: "array"
446
+ });
447
+ const DELETED_VISITOR = defineShape("an erasure", {
448
+ visitorId: "string",
449
+ deletedEvents: "number"
450
+ });
451
+ const DELETED_EXTERNAL_ID = defineShape("an erasure", {
452
+ externalId: "string",
453
+ deletedEvents: "number"
454
+ });
455
+ const ADDED_RELATION = defineShape("a relation", {
456
+ externalId: "string",
457
+ type: "string",
458
+ linkWrite: "boolean"
459
+ });
460
+ const REMOVED = defineShape("a removal", { removed: "boolean" });
461
+ const RELATED_VALUES = defineShape("a user's values", {
462
+ externalId: "string",
463
+ values: "array",
464
+ truncated: "boolean"
465
+ });
466
+ const EXTERNAL_IDS = defineShape("a page of users", { items: "array" });
467
+ const SHARED = defineShape("a page of shared values", { items: "array" });
468
+ const RELATED = defineShape("related users", {
469
+ externalId: "string",
470
+ externalIds: "array",
471
+ connections: "array"
472
+ });
473
+ const EMBED = defineShape("an embed", {
474
+ url: "string",
475
+ expiresAt: "string"
476
+ });
477
+ const VERIFIED = defineShape("verify's answer", {
478
+ action: "string",
479
+ reasons: "array"
480
+ });
481
+ /**
482
+ * A client for the Zeno API, with the project's `apiKey` from your server's environment (`process.env.ZENO_API_KEY`,
483
+ * undefined accepted). It's checked on each call, so a module that makes one at load still builds without the
484
+ * environment (as Next.js does when it collects page data); a missing one rejects the call with a TypeError saying how
485
+ * to set it. A call answered `429 rate_limited` or `503 search_unavailable` is sent again twice, after the API's
486
+ * `Retry-After`.
487
+ */
488
+ const createClient = (apiKey, options = {}) => {
489
+ const { apiUrl, fetch = globalThis.fetch } = options;
490
+ const sendOnce = async (key, base, method, path, jsonBody) => {
491
+ try {
492
+ const response = await fetch(`${base}${path}`, {
493
+ method,
494
+ headers: {
495
+ "auth-api-key": key,
496
+ ...jsonBody ? { "content-type": "application/json" } : {}
497
+ },
498
+ body: jsonBody,
499
+ signal: AbortSignal.timeout(TIMEOUT)
500
+ });
501
+ return {
502
+ response,
503
+ text: await response.text()
504
+ };
505
+ } catch (error) {
506
+ throw new ZenoError(0, "network_error", error instanceof Error && error.name === "TimeoutError" ? `Zeno didn't answer ${method} ${path.split("?")[0]} within ${TIMEOUT} ms` : `Zeno couldn't be reached at ${base}: ${error instanceof Error ? error.message : String(error)}`);
507
+ }
508
+ };
509
+ const callApi = async (method, path, expected, body, isRepeatSafe = false) => {
510
+ const settings = checkApiSettings("createClient", apiKey, apiUrl);
511
+ if (settings.problem !== void 0) throw new TypeError(settings.problem);
512
+ const jsonBody = body && JSON.stringify(body);
513
+ for (let attempt = 0;; attempt++) {
514
+ let sent;
515
+ try {
516
+ sent = await sendOnce(settings.apiKey, settings.base, method, path, jsonBody);
517
+ } catch (error) {
518
+ if (isRepeatSafe && attempt < RETRIES) {
519
+ await sleep(1 + Math.random() * .5);
520
+ continue;
521
+ }
522
+ throw error;
523
+ }
524
+ const { response, text } = sent;
525
+ let data;
526
+ try {
527
+ data = JSON.parse(text);
528
+ } catch {}
529
+ if (response.ok) {
530
+ if (data === void 0) throw new ZenoError(response.status, "request_failed", `Zeno answered ${response.status} without JSON`);
531
+ if (!expected.is(data)) throw new ZenoError(response.status, "request_failed", `Zeno answered ${method} ${path.split("?")[0]} with something that isn't ${expected.name}`);
532
+ return data;
533
+ }
534
+ const { error, message } = isObject(data) ? data : {};
535
+ const code = typeof error === "string" ? error : void 0;
536
+ const isRetryable = response.status === 429 || code === "search_unavailable" || isRepeatSafe && response.status >= 500;
537
+ const retryAfter = isRetryable ? retryAfterOf(response.headers.get("retry-after")) : void 0;
538
+ if (isRetryable && attempt < RETRIES) {
539
+ const waitSeconds = retryAfter ?? 1;
540
+ await sleep(waitSeconds + Math.random() * waitSeconds * .5);
541
+ continue;
542
+ }
543
+ throw new ZenoError(response.status, code ?? "request_failed", typeof message === "string" ? message : void 0, retryAfter);
544
+ }
545
+ };
546
+ const addPageParams = (query, page) => {
547
+ for (const [key, item] of Object.entries(page)) if (item !== void 0) query.set(key, String(item));
548
+ return query;
549
+ };
550
+ /** One event with its details and velocity. */
551
+ const getEvent = async (requestId) => callApi("GET", `/events/${toPathSegment("requestId", requestId)}`, EVENT);
552
+ return {
553
+ /**
554
+ * Checks a request ID the browser sent with an action (a login, a signup, a checkout) and says what to do: `{
555
+ * action: 'allow' | 'challenge' | 'block', reasons, event? }`, in one call (`POST /verify`). Each request ID
556
+ * verifies once. No request ID (`undefined`, `null` or empty: the browser's identification failed or was
557
+ * blocked) is a `challenge` with `no-request-id`, so you decide what happens then. It blocks a request ID that
558
+ * isn't this project's (`not-found`), was verified before (`already-used`), came from another ip than `ip` when
559
+ * you pass one (`ip-mismatch`, for IPv6 another /64; IPv4 and IPv6 are never compared), is older than `maxAge`
560
+ * seconds (`too-old`, 5 minutes by default) or belongs to another user than `externalId`
561
+ * (`external-id-mismatch`); otherwise it answers the event's verdict. Call it after the action succeeded (the
562
+ * password matched, the account exists), with the user's ID: `externalId` is attached to an event without one.
563
+ * It writes nothing else. A lost answer (a network error or a 5xx) is sent again twice with the same
564
+ * idempotency key, which answers the first result rather than `already-used`. Other api errors throw.
565
+ */
566
+ verify: async (requestId, options = {}) => {
567
+ const { ip, externalId, maxAge, idempotencyKey = crypto.randomUUID() } = options;
568
+ return callApi("POST", "/verify", VERIFIED, {
569
+ requestId: requestId ?? void 0,
570
+ ip: ip || void 0,
571
+ externalId,
572
+ maxAge,
573
+ idempotencyKey
574
+ }, true);
575
+ },
576
+ getEvent,
577
+ /** Events matching every filter, newest first; pass the cursor back for the next page. */
578
+ searchEvents: (filters = {}) => {
579
+ const query = new URLSearchParams();
580
+ for (const [key, value] of Object.entries(filters)) for (const item of Array.isArray(value) ? value : [value]) if (item !== void 0) query.append(key, item instanceof Date ? item.toISOString() : String(item));
581
+ return callApi("GET", `/events?${query}`, SEARCH);
582
+ },
583
+ /** A visitor (a browser) with every external id seen with it. */
584
+ getVisitor: async (visitorId) => callApi("GET", `/visitors/${toPathSegment("visitorId", visitorId)}`, VISITOR),
585
+ /** Deletes a visitor (a browser) and all its events. */
586
+ deleteVisitor: async (visitorId) => {
587
+ return callApi("DELETE", `/visitors/${toPathSegment("visitorId", visitorId)}`, DELETED_VISITOR);
588
+ },
589
+ /** Deletes everything stored for one of your users: their events, and what relates them to devices and others. */
590
+ deleteExternalId: (externalId) => {
591
+ const query = new URLSearchParams({ externalId });
592
+ return callApi("DELETE", `/external-ids?${query}`, DELETED_EXTERNAL_ID);
593
+ },
594
+ /**
595
+ * Relates one of your users by hand: to an ip seen by another system, a value of a type of your own (a phone
596
+ * number, your own device id) or another of your users (a referral). Visitor ids only come from events with an
597
+ * external id, so `identified` means the user was seen in a browser.
598
+ *
599
+ * A new link is billed like an identification (`linkWrite: true`); sending one again is free. Once a spend
600
+ * limit you set is reached it throws a `402` `spend_limit_reached` and adds nothing; only a `429` is sent
601
+ * again.
602
+ */
603
+ addRelation: ({ at, ...relation }) => {
604
+ const atIso = at instanceof Date || typeof at === "number" ? new Date(at).toISOString() : at;
605
+ return callApi("POST", "/related", ADDED_RELATION, {
606
+ ...relation,
607
+ ...atIso === void 0 ? {} : { at: atIso }
608
+ });
609
+ },
610
+ /**
611
+ * Takes back a relation added with `addRelation`: a value, or a relation between two users (both sides go,
612
+ * whichever side you name). What events related (a visitor id, an ip seen with an event) stays. Free.
613
+ *
614
+ * Answers `{ removed: false }` when there was nothing added by hand to take back, so it's safe to repeat.
615
+ */
616
+ removeRelation: (relation) => {
617
+ const query = new URLSearchParams(relation);
618
+ return callApi("DELETE", `/related?${query}`, REMOVED);
619
+ },
620
+ /**
621
+ * One of your users' values and relations, of one `type` or every type, each with its weight, and whether they
622
+ * share one value weighing 0.5 or more with another user (`duplicate`). At most 500 (`truncated` past them).
623
+ */
624
+ getRelatedValues: (externalId, { type } = {}) => {
625
+ const query = new URLSearchParams({
626
+ externalId,
627
+ ...type ? { type } : {}
628
+ });
629
+ return callApi("GET", `/related/values?${query}`, RELATED_VALUES);
630
+ },
631
+ /**
632
+ * Your users who have one value, like everyone with one phone number, 20 a page by default (`limit` up to 100);
633
+ * pass the cursor back for the next page.
634
+ */
635
+ lookupRelated: (type, value, page = {}) => {
636
+ const query = addPageParams(new URLSearchParams({
637
+ type,
638
+ value
639
+ }), page);
640
+ return callApi("GET", `/related/lookup?${query}`, EXTERNAL_IDS);
641
+ },
642
+ /** The values of a type more than one of your users share, most shared first, with the type's weight. */
643
+ getSharedValues: (type, page = {}) => {
644
+ const query = addPageParams(new URLSearchParams({ type }), page);
645
+ return callApi("GET", `/related/shared?${query}`, SHARED);
646
+ },
647
+ /**
648
+ * Your users related to one through shared values or relations of every type, or of one `type`, up to `depth`
649
+ * (1 to 5, 1 by default) hops away, heaviest first, each with its weight.
650
+ */
651
+ getRelated: (externalId, { type, depth = 1 } = {}) => {
652
+ const query = new URLSearchParams({
653
+ externalId,
654
+ ...type ? { type } : {},
655
+ depth: String(depth)
656
+ });
657
+ return callApi("GET", `/related?${query}`, RELATED);
658
+ },
659
+ /**
660
+ * A link to one user's Related view (their values, related users and recent events) for your admin panel at
661
+ * `origin` to frame, working for `ttl` minutes (5 to 60, 15 by default). Make one per page view and never hand
662
+ * the API key to the browser.
663
+ */
664
+ createEmbed: (embed) => {
665
+ return callApi("POST", "/embeds", EMBED, embed);
666
+ }
667
+ };
668
+ };
669
+ const encoder = new TextEncoder();
670
+ const fromBase64 = (text) => {
671
+ try {
672
+ return Uint8Array.from(atob(text), (char) => char.charCodeAt(0));
673
+ } catch {
674
+ return;
675
+ }
676
+ };
677
+ const toHex = (bytes) => Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
678
+ const isSameBytes = (a, b) => {
679
+ if (a.length !== b.length) return false;
680
+ let difference = 0;
681
+ for (let index = 0; index < a.length; index++) difference |= a[index] ^ b[index];
682
+ return difference === 0;
683
+ };
684
+ /**
685
+ * Checks a webhook delivery's Zeno-Signature header against the project's webhook secret, and that it was signed in the
686
+ * last `tolerance` seconds, so a captured delivery can't be replayed later. Pass the raw body. Resolves to the event
687
+ * when it matched, else to undefined; rejects with a TypeError when the secret is missing, and with an Error for a
688
+ * signed body that isn't an event.
689
+ */
690
+ const verifyWebhook = async (body, header, secret, { tolerance = 300 } = {}) => {
691
+ const webhookSecret = requireSecret(secret, "verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)");
692
+ const parts = (header ?? "").split(",").map((part) => {
693
+ const [name, ...value] = part.trim().split("=");
694
+ return [name ?? "", value.join("=")];
695
+ });
696
+ const timestamp = Number(parts.find(([name]) => name === "t")?.[1]);
697
+ const signatures = parts.filter(([name, value]) => name === "v1" && value).map(([, value]) => value);
698
+ if (!Number.isInteger(timestamp) || signatures.length === 0 || Math.abs(Date.now() / 1e3 - timestamp) > tolerance) return;
699
+ const hmac = await crypto.subtle.importKey("raw", encoder.encode(webhookSecret), {
700
+ name: "HMAC",
701
+ hash: "SHA-256"
702
+ }, false, ["sign"]);
703
+ const expectedSignature = encoder.encode(toHex(await crypto.subtle.sign("HMAC", hmac, encoder.encode(`${timestamp}.${body}`))));
704
+ if (!signatures.map((signature) => isSameBytes(encoder.encode(signature), expectedSignature)).includes(true)) return;
705
+ let event;
706
+ try {
707
+ event = JSON.parse(body);
708
+ } catch {}
709
+ if (!EVENT.is(event)) throw new Error("The webhook's body is signed but isn't an event; update zeno.id/server");
710
+ return event;
711
+ };
712
+ const UNSEAL_MAX_AGE = 300;
713
+ const notFoundResult = () => ({
714
+ action: "block",
715
+ reasons: ["not-found"]
716
+ });
717
+ const MISSING_KEY = "unsealResult needs the project's encryption key as key (is it set in the environment?)";
718
+ const keyBytesOf = (secret) => {
719
+ const trimmedKey = requireSecret(secret, MISSING_KEY).trim();
720
+ const keyBytes = /^[A-Za-z0-9+/]+={0,2}$/.test(trimmedKey) ? fromBase64(trimmedKey) : void 0;
721
+ if (!keyBytes) throw new TypeError("unsealResult's key isn't base64: pass the project's encryption key as the dashboard shows it");
722
+ if (keyBytes.length !== 32) throw new TypeError(/^[0-9a-f]{64}$/i.test(trimmedKey) ? "unsealResult's key looks like hex: pass the project's encryption key as the dashboard shows it, in base64" : `unsealResult's key is ${keyBytes.length} bytes, not 32: pass the project's encryption key as the dashboard shows it`);
723
+ return keyBytes;
724
+ };
725
+ const decryptWithAnyKey = async (keys, data) => {
726
+ for (const keyBytes of keys) {
727
+ const aes = await crypto.subtle.importKey("raw", keyBytes, "AES-GCM", false, ["decrypt"]);
728
+ try {
729
+ return await crypto.subtle.decrypt({
730
+ name: "AES-GCM",
731
+ iv: data.subarray(1, 13),
732
+ tagLength: 128
733
+ }, aes, data.subarray(13));
734
+ } catch {}
735
+ }
736
+ };
737
+ /**
738
+ * Opens a sealed result from the browser with the project's encryption key and says what to do, in `verify`'s shape: `{
739
+ * action, reasons, event? }`. No sealed result (`undefined`, `null` or empty) is a `challenge` with `no-request-id`;
740
+ * one that doesn't open with any `key` (changed, sealed with another project's key, or not one at all) is a `block`
741
+ * with `not-found`. An opened one from another ip than `ip` blocks with `ip-mismatch`, compared as `verify` does, one
742
+ * older than `maxAge` seconds with `too-old`, another user's than `externalId` with `external-id-mismatch`; otherwise
743
+ * it answers the event's verdict. It can't tell a sealed result sent twice: where a repeat matters, use `verify`, which
744
+ * allows each request ID once. Rejects with a TypeError for a missing or malformed key. The format: base64(version |
745
+ * iv(12) | ciphertext | tag(16)), AES-256-GCM.
746
+ */
747
+ const unsealResult = async (sealed, options) => {
748
+ const givenKeys = (Array.isArray(options?.key) ? options.key : [options?.key]).filter((key) => key);
749
+ if (givenKeys.length === 0) throw new TypeError(MISSING_KEY);
750
+ const keys = givenKeys.map(keyBytesOf);
751
+ if (!sealed) return {
752
+ action: "challenge",
753
+ reasons: ["no-request-id"]
754
+ };
755
+ if (typeof sealed !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(sealed.trim())) return notFoundResult();
756
+ const data = fromBase64(sealed.trim());
757
+ if (!data || data.length < 30 || data[0] !== 1) return notFoundResult();
758
+ const plainBytes = await decryptWithAnyKey(keys, data);
759
+ if (!plainBytes) return notFoundResult();
760
+ let event;
761
+ try {
762
+ event = JSON.parse(new TextDecoder().decode(plainBytes));
763
+ } catch {}
764
+ if (!EVENT.is(event)) throw new Error("The sealed result opened but isn't an event; update zeno.id/server");
765
+ const failedChecks = [];
766
+ const maxAge = options.maxAge ?? UNSEAL_MAX_AGE;
767
+ if (options.ip && isIpMismatch(event.ip, options.ip)) failedChecks.push("ip-mismatch");
768
+ if (Date.now() - Date.parse(event.createdAt) > maxAge * 1e3) failedChecks.push("too-old");
769
+ if (options.externalId !== void 0 && event.externalId !== void 0 && event.externalId !== options.externalId) failedChecks.push("external-id-mismatch");
770
+ if (failedChecks.length > 0) return {
771
+ action: "block",
772
+ reasons: failedChecks,
773
+ event
774
+ };
775
+ return {
776
+ action: event.verdict.action,
777
+ reasons: event.verdict.reasons,
778
+ event
779
+ };
780
+ };
781
+ //#endregion
782
+ exports.SIGNALS = SIGNALS;
783
+ exports.ZenoError = ZenoError;
784
+ exports.createClient = createClient;
785
+ exports.createProxy = createProxy;
786
+ exports.unsealResult = unsealResult;
787
+ exports.verifyWebhook = verifyWebhook;