zeno.id 0.0.0-stage → 0.1.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 +184 -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/package.json +38 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Creative Code Solutions B.V.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,185 @@
|
|
|
1
|
-
#
|
|
1
|
+
# zeno.id
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
Zeno's browser SDK. Zeno tells your server whether a login, signup or checkout came from a real browser, and whether to let it through. This package is a small loader: `start()` imports the script itself at runtime through a route on your own site (the proxy route), so collection fixes reach every site without a release. The script sends device signals to that route, the route adds your API key and passes them on to Zeno, and `identify()` answers a request ID for your server to verify.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install zeno.id @zeno.id/server
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`zeno.id` runs in the browser; `@zeno.id/server` is the route on your server, on any JavaScript runtime with the standard `Request` and `Response` (Node 20 or later, Bun, Deno, Cloudflare Workers, Vercel and so on). Both ship ES modules, CommonJS and their types.
|
|
12
|
+
|
|
13
|
+
## The route on your server
|
|
14
|
+
|
|
15
|
+
The browser never talks to Zeno directly. Add a route to your own site with `createProxy` from `@zeno.id/server`, at a path of your choice (`/zeno` here, the browser SDK's default). It holds the project's API key, so it runs on your server only; pass it the key from your server's environment:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createProxy } from '@zeno.id/server'
|
|
19
|
+
|
|
20
|
+
// Your proxy route: the browser SDK talks to Zeno through it
|
|
21
|
+
const zeno = createProxy(process.env.ZENO_API_KEY)
|
|
22
|
+
|
|
23
|
+
// ip: the IP address the request came from, as your server gives it
|
|
24
|
+
export const handle = (request: Request, ip: string) => {
|
|
25
|
+
if (new URL(request.url).pathname === '/zeno') {
|
|
26
|
+
// the path you chose
|
|
27
|
+
return zeno(request, ip)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// …the rest of your app
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`@zeno.id/server`'s README has Express, Next.js, Bun and Cloudflare Workers, and the docs' quickstart every other framework. The route:
|
|
35
|
+
|
|
36
|
+
- answers `GET` (and `HEAD`) with the script's code, which it fetches from Zeno and caches by its ETag, gzipped when the browser takes it;
|
|
37
|
+
- answers `POST` (an identification) by passing the script's signals on with the visitor's ip and request headers, and keeps the visitor id in an `HttpOnly` cookie of its own;
|
|
38
|
+
- answers `POST` to `?forget` (`forget()` and `stop()`) by clearing that cookie.
|
|
39
|
+
|
|
40
|
+
Which IP to pass as `zeno(request, ip)` is on the docs' proxy route page (`/docs/proxy#the-visitors-ip`).
|
|
41
|
+
|
|
42
|
+
## In the browser
|
|
43
|
+
|
|
44
|
+
Call `start()` on a page with an action you want to identify (a login, signup or checkout), when that page loads, not on every page, with the path of your route on your site. It loads Zeno's script and starts gathering signals in the browser; nothing is sent to Zeno and nothing is billed. Call `identify()` when the user takes the action: that's the identity check, it sends the report and gives you the request ID. Starting early only makes `identify()` quick, and one `start()` serves every `identify()` on that page. Call it in a module, not in a component (a component remounts, and each `start()` collects again). A module's top level is fine in any framework: while a page renders on the server, `start()` does nothing and its `identify()` answers the `not_in_browser` error.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { start } from 'zeno.id'
|
|
48
|
+
|
|
49
|
+
// When the login page loads:
|
|
50
|
+
const zeno = start('/zeno') // the same path as your route
|
|
51
|
+
|
|
52
|
+
// When the user logs in (never throws; requestId is undefined when it failed):
|
|
53
|
+
const { requestId } = await zeno.identify({ action: 'login' })
|
|
54
|
+
|
|
55
|
+
const response = await fetch('/api/login', {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
headers: { 'Content-Type': 'application/json' },
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
email,
|
|
60
|
+
password,
|
|
61
|
+
requestId,
|
|
62
|
+
}),
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
if (response.ok) {
|
|
66
|
+
location.assign('/account')
|
|
67
|
+
} else {
|
|
68
|
+
// A wrong password, or a block or challenge from your server
|
|
69
|
+
showError(await response.text())
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Your server then calls `client.verify(requestId)` from `@zeno.id/server`, which answers `allow`, `challenge` or `block`: that's the answer to trust, never anything the browser says. A login request without a request ID gets `challenge` with `no-request-id`, so your server decides whether to let the action through or ask for more; a request ID verifies once. A project in zero trust mode answers only `requestId` (no `visitorId` or `returning`), and one with sealed results also returns `sealedResult` for your server to open with `unsealResult`.
|
|
74
|
+
|
|
75
|
+
`start()` imports the script as an ES module from that path, and the script identifies with a `POST` to the same path. Nothing else is tried: on a failure `identify()` resolves at once with its error (`script_load_failed`, `csp_block`, `network_connection`…).
|
|
76
|
+
|
|
77
|
+
The script also sends the page url and referrer as origin and path only, without the query string or `#fragment`; set `pageUrls` in the project's settings to `origin` to keep only the site, or `none` to keep neither.
|
|
78
|
+
|
|
79
|
+
## Content Security Policy
|
|
80
|
+
|
|
81
|
+
- `script-src 'self'` for the script's code from the route, and `connect-src 'self'` for the identification and `forget()`.
|
|
82
|
+
- `script-src blob:` and `worker-src blob:` for some of the script's checks (no `eval`). Without them those checks go unreported and the identification still works.
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
Content-Security-Policy: script-src 'self' blob:; connect-src 'self'; worker-src 'self' blob:
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
The script's code uses no `eval` or `new Function`, so `'unsafe-eval'` isn't needed.
|
|
89
|
+
|
|
90
|
+
## Options
|
|
91
|
+
|
|
92
|
+
`start(path)` takes your proxy route's path on this site, `/zeno` when you leave it out. It starts with `/`; a full url, a query string or a `#fragment` is refused with `invalid_options`, since the route answers the page's own origin only.
|
|
93
|
+
|
|
94
|
+
| `identify()` option | |
|
|
95
|
+
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
96
|
+
| `externalId` | Your id for the user behind the browser, to look visitors up by and to delete later. 1 to 256 characters (`invalid_options` otherwise). |
|
|
97
|
+
| `action` | What the visitor is doing, like `login`, `signup` or `checkout`, up to 1,024 characters. Returned with the event. |
|
|
98
|
+
| `metadata` | Your own key-values kept with the event, like `{ orderId: 'A-1042', plan: 'pro' }`: up to 20 keys of 1 to 40 letters, digits, `_`, `.` or `-`, each a string up to 256 characters, a number or a boolean, 2 KB in all. Returned with the event, never used for detection. |
|
|
99
|
+
|
|
100
|
+
The script keeps no visitor id itself. The route keeps it in the `zeno_id` cookie (`HttpOnly`, `SameSite=Lax`, `Secure` on https, a year), on the route's own path, so two routes on one site, like a site's own login and a demo, keep separate ids. Zeno reuses it while it's still the same device, so the id survives browser updates. The script keeps nothing in the browser's storage, and every `identify()` identifies again.
|
|
101
|
+
|
|
102
|
+
## Stop and forget
|
|
103
|
+
|
|
104
|
+
`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.
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
let zeno: Zeno | undefined
|
|
108
|
+
|
|
109
|
+
consentTool.onChange(async ({ fraudPrevention }) => {
|
|
110
|
+
if (fraudPrevention) {
|
|
111
|
+
zeno ??= start('/zeno')
|
|
112
|
+
} else if (zeno) {
|
|
113
|
+
zeno.stop()
|
|
114
|
+
zeno = undefined
|
|
115
|
+
} else {
|
|
116
|
+
await forget('/zeno')
|
|
117
|
+
}
|
|
118
|
+
})
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Errors
|
|
122
|
+
|
|
123
|
+
`identify()` never rejects. When nothing was identified it resolves `{ requestId: undefined, error }`, with `error` a `ZenoError` whose `code` is one of these (`ZenoErrorCode`), and whose `message` says more where there's more to say. For all of them the action can go on without a request ID: your server's `verify` answers `challenge` with `no-request-id`, so it decides. `start()` itself throws a `ZenoError` for options it can't use (`invalid_options`).
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
// Never throws: requestId is undefined when nothing was identified
|
|
127
|
+
const { requestId, error } = await zeno.identify({ action: 'login' })
|
|
128
|
+
|
|
129
|
+
if (error) {
|
|
130
|
+
console.warn('Identification failed', error.code, error.message)
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
| Code | What happened | What to do |
|
|
135
|
+
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
|
|
136
|
+
| `client_timeout` | Zeno didn't answer in time. | Go on without a request ID. |
|
|
137
|
+
| `network_connection` | The route couldn't be reached, or the request was cut off. | Go on without a request ID. |
|
|
138
|
+
| `csp_block` | The page's Content Security Policy blocked the script's code (`script-src`) or the identification (`connect-src`). | Allow the route's origin in both (see Content Security Policy). |
|
|
139
|
+
| `insecure_context` | The page isn't a secure context (https or localhost), which the script needs for its random ids and hashes. | Serve the page over https. |
|
|
140
|
+
| `collection_failed` | The browser data couldn't be collected at all, as when an extension broke the browser's basics. | Go on without a request ID. |
|
|
141
|
+
| `invalid_options` | An option `start()` or `identify()` can't use (a route path that isn't on this site, a bad external id or metadata), or one Zeno refused; the message names it. | Fix the option. |
|
|
142
|
+
| `script_load_failed` | The script couldn't be loaded from the route: nothing answers there (your site's own 404 page), something other than the script does, or the network failed. The message names the url and the status. | Check the route answers at its path; meanwhile go on without a request ID. |
|
|
143
|
+
| `server_error` | The route or Zeno failed, or answered something that isn't the route's JSON. The message says what: a route that wasn't given the visitor's IP says to pass it, a refused API key says to check the route's. | Read the message and the route's server log; go on without a request ID. |
|
|
144
|
+
| `account_closed` | Zeno closed the organization's account (as for unpaid invoices): identification is refused until it's reopened. | Contact support. |
|
|
145
|
+
| `stopped` | `stop()` was called, before or during the `identify()`. | Call `start()` again once consent is back. |
|
|
146
|
+
| `capped` | A limit stopped the identification: a spend limit you set, the key's ceiling or the visitor ip's rate limit. Not a bot. | Go on without a request ID. |
|
|
147
|
+
| `not_in_browser` | `identify()` ran on the server, while a page rendered. | Call it in the action's handler in the browser. |
|
|
148
|
+
|
|
149
|
+
## What it collects
|
|
150
|
+
|
|
151
|
+
- **The device and browser:** technical characteristics of the hardware and software, like the screen, the browser's settings, its languages and time zone.
|
|
152
|
+
- **Integrity checks:** whether a script drives the browser and whether what it reports fits together.
|
|
153
|
+
- **With the request:** the page url and referrer without their query string and fragment. Your route adds the request's headers (the user agent among them, never other cookies or authorization headers) and the visitor's ip.
|
|
154
|
+
|
|
155
|
+
It reads no personal content, like names, messages or what people type, and nothing from other sites. The report is about a kilobyte.
|
|
156
|
+
|
|
157
|
+
## Without a bundler
|
|
158
|
+
|
|
159
|
+
A page without a build step can import `start` from the route itself, which serves the script as an ES module:
|
|
160
|
+
|
|
161
|
+
<!-- prettier-ignore -->
|
|
162
|
+
```html
|
|
163
|
+
<button id="login">Log in</button>
|
|
164
|
+
<script type="module">
|
|
165
|
+
import { start } from '/zeno' // your route's path
|
|
166
|
+
|
|
167
|
+
const zeno = start()
|
|
168
|
+
|
|
169
|
+
document.querySelector('#login').addEventListener('click', async () => {
|
|
170
|
+
const { requestId } = await zeno.identify({ action: 'login' })
|
|
171
|
+
|
|
172
|
+
await fetch('/api/login', {
|
|
173
|
+
method: 'POST',
|
|
174
|
+
headers: { 'Content-Type': 'application/json' },
|
|
175
|
+
body: JSON.stringify({ email, password, requestId }),
|
|
176
|
+
})
|
|
177
|
+
})
|
|
178
|
+
</script>
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
That `start()` takes the path it was imported from unless you pass another, and answers the same `identify()` and `stop()` with the same error codes. What it can't do is report a script that doesn't load: the `import` itself fails, without `script_load_failed` or `csp_block`, and there's no `forget()`. Use `zeno.id` where you can.
|
|
182
|
+
|
|
183
|
+
## License
|
|
184
|
+
|
|
185
|
+
MIT, see `LICENSE`.
|
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/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/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/import.ts
|
|
52
|
+
const importModule = (url) => import(
|
|
53
|
+
/* @vite-ignore */
|
|
54
|
+
/* webpackIgnore: true */
|
|
55
|
+
url
|
|
56
|
+
);
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/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/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/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/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/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/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/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/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/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/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/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/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/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/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/import.ts
|
|
51
|
+
const importModule = (url) => import(
|
|
52
|
+
/* @vite-ignore */
|
|
53
|
+
/* webpackIgnore: true */
|
|
54
|
+
url
|
|
55
|
+
);
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/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/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/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/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 };
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "zeno.id",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Zeno's browser SDK for device identification: a small loader that fetches the current script from your own route at runtime",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist"
|
|
8
|
+
],
|
|
9
|
+
"type": "module",
|
|
10
|
+
"sideEffects": false,
|
|
11
|
+
"main": "./dist/index.cjs",
|
|
12
|
+
"module": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"import": {
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"require": {
|
|
21
|
+
"types": "./dist/index.d.cts",
|
|
22
|
+
"default": "./dist/index.cjs"
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"test": "bun test ./test/loader.ts",
|
|
31
|
+
"build": "tsdown --no-fixed-extension src/index.ts --format cjs,esm --dts --clean --platform browser",
|
|
32
|
+
"prepublishOnly": "if bun run test; then bun run build; else exit; fi",
|
|
33
|
+
"prepack": "bun ../../scripts/package-exports.ts strip",
|
|
34
|
+
"postpack": "bun ../../scripts/package-exports.ts restore"
|
|
35
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=20"
|
|
38
|
+
}
|
|
39
|
+
}
|