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