zeno.id 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +404 -2
- package/dist/index.cjs +233 -0
- package/dist/index.d.cts +87 -0
- package/dist/index.d.ts +87 -0
- package/dist/index.js +230 -0
- package/dist/server/index.cjs +773 -0
- package/dist/server/index.d.cts +606 -0
- package/dist/server/index.d.ts +606 -0
- package/dist/server/index.js +767 -0
- package/dist/server/node.cjs +88 -0
- package/dist/server/node.d.cts +21 -0
- package/dist/server/node.d.ts +21 -0
- package/dist/server/node.js +87 -0
- package/dist/server/proxy-CUZ-Jwgy.d.cts +36 -0
- package/dist/server/proxy-CUZ-Jwgy.d.ts +36 -0
- package/package.json +69 -5
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const IDENTIFY_TIMEOUT = 1e4;
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region src/browser/error.ts
|
|
5
|
+
const messages = {
|
|
6
|
+
client_timeout: "Client timeout",
|
|
7
|
+
network_connection: "Network connection error",
|
|
8
|
+
csp_block: "Blocked by the Content Security Policy",
|
|
9
|
+
insecure_context: "Zeno needs a secure context (https)",
|
|
10
|
+
collection_failed: "Collecting the browser data failed",
|
|
11
|
+
invalid_options: "The options are invalid",
|
|
12
|
+
server_error: "The identification api failed",
|
|
13
|
+
account_closed: "The project's organization is closed; contact Zeno support to reopen it",
|
|
14
|
+
script_load_failed: "The script couldn't be loaded from the endpoint",
|
|
15
|
+
stopped: "Identification was stopped; call start() again to identify",
|
|
16
|
+
capped: "Nothing was identified: a spend limit or rate limit was reached",
|
|
17
|
+
not_in_browser: "Zeno identifies in the browser only; this ran on the server"
|
|
18
|
+
};
|
|
19
|
+
const REFUSED_KEY = "The proxy route's API key was refused: check the API key the route on your server is set up with";
|
|
20
|
+
var ZenoError = class extends Error {
|
|
21
|
+
code;
|
|
22
|
+
constructor(code, message) {
|
|
23
|
+
super(message ?? messages[code]);
|
|
24
|
+
this.code = code;
|
|
25
|
+
this.name = "ZenoError";
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
const toZenoError = (error) => {
|
|
29
|
+
if (error instanceof ZenoError) return error;
|
|
30
|
+
const { name, code, message } = typeof error === "object" && error !== null ? error : {};
|
|
31
|
+
const text = typeof message === "string" ? message : void 0;
|
|
32
|
+
return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, text) : new ZenoError("collection_failed", text);
|
|
33
|
+
};
|
|
34
|
+
//#endregion
|
|
35
|
+
//#region src/browser/csp.ts
|
|
36
|
+
const watchCsp = (origin) => {
|
|
37
|
+
let blocked = false;
|
|
38
|
+
const listener = (event) => {
|
|
39
|
+
if (event.blockedURI.startsWith(origin)) blocked = true;
|
|
40
|
+
};
|
|
41
|
+
globalThis.document?.addEventListener("securitypolicyviolation", listener);
|
|
42
|
+
return {
|
|
43
|
+
failure: async (otherwise, blockedMessage) => {
|
|
44
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
45
|
+
return blocked ? new ZenoError("csp_block", blockedMessage) : otherwise;
|
|
46
|
+
},
|
|
47
|
+
stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/browser/import.ts
|
|
52
|
+
const importModule = (url) => import(
|
|
53
|
+
/* @vite-ignore */
|
|
54
|
+
/* webpackIgnore: true */
|
|
55
|
+
url
|
|
56
|
+
);
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/browser/options.ts
|
|
59
|
+
const invalid = (message) => new ZenoError("invalid_options", message);
|
|
60
|
+
const resolveEndpoint = (value) => {
|
|
61
|
+
if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
|
|
62
|
+
try {
|
|
63
|
+
const page = new URL(globalThis.location.href);
|
|
64
|
+
const url = new URL(value, page);
|
|
65
|
+
return url.origin === page.origin ? `${url.origin}${url.pathname}` : void 0;
|
|
66
|
+
} catch {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
|
|
71
|
+
const checkProxyEndpoint = (path, call = "start") => {
|
|
72
|
+
const url = resolveEndpoint(path ?? "/zeno");
|
|
73
|
+
if (!url) throw invalid(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
|
|
74
|
+
return url;
|
|
75
|
+
};
|
|
76
|
+
const checkIdentifyOptions = (options) => {
|
|
77
|
+
if (typeof options !== "object" || options === null) throw invalid("Pass the identify() options as an object: identify({ externalId, action })");
|
|
78
|
+
const { externalId, action, metadata } = options;
|
|
79
|
+
if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalid("externalId must be a string of 1 to 256 characters");
|
|
80
|
+
if (externalId === "." || externalId === "..") throw invalid("externalId can’t be . or ..");
|
|
81
|
+
if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalid("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 invalid("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
|
|
83
|
+
};
|
|
84
|
+
//#endregion
|
|
85
|
+
//#region src/browser/storage.ts
|
|
86
|
+
const forgetStored = (endpoint) => {
|
|
87
|
+
return fetch(`${endpoint}?forget`, {
|
|
88
|
+
method: "POST",
|
|
89
|
+
credentials: "same-origin",
|
|
90
|
+
keepalive: true
|
|
91
|
+
});
|
|
92
|
+
};
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/browser/forget.ts
|
|
95
|
+
/**
|
|
96
|
+
* Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
|
|
97
|
+
* withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
|
|
98
|
+
* stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
|
|
99
|
+
*
|
|
100
|
+
* @param path The same path on this site you pass to `start()`, `/zeno` by default.
|
|
101
|
+
*/
|
|
102
|
+
const forget = async (path) => {
|
|
103
|
+
if (typeof document === "undefined") throw new ZenoError("not_in_browser");
|
|
104
|
+
const endpoint = checkProxyEndpoint(path, "forget");
|
|
105
|
+
const csp = watchCsp(new URL(endpoint).origin);
|
|
106
|
+
let response;
|
|
107
|
+
try {
|
|
108
|
+
response = await forgetStored(endpoint);
|
|
109
|
+
} catch {
|
|
110
|
+
throw await csp.failure(new ZenoError("network_connection"));
|
|
111
|
+
} finally {
|
|
112
|
+
csp.stop();
|
|
113
|
+
}
|
|
114
|
+
if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
|
|
115
|
+
};
|
|
116
|
+
//#endregion
|
|
117
|
+
//#region src/browser/index.ts
|
|
118
|
+
const withTimeout = (promise, ms, error) => {
|
|
119
|
+
let timer;
|
|
120
|
+
return Promise.race([promise, new Promise((_, reject) => {
|
|
121
|
+
timer = setTimeout(() => reject(error()), ms);
|
|
122
|
+
})]).finally(() => clearTimeout(timer));
|
|
123
|
+
};
|
|
124
|
+
const failed = (error) => ({
|
|
125
|
+
requestId: void 0,
|
|
126
|
+
error: toZenoError(error)
|
|
127
|
+
});
|
|
128
|
+
const ownAnswer = (identification) => {
|
|
129
|
+
return identification.error ? {
|
|
130
|
+
...identification,
|
|
131
|
+
error: toZenoError(identification.error)
|
|
132
|
+
} : identification;
|
|
133
|
+
};
|
|
134
|
+
const onServer = () => ({
|
|
135
|
+
identify: () => Promise.resolve(failed(new ZenoError("not_in_browser"))),
|
|
136
|
+
stop() {}
|
|
137
|
+
});
|
|
138
|
+
const refreshChallengeToken = (endpoint) => async () => {
|
|
139
|
+
try {
|
|
140
|
+
const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
|
|
141
|
+
return toChallengeToken(module?.challengeToken);
|
|
142
|
+
} catch {
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
const loadFailure = async (endpoint) => {
|
|
147
|
+
const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
|
|
148
|
+
try {
|
|
149
|
+
const response = await fetch(endpoint, { credentials: "same-origin" });
|
|
150
|
+
if (response.ok) {
|
|
151
|
+
await response.body?.cancel();
|
|
152
|
+
return /javascript/i.test(response.headers.get("content-type") ?? "") ? fallback : new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
|
|
153
|
+
}
|
|
154
|
+
const body = await response.json().catch(() => void 0);
|
|
155
|
+
const code = typeof body?.error === "string" ? body.error : void 0;
|
|
156
|
+
if (code === "invalid_api_key") return new ZenoError("server_error", REFUSED_KEY);
|
|
157
|
+
if (code === "account_closed") return new ZenoError("account_closed");
|
|
158
|
+
return code || response.status >= 500 ? new ZenoError("server_error", `The route at ${endpoint} answered ${response.status}${code ? ` ${code}` : ""} for the script`) : new ZenoError("script_load_failed", `The route at ${endpoint} answered ${response.status}: check that your proxy route answers there`);
|
|
159
|
+
} catch {
|
|
160
|
+
return fallback;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
const loadAgent = async (endpoint, stopped, started) => {
|
|
164
|
+
const csp = watchCsp(new URL(endpoint).origin);
|
|
165
|
+
let module;
|
|
166
|
+
try {
|
|
167
|
+
module = await importModule(endpoint);
|
|
168
|
+
} catch {
|
|
169
|
+
const blocked = await csp.failure(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
|
|
170
|
+
throw blocked.code === "csp_block" ? blocked : await loadFailure(endpoint);
|
|
171
|
+
} finally {
|
|
172
|
+
csp.stop();
|
|
173
|
+
}
|
|
174
|
+
if (stopped()) throw new ZenoError("stopped");
|
|
175
|
+
if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
|
|
176
|
+
try {
|
|
177
|
+
const agent = module.start(new URL(endpoint).pathname, {
|
|
178
|
+
challengeToken: toChallengeToken(module.challengeToken),
|
|
179
|
+
refreshChallengeToken: refreshChallengeToken(endpoint)
|
|
180
|
+
});
|
|
181
|
+
started(agent);
|
|
182
|
+
return agent;
|
|
183
|
+
} catch (error) {
|
|
184
|
+
throw toZenoError(error);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
|
|
189
|
+
*
|
|
190
|
+
* @param path The path on this site you mounted `createProxy` at, `/zeno` by default, without a query string or
|
|
191
|
+
* fragment. The script loads from it and identifies through it.
|
|
192
|
+
*/
|
|
193
|
+
const start = (path) => {
|
|
194
|
+
if (typeof document === "undefined") return onServer();
|
|
195
|
+
const endpoint = checkProxyEndpoint(path);
|
|
196
|
+
let stopped = false;
|
|
197
|
+
let running;
|
|
198
|
+
let rejectStopped = () => {};
|
|
199
|
+
const stopping = new Promise((_, reject) => {
|
|
200
|
+
rejectStopped = reject;
|
|
201
|
+
});
|
|
202
|
+
stopping.catch(() => {});
|
|
203
|
+
const loaded = loadAgent(endpoint, () => stopped, (agent) => running = agent);
|
|
204
|
+
loaded.catch(() => {});
|
|
205
|
+
const identify = async (identifyOptions) => {
|
|
206
|
+
if (stopped) throw new ZenoError("stopped");
|
|
207
|
+
checkIdentifyOptions(identifyOptions);
|
|
208
|
+
const timeout = IDENTIFY_TIMEOUT;
|
|
209
|
+
const started = performance.now();
|
|
210
|
+
const agent = await withTimeout(Promise.race([loaded, stopping]), timeout, () => new ZenoError("client_timeout"));
|
|
211
|
+
const left = Math.max(1, timeout - (performance.now() - started));
|
|
212
|
+
if (stopped) throw new ZenoError("stopped");
|
|
213
|
+
return ownAnswer(await agent.identify({
|
|
214
|
+
...identifyOptions,
|
|
215
|
+
timeout: left
|
|
216
|
+
}));
|
|
217
|
+
};
|
|
218
|
+
return {
|
|
219
|
+
identify: (identifyOptions = {}) => identify(identifyOptions).catch(failed),
|
|
220
|
+
stop() {
|
|
221
|
+
if (!stopped) {
|
|
222
|
+
stopped = true;
|
|
223
|
+
rejectStopped(new ZenoError("stopped"));
|
|
224
|
+
}
|
|
225
|
+
if (running) running.stop();
|
|
226
|
+
else forgetStored(endpoint).catch(() => {});
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
};
|
|
230
|
+
//#endregion
|
|
231
|
+
exports.ZenoError = ZenoError;
|
|
232
|
+
exports.forget = forget;
|
|
233
|
+
exports.start = start;
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
//#region src/browser/error.d.ts
|
|
2
|
+
type ZenoErrorCode = 'client_timeout' | 'network_connection' | 'csp_block' | 'insecure_context' | 'collection_failed' | 'invalid_options' | 'server_error' | 'account_closed' | 'script_load_failed' | 'stopped' | 'capped' | 'not_in_browser';
|
|
3
|
+
declare class ZenoError extends Error {
|
|
4
|
+
readonly code: ZenoErrorCode;
|
|
5
|
+
constructor(code: ZenoErrorCode, message?: string);
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/browser/types.d.ts
|
|
9
|
+
/** Values a metadata key can hold; nothing nested. */
|
|
10
|
+
type Metadata = Record<string, string | number | boolean>;
|
|
11
|
+
type IdentifyOptions = {
|
|
12
|
+
/**
|
|
13
|
+
* Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 characters;
|
|
14
|
+
* anything else is refused with `invalid_options` before anything is sent.
|
|
15
|
+
*/
|
|
16
|
+
externalId?: string;
|
|
17
|
+
/** What the visitor is doing, like `login`, `signup` or `checkout`, up to 1,024 characters. */
|
|
18
|
+
action?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Your own key-values kept with the event, like `{ orderId: 'A-1042', plan: 'pro' }`: at most 20 keys of 1 to 40
|
|
21
|
+
* letters, digits, `_`, `.` or `-`; text values up to 256 characters, numbers or booleans; 2 KB as JSON. Returned
|
|
22
|
+
* with the event by the server api, never used for detection.
|
|
23
|
+
*/
|
|
24
|
+
metadata?: Metadata;
|
|
25
|
+
};
|
|
26
|
+
type Identification = {
|
|
27
|
+
/** Left out when the project runs in zero trust mode: only your backend learns the visitor. */
|
|
28
|
+
visitorId?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Send it to your server with the action, where `verify` from `zeno.id/server` says to allow, challenge or
|
|
31
|
+
* block.
|
|
32
|
+
*/
|
|
33
|
+
requestId: string;
|
|
34
|
+
/** Whether the api had seen this visitor before; left out in zero trust mode. */
|
|
35
|
+
returning?: boolean;
|
|
36
|
+
/** The event encrypted with the project's key, when the project seals results. */
|
|
37
|
+
sealedResult?: string;
|
|
38
|
+
error?: undefined;
|
|
39
|
+
} | {
|
|
40
|
+
/**
|
|
41
|
+
* Nothing was identified: send the action on without a request ID, and your server's `verify` answers
|
|
42
|
+
* `challenge` with `no-request-id` (a bot that skips the script sends none either), so it decides.
|
|
43
|
+
*/
|
|
44
|
+
requestId?: undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Why, by its `code`: a failure, `stopped`, `not_in_browser` on the server, or `capped` (a spend limit you
|
|
47
|
+
* set, the key's ceiling or the visitor ip's rate limit; not a bot).
|
|
48
|
+
*/
|
|
49
|
+
error: ZenoError;
|
|
50
|
+
visitorId?: undefined;
|
|
51
|
+
returning?: undefined;
|
|
52
|
+
sealedResult?: undefined;
|
|
53
|
+
};
|
|
54
|
+
type Zeno = {
|
|
55
|
+
/**
|
|
56
|
+
* Identifies the browser: sends the report through the proxy route and answers the request ID. It never rejects:
|
|
57
|
+
* when nothing was identified it resolves `{ requestId: undefined, error }`.
|
|
58
|
+
*/
|
|
59
|
+
identify(options?: IdentifyOptions): Promise<Identification>;
|
|
60
|
+
/**
|
|
61
|
+
* Stops identifying for good, as when the visitor withdraws consent: nothing more is collected or sent, an
|
|
62
|
+
* identify() in progress and every later one answer the `stopped` error, and the route is asked to clear its
|
|
63
|
+
* visitor cookie. A script still loading never starts. Call start() again to identify once consent is given again.
|
|
64
|
+
*/
|
|
65
|
+
stop(): void;
|
|
66
|
+
};
|
|
67
|
+
//#endregion
|
|
68
|
+
//#region src/browser/forget.d.ts
|
|
69
|
+
/**
|
|
70
|
+
* Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
|
|
71
|
+
* withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
|
|
72
|
+
* stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
|
|
73
|
+
*
|
|
74
|
+
* @param path The same path on this site you pass to `start()`, `/zeno` by default.
|
|
75
|
+
*/
|
|
76
|
+
declare const forget: (path?: string) => Promise<void>;
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/browser/index.d.ts
|
|
79
|
+
/**
|
|
80
|
+
* Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
|
|
81
|
+
*
|
|
82
|
+
* @param path The path on this site you mounted `createProxy` at, `/zeno` by default, without a query string or
|
|
83
|
+
* fragment. The script loads from it and identifies through it.
|
|
84
|
+
*/
|
|
85
|
+
declare const start: (path?: string) => Zeno;
|
|
86
|
+
//#endregion
|
|
87
|
+
export { type Identification, type IdentifyOptions, type Metadata, type Zeno, ZenoError, type ZenoErrorCode, forget, start };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
//#region src/browser/error.d.ts
|
|
2
|
+
type ZenoErrorCode = 'client_timeout' | 'network_connection' | 'csp_block' | 'insecure_context' | 'collection_failed' | 'invalid_options' | 'server_error' | 'account_closed' | 'script_load_failed' | 'stopped' | 'capped' | 'not_in_browser';
|
|
3
|
+
declare class ZenoError extends Error {
|
|
4
|
+
readonly code: ZenoErrorCode;
|
|
5
|
+
constructor(code: ZenoErrorCode, message?: string);
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/browser/types.d.ts
|
|
9
|
+
/** Values a metadata key can hold; nothing nested. */
|
|
10
|
+
type Metadata = Record<string, string | number | boolean>;
|
|
11
|
+
type IdentifyOptions = {
|
|
12
|
+
/**
|
|
13
|
+
* Your own id for whoever is behind the browser, like a user id, to look visitors up by later. 1 to 256 characters;
|
|
14
|
+
* anything else is refused with `invalid_options` before anything is sent.
|
|
15
|
+
*/
|
|
16
|
+
externalId?: string;
|
|
17
|
+
/** What the visitor is doing, like `login`, `signup` or `checkout`, up to 1,024 characters. */
|
|
18
|
+
action?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Your own key-values kept with the event, like `{ orderId: 'A-1042', plan: 'pro' }`: at most 20 keys of 1 to 40
|
|
21
|
+
* letters, digits, `_`, `.` or `-`; text values up to 256 characters, numbers or booleans; 2 KB as JSON. Returned
|
|
22
|
+
* with the event by the server api, never used for detection.
|
|
23
|
+
*/
|
|
24
|
+
metadata?: Metadata;
|
|
25
|
+
};
|
|
26
|
+
type Identification = {
|
|
27
|
+
/** Left out when the project runs in zero trust mode: only your backend learns the visitor. */
|
|
28
|
+
visitorId?: string;
|
|
29
|
+
/**
|
|
30
|
+
* Send it to your server with the action, where `verify` from `zeno.id/server` says to allow, challenge or
|
|
31
|
+
* block.
|
|
32
|
+
*/
|
|
33
|
+
requestId: string;
|
|
34
|
+
/** Whether the api had seen this visitor before; left out in zero trust mode. */
|
|
35
|
+
returning?: boolean;
|
|
36
|
+
/** The event encrypted with the project's key, when the project seals results. */
|
|
37
|
+
sealedResult?: string;
|
|
38
|
+
error?: undefined;
|
|
39
|
+
} | {
|
|
40
|
+
/**
|
|
41
|
+
* Nothing was identified: send the action on without a request ID, and your server's `verify` answers
|
|
42
|
+
* `challenge` with `no-request-id` (a bot that skips the script sends none either), so it decides.
|
|
43
|
+
*/
|
|
44
|
+
requestId?: undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Why, by its `code`: a failure, `stopped`, `not_in_browser` on the server, or `capped` (a spend limit you
|
|
47
|
+
* set, the key's ceiling or the visitor ip's rate limit; not a bot).
|
|
48
|
+
*/
|
|
49
|
+
error: ZenoError;
|
|
50
|
+
visitorId?: undefined;
|
|
51
|
+
returning?: undefined;
|
|
52
|
+
sealedResult?: undefined;
|
|
53
|
+
};
|
|
54
|
+
type Zeno = {
|
|
55
|
+
/**
|
|
56
|
+
* Identifies the browser: sends the report through the proxy route and answers the request ID. It never rejects:
|
|
57
|
+
* when nothing was identified it resolves `{ requestId: undefined, error }`.
|
|
58
|
+
*/
|
|
59
|
+
identify(options?: IdentifyOptions): Promise<Identification>;
|
|
60
|
+
/**
|
|
61
|
+
* Stops identifying for good, as when the visitor withdraws consent: nothing more is collected or sent, an
|
|
62
|
+
* identify() in progress and every later one answer the `stopped` error, and the route is asked to clear its
|
|
63
|
+
* visitor cookie. A script still loading never starts. Call start() again to identify once consent is given again.
|
|
64
|
+
*/
|
|
65
|
+
stop(): void;
|
|
66
|
+
};
|
|
67
|
+
//#endregion
|
|
68
|
+
//#region src/browser/forget.d.ts
|
|
69
|
+
/**
|
|
70
|
+
* Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
|
|
71
|
+
* withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
|
|
72
|
+
* stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
|
|
73
|
+
*
|
|
74
|
+
* @param path The same path on this site you pass to `start()`, `/zeno` by default.
|
|
75
|
+
*/
|
|
76
|
+
declare const forget: (path?: string) => Promise<void>;
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/browser/index.d.ts
|
|
79
|
+
/**
|
|
80
|
+
* Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
|
|
81
|
+
*
|
|
82
|
+
* @param path The path on this site you mounted `createProxy` at, `/zeno` by default, without a query string or
|
|
83
|
+
* fragment. The script loads from it and identifies through it.
|
|
84
|
+
*/
|
|
85
|
+
declare const start: (path?: string) => Zeno;
|
|
86
|
+
//#endregion
|
|
87
|
+
export { type Identification, type IdentifyOptions, type Metadata, type Zeno, ZenoError, type ZenoErrorCode, forget, start };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
const IDENTIFY_TIMEOUT = 1e4;
|
|
2
|
+
//#endregion
|
|
3
|
+
//#region src/browser/error.ts
|
|
4
|
+
const messages = {
|
|
5
|
+
client_timeout: "Client timeout",
|
|
6
|
+
network_connection: "Network connection error",
|
|
7
|
+
csp_block: "Blocked by the Content Security Policy",
|
|
8
|
+
insecure_context: "Zeno needs a secure context (https)",
|
|
9
|
+
collection_failed: "Collecting the browser data failed",
|
|
10
|
+
invalid_options: "The options are invalid",
|
|
11
|
+
server_error: "The identification api failed",
|
|
12
|
+
account_closed: "The project's organization is closed; contact Zeno support to reopen it",
|
|
13
|
+
script_load_failed: "The script couldn't be loaded from the endpoint",
|
|
14
|
+
stopped: "Identification was stopped; call start() again to identify",
|
|
15
|
+
capped: "Nothing was identified: a spend limit or rate limit was reached",
|
|
16
|
+
not_in_browser: "Zeno identifies in the browser only; this ran on the server"
|
|
17
|
+
};
|
|
18
|
+
const REFUSED_KEY = "The proxy route's API key was refused: check the API key the route on your server is set up with";
|
|
19
|
+
var ZenoError = class extends Error {
|
|
20
|
+
code;
|
|
21
|
+
constructor(code, message) {
|
|
22
|
+
super(message ?? messages[code]);
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.name = "ZenoError";
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
const toZenoError = (error) => {
|
|
28
|
+
if (error instanceof ZenoError) return error;
|
|
29
|
+
const { name, code, message } = typeof error === "object" && error !== null ? error : {};
|
|
30
|
+
const text = typeof message === "string" ? message : void 0;
|
|
31
|
+
return name === "ZenoError" && typeof code === "string" && code in messages ? new ZenoError(code, text) : new ZenoError("collection_failed", text);
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/browser/csp.ts
|
|
35
|
+
const watchCsp = (origin) => {
|
|
36
|
+
let blocked = false;
|
|
37
|
+
const listener = (event) => {
|
|
38
|
+
if (event.blockedURI.startsWith(origin)) blocked = true;
|
|
39
|
+
};
|
|
40
|
+
globalThis.document?.addEventListener("securitypolicyviolation", listener);
|
|
41
|
+
return {
|
|
42
|
+
failure: async (otherwise, blockedMessage) => {
|
|
43
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
44
|
+
return blocked ? new ZenoError("csp_block", blockedMessage) : otherwise;
|
|
45
|
+
},
|
|
46
|
+
stop: () => globalThis.document?.removeEventListener("securitypolicyviolation", listener)
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
//#endregion
|
|
50
|
+
//#region src/browser/import.ts
|
|
51
|
+
const importModule = (url) => import(
|
|
52
|
+
/* @vite-ignore */
|
|
53
|
+
/* webpackIgnore: true */
|
|
54
|
+
url
|
|
55
|
+
);
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/browser/options.ts
|
|
58
|
+
const invalid = (message) => new ZenoError("invalid_options", message);
|
|
59
|
+
const resolveEndpoint = (value) => {
|
|
60
|
+
if (typeof value !== "string" || !/^\/(?![/\\])[^?#\\]*$/.test(value)) return;
|
|
61
|
+
try {
|
|
62
|
+
const page = new URL(globalThis.location.href);
|
|
63
|
+
const url = new URL(value, page);
|
|
64
|
+
return url.origin === page.origin ? `${url.origin}${url.pathname}` : void 0;
|
|
65
|
+
} catch {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const toChallengeToken = (value) => typeof value === "string" && value.length > 0 && value.length <= 200 ? value : void 0;
|
|
70
|
+
const checkProxyEndpoint = (path, call = "start") => {
|
|
71
|
+
const url = resolveEndpoint(path ?? "/zeno");
|
|
72
|
+
if (!url) throw invalid(`${call}() takes your proxy route's path on this site, like ${call}('/zeno')`);
|
|
73
|
+
return url;
|
|
74
|
+
};
|
|
75
|
+
const checkIdentifyOptions = (options) => {
|
|
76
|
+
if (typeof options !== "object" || options === null) throw invalid("Pass the identify() options as an object: identify({ externalId, action })");
|
|
77
|
+
const { externalId, action, metadata } = options;
|
|
78
|
+
if (externalId !== void 0 && (typeof externalId !== "string" || !externalId || externalId.length > 256)) throw invalid("externalId must be a string of 1 to 256 characters");
|
|
79
|
+
if (externalId === "." || externalId === "..") throw invalid("externalId can’t be . or ..");
|
|
80
|
+
if (action !== void 0 && (typeof action !== "string" || action.length > 1024)) throw invalid("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 invalid("metadata must be an object of keys and values, like { orderId: 'A-1042' }");
|
|
82
|
+
};
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/browser/storage.ts
|
|
85
|
+
const forgetStored = (endpoint) => {
|
|
86
|
+
return fetch(`${endpoint}?forget`, {
|
|
87
|
+
method: "POST",
|
|
88
|
+
credentials: "same-origin",
|
|
89
|
+
keepalive: true
|
|
90
|
+
});
|
|
91
|
+
};
|
|
92
|
+
//#endregion
|
|
93
|
+
//#region src/browser/forget.ts
|
|
94
|
+
/**
|
|
95
|
+
* Has the route clear its visitor cookie, without loading or starting anything: for a visitor who withdraws consent, or
|
|
96
|
+
* withdrew it on an earlier visit, on a page that never called `start()`. `stop()` on a started one does the same and
|
|
97
|
+
* stops it. Resolves once the route cleared the cookie; on the server it rejects with `not_in_browser`.
|
|
98
|
+
*
|
|
99
|
+
* @param path The same path on this site you pass to `start()`, `/zeno` by default.
|
|
100
|
+
*/
|
|
101
|
+
const forget = async (path) => {
|
|
102
|
+
if (typeof document === "undefined") throw new ZenoError("not_in_browser");
|
|
103
|
+
const endpoint = checkProxyEndpoint(path, "forget");
|
|
104
|
+
const csp = watchCsp(new URL(endpoint).origin);
|
|
105
|
+
let response;
|
|
106
|
+
try {
|
|
107
|
+
response = await forgetStored(endpoint);
|
|
108
|
+
} catch {
|
|
109
|
+
throw await csp.failure(new ZenoError("network_connection"));
|
|
110
|
+
} finally {
|
|
111
|
+
csp.stop();
|
|
112
|
+
}
|
|
113
|
+
if (!response.ok) throw new ZenoError("server_error", `The route answered ${response.status} when asked to clear its cookie`);
|
|
114
|
+
};
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/browser/index.ts
|
|
117
|
+
const withTimeout = (promise, ms, error) => {
|
|
118
|
+
let timer;
|
|
119
|
+
return Promise.race([promise, new Promise((_, reject) => {
|
|
120
|
+
timer = setTimeout(() => reject(error()), ms);
|
|
121
|
+
})]).finally(() => clearTimeout(timer));
|
|
122
|
+
};
|
|
123
|
+
const failed = (error) => ({
|
|
124
|
+
requestId: void 0,
|
|
125
|
+
error: toZenoError(error)
|
|
126
|
+
});
|
|
127
|
+
const ownAnswer = (identification) => {
|
|
128
|
+
return identification.error ? {
|
|
129
|
+
...identification,
|
|
130
|
+
error: toZenoError(identification.error)
|
|
131
|
+
} : identification;
|
|
132
|
+
};
|
|
133
|
+
const onServer = () => ({
|
|
134
|
+
identify: () => Promise.resolve(failed(new ZenoError("not_in_browser"))),
|
|
135
|
+
stop() {}
|
|
136
|
+
});
|
|
137
|
+
const refreshChallengeToken = (endpoint) => async () => {
|
|
138
|
+
try {
|
|
139
|
+
const module = await importModule(`${endpoint}?challenge=${Date.now()}`);
|
|
140
|
+
return toChallengeToken(module?.challengeToken);
|
|
141
|
+
} catch {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
const loadFailure = async (endpoint) => {
|
|
146
|
+
const fallback = new ZenoError("script_load_failed", `The script couldn't be loaded from ${endpoint}: check that your proxy route answers there`);
|
|
147
|
+
try {
|
|
148
|
+
const response = await fetch(endpoint, { credentials: "same-origin" });
|
|
149
|
+
if (response.ok) {
|
|
150
|
+
await response.body?.cancel();
|
|
151
|
+
return /javascript/i.test(response.headers.get("content-type") ?? "") ? fallback : new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
|
|
152
|
+
}
|
|
153
|
+
const body = await response.json().catch(() => void 0);
|
|
154
|
+
const code = typeof body?.error === "string" ? body.error : void 0;
|
|
155
|
+
if (code === "invalid_api_key") return new ZenoError("server_error", REFUSED_KEY);
|
|
156
|
+
if (code === "account_closed") return new ZenoError("account_closed");
|
|
157
|
+
return code || response.status >= 500 ? new ZenoError("server_error", `The route at ${endpoint} answered ${response.status}${code ? ` ${code}` : ""} for the script`) : new ZenoError("script_load_failed", `The route at ${endpoint} answered ${response.status}: check that your proxy route answers there`);
|
|
158
|
+
} catch {
|
|
159
|
+
return fallback;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
const loadAgent = async (endpoint, stopped, started) => {
|
|
163
|
+
const csp = watchCsp(new URL(endpoint).origin);
|
|
164
|
+
let module;
|
|
165
|
+
try {
|
|
166
|
+
module = await importModule(endpoint);
|
|
167
|
+
} catch {
|
|
168
|
+
const blocked = await csp.failure(new ZenoError("script_load_failed"), `The page's Content Security Policy blocked loading the script from ${endpoint}: allow it in script-src`);
|
|
169
|
+
throw blocked.code === "csp_block" ? blocked : await loadFailure(endpoint);
|
|
170
|
+
} finally {
|
|
171
|
+
csp.stop();
|
|
172
|
+
}
|
|
173
|
+
if (stopped()) throw new ZenoError("stopped");
|
|
174
|
+
if (typeof module?.start !== "function") throw new ZenoError("script_load_failed", `${endpoint} didn't answer with the script; check the endpoint`);
|
|
175
|
+
try {
|
|
176
|
+
const agent = module.start(new URL(endpoint).pathname, {
|
|
177
|
+
challengeToken: toChallengeToken(module.challengeToken),
|
|
178
|
+
refreshChallengeToken: refreshChallengeToken(endpoint)
|
|
179
|
+
});
|
|
180
|
+
started(agent);
|
|
181
|
+
return agent;
|
|
182
|
+
} catch (error) {
|
|
183
|
+
throw toZenoError(error);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
/**
|
|
187
|
+
* Loads Zeno's script from your proxy route and starts gathering signals; nothing is sent until `identify()`.
|
|
188
|
+
*
|
|
189
|
+
* @param path The path on this site you mounted `createProxy` at, `/zeno` by default, without a query string or
|
|
190
|
+
* fragment. The script loads from it and identifies through it.
|
|
191
|
+
*/
|
|
192
|
+
const start = (path) => {
|
|
193
|
+
if (typeof document === "undefined") return onServer();
|
|
194
|
+
const endpoint = checkProxyEndpoint(path);
|
|
195
|
+
let stopped = false;
|
|
196
|
+
let running;
|
|
197
|
+
let rejectStopped = () => {};
|
|
198
|
+
const stopping = new Promise((_, reject) => {
|
|
199
|
+
rejectStopped = reject;
|
|
200
|
+
});
|
|
201
|
+
stopping.catch(() => {});
|
|
202
|
+
const loaded = loadAgent(endpoint, () => stopped, (agent) => running = agent);
|
|
203
|
+
loaded.catch(() => {});
|
|
204
|
+
const identify = async (identifyOptions) => {
|
|
205
|
+
if (stopped) throw new ZenoError("stopped");
|
|
206
|
+
checkIdentifyOptions(identifyOptions);
|
|
207
|
+
const timeout = IDENTIFY_TIMEOUT;
|
|
208
|
+
const started = performance.now();
|
|
209
|
+
const agent = await withTimeout(Promise.race([loaded, stopping]), timeout, () => new ZenoError("client_timeout"));
|
|
210
|
+
const left = Math.max(1, timeout - (performance.now() - started));
|
|
211
|
+
if (stopped) throw new ZenoError("stopped");
|
|
212
|
+
return ownAnswer(await agent.identify({
|
|
213
|
+
...identifyOptions,
|
|
214
|
+
timeout: left
|
|
215
|
+
}));
|
|
216
|
+
};
|
|
217
|
+
return {
|
|
218
|
+
identify: (identifyOptions = {}) => identify(identifyOptions).catch(failed),
|
|
219
|
+
stop() {
|
|
220
|
+
if (!stopped) {
|
|
221
|
+
stopped = true;
|
|
222
|
+
rejectStopped(new ZenoError("stopped"));
|
|
223
|
+
}
|
|
224
|
+
if (running) running.stop();
|
|
225
|
+
else forgetStored(endpoint).catch(() => {});
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
};
|
|
229
|
+
//#endregion
|
|
230
|
+
export { ZenoError, forget, start };
|