@valiron/crawler-protection 0.3.0 → 0.4.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 CHANGED
@@ -21,6 +21,50 @@ Implemented:
21
21
 
22
22
  This is an origin admission library, not a complete bot detector. A matching user-agent and source network establish provenance, not human identity or proven crawler intent. Meta classes can use verified AWS WAF evidence over a protected ingress path; no Meta CIDR/ASN verifier is assumed. Header spoofing without a network match does not receive verified allowances.
23
23
 
24
+ ## Returning-browser recognition (optional, observe-only)
25
+
26
+ The package also includes returning-browser recognition, folded in from the former standalone `@valiron/device-identity` package so an existing Crawler Protection install gains it without a second SDK. Two signal classes stay strictly separate:
27
+
28
+ 1. **Deterministic** - a first-party, server-signed visitor cookie (`HttpOnly; Secure; SameSite=Lax`). A valid cookie is the only `exact` match.
29
+ 2. **Probabilistic** - coarsened device signals (browser family/major, languages, timezone, platform, screen, hardware hints), compared per component with weighted scoring. A strong match produces a `similar` link, never an `exact` one.
30
+
31
+ Recognition is **evidence, not a verdict**: no risk score, no block decision, no enforcement hook. `similar` means "this browser resembles one we have seen" - shared devices, corporate fleets and fresh installs all produce false links, so a `similar` link is never sufficient grounds to deny or limit service.
32
+
33
+ Mount the middleware to expose the endpoints, then call the browser collector to begin recognition:
34
+
35
+ ```ts
36
+ import { DeviceIdentity, RedisIdentityStore, createNodeDeviceIdentityMiddleware } from '@valiron/crawler-protection';
37
+
38
+ const identity = new DeviceIdentity({
39
+ salt: process.env.DEVICE_IDENTITY_SALT!, // per-deployment, 16+ chars, from a secret manager
40
+ cookie: {
41
+ name: '__Host-vid',
42
+ secret: process.env.DEVICE_IDENTITY_COOKIE_SECRET!,
43
+ maxAgeMs: 180 * 24 * 3600 * 1000,
44
+ },
45
+ store: new RedisIdentityStore(redis), // or omit for the in-memory store
46
+ retentionMs: 30 * 24 * 3600 * 1000, // enforced bounds: 1h..90d
47
+ });
48
+
49
+ app.use(createNodeDeviceIdentityMiddleware({
50
+ identity,
51
+ onRecognition: (recognition) => analytics.record(recognition), // server-side only
52
+ }));
53
+ ```
54
+
55
+ Load the collector script and call `ValironDevice.identify({ endpoint: "/api/valiron/device-identity/identify", respectPrivacySignals: true })` only when your deployment permits collection. Mounting the middleware alone does not run the browser collector. Recognition is not automatically sent to the hosted crawler dashboard.
56
+
57
+ The middleware serves the browser collector at `GET /api/valiron/device-identity/collector.js` and recognition at `POST /api/valiron/device-identity/identify` (override with `basePath`). The browser only ever receives `{ state }` - visitor ids, matched ids and evidence stay server-side, because echoing them would let a caller mimicking another browser's signals harvest that browser's identity. The collector never reads the cookie and never uses localStorage; pass `respectPrivacySignals: true` to skip collection when the browser sends DNT/GPC.
58
+
59
+ Privacy properties enforced in code:
60
+
61
+ - Raw signal values, raw user agents and IP addresses are never stored. Profiles hold per-component salted SHA-256 hashes only. These hashes are **pseudonymous, not anonymous**: anyone holding the deployment salt can test candidate values. Protect the salt like a signing key, rotate `saltVersion` on schedule, and treat stored profiles as personal data for retention and deletion purposes.
62
+ - Every stored profile carries a TTL; retention is bounded to 1 hour - 90 days (default 30).
63
+ - The cookie carries only a random id and an HMAC - no device data.
64
+ - `identity.forget(visitorId)` deletes a profile and its index entries (data-subject deletion hook).
65
+
66
+ Every default here - 30-day retention, the 8/11.5 similarity threshold, the 180-day example cookie lifetime, optional privacy-signal handling - is a placeholder so the module runs, **not an approved production policy**. Before production rollout, the deployment must explicitly decide: consent flow per jurisdiction (a first-party identification cookie is not strictly necessary for most sites), DNT/GPC behavior, retention, similarity-threshold tuning against real traffic, what may consume `similar` links (recommend observe-only analytics first; the link graph is attacker-influenceable, though links and matched ids never leave the server), and cookie lifetime/rotation. Account metering/gating for this module is likewise a follow-up decision; activation is not currently required to use it.
67
+
24
68
  ## Account activation and monthly usage
25
69
 
26
70
  Sign up at Valiron and create an operator API key in Dashboard → API Keys. Keep it server-side as `VALIRON_API_KEY`. Use your dashboard-exported `operator_<account ID>` tenant. `activateCrawlerProtection()` obtains a five-minute lease and refreshes every minute; pass its handle to the runtime/guard. Missing, invalid or revoked credentials cannot activate the supported SDK. Startup/background refresh use HTTPS. Each protected HTTP request obtains quota admission through the hosted usage endpoint; a database operation within that request is not counted again. Outages never extend a lease. After revocation/expiry, new protected work stops, while confirmed releases and recovery remain available. Call `activation.stop()` on shutdown. The public SDK is modifiable; these checks are not tamper-proof and do not retroactively restrict version 0.1.0. Deploy the account activation endpoint before upgrading clients.
