zeno.id 0.2.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.
@@ -4,7 +4,7 @@ const isObject = (value) => {
4
4
  return typeof value === "object" && value !== null && !Array.isArray(value);
5
5
  };
6
6
  const DEFAULT_API_URL = "https://api.zeno.id";
7
- const settingsOf = (name, apiKey, apiUrl = DEFAULT_API_URL) => {
7
+ const checkApiSettings = (name, apiKey, apiUrl = DEFAULT_API_URL) => {
8
8
  if (!apiKey) return { problem: `${name}'s apiKey is missing: pass your API key (ZENO_API_KEY in your environment)` };
9
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
10
  try {
@@ -17,19 +17,19 @@ const settingsOf = (name, apiKey, apiUrl = DEFAULT_API_URL) => {
17
17
  };
18
18
  const networkOf = (address) => {
19
19
  if (!address.includes(":")) return address;
20
- const dotted = address.match(/^(?:::|(?:0{1,4}:){5})ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
21
- if (dotted) return dotted[1];
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
22
  const [head = "", tail = ""] = address.split("::");
23
- const left = head ? head.split(":") : [];
24
- const right = tail ? tail.split(":") : [];
25
- const missing = Math.max(0, 8 - left.length - right.length);
26
- const full = [
27
- ...left,
28
- ...Array.from({ length: missing }, () => "0"),
29
- ...right
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
30
  ].map((group) => group.toLowerCase().replace(/^0+(?=\w)/, ""));
31
- if (full.slice(0, 5).every((group) => group === "0") && full[5] === "ffff") {
32
- const [high = 0, low = 0] = full.slice(6).map((group) => parseInt(group, 16));
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
33
  return [
34
34
  high >> 8,
35
35
  high & 255,
@@ -37,11 +37,11 @@ const networkOf = (address) => {
37
37
  low & 255
38
38
  ].join(".");
39
39
  }
40
- return full.slice(0, 4).join(":");
40
+ return groups.slice(0, 4).join(":");
41
41
  };
42
- const ipMismatch = (eventIp, ip) => {
43
- const given = ip.trim();
44
- return eventIp.includes(":") === given.includes(":") && networkOf(eventIp) !== networkOf(given);
42
+ const isIpMismatch = (eventIp, ip) => {
43
+ const requestIp = ip.trim();
44
+ return eventIp.includes(":") === requestIp.includes(":") && networkOf(eventIp) !== networkOf(requestIp);
45
45
  };
46
46
  //#endregion
47
47
  //#region src/server/proxy.ts
@@ -55,7 +55,7 @@ const rawHeadersOf = (internal) => {
55
55
  const COOKIE = "zeno_id";
56
56
  const MAX_BODY = 131072;
57
57
  const TIMEOUT$1 = 1e4;
58
- const json = (status, body, headers = {}) => {
58
+ const jsonResponse = (status, body, headers = {}) => {
59
59
  return new Response(JSON.stringify(body), {
60
60
  status,
61
61
  headers: {
@@ -65,16 +65,16 @@ const json = (status, body, headers = {}) => {
65
65
  }
66
66
  });
67
67
  };
68
- const invalid = (message) => json(400, {
68
+ const invalidRequest = (message) => jsonResponse(400, {
69
69
  error: "invalid_request",
70
70
  message
71
71
  });
72
- const serverError = (message, status = 500) => json(status, {
72
+ const serverError = (message, status = 500) => jsonResponse(status, {
73
73
  error: "server_error",
74
74
  message
75
75
  });
76
76
  const NO_IP = "Pass the IP address the request came from: zeno(request, ip)";
77
- const readCapped = async (request, limit) => {
77
+ const readCappedBody = async (request, limit) => {
78
78
  if (Number(request.headers.get("content-length")) > limit) return;
79
79
  if (!request.body) return "";
80
80
  const reader = request.body.getReader();
@@ -98,13 +98,13 @@ const readCapped = async (request, limit) => {
98
98
  }
99
99
  return new TextDecoder().decode(bytes);
100
100
  };
101
- const ownCookie = (header) => {
101
+ const findOwnCookie = (header) => {
102
102
  for (const part of header.split(";")) {
103
103
  const index = part.indexOf("=");
104
104
  if (index !== -1 && part.slice(0, index).trim() === COOKIE) return part.slice(index + 1).trim();
105
105
  }
106
106
  };
107
- const headerPairs = (request, rawHeaders) => {
107
+ const toHeaderPairs = (request, rawHeaders) => {
108
108
  if (!rawHeaders) return Array.from(request.headers.entries());
109
109
  const pairs = [];
110
110
  for (let index = 0; index + 1 < rawHeaders.length; index += 2) pairs.push([rawHeaders[index], rawHeaders[index + 1]]);
@@ -116,36 +116,36 @@ const READ_HEADERS = /* @__PURE__ */ new Set([
116
116
  "signature-agent",
117
117
  "signature-input"
118
118
  ]);
119
- const forwardedHeaders = (pairs) => {
119
+ const toForwardedHeaders = (pairs) => {
120
120
  return pairs.map(([name, value]) => [name, READ_HEADERS.has(name.toLowerCase()) ? value : ""]);
121
121
  };
122
122
  const visitorIdOf = (pairs) => {
123
123
  for (const [name, value] of pairs) {
124
- const own = name.toLowerCase() === "cookie" ? ownCookie(value) : void 0;
125
- if (own !== void 0) return /^[A-Za-z0-9]{20}$/.test(own) ? own : void 0;
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
126
  }
127
127
  };
128
- const plainAddress = (address) => {
128
+ const toPlainAddress = (address) => {
129
129
  return address?.trim().replace(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i, "$1") || void 0;
130
130
  };
131
- const cookieHeader = (url, value, maxAge, cookiePath = url.pathname) => {
132
- const localhost = [
131
+ const toCookieHeader = (url, value, maxAge, cookiePath = url.pathname) => {
132
+ const isLocalhost = [
133
133
  "localhost",
134
134
  "127.0.0.1",
135
135
  "[::1]"
136
136
  ].includes(url.hostname) || url.hostname.endsWith(".localhost");
137
- const secure = url.protocol === "http:" && localhost ? "" : "; Secure";
138
- const path = cookiePath.replace(/[;,\s]/g, encodeURIComponent);
139
- return `${COOKIE}=${value}; Max-Age=${maxAge}; Path=${path}; HttpOnly${secure}; SameSite=Lax`;
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
140
  };
141
- const acceptsGzip = (request) => {
141
+ const isGzipAccepted = (request) => {
142
142
  return (request.headers.get("accept-encoding") ?? "").split(",").some((part) => {
143
143
  const [name = "", ...params] = part.split(";").map((item) => item.trim().toLowerCase());
144
144
  const quality = params.find((param) => param.startsWith("q="));
145
145
  return (name === "gzip" || name === "*") && !(quality && Number(quality.slice(2)) === 0);
146
146
  });
147
147
  };
148
- const isResult = (value) => {
148
+ const isIdentifyResult = (value) => {
149
149
  if (!isObject(value)) return false;
150
150
  if (value.capped === true) return true;
151
151
  return typeof value.requestId === "string" && ["undefined", "string"].includes(typeof value.visitorId) && ["undefined", "boolean"].includes(typeof value.returning) && ["undefined", "string"].includes(typeof value.sealedResult);
@@ -158,24 +158,24 @@ const cookieOf = (cookie) => {
158
158
  maxAge
159
159
  } : void 0;
160
160
  };
161
- const gzip = (text) => {
161
+ const gzipText = (text) => {
162
162
  return new Response(new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer();
163
163
  };
164
- const javascript = async (request, module, cacheControl) => {
164
+ const javascriptResponse = async (request, module, cacheControl) => {
165
165
  const headers = {
166
166
  "content-type": "text/javascript; charset=utf-8",
167
167
  "cache-control": cacheControl,
168
168
  vary: "accept-encoding"
169
169
  };
170
170
  const text = typeof module === "string" ? module : module.code;
171
- if (!acceptsGzip(request) || typeof CompressionStream !== "function") return new Response(text, { headers });
172
- const bytes = typeof module === "string" ? gzip(text) : module.gzipped ??= gzip(text);
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
173
  return new Response(await bytes, { headers: {
174
174
  ...headers,
175
175
  "content-encoding": "gzip"
176
176
  } });
177
177
  };
178
- const pageCode = (etag, challengeToken) => {
178
+ const buildPageCode = (etag, challengeToken) => {
179
179
  return [
180
180
  `const code = await import(new URL(${JSON.stringify(`?${new URLSearchParams({ v: etag })}`)}, import.meta.url))`,
181
181
  `export const challengeToken = ${challengeToken}`,
@@ -196,28 +196,28 @@ const pageCode = (etag, challengeToken) => {
196
196
  */
197
197
  const createProxy = (apiKey, options = {}) => {
198
198
  const { apiUrl, cookiePath, fetch = globalThis.fetch } = options;
199
- let agent;
200
- let key = "";
201
- let base = "";
202
- const call = async (path, init) => {
199
+ let heldScript;
200
+ let activeApiKey = "";
201
+ let apiBase = "";
202
+ const callApi = async (path, init) => {
203
203
  try {
204
- return await fetch(`${base}${path}`, {
204
+ return await fetch(`${apiBase}${path}`, {
205
205
  ...init,
206
206
  signal: AbortSignal.timeout(TIMEOUT$1)
207
207
  });
208
208
  } catch (error) {
209
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 ${base}${path}: ${reason}`);
210
+ console.error(`The proxy route couldn't reach Zeno at ${apiBase}${path}: ${reason}`);
211
211
  return;
212
212
  }
213
213
  };
214
- const passError = async (response, path) => {
214
+ const passApiError = async (response, path) => {
215
215
  const body = await response.json().catch(() => void 0);
216
216
  const code = isObject(body) && typeof body.error === "string" ? body.error : void 0;
217
217
  const message = isObject(body) && typeof body.message === "string" ? body.message : void 0;
218
218
  if (response.status === 401) {
219
219
  console.error(`Zeno refused the proxy route's API key (401${code ? ` ${code}` : ""}${message ? `: ${message}` : ""}): check createProxy's apiKey`);
220
- return json(401, {
220
+ return jsonResponse(401, {
221
221
  error: "invalid_api_key",
222
222
  message: "Zeno refused the proxy route's API key; the route's server log says more"
223
223
  });
@@ -228,126 +228,126 @@ const createProxy = (apiKey, options = {}) => {
228
228
  }
229
229
  if (code === "account_closed") console.error("Zeno closed this project's organization (402 account_closed): contact Zeno support");
230
230
  const retryAfter = response.headers.get("retry-after");
231
- return json(response.status, {
231
+ return jsonResponse(response.status, {
232
232
  error: code,
233
233
  ...message ? { message } : {}
234
234
  }, retryAfter ? { "retry-after": retryAfter } : {});
235
235
  };
236
- const unreachable = () => serverError("Zeno could not be reached", 502);
236
+ const unreachableResponse = () => serverError("Zeno could not be reached", 502);
237
237
  const fetchScript = async (visitorIp) => {
238
- const cached = agent;
239
- const path = cached ? `/script?${new URLSearchParams({ v: cached.etag })}` : "/script";
240
- const response = await call(path, { headers: {
241
- "auth-api-key": key,
242
- ...cached ? { "if-none-match": cached.etag } : {},
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
243
  ...visitorIp ? { "zeno-visitor-ip": visitorIp } : {}
244
244
  } });
245
- if (!response) return { failed: unreachable() };
246
- if (response.status !== 304 && !response.ok) return { failed: await passError(response, "/script") };
247
- const token = response.headers.get("zeno-challenge-token");
248
- const challengeToken = token ? JSON.stringify(token) : "undefined";
249
- if (response.status === 304) return cached ? {
250
- script: cached,
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
251
  challengeToken
252
252
  } : { failed: serverError("Zeno answered 304 for code this route never had") };
253
253
  const code = await response.text().catch(() => void 0);
254
- if (code === void 0) return { failed: unreachable() };
254
+ if (code === void 0) return { failed: unreachableResponse() };
255
255
  const etag = response.headers.get("etag");
256
- agent = etag ? {
256
+ heldScript = etag ? {
257
257
  etag,
258
258
  code
259
259
  } : void 0;
260
260
  return {
261
- script: agent ?? { code },
261
+ script: heldScript ?? { code },
262
262
  challengeToken
263
263
  };
264
264
  };
265
- const pageModule = async (request, ip) => {
265
+ const servePageModule = async (request, ip) => {
266
266
  const fetched = await fetchScript(ip);
267
267
  if (fetched.failed) return fetched.failed;
268
268
  const { script, challengeToken } = fetched;
269
- if (script.etag === void 0) return javascript(request, `${script.code}\nexport const challengeToken = ${challengeToken}\n`, "private, max-age=60");
270
- return javascript(request, pageCode(script.etag, challengeToken), "private, max-age=60");
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
271
  };
272
- const codeModule = async (request, version) => {
273
- let script = agent;
272
+ const serveCodeModule = async (request, version) => {
273
+ let script = heldScript;
274
274
  if (script?.etag !== version) {
275
275
  const fetched = await fetchScript(void 0);
276
276
  if (fetched.failed) return fetched.failed;
277
277
  script = fetched.script;
278
278
  }
279
- return javascript(request, script, script.etag === version ? "private, max-age=31536000, immutable" : "no-store");
279
+ return javascriptResponse(request, script, script.etag === version ? "private, max-age=31536000, immutable" : "no-store");
280
280
  };
281
- const get = (request, ip) => {
281
+ const handleGet = (request, ip) => {
282
282
  const version = new URL(request.url).searchParams.get("v");
283
- return version === null ? pageModule(request, ip) : codeModule(request, version);
283
+ return version === null ? servePageModule(request, ip) : serveCodeModule(request, version);
284
284
  };
285
- const post = async (request, ip, internal) => {
286
- if (!/^application\/json\s*(;|$)/i.test(request.headers.get("content-type") ?? "")) return invalid("The body must be JSON");
287
- if (request.headers.get("sec-fetch-site") === "cross-site") return invalid("Cross-site requests are refused");
288
- const text = await readCapped(request, MAX_BODY);
289
- if (text === void 0) return invalid("The body is larger than 128 KB");
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
290
  let payload;
291
291
  try {
292
- payload = JSON.parse(text);
292
+ payload = JSON.parse(bodyText);
293
293
  } catch {
294
- return invalid("The body is not valid JSON");
294
+ return invalidRequest("The body is not valid JSON");
295
295
  }
296
- if (!isObject(payload) || !isObject(payload.browserData)) return invalid("The body has no browserData");
296
+ if (!isObject(payload) || !isObject(payload.browserData)) return invalidRequest("The body has no browserData");
297
297
  if (!ip) {
298
298
  console.error(`The proxy route got no IP address: ${NO_IP}, or nodeHandler(zeno) on Node`);
299
299
  return serverError(NO_IP);
300
300
  }
301
- const pairs = headerPairs(request, rawHeadersOf(internal));
301
+ const pairs = toHeaderPairs(request, rawHeadersOf(internal));
302
302
  const visitorId = visitorIdOf(pairs);
303
303
  const envelope = {
304
304
  ...visitorId ? { visitorId } : {},
305
305
  ip,
306
- headers: forwardedHeaders(pairs),
306
+ headers: toForwardedHeaders(pairs),
307
307
  payload
308
308
  };
309
- const response = await call("/identify", {
309
+ const response = await callApi("/identify", {
310
310
  method: "POST",
311
311
  headers: {
312
- "auth-api-key": key,
312
+ "auth-api-key": activeApiKey,
313
313
  "content-type": "application/json"
314
314
  },
315
315
  body: JSON.stringify(envelope)
316
316
  });
317
- if (!response) return unreachable();
318
- if (!response.ok) return passError(response, "/identify");
317
+ if (!response) return unreachableResponse();
318
+ if (!response.ok) return passApiError(response, "/identify");
319
319
  const answer = await response.json().catch(() => void 0);
320
- if (!isObject(answer) || !isResult(answer.result)) {
320
+ if (!isObject(answer) || !isIdentifyResult(answer.result)) {
321
321
  console.error("Zeno's answer to the proxy route's identification couldn't be read");
322
322
  return serverError("Zeno's answer couldn't be read", 502);
323
323
  }
324
324
  const cookie = cookieOf(answer.cookie);
325
- return json(200, answer.result, cookie ? { "set-cookie": cookieHeader(new URL(request.url), cookie.value, cookie.maxAge, cookiePath) } : {});
325
+ return jsonResponse(200, answer.result, cookie ? { "set-cookie": toCookieHeader(new URL(request.url), cookie.value, cookie.maxAge, cookiePath) } : {});
326
326
  };
327
- const handler = async (request, given, internal) => {
327
+ const handler = async (request, givenIp, internal) => {
328
328
  const url = new URL(request.url);
329
329
  if (request.method === "POST" && url.searchParams.has("forget")) return new Response(null, {
330
330
  status: 204,
331
- headers: { "set-cookie": cookieHeader(url, "", 0, cookiePath) }
331
+ headers: { "set-cookie": toCookieHeader(url, "", 0, cookiePath) }
332
332
  });
333
333
  if (![
334
334
  "GET",
335
335
  "HEAD",
336
336
  "POST"
337
- ].includes(request.method)) return json(405, {
337
+ ].includes(request.method)) return jsonResponse(405, {
338
338
  error: "method_not_allowed",
339
339
  message: "Use GET or POST"
340
340
  }, { allow: "GET, HEAD, POST" });
341
- const settings = settingsOf("createProxy", apiKey, apiUrl);
341
+ const settings = checkApiSettings("createProxy", apiKey, apiUrl);
342
342
  if (settings.problem !== void 0) {
343
343
  console.error(settings.problem);
344
344
  return serverError("The proxy route isn't set up; its server log says what's missing");
345
345
  }
346
- key = settings.apiKey;
347
- base = settings.base;
348
- const ip = plainAddress(given);
349
- if (request.method === "POST") return post(request, ip, internal);
350
- const response = await get(request, ip);
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
351
  if (request.method === "HEAD") {
352
352
  await response.body?.cancel();
353
353
  return new Response(null, {
@@ -406,7 +406,7 @@ var ZenoError = class extends Error {
406
406
  this.name = "ZenoError";
407
407
  }
408
408
  };
409
- const required = (value, message) => {
409
+ const requireSecret = (value, message) => {
410
410
  if (!value) throw new TypeError(message);
411
411
  return value;
412
412
  };
@@ -416,7 +416,7 @@ const retryAfterOf = (header) => {
416
416
  return Number.isFinite(seconds) ? Math.min(Math.max(seconds, 0), 60) : void 0;
417
417
  };
418
418
  const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
419
- const segment = (name, value) => {
419
+ const toPathSegment = (name, value) => {
420
420
  if (typeof value !== "string" || !value || value === "." || value === "..") throw new ZenoError(0, "invalid_request", `${name} must be a non-empty string`);
421
421
  return encodeURIComponent(value);
422
422
  };
@@ -424,11 +424,11 @@ const isKind = (value, kind) => {
424
424
  if (kind === "array") return Array.isArray(value);
425
425
  return kind === "object" ? isObject(value) : typeof value === kind;
426
426
  };
427
- const shape = (name, fields) => ({
427
+ const defineShape = (name, fields) => ({
428
428
  name,
429
429
  is: (value) => isObject(value) && Object.entries(fields).every(([field, kind]) => isKind(value[field], kind))
430
430
  });
431
- const EVENT = shape("an event", {
431
+ const EVENT = defineShape("an event", {
432
432
  requestId: "string",
433
433
  visitorId: "string",
434
434
  ip: "string",
@@ -437,43 +437,44 @@ const EVENT = shape("an event", {
437
437
  signals: "object",
438
438
  verdict: "object"
439
439
  });
440
- const SEARCH = shape("a page of events", { items: "array" });
441
- const VISITOR = shape("a visitor", {
440
+ const SEARCH = defineShape("a page of events", { items: "array" });
441
+ const VISITOR = defineShape("a visitor", {
442
442
  visitorId: "string",
443
443
  externalIds: "array",
444
444
  externalIdCount: "number",
445
445
  recentEvents: "array"
446
446
  });
447
- const DELETED_VISITOR = shape("an erasure", {
447
+ const DELETED_VISITOR = defineShape("an erasure", {
448
448
  visitorId: "string",
449
449
  deletedEvents: "number"
450
450
  });
451
- const DELETED_EXTERNAL_ID = shape("an erasure", {
451
+ const DELETED_EXTERNAL_ID = defineShape("an erasure", {
452
452
  externalId: "string",
453
453
  deletedEvents: "number"
454
454
  });
455
- const RELATION = shape("a relation", {
455
+ const ADDED_RELATION = defineShape("a relation", {
456
456
  externalId: "string",
457
- type: "string"
457
+ type: "string",
458
+ linkWrite: "boolean"
458
459
  });
459
- const REMOVED = shape("a removal", { removed: "boolean" });
460
- const RELATED_VALUES = shape("a user's values", {
460
+ const REMOVED = defineShape("a removal", { removed: "boolean" });
461
+ const RELATED_VALUES = defineShape("a user's values", {
461
462
  externalId: "string",
462
463
  values: "array",
463
464
  truncated: "boolean"
464
465
  });
465
- const EXTERNAL_IDS = shape("a page of users", { items: "array" });
466
- const SHARED = shape("a page of shared values", { items: "array" });
467
- const RELATED = shape("related users", {
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", {
468
469
  externalId: "string",
469
470
  externalIds: "array",
470
471
  connections: "array"
471
472
  });
472
- const EMBED = shape("an embed", {
473
+ const EMBED = defineShape("an embed", {
473
474
  url: "string",
474
475
  expiresAt: "string"
475
476
  });
476
- const VERIFIED = shape("verify's answer", {
477
+ const VERIFIED = defineShape("verify's answer", {
477
478
  action: "string",
478
479
  reasons: "array"
479
480
  });
@@ -486,15 +487,15 @@ const VERIFIED = shape("verify's answer", {
486
487
  */
487
488
  const createClient = (apiKey, options = {}) => {
488
489
  const { apiUrl, fetch = globalThis.fetch } = options;
489
- const send = async (key, base, method, path, json) => {
490
+ const sendOnce = async (key, base, method, path, jsonBody) => {
490
491
  try {
491
492
  const response = await fetch(`${base}${path}`, {
492
493
  method,
493
494
  headers: {
494
495
  "auth-api-key": key,
495
- ...json ? { "content-type": "application/json" } : {}
496
+ ...jsonBody ? { "content-type": "application/json" } : {}
496
497
  },
497
- body: json,
498
+ body: jsonBody,
498
499
  signal: AbortSignal.timeout(TIMEOUT)
499
500
  });
500
501
  return {
@@ -505,12 +506,22 @@ const createClient = (apiKey, options = {}) => {
505
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)}`);
506
507
  }
507
508
  };
508
- const call = async (method, path, expected, body) => {
509
- const settings = settingsOf("createClient", apiKey, apiUrl);
509
+ const callApi = async (method, path, expected, body, isRepeatSafe = false) => {
510
+ const settings = checkApiSettings("createClient", apiKey, apiUrl);
510
511
  if (settings.problem !== void 0) throw new TypeError(settings.problem);
511
- const json = body && JSON.stringify(body);
512
+ const jsonBody = body && JSON.stringify(body);
512
513
  for (let attempt = 0;; attempt++) {
513
- const { response, text } = await send(settings.apiKey, settings.base, method, path, json);
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;
514
525
  let data;
515
526
  try {
516
527
  data = JSON.parse(text);
@@ -522,22 +533,22 @@ const createClient = (apiKey, options = {}) => {
522
533
  }
523
534
  const { error, message } = isObject(data) ? data : {};
524
535
  const code = typeof error === "string" ? error : void 0;
525
- const retryable = response.status === 429 || code === "search_unavailable";
526
- const retryAfter = retryable ? retryAfterOf(response.headers.get("retry-after")) : void 0;
527
- if (retryable && attempt < RETRIES) {
528
- const wait = retryAfter ?? 1;
529
- await sleep(wait + Math.random() * wait * .5);
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);
530
541
  continue;
531
542
  }
532
543
  throw new ZenoError(response.status, code ?? "request_failed", typeof message === "string" ? message : void 0, retryAfter);
533
544
  }
534
545
  };
535
- const withPage = (query, page) => {
546
+ const addPageParams = (query, page) => {
536
547
  for (const [key, item] of Object.entries(page)) if (item !== void 0) query.set(key, String(item));
537
548
  return query;
538
549
  };
539
550
  /** One event with its details and velocity. */
540
- const getEvent = async (requestId) => call("GET", `/events/${segment("requestId", requestId)}`, EVENT);
551
+ const getEvent = async (requestId) => callApi("GET", `/events/${toPathSegment("requestId", requestId)}`, EVENT);
541
552
  return {
542
553
  /**
543
554
  * Checks a request ID the browser sent with an action (a login, a signup, a checkout) and says what to do: `{
@@ -549,48 +560,51 @@ const createClient = (apiKey, options = {}) => {
549
560
  * seconds (`too-old`, 5 minutes by default) or belongs to another user than `externalId`
550
561
  * (`external-id-mismatch`); otherwise it answers the event's verdict. Call it after the action succeeded (the
551
562
  * password matched, the account exists), with the user's ID: `externalId` is attached to an event without one.
552
- * It writes nothing else. Other api errors throw.
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.
553
565
  */
554
566
  verify: async (requestId, options = {}) => {
555
- const { ip, externalId, maxAge } = options;
556
- return call("POST", "/verify", VERIFIED, {
567
+ const { ip, externalId, maxAge, idempotencyKey = crypto.randomUUID() } = options;
568
+ return callApi("POST", "/verify", VERIFIED, {
557
569
  requestId: requestId ?? void 0,
558
570
  ip: ip || void 0,
559
571
  externalId,
560
- maxAge
561
- });
572
+ maxAge,
573
+ idempotencyKey
574
+ }, true);
562
575
  },
563
576
  getEvent,
564
577
  /** Events matching every filter, newest first; pass the cursor back for the next page. */
565
578
  searchEvents: (filters = {}) => {
566
579
  const query = new URLSearchParams();
567
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));
568
- return call("GET", `/events?${query}`, SEARCH);
581
+ return callApi("GET", `/events?${query}`, SEARCH);
569
582
  },
570
583
  /** A visitor (a browser) with every external id seen with it. */
571
- getVisitor: async (visitorId) => call("GET", `/visitors/${segment("visitorId", visitorId)}`, VISITOR),
584
+ getVisitor: async (visitorId) => callApi("GET", `/visitors/${toPathSegment("visitorId", visitorId)}`, VISITOR),
572
585
  /** Deletes a visitor (a browser) and all its events. */
573
586
  deleteVisitor: async (visitorId) => {
574
- return call("DELETE", `/visitors/${segment("visitorId", visitorId)}`, DELETED_VISITOR);
587
+ return callApi("DELETE", `/visitors/${toPathSegment("visitorId", visitorId)}`, DELETED_VISITOR);
575
588
  },
576
589
  /** Deletes everything stored for one of your users: their events, and what relates them to devices and others. */
577
590
  deleteExternalId: (externalId) => {
578
591
  const query = new URLSearchParams({ externalId });
579
- return call("DELETE", `/external-ids?${query}`, DELETED_EXTERNAL_ID);
592
+ return callApi("DELETE", `/external-ids?${query}`, DELETED_EXTERNAL_ID);
580
593
  },
581
594
  /**
582
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
583
596
  * number, your own device id) or another of your users (a referral). Visitor ids only come from events with an
584
597
  * external id, so `identified` means the user was seen in a browser.
585
598
  *
586
- * Each call is billed like an identification, so once a spend limit you set is reached it throws a `402`
587
- * `spend_limit_reached` and adds nothing; only a `429` is sent again.
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.
588
602
  */
589
603
  addRelation: ({ at, ...relation }) => {
590
- const when = at instanceof Date || typeof at === "number" ? new Date(at).toISOString() : at;
591
- return call("POST", "/related", RELATION, {
604
+ const atIso = at instanceof Date || typeof at === "number" ? new Date(at).toISOString() : at;
605
+ return callApi("POST", "/related", ADDED_RELATION, {
592
606
  ...relation,
593
- ...when === void 0 ? {} : { at: when }
607
+ ...atIso === void 0 ? {} : { at: atIso }
594
608
  });
595
609
  },
596
610
  /**
@@ -601,7 +615,7 @@ const createClient = (apiKey, options = {}) => {
601
615
  */
602
616
  removeRelation: (relation) => {
603
617
  const query = new URLSearchParams(relation);
604
- return call("DELETE", `/related?${query}`, REMOVED);
618
+ return callApi("DELETE", `/related?${query}`, REMOVED);
605
619
  },
606
620
  /**
607
621
  * One of your users' values and relations, of one `type` or every type, each with its weight, and whether they
@@ -612,23 +626,23 @@ const createClient = (apiKey, options = {}) => {
612
626
  externalId,
613
627
  ...type ? { type } : {}
614
628
  });
615
- return call("GET", `/related/values?${query}`, RELATED_VALUES);
629
+ return callApi("GET", `/related/values?${query}`, RELATED_VALUES);
616
630
  },
617
631
  /**
618
632
  * Your users who have one value, like everyone with one phone number, 20 a page by default (`limit` up to 100);
619
633
  * pass the cursor back for the next page.
620
634
  */
621
635
  lookupRelated: (type, value, page = {}) => {
622
- const query = withPage(new URLSearchParams({
636
+ const query = addPageParams(new URLSearchParams({
623
637
  type,
624
638
  value
625
639
  }), page);
626
- return call("GET", `/related/lookup?${query}`, EXTERNAL_IDS);
640
+ return callApi("GET", `/related/lookup?${query}`, EXTERNAL_IDS);
627
641
  },
628
642
  /** The values of a type more than one of your users share, most shared first, with the type's weight. */
629
643
  getSharedValues: (type, page = {}) => {
630
- const query = withPage(new URLSearchParams({ type }), page);
631
- return call("GET", `/related/shared?${query}`, SHARED);
644
+ const query = addPageParams(new URLSearchParams({ type }), page);
645
+ return callApi("GET", `/related/shared?${query}`, SHARED);
632
646
  },
633
647
  /**
634
648
  * Your users related to one through shared values or relations of every type, or of one `type`, up to `depth`
@@ -640,7 +654,7 @@ const createClient = (apiKey, options = {}) => {
640
654
  ...type ? { type } : {},
641
655
  depth: String(depth)
642
656
  });
643
- return call("GET", `/related?${query}`, RELATED);
657
+ return callApi("GET", `/related?${query}`, RELATED);
644
658
  },
645
659
  /**
646
660
  * A link to one user's Related view (their values, related users and recent events) for your admin panel at
@@ -648,7 +662,7 @@ const createClient = (apiKey, options = {}) => {
648
662
  * the API key to the browser.
649
663
  */
650
664
  createEmbed: (embed) => {
651
- return call("POST", "/embeds", EMBED, embed);
665
+ return callApi("POST", "/embeds", EMBED, embed);
652
666
  }
653
667
  };
654
668
  };
@@ -660,8 +674,8 @@ const fromBase64 = (text) => {
660
674
  return;
661
675
  }
662
676
  };
663
- const hex = (bytes) => Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
664
- const sameBytes = (a, b) => {
677
+ const toHex = (bytes) => Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
678
+ const isSameBytes = (a, b) => {
665
679
  if (a.length !== b.length) return false;
666
680
  let difference = 0;
667
681
  for (let index = 0; index < a.length; index++) difference |= a[index] ^ b[index];
@@ -674,7 +688,7 @@ const sameBytes = (a, b) => {
674
688
  * signed body that isn't an event.
675
689
  */
676
690
  const verifyWebhook = async (body, header, secret, { tolerance = 300 } = {}) => {
677
- const key = required(secret, "verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)");
691
+ const webhookSecret = requireSecret(secret, "verifyWebhook needs the webhook secret, whsec_… (is it set in the environment?)");
678
692
  const parts = (header ?? "").split(",").map((part) => {
679
693
  const [name, ...value] = part.trim().split("=");
680
694
  return [name ?? "", value.join("=")];
@@ -682,12 +696,12 @@ const verifyWebhook = async (body, header, secret, { tolerance = 300 } = {}) =>
682
696
  const timestamp = Number(parts.find(([name]) => name === "t")?.[1]);
683
697
  const signatures = parts.filter(([name, value]) => name === "v1" && value).map(([, value]) => value);
684
698
  if (!Number.isInteger(timestamp) || signatures.length === 0 || Math.abs(Date.now() / 1e3 - timestamp) > tolerance) return;
685
- const hmac = await crypto.subtle.importKey("raw", encoder.encode(key), {
699
+ const hmac = await crypto.subtle.importKey("raw", encoder.encode(webhookSecret), {
686
700
  name: "HMAC",
687
701
  hash: "SHA-256"
688
702
  }, false, ["sign"]);
689
- const expected = encoder.encode(hex(await crypto.subtle.sign("HMAC", hmac, encoder.encode(`${timestamp}.${body}`))));
690
- if (!signatures.map((signature) => sameBytes(encoder.encode(signature), expected)).includes(true)) return;
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;
691
705
  let event;
692
706
  try {
693
707
  event = JSON.parse(body);
@@ -696,19 +710,19 @@ const verifyWebhook = async (body, header, secret, { tolerance = 300 } = {}) =>
696
710
  return event;
697
711
  };
698
712
  const UNSEAL_MAX_AGE = 300;
699
- const notFound = () => ({
713
+ const notFoundResult = () => ({
700
714
  action: "block",
701
715
  reasons: ["not-found"]
702
716
  });
703
717
  const MISSING_KEY = "unsealResult needs the project's encryption key as key (is it set in the environment?)";
704
718
  const keyBytesOf = (secret) => {
705
- const trimmed = required(secret, MISSING_KEY).trim();
706
- const keyBytes = /^[A-Za-z0-9+/]+={0,2}$/.test(trimmed) ? fromBase64(trimmed) : void 0;
719
+ const trimmedKey = requireSecret(secret, MISSING_KEY).trim();
720
+ const keyBytes = /^[A-Za-z0-9+/]+={0,2}$/.test(trimmedKey) ? fromBase64(trimmedKey) : void 0;
707
721
  if (!keyBytes) throw new TypeError("unsealResult's key isn't base64: pass the project's encryption key as the dashboard shows it");
708
- if (keyBytes.length !== 32) throw new TypeError(/^[0-9a-f]{64}$/i.test(trimmed) ? "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`);
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`);
709
723
  return keyBytes;
710
724
  };
711
- const openWith = async (keys, data) => {
725
+ const decryptWithAnyKey = async (keys, data) => {
712
726
  for (const keyBytes of keys) {
713
727
  const aes = await crypto.subtle.importKey("raw", keyBytes, "AES-GCM", false, ["decrypt"]);
714
728
  try {
@@ -731,31 +745,31 @@ const openWith = async (keys, data) => {
731
745
  * iv(12) | ciphertext | tag(16)), AES-256-GCM.
732
746
  */
733
747
  const unsealResult = async (sealed, options) => {
734
- const given = (Array.isArray(options?.key) ? options.key : [options?.key]).filter((key) => key);
735
- if (given.length === 0) throw new TypeError(MISSING_KEY);
736
- const keys = given.map(keyBytesOf);
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);
737
751
  if (!sealed) return {
738
752
  action: "challenge",
739
753
  reasons: ["no-request-id"]
740
754
  };
741
- if (typeof sealed !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(sealed.trim())) return notFound();
755
+ if (typeof sealed !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(sealed.trim())) return notFoundResult();
742
756
  const data = fromBase64(sealed.trim());
743
- if (!data || data.length < 30 || data[0] !== 1) return notFound();
744
- const plain = await openWith(keys, data);
745
- if (!plain) return notFound();
757
+ if (!data || data.length < 30 || data[0] !== 1) return notFoundResult();
758
+ const plainBytes = await decryptWithAnyKey(keys, data);
759
+ if (!plainBytes) return notFoundResult();
746
760
  let event;
747
761
  try {
748
- event = JSON.parse(new TextDecoder().decode(plain));
762
+ event = JSON.parse(new TextDecoder().decode(plainBytes));
749
763
  } catch {}
750
764
  if (!EVENT.is(event)) throw new Error("The sealed result opened but isn't an event; update zeno.id/server");
751
- const failed = [];
765
+ const failedChecks = [];
752
766
  const maxAge = options.maxAge ?? UNSEAL_MAX_AGE;
753
- if (options.ip && ipMismatch(event.ip, options.ip)) failed.push("ip-mismatch");
754
- if (Date.now() - Date.parse(event.createdAt) > maxAge * 1e3) failed.push("too-old");
755
- if (options.externalId !== void 0 && event.externalId !== void 0 && event.externalId !== options.externalId) failed.push("external-id-mismatch");
756
- if (failed.length > 0) return {
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 {
757
771
  action: "block",
758
- reasons: failed,
772
+ reasons: failedChecks,
759
773
  event
760
774
  };
761
775
  return {