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.
- package/README.md +9 -6
- 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/README.md
CHANGED
|
@@ -47,7 +47,7 @@ if (action === 'block') {
|
|
|
47
47
|
}
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
-
The package reads no option or secret from the environment: `createProxy(apiKey, options?)` and `createClient(apiKey, options?)` take the key from `process.env` or wherever your secrets live (`env` on Cloudflare Workers). It may be `undefined` where the route or client is made: neither fails at import or at build time, where the environment may be missing (Next.js collecting page data), and a call, or a request to the route, without it fails saying how to set it. Both know where the Zeno API is
|
|
50
|
+
The package reads no option or secret from the environment: `createProxy(apiKey, options?)` and `createClient(apiKey, options?)` take the key from `process.env` or wherever your secrets live (`env` on Cloudflare Workers). It may be `undefined` where the route or client is made: neither fails at import or at build time, where the environment may be missing (Next.js collecting page data), and a call, or a request to the route, without it fails saying how to set it. Both know where the Zeno API is, so there's no address to set.
|
|
51
51
|
|
|
52
52
|
## In the browser
|
|
53
53
|
|
|
@@ -56,10 +56,12 @@ Call `start()` on a page with an action you want to identify (a login, signup or
|
|
|
56
56
|
```ts
|
|
57
57
|
import { start } from 'zeno.id'
|
|
58
58
|
|
|
59
|
-
//
|
|
60
|
-
|
|
59
|
+
// Start as early as you can: it loads Zeno and starts reading the browser,
|
|
60
|
+
// so identify() is quick later (your proxy route's path)
|
|
61
|
+
const zeno = start('/zeno')
|
|
61
62
|
|
|
62
|
-
//
|
|
63
|
+
// Recognise the browser the moment the user logs in
|
|
64
|
+
// (never throws: requestId is undefined when nothing was identified)
|
|
63
65
|
const { requestId } = await zeno.identify({ action: 'login' })
|
|
64
66
|
|
|
65
67
|
const response = await fetch('/api/login', {
|
|
@@ -114,6 +116,8 @@ The script keeps no visitor id itself. The route keeps it in the `zeno_id` cooki
|
|
|
114
116
|
`zeno.stop()` ends identification for good, for a visitor who withdraws consent: an `identify()` in progress and every later one answer the `stopped` error, nothing more is collected or sent, and a `POST` to the route's `?forget` clears its cookie. A script still loading never starts: its module may finish downloading, but it isn't started. `forget(path)` does the same without loading or starting anything, and resolves once the route cleared the cookie (it rejects with `network_connection` or `server_error` when it couldn't, and `not_in_browser` on the server). Call `start()` again to identify once consent is back.
|
|
115
117
|
|
|
116
118
|
```ts
|
|
119
|
+
import { forget, start, type Zeno } from 'zeno.id'
|
|
120
|
+
|
|
117
121
|
let zeno: Zeno | undefined
|
|
118
122
|
|
|
119
123
|
consentTool.onChange(async ({ fraudPrevention }) => {
|
|
@@ -242,8 +246,8 @@ Bun.serve({
|
|
|
242
246
|
```
|
|
243
247
|
|
|
244
248
|
```ts
|
|
245
|
-
import { env } from 'cloudflare:workers'
|
|
246
249
|
// A Cloudflare Worker
|
|
250
|
+
import { env } from 'cloudflare:workers'
|
|
247
251
|
import { createProxy } from 'zeno.id/server'
|
|
248
252
|
|
|
249
253
|
// Your proxy route: the browser SDK talks to Zeno through it
|
|
@@ -262,7 +266,6 @@ The docs' quickstart has SvelteKit, Nuxt, React Router, SolidStart, Astro and Ho
|
|
|
262
266
|
| Option | |
|
|
263
267
|
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
264
268
|
| `cookiePath` | The path the browser calls the route on, when something in front of the handler rewrites it (the browser calls `/zeno`, a handler at `/api/proxy` answers); by default the request's. |
|
|
265
|
-
| `apiUrl` | Only for another Zeno API than the live one, like a staging deployment. |
|
|
266
269
|
|
|
267
270
|
The route forwards your visitors' headers by name only, apart from the values Zeno reads (`User-Agent`, `Origin`, `Signature-Agent`, `Signature-Input`), so your cookies and credentials never leave your server.
|
|
268
271
|
|
package/dist/index.cjs
CHANGED
|
@@ -28,21 +28,21 @@ var ZenoError = class extends Error {
|
|
|
28
28
|
const toZenoError = (error) => {
|
|
29
29
|
if (error instanceof ZenoError) return error;
|
|
30
30
|
const { name, code, message } = typeof error === "object" && error !== null ? error : {};
|
|
31
|
-
const
|
|
32
|
-
return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code,
|
|
31
|
+
const messageText = typeof message === "string" ? message : void 0;
|
|
32
|
+
return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, messageText) : new ZenoError("collection_failed", messageText);
|
|
33
33
|
};
|
|
34
34
|
//#endregion
|
|
35
35
|
//#region src/browser/csp.ts
|
|
36
36
|
const watchCsp = (origin) => {
|
|
37
|
-
let
|
|
37
|
+
let isBlocked = false;
|
|
38
38
|
const listener = (event) => {
|
|
39
|
-
if (event.blockedURI.startsWith(origin))
|
|
39
|
+
if (event.blockedURI.startsWith(origin)) isBlocked = true;
|
|
40
40
|
};
|
|
41
41
|
globalThis.document?.addEventListener("securitypolicyviolation", listener);
|
|
42
42
|
return {
|
|
43
|
-
|
|
43
|
+
errorFor: async (fallback, blockedMessage) => {
|
|
44
44
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
45
|
-
return
|
|
45
|
+
return isBlocked ? new ZenoError("csp_block", blockedMessage) : fallback;
|
|
46
46
|
},
|
|
47
47
|
stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
|
|
48
48
|
};
|
|
@@ -56,13 +56,13 @@ const importModule = (url) => import(
|
|
|
56
56
|
);
|
|
57
57
|
//#endregion
|
|
58
58
|
//#region src/browser/options.ts
|
|
59
|
-
const
|
|
59
|
+
const invalidOptions = (message) => new ZenoError("invalid_options", message);
|
|
60
60
|
const resolveEndpoint = (value) => {
|
|
61
61
|
if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
|
|
62
62
|
try {
|
|
63
|
-
const
|
|
64
|
-
const url = new URL(value,
|
|
65
|
-
return url.origin ===
|
|
63
|
+
const pageUrl = new URL(globalThis.location.href);
|
|
64
|
+
const url = new URL(value, pageUrl);
|
|
65
|
+
return url.origin === pageUrl.origin ? `${url.origin}${url.pathname}` : void 0;
|
|
66
66
|
} catch {
|
|
67
67
|
return;
|
|
68
68
|
}
|
|
@@ -70,20 +70,20 @@ const resolveEndpoint = (value) => {
|
|
|
70
70
|
const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
|
|
71
71
|
const checkProxyEndpoint = (path, call = "start") => {
|
|
72
72
|
const url = resolveEndpoint(path ?? "/zeno");
|
|
73
|
-
if (!url) throw
|
|
73
|
+
if (!url) throw invalidOptions(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
|
|
74
74
|
return url;
|
|
75
75
|
};
|
|
76
76
|
const checkIdentifyOptions = (options) => {
|
|
77
|
-
if (typeof options !== "object" || options === null) throw
|
|
77
|
+
if (typeof options !== "object" || options === null) throw invalidOptions("Pass the identify() options as an object: identify({ externalId, action })");
|
|
78
78
|
const { externalId, action, metadata } = options;
|
|
79
|
-
if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw
|
|
80
|
-
if (externalId === "." || externalId === "..") throw
|
|
81
|
-
if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw
|
|
82
|
-
if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw
|
|
79
|
+
if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalidOptions("externalId must be a string of 1 to 256 characters");
|
|
80
|
+
if (externalId === "." || externalId === "..") throw invalidOptions("externalId can’t be . or ..");
|
|
81
|
+
if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalidOptions("action must be a string of at most 1,024 characters");
|
|
82
|
+
if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalidOptions("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
|
|
83
83
|
};
|
|
84
84
|
//#endregion
|
|
85
85
|
//#region src/browser/storage.ts
|
|
86
|
-
const
|
|
86
|
+
const clearVisitorCookie = (endpoint) => {
|
|
87
87
|
return fetch(`${endpoint}?forget`, {
|
|
88
88
|
method: "POST",
|
|
89
89
|
credentials: "same-origin",
|
|
@@ -93,49 +93,49 @@ const forgetStored = (endpoint) => {
|
|
|
93
93
|
//#endregion
|
|
94
94
|
//#region src/browser/forget.ts
|
|
95
95
|
/**
|
|
96
|
-
* Has the route clear its visitor cookie
|
|
97
|
-
*
|
|
98
|
-
*
|
|
96
|
+
* Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
|
|
97
|
+
* page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
|
|
98
|
+
* cleared the cookie; on the server it rejects with `not_in_browser`.
|
|
99
99
|
*
|
|
100
100
|
* @param path The same path on this site you pass to `start()`, `/zeno` by default.
|
|
101
101
|
*/
|
|
102
102
|
const forget = async (path) => {
|
|
103
103
|
if (typeof document === "undefined") throw new ZenoError("not_in_browser");
|
|
104
104
|
const endpoint = checkProxyEndpoint(path, "forget");
|
|
105
|
-
const
|
|
105
|
+
const cspWatcher = watchCsp(new URL(endpoint).origin);
|
|
106
106
|
let response;
|
|
107
107
|
try {
|
|
108
|
-
response = await
|
|
108
|
+
response = await clearVisitorCookie(endpoint);
|
|
109
109
|
} catch {
|
|
110
|
-
throw await
|
|
110
|
+
throw await cspWatcher.errorFor(new ZenoError("network_connection"));
|
|
111
111
|
} finally {
|
|
112
|
-
|
|
112
|
+
cspWatcher.stop();
|
|
113
113
|
}
|
|
114
114
|
if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
|
|
115
115
|
};
|
|
116
116
|
//#endregion
|
|
117
117
|
//#region src/browser/index.ts
|
|
118
|
-
const withTimeout = (promise, ms,
|
|
118
|
+
const withTimeout = (promise, ms, makeError) => {
|
|
119
119
|
let timer;
|
|
120
120
|
return Promise.race([promise, new Promise((_, reject) => {
|
|
121
|
-
timer = setTimeout(() => reject(
|
|
121
|
+
timer = setTimeout(() => reject(makeError()), ms);
|
|
122
122
|
})]).finally(() => clearTimeout(timer));
|
|
123
123
|
};
|
|
124
|
-
const
|
|
124
|
+
const toFailedIdentification = (error) => ({
|
|
125
125
|
requestId: void 0,
|
|
126
126
|
error: toZenoError(error)
|
|
127
127
|
});
|
|
128
|
-
const
|
|
128
|
+
const withOwnError = (identification) => {
|
|
129
129
|
return identification.error ? {
|
|
130
130
|
...identification,
|
|
131
131
|
error: toZenoError(identification.error)
|
|
132
132
|
} : identification;
|
|
133
133
|
};
|
|
134
|
-
const
|
|
135
|
-
identify: () => Promise.resolve(
|
|
134
|
+
const makeServerStub = () => ({
|
|
135
|
+
identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
|
|
136
136
|
stop() {}
|
|
137
137
|
});
|
|
138
|
-
const
|
|
138
|
+
const makeChallengeTokenRefresh = (endpoint) => async () => {
|
|
139
139
|
try {
|
|
140
140
|
const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
|
|
141
141
|
return toChallengeToken(module?.challengeToken);
|
|
@@ -143,7 +143,7 @@ const refreshChallengeToken = (endpoint) => async () => {
|
|
|
143
143
|
return;
|
|
144
144
|
}
|
|
145
145
|
};
|
|
146
|
-
const
|
|
146
|
+
const explainLoadFailure = async (endpoint) => {
|
|
147
147
|
const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
|
|
148
148
|
try {
|
|
149
149
|
const response = await fetch(endpoint, { credentials: "same-origin" });
|
|
@@ -160,25 +160,25 @@ const loadFailure = async (endpoint) => {
|
|
|
160
160
|
return fallback;
|
|
161
161
|
}
|
|
162
162
|
};
|
|
163
|
-
const loadAgent = async (endpoint,
|
|
164
|
-
const
|
|
163
|
+
const loadAgent = async (endpoint, isStopped, onStarted) => {
|
|
164
|
+
const cspWatcher = watchCsp(new URL(endpoint).origin);
|
|
165
165
|
let module;
|
|
166
166
|
try {
|
|
167
167
|
module = await importModule(endpoint);
|
|
168
168
|
} catch {
|
|
169
|
-
const
|
|
170
|
-
throw
|
|
169
|
+
const importError = await cspWatcher.errorFor(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
|
|
170
|
+
throw importError.code === "csp_block" ? importError : await explainLoadFailure(endpoint);
|
|
171
171
|
} finally {
|
|
172
|
-
|
|
172
|
+
cspWatcher.stop();
|
|
173
173
|
}
|
|
174
|
-
if (
|
|
174
|
+
if (isStopped()) throw new ZenoError("stopped");
|
|
175
175
|
if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
|
|
176
176
|
try {
|
|
177
177
|
const agent = module.start(new URL(endpoint).pathname, {
|
|
178
178
|
challengeToken: toChallengeToken(module.challengeToken),
|
|
179
|
-
refreshChallengeToken:
|
|
179
|
+
refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
|
|
180
180
|
});
|
|
181
|
-
|
|
181
|
+
onStarted(agent);
|
|
182
182
|
return agent;
|
|
183
183
|
} catch (error) {
|
|
184
184
|
throw toZenoError(error);
|
|
@@ -191,39 +191,39 @@ const loadAgent = async (endpoint, stopped, started) => {
|
|
|
191
191
|
* fragment. The script loads from it and identifies through it.
|
|
192
192
|
*/
|
|
193
193
|
const start = (path) => {
|
|
194
|
-
if (typeof document === "undefined") return
|
|
194
|
+
if (typeof document === "undefined") return makeServerStub();
|
|
195
195
|
const endpoint = checkProxyEndpoint(path);
|
|
196
|
-
let
|
|
197
|
-
let
|
|
198
|
-
let
|
|
199
|
-
const
|
|
200
|
-
|
|
196
|
+
let isStopped = false;
|
|
197
|
+
let runningAgent;
|
|
198
|
+
let rejectOnStop = () => {};
|
|
199
|
+
const stopSignal = new Promise((_, reject) => {
|
|
200
|
+
rejectOnStop = reject;
|
|
201
201
|
});
|
|
202
|
-
|
|
203
|
-
const
|
|
204
|
-
|
|
202
|
+
stopSignal.catch(() => {});
|
|
203
|
+
const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
|
|
204
|
+
agentLoading.catch(() => {});
|
|
205
205
|
const identify = async (identifyOptions) => {
|
|
206
|
-
if (
|
|
206
|
+
if (isStopped) throw new ZenoError("stopped");
|
|
207
207
|
checkIdentifyOptions(identifyOptions);
|
|
208
208
|
const timeout = IDENTIFY_TIMEOUT;
|
|
209
|
-
const
|
|
210
|
-
const agent = await withTimeout(Promise.race([
|
|
211
|
-
const
|
|
212
|
-
if (
|
|
213
|
-
return
|
|
209
|
+
const startedAt = performance.now();
|
|
210
|
+
const agent = await withTimeout(Promise.race([agentLoading, stopSignal]), timeout, () => new ZenoError("client_timeout"));
|
|
211
|
+
const timeLeft = Math.max(1, timeout - (performance.now() - startedAt));
|
|
212
|
+
if (isStopped) throw new ZenoError("stopped");
|
|
213
|
+
return withOwnError(await agent.identify({
|
|
214
214
|
...identifyOptions,
|
|
215
|
-
timeout:
|
|
215
|
+
timeout: timeLeft
|
|
216
216
|
}));
|
|
217
217
|
};
|
|
218
218
|
return {
|
|
219
|
-
identify: (identifyOptions = {}) => identify(identifyOptions).catch(
|
|
219
|
+
identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
|
|
220
220
|
stop() {
|
|
221
|
-
if (!
|
|
222
|
-
|
|
223
|
-
|
|
221
|
+
if (!isStopped) {
|
|
222
|
+
isStopped = true;
|
|
223
|
+
rejectOnStop(new ZenoError("stopped"));
|
|
224
224
|
}
|
|
225
|
-
if (
|
|
226
|
-
else
|
|
225
|
+
if (runningAgent) runningAgent.stop();
|
|
226
|
+
else clearVisitorCookie(endpoint).catch(() => {});
|
|
227
227
|
}
|
|
228
228
|
};
|
|
229
229
|
};
|
package/dist/index.d.cts
CHANGED
|
@@ -67,9 +67,9 @@ type Zeno = {
|
|
|
67
67
|
//#endregion
|
|
68
68
|
//#region src/browser/forget.d.ts
|
|
69
69
|
/**
|
|
70
|
-
* Has the route clear its visitor cookie
|
|
71
|
-
*
|
|
72
|
-
*
|
|
70
|
+
* Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
|
|
71
|
+
* page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
|
|
72
|
+
* cleared the cookie; on the server it rejects with `not_in_browser`.
|
|
73
73
|
*
|
|
74
74
|
* @param path The same path on this site you pass to `start()`, `/zeno` by default.
|
|
75
75
|
*/
|
package/dist/index.d.ts
CHANGED
|
@@ -67,9 +67,9 @@ type Zeno = {
|
|
|
67
67
|
//#endregion
|
|
68
68
|
//#region src/browser/forget.d.ts
|
|
69
69
|
/**
|
|
70
|
-
* Has the route clear its visitor cookie
|
|
71
|
-
*
|
|
72
|
-
*
|
|
70
|
+
* Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
|
|
71
|
+
* page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
|
|
72
|
+
* cleared the cookie; on the server it rejects with `not_in_browser`.
|
|
73
73
|
*
|
|
74
74
|
* @param path The same path on this site you pass to `start()`, `/zeno` by default.
|
|
75
75
|
*/
|
package/dist/index.js
CHANGED
|
@@ -27,21 +27,21 @@ var ZenoError = class extends Error {
|
|
|
27
27
|
const toZenoError = (error) => {
|
|
28
28
|
if (error instanceof ZenoError) return error;
|
|
29
29
|
const { name, code, message } = typeof error === "object" && error !== null ? error : {};
|
|
30
|
-
const
|
|
31
|
-
return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code,
|
|
30
|
+
const messageText = typeof message === "string" ? message : void 0;
|
|
31
|
+
return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, messageText) : new ZenoError("collection_failed", messageText);
|
|
32
32
|
};
|
|
33
33
|
//#endregion
|
|
34
34
|
//#region src/browser/csp.ts
|
|
35
35
|
const watchCsp = (origin) => {
|
|
36
|
-
let
|
|
36
|
+
let isBlocked = false;
|
|
37
37
|
const listener = (event) => {
|
|
38
|
-
if (event.blockedURI.startsWith(origin))
|
|
38
|
+
if (event.blockedURI.startsWith(origin)) isBlocked = true;
|
|
39
39
|
};
|
|
40
40
|
globalThis.document?.addEventListener("securitypolicyviolation", listener);
|
|
41
41
|
return {
|
|
42
|
-
|
|
42
|
+
errorFor: async (fallback, blockedMessage) => {
|
|
43
43
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
44
|
-
return
|
|
44
|
+
return isBlocked ? new ZenoError("csp_block", blockedMessage) : fallback;
|
|
45
45
|
},
|
|
46
46
|
stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
|
|
47
47
|
};
|
|
@@ -55,13 +55,13 @@ const importModule = (url) => import(
|
|
|
55
55
|
);
|
|
56
56
|
//#endregion
|
|
57
57
|
//#region src/browser/options.ts
|
|
58
|
-
const
|
|
58
|
+
const invalidOptions = (message) => new ZenoError("invalid_options", message);
|
|
59
59
|
const resolveEndpoint = (value) => {
|
|
60
60
|
if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
|
|
61
61
|
try {
|
|
62
|
-
const
|
|
63
|
-
const url = new URL(value,
|
|
64
|
-
return url.origin ===
|
|
62
|
+
const pageUrl = new URL(globalThis.location.href);
|
|
63
|
+
const url = new URL(value, pageUrl);
|
|
64
|
+
return url.origin === pageUrl.origin ? `${url.origin}${url.pathname}` : void 0;
|
|
65
65
|
} catch {
|
|
66
66
|
return;
|
|
67
67
|
}
|
|
@@ -69,20 +69,20 @@ const resolveEndpoint = (value) => {
|
|
|
69
69
|
const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
|
|
70
70
|
const checkProxyEndpoint = (path, call = "start") => {
|
|
71
71
|
const url = resolveEndpoint(path ?? "/zeno");
|
|
72
|
-
if (!url) throw
|
|
72
|
+
if (!url) throw invalidOptions(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
|
|
73
73
|
return url;
|
|
74
74
|
};
|
|
75
75
|
const checkIdentifyOptions = (options) => {
|
|
76
|
-
if (typeof options !== "object" || options === null) throw
|
|
76
|
+
if (typeof options !== "object" || options === null) throw invalidOptions("Pass the identify() options as an object: identify({ externalId, action })");
|
|
77
77
|
const { externalId, action, metadata } = options;
|
|
78
|
-
if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw
|
|
79
|
-
if (externalId === "." || externalId === "..") throw
|
|
80
|
-
if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw
|
|
81
|
-
if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw
|
|
78
|
+
if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalidOptions("externalId must be a string of 1 to 256 characters");
|
|
79
|
+
if (externalId === "." || externalId === "..") throw invalidOptions("externalId can’t be . or ..");
|
|
80
|
+
if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalidOptions("action must be a string of at most 1,024 characters");
|
|
81
|
+
if (metadata !== void 0 && (typeof metadata !== "object" || metadata === null || Array.isArray(metadata))) throw invalidOptions("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
|
|
82
82
|
};
|
|
83
83
|
//#endregion
|
|
84
84
|
//#region src/browser/storage.ts
|
|
85
|
-
const
|
|
85
|
+
const clearVisitorCookie = (endpoint) => {
|
|
86
86
|
return fetch(`${endpoint}?forget`, {
|
|
87
87
|
method: "POST",
|
|
88
88
|
credentials: "same-origin",
|
|
@@ -92,49 +92,49 @@ const forgetStored = (endpoint) => {
|
|
|
92
92
|
//#endregion
|
|
93
93
|
//#region src/browser/forget.ts
|
|
94
94
|
/**
|
|
95
|
-
* Has the route clear its visitor cookie
|
|
96
|
-
*
|
|
97
|
-
*
|
|
95
|
+
* Has the route clear its visitor cookie without loading or starting anything, for a visitor who withdraws consent on a
|
|
96
|
+
* page that never called `start()` (`stop()` on a started one does the same and stops it). Resolves once the route
|
|
97
|
+
* cleared the cookie; on the server it rejects with `not_in_browser`.
|
|
98
98
|
*
|
|
99
99
|
* @param path The same path on this site you pass to `start()`, `/zeno` by default.
|
|
100
100
|
*/
|
|
101
101
|
const forget = async (path) => {
|
|
102
102
|
if (typeof document === "undefined") throw new ZenoError("not_in_browser");
|
|
103
103
|
const endpoint = checkProxyEndpoint(path, "forget");
|
|
104
|
-
const
|
|
104
|
+
const cspWatcher = watchCsp(new URL(endpoint).origin);
|
|
105
105
|
let response;
|
|
106
106
|
try {
|
|
107
|
-
response = await
|
|
107
|
+
response = await clearVisitorCookie(endpoint);
|
|
108
108
|
} catch {
|
|
109
|
-
throw await
|
|
109
|
+
throw await cspWatcher.errorFor(new ZenoError("network_connection"));
|
|
110
110
|
} finally {
|
|
111
|
-
|
|
111
|
+
cspWatcher.stop();
|
|
112
112
|
}
|
|
113
113
|
if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
|
|
114
114
|
};
|
|
115
115
|
//#endregion
|
|
116
116
|
//#region src/browser/index.ts
|
|
117
|
-
const withTimeout = (promise, ms,
|
|
117
|
+
const withTimeout = (promise, ms, makeError) => {
|
|
118
118
|
let timer;
|
|
119
119
|
return Promise.race([promise, new Promise((_, reject) => {
|
|
120
|
-
timer = setTimeout(() => reject(
|
|
120
|
+
timer = setTimeout(() => reject(makeError()), ms);
|
|
121
121
|
})]).finally(() => clearTimeout(timer));
|
|
122
122
|
};
|
|
123
|
-
const
|
|
123
|
+
const toFailedIdentification = (error) => ({
|
|
124
124
|
requestId: void 0,
|
|
125
125
|
error: toZenoError(error)
|
|
126
126
|
});
|
|
127
|
-
const
|
|
127
|
+
const withOwnError = (identification) => {
|
|
128
128
|
return identification.error ? {
|
|
129
129
|
...identification,
|
|
130
130
|
error: toZenoError(identification.error)
|
|
131
131
|
} : identification;
|
|
132
132
|
};
|
|
133
|
-
const
|
|
134
|
-
identify: () => Promise.resolve(
|
|
133
|
+
const makeServerStub = () => ({
|
|
134
|
+
identify: () => Promise.resolve(toFailedIdentification(new ZenoError("not_in_browser"))),
|
|
135
135
|
stop() {}
|
|
136
136
|
});
|
|
137
|
-
const
|
|
137
|
+
const makeChallengeTokenRefresh = (endpoint) => async () => {
|
|
138
138
|
try {
|
|
139
139
|
const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
|
|
140
140
|
return toChallengeToken(module?.challengeToken);
|
|
@@ -142,7 +142,7 @@ const refreshChallengeToken = (endpoint) => async () => {
|
|
|
142
142
|
return;
|
|
143
143
|
}
|
|
144
144
|
};
|
|
145
|
-
const
|
|
145
|
+
const explainLoadFailure = async (endpoint) => {
|
|
146
146
|
const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
|
|
147
147
|
try {
|
|
148
148
|
const response = await fetch(endpoint, { credentials: "same-origin" });
|
|
@@ -159,25 +159,25 @@ const loadFailure = async (endpoint) => {
|
|
|
159
159
|
return fallback;
|
|
160
160
|
}
|
|
161
161
|
};
|
|
162
|
-
const loadAgent = async (endpoint,
|
|
163
|
-
const
|
|
162
|
+
const loadAgent = async (endpoint, isStopped, onStarted) => {
|
|
163
|
+
const cspWatcher = watchCsp(new URL(endpoint).origin);
|
|
164
164
|
let module;
|
|
165
165
|
try {
|
|
166
166
|
module = await importModule(endpoint);
|
|
167
167
|
} catch {
|
|
168
|
-
const
|
|
169
|
-
throw
|
|
168
|
+
const importError = await cspWatcher.errorFor(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
|
|
169
|
+
throw importError.code === "csp_block" ? importError : await explainLoadFailure(endpoint);
|
|
170
170
|
} finally {
|
|
171
|
-
|
|
171
|
+
cspWatcher.stop();
|
|
172
172
|
}
|
|
173
|
-
if (
|
|
173
|
+
if (isStopped()) throw new ZenoError("stopped");
|
|
174
174
|
if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
|
|
175
175
|
try {
|
|
176
176
|
const agent = module.start(new URL(endpoint).pathname, {
|
|
177
177
|
challengeToken: toChallengeToken(module.challengeToken),
|
|
178
|
-
refreshChallengeToken:
|
|
178
|
+
refreshChallengeToken: makeChallengeTokenRefresh(endpoint)
|
|
179
179
|
});
|
|
180
|
-
|
|
180
|
+
onStarted(agent);
|
|
181
181
|
return agent;
|
|
182
182
|
} catch (error) {
|
|
183
183
|
throw toZenoError(error);
|
|
@@ -190,39 +190,39 @@ const loadAgent = async (endpoint, stopped, started) => {
|
|
|
190
190
|
* fragment. The script loads from it and identifies through it.
|
|
191
191
|
*/
|
|
192
192
|
const start = (path) => {
|
|
193
|
-
if (typeof document === "undefined") return
|
|
193
|
+
if (typeof document === "undefined") return makeServerStub();
|
|
194
194
|
const endpoint = checkProxyEndpoint(path);
|
|
195
|
-
let
|
|
196
|
-
let
|
|
197
|
-
let
|
|
198
|
-
const
|
|
199
|
-
|
|
195
|
+
let isStopped = false;
|
|
196
|
+
let runningAgent;
|
|
197
|
+
let rejectOnStop = () => {};
|
|
198
|
+
const stopSignal = new Promise((_, reject) => {
|
|
199
|
+
rejectOnStop = reject;
|
|
200
200
|
});
|
|
201
|
-
|
|
202
|
-
const
|
|
203
|
-
|
|
201
|
+
stopSignal.catch(() => {});
|
|
202
|
+
const agentLoading = loadAgent(endpoint, () => isStopped, (agent) => runningAgent = agent);
|
|
203
|
+
agentLoading.catch(() => {});
|
|
204
204
|
const identify = async (identifyOptions) => {
|
|
205
|
-
if (
|
|
205
|
+
if (isStopped) throw new ZenoError("stopped");
|
|
206
206
|
checkIdentifyOptions(identifyOptions);
|
|
207
207
|
const timeout = IDENTIFY_TIMEOUT;
|
|
208
|
-
const
|
|
209
|
-
const agent = await withTimeout(Promise.race([
|
|
210
|
-
const
|
|
211
|
-
if (
|
|
212
|
-
return
|
|
208
|
+
const startedAt = performance.now();
|
|
209
|
+
const agent = await withTimeout(Promise.race([agentLoading, stopSignal]), timeout, () => new ZenoError("client_timeout"));
|
|
210
|
+
const timeLeft = Math.max(1, timeout - (performance.now() - startedAt));
|
|
211
|
+
if (isStopped) throw new ZenoError("stopped");
|
|
212
|
+
return withOwnError(await agent.identify({
|
|
213
213
|
...identifyOptions,
|
|
214
|
-
timeout:
|
|
214
|
+
timeout: timeLeft
|
|
215
215
|
}));
|
|
216
216
|
};
|
|
217
217
|
return {
|
|
218
|
-
identify: (identifyOptions = {}) => identify(identifyOptions).catch(
|
|
218
|
+
identify: (identifyOptions = {}) => identify(identifyOptions).catch(toFailedIdentification),
|
|
219
219
|
stop() {
|
|
220
|
-
if (!
|
|
221
|
-
|
|
222
|
-
|
|
220
|
+
if (!isStopped) {
|
|
221
|
+
isStopped = true;
|
|
222
|
+
rejectOnStop(new ZenoError("stopped"));
|
|
223
223
|
}
|
|
224
|
-
if (
|
|
225
|
-
else
|
|
224
|
+
if (runningAgent) runningAgent.stop();
|
|
225
|
+
else clearVisitorCookie(endpoint).catch(() => {});
|
|
226
226
|
}
|
|
227
227
|
};
|
|
228
228
|
};
|