@@ -37,7 +81,7 @@ pnpm test:crawlers:service
37
81
 
38
82
  The Redis and service tests start temporary Redis processes and loopback Python/SQLite origins with generated fixture credentials. `redis-server` and Python 3 must be installed. External verification-feed egress is disabled in service lifecycle fixtures; no customer URLs or production databases are used. The Python unit suite uses local HTTP fixtures only for deliberate authentication/error/redirect cases. The package is distributed through npm as `@valiron/crawler-protection`.
39
83
 
40
- Website availability: **Pro** (also Enterprise). Dashboard → Crawler Protection offers authenticated configuration validation/export and integration guidance. Optional `createCrawlerTelemetry` reporting adds hosted rolling origin analytics, shared capacity, instance status and dashboard monitoring alerts. It does not deploy customer policies. See the public integration guide for telemetry setup, retention and measurement limits.
84
+ Website availability: **Free, Pro and Enterprise**, within each plan’s usage allowance. Dashboard → Crawler Protection offers authenticated configuration validation/export and integration guidance. Optional `createCrawlerTelemetry` reporting adds hosted rolling origin analytics, shared capacity, instance status and dashboard monitoring alerts. It does not deploy customer policies. See the public integration guide for telemetry setup, retention and measurement limits.
41
85
 
42
86
  ## Release CI coverage
43
87
 
@@ -67,7 +111,7 @@ const runtime = createCrawlerRuntime({ activation,
67
111
  app.use(runtime.nodeMiddleware);
68
112
  // Nuxt: defineEventHandler(runtime.nuxtMiddleware)
69
113
  // Handlers: runtime.withRenderingAdmission(context, renderAndFetch)
70
- // Queries: runtime.withDatabaseAdmission(context, actualQueryPromise)
114
+ // Queries: runtime.withDatabaseAdmission(context, () => queryProduct(productId))
71
115
  ```
72
116
 
73
117
  These imports are package exports; the configuration/Redis/ingress/customer dependencies are application supplied. Use `runtime.guard` for page admission and signed internal forwarding. The runtime's `store` uses an effective policy that binds the whole configuration fingerprint, not just rate numbers. Use `runtime.compiled.policy` with private management tools. Never initialize admission from worker startup.
@@ -167,6 +211,27 @@ export default defineEventHandler(middleware);
167
211
 
168
212
  The Nuxt adapter ends denied Node responses before returning. It stores an admitted context on `event.context.valironCrawler`. The structural adapter and a separate Nuxt/Nitro Vue SSR route fixture are tested locally; application-specific response-cache ordering still requires validation. It is server middleware, not Vue navigation middleware.
169
213
 
214
+ ## Next.js (App Router, bundled consumers)
215
+
216
+ The package is safe to import from code that a bundler processes. The device-identity browser collector is embedded in the built package as a string at publish time - `deviceIdentityCollectorScript()` performs no filesystem reads - so it works unchanged in Next.js dev (Turbopack) and production builds, with no `serverExternalPackages` entry, asset copying, or `__dirname` assumptions. A regression test asserts the embedded script is byte-identical to `public/collector.js` in this repository, so the shipped asset and the embedded copy cannot drift apart.
217
+
218
+ Mount the device-identity endpoints from Node-runtime route handlers (the middleware uses Node APIs; do not use the Edge runtime):
219
+
220
+ ```ts
221
+ // app/api/valiron/device-identity/collector.js/route.ts
222
+ import { deviceIdentityCollectorScript } from '@valiron/crawler-protection';
223
+
224
+ export const runtime = 'nodejs';
225
+
226
+ export function GET() {
227
+ return new Response(deviceIdentityCollectorScript(), {
228
+ headers: { 'Content-Type': 'application/javascript; charset=utf-8', 'Cache-Control': 'no-store' },
229
+ });
230
+ }
231
+ ```
232
+
233
+ The crawler guard itself runs wherever a Node runtime is available; the same bundling note applies - no special configuration is required.
234
+
170
235
  ## Node API and actual database work
171
236
 
172
237
  ```ts
@@ -225,4 +290,36 @@ Directory data attribution: Verified Bots Directory by Mayank Gupta (https://ver
225
290
 
226
291
  Monthly bot quotas require Crawler SDK 0.3.0 or later. Upgrade existing 0.2.x deployments to use Free accounts and hosted per-request quota admission. Earlier public SDK versions are not retroactively metered.
227
292
 
228
- Free includes 10,000 protected HTTP requests per UTC calendar month; Pro ($149/month) includes 100,000. The bot allowance is independent from agent access and shared across an account's API keys, sites and replicas. Every protected request consumes one admission, including requests later blocked by local policy. Quota exhaustion returns HTTP 429; an unavailable usage check fails closed with 503. This adds a hosted round trip before protected origin work. Enterprise: email founders@valiron.co.
293
+ Free includes 10,000 protected HTTP requests per UTC calendar month; Pro ($149/month) includes 100,000. The bot allowance is independent from agent access and shared across an account's API keys, sites and replicas. Local access/rate denials run before hosted quota admission and do not consume the allowance. Once hosted admission succeeds, the request is counted even if a later work-capacity check fails. Quota exhaustion returns HTTP 429; an unavailable usage check fails closed with 503. This adds a hosted round trip before protected origin work. Enterprise: email founders@valiron.co.
294
+
295
+ ## Security compatibility and admission recovery
296
+
297
+ Directory approval hashes include the resolved CIDR set. Review and approve again when that evidence changes; a generic browser user-agent token cannot override an official crawler claim that fails source verification. Local access/rate denials run before hosted monthly quota admission, so rejected requests do not consume the account allowance.
298
+
299
+ Uncertain or timed-out permit acquisitions carry a deadline and cancellation tombstone so late execution cannot leave an unstarted reservation. This does not cancel work that already started: retain its hold until settlement is confirmed, or pause admission and reconcile the exact hold with confirmed-drain evidence. An HTTP timeout alone never proves database work has stopped.
300
+
301
+
302
+ ## Web Bot Auth verification (draft protocol, opt-in)
303
+
304
+ `WebBotAuthVerifier` verifies Web Bot Auth signatures (draft-ietf-webbotauth-httpsig-protocol, an active IETF draft) as a third evidence path for crawlers and agents that cannot publish IP ranges. A signer proves control of an Ed25519 key pinned for its `Signature-Agent` HTTPS URL; a valid signature produces evidence with `method: 'web_bot_auth'` and the operator-configured provider/class, and the usual provider budgets still apply. Wire it through the guard's `fallbackEvidence` hook, which is consulted only when trusted/IP/DNS evidence did not verify - an existing verified identity always stands:
305
+
306
+ ```js
307
+ const wba = new WebBotAuthVerifier({ agents: {
308
+ 'https://signer.example.com/.well-known/http-message-signatures-directory': {
309
+ provider: 'example-ai', crawlerClass: 'examplebot',
310
+ keys: [/* pinned Ed25519 JWKs from the signer's directory */],
311
+ promote: true, // opt-in per signer; default only reports the authenticated signer
312
+ },
313
+ } });
314
+ new CrawlerGuard({ /* ... */ fallbackEvidence: (request) => wba.fallbackEvidence(request) });
315
+ ```
316
+
317
+ The standalone gateway and `createCrawlerRuntime()` do not automatically enable this verifier; wire it explicitly when constructing `CrawlerGuard`.
318
+
319
+ Trust boundaries, deliberately stricter than the draft minimum:
320
+
321
+ - Pin-only key sources. The verifier performs no network fetch, so a request cannot steer this process into contacting an attacker-chosen directory URL. Dynamic directory resolution is omitted until it can ship with connect-time destination validation and bounded egress.
322
+ - A valid signature is proof of key control, not good intent or authorization. Unpinned signer URLs stay unverified, and pinned-but-not-promoted signers keep unverified budgets while telemetry records the authenticated `signerUrl`. Promotion is an explicit per-signer opt-in.
323
+ - Freshness is not replay protection. The draft's minimum coverage binds only `@authority`, so a captured signature can be replayed against this origin until `expires` (bounded to the draft's recommended 24-hour maximum, configurable down). Verified signers remain subject to every budget, which bounds replay damage; `profile: 'strict'` additionally requires `@method` and `@path` coverage. The strict profile is a Valiron-specific strengthening, not a standard compliance claim.
324
+ - The protocol is a draft. Verification is signature-only and tolerates non-Web-Bot-Auth signatures on the same request; expect wire-format changes before RFC publication.
325
+
@@ -28,7 +28,7 @@ function createCrawlerActivation(input) {
28
28
  throw Error('A Valiron operator API key and tenant are required');
29
29
  const url = new URL(input.endpoint ?? exports.CRAWLER_ACTIVATION_ENDPOINT);
30
30
  const fixture = url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
31
- if (url.href !== exports.CRAWLER_ACTIVATION_ENDPOINT && (!fixture || url.pathname !== '/operator/crawlers/activation' || url.username || url.password || url.search || url.hash))
31
+ if ((!fixture && url.protocol !== 'https:') || url.pathname !== '/operator/crawlers/activation' || url.username || url.password || url.search || url.hash)
32
32
  throw Error('Invalid Crawler Protection activation endpoint');
33
33
  const now = input.now ?? Date.now, monotonic = input.monotonicNow ?? (() => performance.now());
34
34
  let expiresAt = 0, deadline = 0, stopped = false, pending;
@@ -26,7 +26,7 @@ export type WorkPermit = Readonly<{
26
26
  export declare function keyPart(input: string): string;
27
27
  export declare class RedisAdmission {
28
28
  protected readonly redis: RedisEval;
29
- private readonly timeoutMs;
29
+ protected readonly timeoutMs: number;
30
30
  protected readonly prefix: string;
31
31
  constructor(redis: RedisEval, tenant: string, timeoutMs?: number);
32
32
  protected keys(stage: string, names: string[]): string[];
package/dist/admission.js CHANGED
@@ -36,6 +36,8 @@ return {1,0}
36
36
  const ACQUIRE = `
37
37
  -- ADMISSION
38
38
  -- WORK_ACQUIRE
39
+ local cancelled = table.remove(KEYS,1)
40
+ if redis.call('EXISTS',cancelled)==1 then return 0 end
39
41
  local inventory = table.remove(KEYS,1)
40
42
  local metadata = cjson.decode(table.remove(ARGV,1))
41
43
  if redis.call('HLEN',inventory) >= 10000 then return 0 end
@@ -44,6 +46,8 @@ for i,key in ipairs(KEYS) do
44
46
  end
45
47
  local clock = redis.call('TIME')
46
48
  metadata.acquiredAt = tonumber(clock[1])*1000+math.floor(tonumber(clock[2])/1000)
49
+ if metadata.acquiredAt > metadata.deadlineAt then return 0 end
50
+ metadata.deadlineAt = nil
47
51
  metadata.keys = KEYS
48
52
  for i,key in ipairs(KEYS) do redis.call('HSET',key,ARGV[1],1) end
49
53
  redis.call('HSET',inventory,ARGV[1],cjson.encode(metadata))
@@ -125,8 +129,18 @@ class RedisAdmission {
125
129
  const keys = this.keys('work', slots.map(s => s.key));
126
130
  const id = (0, node_crypto_1.randomUUID)();
127
131
  const secret = (0, node_crypto_1.randomBytes)(32).toString('base64url');
128
- const result = Number(await this.run(ACQUIRE, [this.prefix + 'holds', ...keys], [JSON.stringify({ ...fields,
129
- slots: slots.map(s => s.key), owner: (0, node_os_1.hostname)() + ':' + process.pid + ':' + id, releaseHash: keyPart(secret) }), id, ...slots.map(s => s.limit)]));
132
+ const cancelKey = this.prefix + 'cancel:' + id;
133
+ const arguments_ = [JSON.stringify({ ...fields, deadlineAt: Date.now() + this.timeoutMs,
134
+ slots: slots.map(s => s.key), owner: (0, node_os_1.hostname)() + ':' + process.pid + ':' + id, releaseHash: keyPart(secret) }), id, ...slots.map(s => s.limit)];
135
+ let result;
136
+ try {
137
+ result = Number(await this.run(ACQUIRE, [cancelKey, this.prefix + 'holds', ...keys], arguments_));
138
+ }
139
+ catch (error) {
140
+ // Cancel before releasing; queued ACQUIRE cannot create a hold after cleanup.
141
+ void this.redis.eval(`redis.call('SET',KEYS[1],'1','EX',60); local raw=redis.call('HGET',KEYS[2],ARGV[1]); if raw then local r=cjson.decode(raw); for _,key in ipairs(r.keys) do redis.call('HDEL',key,ARGV[1]) end; redis.call('HDEL',KEYS[2],ARGV[1]); end; return 1`, 2, cancelKey, this.prefix + 'holds', id).catch(() => { });
142
+ throw error;
143
+ }
130
144
  if (result === 0)
131
145
  return undefined;
132
146
  if (result !== 1)
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The browser collector, embedded at build time so bundlers (Next.js, Turbopack,
3
+ * webpack server builds) never need a filesystem read of public/collector.js.
4
+ * test/device-identity-collector.test.cjs asserts this matches public/collector.js.
5
+ */
6
+ export declare const COLLECTOR_SCRIPT: string;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.COLLECTOR_SCRIPT = void 0;
4
+ /**
5
+ * The browser collector, embedded at build time so bundlers (Next.js, Turbopack,
6
+ * webpack server builds) never need a filesystem read of public/collector.js.
7
+ * test/device-identity-collector.test.cjs asserts this matches public/collector.js.
8
+ */
9
+ exports.COLLECTOR_SCRIPT = "/*!\r\n * Valiron Device Identity collector (browser), shipped inside\r\n * Valiron Crawler Protection and served by createNodeDeviceIdentityMiddleware().\r\n *\r\n * Collects coarsened device signals and POSTs them to the deployment's\r\n * identify endpoint. The deterministic visitor id lives in a first-party,\r\n * HttpOnly cookie set by the server; this script never reads or writes it,\r\n * and it never touches localStorage. No third-party requests are made.\r\n *\r\n * Usage:\r\n * <script src=\"/api/valiron/device-identity/collector.js\"></script>\r\n * <script>\r\n * ValironDevice.identify({ endpoint: '/api/valiron/device-identity/identify' })\r\n * .then(function (result) { console.log(result.state); });\r\n * </script>\r\n *\r\n * Set respectPrivacySignals: true to skip collection entirely when the\r\n * browser sends Do Not Track or Global Privacy Control.\r\n */\r\n(function () {\r\n 'use strict';\r\n\r\n function safe(fn, fallback) {\r\n try {\r\n var value = fn();\r\n return value === undefined ? fallback : value;\r\n } catch (_) {\r\n return fallback;\r\n }\r\n }\r\n\r\n function privacyRequested() {\r\n return safe(function () { return navigator.globalPrivacyControl === true; }, false)\r\n || safe(function () { return navigator.doNotTrack === '1' || window.doNotTrack === '1'; }, false);\r\n }\r\n\r\n function collect() {\r\n var screen_ = safe(function () {\r\n return {\r\n width: window.screen.width,\r\n height: window.screen.height,\r\n colorDepth: window.screen.colorDepth,\r\n pixelRatio: window.devicePixelRatio,\r\n };\r\n }, undefined);\r\n return {\r\n userAgent: safe(function () { return navigator.userAgent; }, undefined),\r\n languages: safe(function () {\r\n return navigator.languages && navigator.languages.length ? Array.from(navigator.languages) : [navigator.language];\r\n }, undefined),\r\n timezone: safe(function () { return Intl.DateTimeFormat().resolvedOptions().timeZone; }, undefined),\r\n platform: safe(function () { return navigator.platform; }, undefined),\r\n hardwareConcurrency: safe(function () { return navigator.hardwareConcurrency; }, undefined),\r\n deviceMemory: safe(function () { return navigator.deviceMemory; }, undefined),\r\n maxTouchPoints: safe(function () { return navigator.maxTouchPoints; }, undefined),\r\n screen: screen_,\r\n cookiesEnabled: safe(function () { return navigator.cookieEnabled; }, undefined),\r\n doNotTrack: privacyRequested(),\r\n webdriver: safe(function () { return navigator.webdriver === true; }, undefined),\r\n };\r\n }\r\n\r\n function identify(options) {\r\n if (!options || typeof options.endpoint !== 'string' || options.endpoint.length > 2048) {\r\n return Promise.reject(new Error('ValironDevice: endpoint is required'));\r\n }\r\n if (options.respectPrivacySignals === true && privacyRequested()) {\r\n return Promise.resolve({ state: 'skipped', reason: 'privacy_signal' });\r\n }\r\n var timeoutMs = typeof options.timeoutMs === 'number' && options.timeoutMs >= 500 && options.timeoutMs <= 10000\r\n ? options.timeoutMs : 4000;\r\n var controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;\r\n var timer = controller ? setTimeout(function () { controller.abort(); }, timeoutMs) : undefined;\r\n return fetch(options.endpoint, {\r\n method: 'POST',\r\n headers: { 'content-type': 'application/json' },\r\n credentials: options.credentials || 'same-origin',\r\n body: JSON.stringify({ signals: collect() }),\r\n signal: controller ? controller.signal : undefined,\r\n }).then(function (response) {\r\n if (!response.ok) throw new Error('ValironDevice: identify failed with ' + response.status);\r\n return response.json();\r\n }).finally(function () {\r\n if (timer) clearTimeout(timer);\r\n });\r\n }\r\n\r\n window.ValironDevice = Object.freeze({ identify: identify, collect: collect });\r\n})();\r\n\r\n";
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Deterministic identity: a first-party, server-signed visitor cookie.
3
+ *
4
+ * The cookie is the only exact-match signal in this package. It carries a
5
+ * random visitor id and an HMAC, never any device data. Signature failure
6
+ * or expiry is evidence ('invalid'), not an accusation.
7
+ */
8
+ export type CookieOptions = Readonly<{
9
+ name: string;
10
+ secret: string;
11
+ maxAgeMs: number;
12
+ }>;
13
+ export declare function validateCookieOptions(options: CookieOptions): void;
14
+ export declare function newVisitorId(): string;
15
+ export declare function signVisitorCookie(options: CookieOptions, visitorId: string, issuedAt: number): string;
16
+ export type VerifiedCookie = Readonly<{
17
+ state: 'valid';
18
+ visitorId: string;
19
+ issuedAt: number;
20
+ }> | Readonly<{
21
+ state: 'missing' | 'invalid';
22
+ }>;
23
+ /** Extract and verify this cookie from a Cookie header. Bounded scan; first match wins. */
24
+ export declare function verifyVisitorCookie(options: CookieOptions, cookieHeader: string | undefined, now: number): VerifiedCookie;
25
+ /** Serialize the Set-Cookie response header. HttpOnly, Secure, SameSite=Lax are not optional. */
26
+ export declare function serializeVisitorCookie(options: CookieOptions, value: string): string;
27
+ /** Expire the cookie immediately (used when a deployment disables collection). */
28
+ export declare function serializeCookieClear(options: CookieOptions): string;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * Deterministic identity: a first-party, server-signed visitor cookie.
4
+ *
5
+ * The cookie is the only exact-match signal in this package. It carries a
6
+ * random visitor id and an HMAC, never any device data. Signature failure
7
+ * or expiry is evidence ('invalid'), not an accusation.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.validateCookieOptions = validateCookieOptions;
11
+ exports.newVisitorId = newVisitorId;
12
+ exports.signVisitorCookie = signVisitorCookie;
13
+ exports.verifyVisitorCookie = verifyVisitorCookie;
14
+ exports.serializeVisitorCookie = serializeVisitorCookie;
15
+ exports.serializeCookieClear = serializeCookieClear;
16
+ const node_crypto_1 = require("node:crypto");
17
+ const VALUE_PATTERN = /^v1\.(\d{1,16})\.([A-Za-z0-9_-]{16,48})\.([A-Za-z0-9_-]{43})$/;
18
+ const NAME_PATTERN = /^(?:__Host-)?[A-Za-z][A-Za-z0-9_-]{0,63}$/;
19
+ function validateCookieOptions(options) {
20
+ if (!NAME_PATTERN.test(options.name))
21
+ throw new Error('Invalid visitor cookie name');
22
+ if (typeof options.secret !== 'string' || options.secret.length < 16 || options.secret.length > 256) {
23
+ throw new Error('Invalid visitor cookie secret');
24
+ }
25
+ if (!Number.isSafeInteger(options.maxAgeMs) || options.maxAgeMs < 3600000 || options.maxAgeMs > 400 * 86400000) {
26
+ throw new Error('Invalid visitor cookie max age');
27
+ }
28
+ }
29
+ function newVisitorId() {
30
+ return (0, node_crypto_1.randomBytes)(16).toString('base64url');
31
+ }
32
+ function mac(secret, payload) {
33
+ return (0, node_crypto_1.createHmac)('sha256', secret).update(payload).digest('base64url');
34
+ }
35
+ function signVisitorCookie(options, visitorId, issuedAt) {
36
+ const payload = `v1.${issuedAt}.${visitorId}`;
37
+ return `${payload}.${mac(options.secret, payload)}`;
38
+ }
39
+ /** Extract and verify this cookie from a Cookie header. Bounded scan; first match wins. */
40
+ function verifyVisitorCookie(options, cookieHeader, now) {
41
+ if (!cookieHeader || cookieHeader.length > 8192)
42
+ return { state: 'missing' };
43
+ let raw;
44
+ for (const part of cookieHeader.split(';')) {
45
+ const eq = part.indexOf('=');
46
+ if (eq === -1)
47
+ continue;
48
+ if (part.slice(0, eq).trim() === options.name) {
49
+ raw = part.slice(eq + 1).trim();
50
+ break;
51
+ }
52
+ }
53
+ if (!raw || raw.length > 256)
54
+ return { state: raw === undefined ? 'missing' : 'invalid' };
55
+ const match = raw.match(VALUE_PATTERN);
56
+ if (!match)
57
+ return { state: 'invalid' };
58
+ const [, issuedText, visitorId, tag] = match;
59
+ const issuedAt = Number(issuedText);
60
+ if (!Number.isSafeInteger(issuedAt) || issuedAt > now || now - issuedAt > options.maxAgeMs)
61
+ return { state: 'invalid' };
62
+ const expected = Buffer.from(mac(options.secret, `v1.${issuedText}.${visitorId}`));
63
+ const actual = Buffer.from(tag);
64
+ if (expected.length !== actual.length || !(0, node_crypto_1.timingSafeEqual)(expected, actual))
65
+ return { state: 'invalid' };
66
+ return { state: 'valid', visitorId, issuedAt };
67
+ }
68
+ /** Serialize the Set-Cookie response header. HttpOnly, Secure, SameSite=Lax are not optional. */
69
+ function serializeVisitorCookie(options, value) {
70
+ const seconds = Math.floor(options.maxAgeMs / 1000);
71
+ return `${options.name}=${value}; Path=/; Max-Age=${seconds}; HttpOnly; Secure; SameSite=Lax`;
72
+ }
73
+ /** Expire the cookie immediately (used when a deployment disables collection). */
74
+ function serializeCookieClear(options) {
75
+ return `${options.name}=; Path=/; Max-Age=0; HttpOnly; Secure; SameSite=Lax`;
76
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Valiron Device Identity.
3
+ *
4
+ * Recognizes a returning browser from two independent signal classes:
5
+ * 1. deterministic - the server-signed first-party visitor cookie
6
+ * 2. probabilistic - coarsened device signals, compared per component
7
+ *
8
+ * The output is identification evidence, nothing more. This package has no
9
+ * notion of fraud, risk, or enforcement. A 'similar' result means "this
10
+ * browser resembles a browser we have seen"; it does not establish the
11
+ * same person (shared devices, managed fleets, fresh installs all break
12
+ * that inference), and it is never sufficient grounds to deny service.
13
+ * Abuse decisions belong to the policy layer (crawler protection, the
14
+ * identity gate), which may consume this evidence alongside its own.
15
+ */
16
+ import { type CookieOptions } from './cookie';
17
+ import { type RawSignals } from './signals';
18
+ import { type IdentityStore } from './store';
19
+ export declare const COMPONENT_WEIGHTS: Readonly<Record<string, number>>;
20
+ export type RecognitionState = 'exact' | 'similar' | 'new';
21
+ export type Recognition = Readonly<{
22
+ state: RecognitionState;
23
+ /** The visitor id the deployment should treat as this browser going forward (from the newly set cookie). */
24
+ visitorId: string;
25
+ /** When 'similar': the prior visitor id this browser was linked from. */
26
+ matchedVisitorId?: string;
27
+ similarity?: Readonly<{
28
+ score: number;
29
+ threshold: number;
30
+ matched: readonly string[];
31
+ mismatched: readonly string[];
32
+ }>;
33
+ /** Observations a policy layer may use. Presence of a flag is evidence, not a verdict. */
34
+ evidence: Readonly<{
35
+ cookie: 'valid' | 'missing' | 'invalid';
36
+ webdriver: boolean;
37
+ doNotTrack: boolean;
38
+ signalVersion: number;
39
+ }>;
40
+ }>;
41
+ export type RecognizeResult = Readonly<{
42
+ recognition: Recognition;
43
+ /** Set-Cookie header value the server must send with its response. */
44
+ setCookie: string;
45
+ }>;
46
+ export type DeviceIdentityOptions = Readonly<{
47
+ /** Per-deployment salt for component hashes. Required; never shared across deployments. */
48
+ salt: string;
49
+ /** Bump when rotating the salt. Old profiles stop matching similarity lookups after rotation. */
50
+ saltVersion?: number;
51
+ store?: IdentityStore;
52
+ cookie: CookieOptions;
53
+ /** Profile retention. Enforced bounds: 1 hour .. 90 days. Default 30 days. */
54
+ retentionMs?: number;
55
+ /** Similarity score needed for a 'similar' link. Default 8 of 11.5. */
56
+ similarityThreshold?: number;
57
+ /**
58
+ * Component pair whose simultaneous mismatch vetoes a similarity link,
59
+ * or false to rely on the weighted score alone. Default ['tz', 'lang']:
60
+ * a traveler usually keeps their language, so a changed timezone alone
61
+ * never vetoes; both changing at once is the shared-device case this
62
+ * guard exists for. Set false only after measuring false-link rates.
63
+ */
64
+ hardMismatch?: readonly [string, string] | false;
65
+ now?: () => number;
66
+ }>;
67
+ export declare class DeviceIdentity {
68
+ private readonly options;
69
+ private readonly store;
70
+ private readonly retentionMs;
71
+ private readonly threshold;
72
+ private readonly now;
73
+ private readonly saltVersion;
74
+ private readonly hardMismatch;
75
+ constructor(options: DeviceIdentityOptions);
76
+ private hash;
77
+ private hashedComponents;
78
+ /**
79
+ * Recall filter for similarity candidates: language + platform only.
80
+ * Timezone is deliberately NOT part of the index - a traveler keeps
81
+ * their language and platform, so they remain a candidate and the
82
+ * weighted score absorbs the tz change. The index only bounds recall;
83
+ * scoring decides. Cardinality is capped by the store.
84
+ */
85
+ private indexKey;
86
+ private score;
87
+ /**
88
+ * Recognize one request. Always issues a fresh signed cookie; a 'similar'
89
+ * browser receives a NEW visitor id linked to the prior one - cookie
90
+ * continuity belongs only to the browser that actually holds the cookie.
91
+ */
92
+ recognize(input: {
93
+ cookieHeader?: string;
94
+ signals: RawSignals;
95
+ }): Promise<RecognizeResult>;
96
+ /** Data-subject deletion: remove one visitor profile and its similarity index entries. */
97
+ forget(visitorId: string): Promise<void>;
98
+ }
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ /**
3
+ * Valiron Device Identity.
4
+ *
5
+ * Recognizes a returning browser from two independent signal classes:
6
+ * 1. deterministic - the server-signed first-party visitor cookie
7
+ * 2. probabilistic - coarsened device signals, compared per component
8
+ *
9
+ * The output is identification evidence, nothing more. This package has no
10
+ * notion of fraud, risk, or enforcement. A 'similar' result means "this
11
+ * browser resembles a browser we have seen"; it does not establish the
12
+ * same person (shared devices, managed fleets, fresh installs all break
13
+ * that inference), and it is never sufficient grounds to deny service.
14
+ * Abuse decisions belong to the policy layer (crawler protection, the
15
+ * identity gate), which may consume this evidence alongside its own.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.DeviceIdentity = exports.COMPONENT_WEIGHTS = void 0;
19
+ const node_crypto_1 = require("node:crypto");
20
+ const cookie_1 = require("./cookie");
21
+ const signals_1 = require("./signals");
22
+ const store_1 = require("./store");
23
+ exports.COMPONENT_WEIGHTS = Object.freeze({
24
+ tz: 2,
25
+ lang: 2,
26
+ ua: 2,
27
+ platform: 1,
28
+ screen: 2,
29
+ depth: 1,
30
+ cores: 0.5,
31
+ mem: 0.5,
32
+ touch: 0.5,
33
+ });
34
+ const TOTAL_WEIGHT = Object.values(exports.COMPONENT_WEIGHTS).reduce((a, b) => a + b, 0);
35
+ const MIN_RETENTION_MS = 3600000;
36
+ const MAX_RETENTION_MS = 90 * 86400000;
37
+ const MAX_CANDIDATES = 25;
38
+ class DeviceIdentity {
39
+ options;
40
+ store;
41
+ retentionMs;
42
+ threshold;
43
+ now;
44
+ saltVersion;
45
+ hardMismatch;
46
+ constructor(options) {
47
+ this.options = options;
48
+ if (typeof options.salt !== 'string' || options.salt.length < 16 || options.salt.length > 256) {
49
+ throw new Error('Invalid identity salt');
50
+ }
51
+ (0, cookie_1.validateCookieOptions)(options.cookie);
52
+ this.retentionMs = options.retentionMs ?? 30 * 86400000;
53
+ if (!Number.isSafeInteger(this.retentionMs) || this.retentionMs < MIN_RETENTION_MS || this.retentionMs > MAX_RETENTION_MS) {
54
+ throw new Error('Invalid identity retention');
55
+ }
56
+ this.threshold = options.similarityThreshold ?? 8;
57
+ if (typeof this.threshold !== 'number' || this.threshold < 4 || this.threshold > TOTAL_WEIGHT) {
58
+ throw new Error('Invalid similarity threshold');
59
+ }
60
+ this.saltVersion = options.saltVersion ?? 1;
61
+ if (!Number.isSafeInteger(this.saltVersion) || this.saltVersion < 1 || this.saltVersion > 1000) {
62
+ throw new Error('Invalid salt version');
63
+ }
64
+ this.hardMismatch = options.hardMismatch === undefined ? ['tz', 'lang'] : options.hardMismatch;
65
+ if (this.hardMismatch !== false) {
66
+ const [a, b] = this.hardMismatch;
67
+ if (a === b || !(a in exports.COMPONENT_WEIGHTS) || !(b in exports.COMPONENT_WEIGHTS)) {
68
+ throw new Error('Invalid hard mismatch pair');
69
+ }
70
+ }
71
+ this.store = options.store ?? new store_1.MemoryIdentityStore(options.now ?? Date.now);
72
+ this.now = options.now ?? Date.now;
73
+ }
74
+ hash(value) {
75
+ return (0, node_crypto_1.createHash)('sha256').update(`v${this.saltVersion}.${this.options.salt}.${value}`).digest('hex');
76
+ }
77
+ hashedComponents(signals) {
78
+ const out = {};
79
+ for (const [name, value] of Object.entries((0, signals_1.signalComponents)(signals))) {
80
+ if (value)
81
+ out[name] = this.hash(`${name}=${value}`);
82
+ }
83
+ return out;
84
+ }
85
+ /**
86
+ * Recall filter for similarity candidates: language + platform only.
87
+ * Timezone is deliberately NOT part of the index - a traveler keeps
88
+ * their language and platform, so they remain a candidate and the
89
+ * weighted score absorbs the tz change. The index only bounds recall;
90
+ * scoring decides. Cardinality is capped by the store.
91
+ */
92
+ indexKey(signals) {
93
+ const components = (0, signals_1.signalComponents)(signals);
94
+ return this.hash(`idx=${components.lang}|${components.platform}`);
95
+ }
96
+ score(mine, theirs) {
97
+ const matched = [];
98
+ const mismatched = [];
99
+ let score = 0;
100
+ for (const [name, weight] of Object.entries(exports.COMPONENT_WEIGHTS)) {
101
+ const a = mine[name];
102
+ const b = theirs[name];
103
+ if (a === undefined || b === undefined)
104
+ continue;
105
+ if (a === b) {
106
+ score += weight;
107
+ matched.push(name);
108
+ }
109
+ else {
110
+ mismatched.push(name);
111
+ }
112
+ }
113
+ return { score, matched, mismatched };
114
+ }
115
+ /**
116
+ * Recognize one request. Always issues a fresh signed cookie; a 'similar'
117
+ * browser receives a NEW visitor id linked to the prior one - cookie
118
+ * continuity belongs only to the browser that actually holds the cookie.
119
+ */
120
+ async recognize(input) {
121
+ const now = this.now();
122
+ const signals = (0, signals_1.normalizeSignals)(input.signals ?? {});
123
+ const verified = (0, cookie_1.verifyVisitorCookie)(this.options.cookie, input.cookieHeader, now);
124
+ const components = this.hashedComponents(signals);
125
+ const indexKey = this.indexKey(signals);
126
+ const evidence = {
127
+ cookie: verified.state,
128
+ webdriver: signals.webdriver,
129
+ doNotTrack: signals.doNotTrack,
130
+ signalVersion: signals.schemaVersion,
131
+ };
132
+ let recognition;
133
+ if (verified.state === 'valid') {
134
+ const existing = await this.store.getProfile(verified.visitorId);
135
+ const profile = {
136
+ visitorId: verified.visitorId,
137
+ components,
138
+ indexKey,
139
+ linkedFrom: existing?.linkedFrom,
140
+ createdAt: existing?.createdAt ?? now,
141
+ lastSeenAt: now,
142
+ seenCount: (existing?.seenCount ?? 0) + 1,
143
+ };
144
+ await this.store.saveProfile(profile, this.retentionMs);
145
+ recognition = { state: 'exact', visitorId: verified.visitorId, evidence };
146
+ }
147
+ else {
148
+ const visitorId = (0, cookie_1.newVisitorId)();
149
+ let best;
150
+ for (const candidate of await this.store.candidates(indexKey, MAX_CANDIDATES)) {
151
+ if (now - candidate.lastSeenAt > this.retentionMs)
152
+ continue;
153
+ const scored = this.score(components, candidate.components);
154
+ if (this.hardMismatch !== false) {
155
+ const [a, b] = this.hardMismatch;
156
+ // Default pair is tz+lang: the shared-device case. A traveler
157
+ // changes tz but keeps lang, so this veto does not split them.
158
+ if (scored.mismatched.includes(a) && scored.mismatched.includes(b))
159
+ continue;
160
+ }
161
+ if (scored.score >= this.threshold && (!best || scored.score > best.score)) {
162
+ best = { profile: candidate, ...scored };
163
+ }
164
+ }
165
+ const profile = {
166
+ visitorId,
167
+ components,
168
+ indexKey,
169
+ linkedFrom: best?.profile.visitorId,
170
+ createdAt: now,
171
+ lastSeenAt: now,
172
+ seenCount: 1,
173
+ };
174
+ await this.store.saveProfile(profile, this.retentionMs);
175
+ recognition = best
176
+ ? {
177
+ state: 'similar',
178
+ visitorId,
179
+ matchedVisitorId: best.profile.visitorId,
180
+ similarity: {
181
+ score: best.score,
182
+ threshold: this.threshold,
183
+ matched: best.matched,
184
+ mismatched: best.mismatched,
185
+ },
186
+ evidence,
187
+ }
188
+ : { state: 'new', visitorId, evidence };
189
+ }
190
+ const setCookie = (0, cookie_1.serializeVisitorCookie)(this.options.cookie, (0, cookie_1.signVisitorCookie)(this.options.cookie, recognition.visitorId, now));
191
+ return { recognition, setCookie };
192
+ }
193
+ /** Data-subject deletion: remove one visitor profile and its similarity index entries. */
194
+ async forget(visitorId) {
195
+ await this.store.deleteProfile(visitorId);
196
+ }
197
+ }
198
+ exports.DeviceIdentity = DeviceIdentity;