@valiron/crawler-protection 0.2.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.
@@ -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;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Returning-browser recognition for Valiron Crawler Protection.
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. There is no notion
9
+ * of fraud, risk, or enforcement here. 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, which may consume this
14
+ * evidence alongside its own signals.
15
+ *
16
+ * Nothing in this module activates collection on its own. Mounting
17
+ * createNodeDeviceIdentityMiddleware() is the integration decision that
18
+ * wires the endpoint and serves the collector.
19
+ */
20
+ export * from './signals';
21
+ export * from './cookie';
22
+ export * from './store';
23
+ export * from './identity';
24
+ export * from './redis';
25
+ export * from './middleware';
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /**
18
+ * Returning-browser recognition for Valiron Crawler Protection.
19
+ *
20
+ * Recognizes a returning browser from two independent signal classes:
21
+ * 1. deterministic - the server-signed first-party visitor cookie
22
+ * 2. probabilistic - coarsened device signals, compared per component
23
+ *
24
+ * The output is identification evidence, nothing more. There is no notion
25
+ * of fraud, risk, or enforcement here. A 'similar' result means "this
26
+ * browser resembles a browser we have seen"; it does not establish the
27
+ * same person (shared devices, managed fleets, fresh installs all break
28
+ * that inference), and it is never sufficient grounds to deny service.
29
+ * Abuse decisions belong to the policy layer, which may consume this
30
+ * evidence alongside its own signals.
31
+ *
32
+ * Nothing in this module activates collection on its own. Mounting
33
+ * createNodeDeviceIdentityMiddleware() is the integration decision that
34
+ * wires the endpoint and serves the collector.
35
+ */
36
+ __exportStar(require("./signals"), exports);
37
+ __exportStar(require("./cookie"), exports);
38
+ __exportStar(require("./store"), exports);
39
+ __exportStar(require("./identity"), exports);
40
+ __exportStar(require("./redis"), exports);
41
+ __exportStar(require("./middleware"), exports);
@@ -0,0 +1,26 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { DeviceIdentity, Recognition } from './identity';
3
+ export declare const DEVICE_IDENTITY_DEFAULT_BASE_PATH = "/api/valiron/device-identity";
4
+ export type DeviceIdentityMiddlewareConfig = Readonly<{
5
+ identity: DeviceIdentity;
6
+ /** Mount path prefix. Default '/api/valiron/device-identity'. */
7
+ basePath?: string;
8
+ /** Maximum accepted identify body in bytes. Default 4096; bounds 256..65536. */
9
+ maxBodyBytes?: number;
10
+ /**
11
+ * Server-side sink for the full recognition (visitor id, matched visitor
12
+ * id, evidence). Never sent to the browser; the HTTP response carries
13
+ * only the recognition state. Intended for logs/analytics; consuming it
14
+ * in policy requires an explicit rollout decision.
15
+ */
16
+ onRecognition?: (recognition: Recognition, request: IncomingMessage) => void;
17
+ }>;
18
+ /** The browser collector shipped with this package (public/collector.js). */
19
+ export declare function deviceIdentityCollectorScript(): string;
20
+ /**
21
+ * Express-compatible middleware, also usable with a plain Node handler
22
+ * chain. Handles exactly two routes and delegates everything else:
23
+ * GET <basePath>/collector.js - the static browser collector
24
+ * POST <basePath>/identify - recognition; the response is { state } only
25
+ */
26
+ export declare function createNodeDeviceIdentityMiddleware(config: DeviceIdentityMiddlewareConfig): (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = void 0;
4
+ exports.deviceIdentityCollectorScript = deviceIdentityCollectorScript;
5
+ exports.createNodeDeviceIdentityMiddleware = createNodeDeviceIdentityMiddleware;
6
+ const collector_script_1 = require("./collector-script");
7
+ exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = '/api/valiron/device-identity';
8
+ let collectorCache;
9
+ /** The browser collector shipped with this package (public/collector.js). */
10
+ function deviceIdentityCollectorScript() {
11
+ if (collectorCache === undefined) {
12
+ collectorCache = collector_script_1.COLLECTOR_SCRIPT;
13
+ }
14
+ return collectorCache;
15
+ }
16
+ function sendJson(response, status, body, headers = {}) {
17
+ response.statusCode = status;
18
+ response.setHeader('Cache-Control', 'no-store');
19
+ response.setHeader('Content-Type', 'application/json; charset=utf-8');
20
+ for (const [name, value] of Object.entries(headers))
21
+ response.setHeader(name, value);
22
+ response.end(JSON.stringify(body));
23
+ }
24
+ function readBody(request, maxBytes) {
25
+ return new Promise((resolve, reject) => {
26
+ const chunks = [];
27
+ let size = 0;
28
+ request.on('data', (chunk) => {
29
+ size += chunk.length;
30
+ if (size > maxBytes) {
31
+ reject(new Error('body_too_large'));
32
+ request.destroy();
33
+ return;
34
+ }
35
+ chunks.push(chunk);
36
+ });
37
+ request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
38
+ request.on('error', reject);
39
+ });
40
+ }
41
+ function pathOf(request) {
42
+ const url = request.url ?? '';
43
+ const path = url.split('?')[0].replace(/\/+$/, '');
44
+ return path || '/';
45
+ }
46
+ /**
47
+ * Express-compatible middleware, also usable with a plain Node handler
48
+ * chain. Handles exactly two routes and delegates everything else:
49
+ * GET <basePath>/collector.js - the static browser collector
50
+ * POST <basePath>/identify - recognition; the response is { state } only
51
+ */
52
+ function createNodeDeviceIdentityMiddleware(config) {
53
+ const basePath = (config.basePath ?? exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH).replace(/\/+$/, '');
54
+ if (!basePath.startsWith('/'))
55
+ throw new Error('Invalid device identity base path');
56
+ const maxBodyBytes = config.maxBodyBytes ?? 4096;
57
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 256 || maxBodyBytes > 65536) {
58
+ throw new Error('Invalid device identity body limit');
59
+ }
60
+ return (request, response, next) => {
61
+ const path = pathOf(request);
62
+ if (request.method === 'GET' && path === `${basePath}/collector.js`) {
63
+ let script;
64
+ try {
65
+ script = deviceIdentityCollectorScript();
66
+ }
67
+ catch (error) {
68
+ next(error);
69
+ return;
70
+ }
71
+ response.statusCode = 200;
72
+ response.setHeader('Content-Type', 'application/javascript; charset=utf-8');
73
+ response.setHeader('Cache-Control', 'public, max-age=300');
74
+ response.end(script);
75
+ return;
76
+ }
77
+ if (path === `${basePath}/identify`) {
78
+ if (request.method !== 'POST') {
79
+ sendJson(response, 405, { error: 'method_not_allowed' }, { Allow: 'POST' });
80
+ return;
81
+ }
82
+ void (async () => {
83
+ let parsed;
84
+ try {
85
+ parsed = JSON.parse(await readBody(request, maxBodyBytes));
86
+ }
87
+ catch {
88
+ sendJson(response, 400, { error: 'invalid_body' });
89
+ return;
90
+ }
91
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
92
+ sendJson(response, 400, { error: 'invalid_body' });
93
+ return;
94
+ }
95
+ const { recognition, setCookie } = await config.identity.recognize({
96
+ cookieHeader: request.headers.cookie,
97
+ // Untrusted client input; only ever feeds similarity.
98
+ signals: (parsed.signals ?? {}),
99
+ });
100
+ config.onRecognition?.(recognition, request);
101
+ // The browser learns its state only. Echoing matched visitor ids or
102
+ // evidence would let a caller mimicking another browser's signals
103
+ // harvest that browser's identity.
104
+ sendJson(response, 200, { state: recognition.state }, { 'Set-Cookie': setCookie });
105
+ })().catch(next);
106
+ return;
107
+ }
108
+ next();
109
+ };
110
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Redis-backed identity store for multi-instance deployments.
3
+ *
4
+ * Uses a minimal command surface so any ioredis-compatible client works.
5
+ * Every key carries a TTL; the similarity index is a capped sorted set
6
+ * scored by lastSeenAt.
7
+ */
8
+ import type { IdentityStore, StoredProfile } from './store';
9
+ export type RedisLike = {
10
+ get(key: string): Promise<string | null>;
11
+ set(key: string, value: string, px: 'PX', ttlMs: number): Promise<unknown>;
12
+ del(...keys: string[]): Promise<unknown>;
13
+ zadd(key: string, score: number, member: string): Promise<unknown>;
14
+ zremrangebyrank(key: string, start: number, stop: number): Promise<unknown>;
15
+ zrevrange(key: string, start: number, stop: number): Promise<string[]>;
16
+ zrem(key: string, member: string): Promise<unknown>;
17
+ pexpire(key: string, ttlMs: number): Promise<unknown>;
18
+ };
19
+ export declare class RedisIdentityStore implements IdentityStore {
20
+ private readonly redis;
21
+ private readonly prefix;
22
+ private readonly maxIndexMembers;
23
+ constructor(redis: RedisLike, options?: {
24
+ keyPrefix?: string;
25
+ maxIndexMembers?: number;
26
+ });
27
+ private profileKey;
28
+ private indexKeyFor;
29
+ getProfile(visitorId: string): Promise<StoredProfile | undefined>;
30
+ saveProfile(profile: StoredProfile, ttlMs: number): Promise<void>;
31
+ deleteProfile(visitorId: string, indexKey?: string): Promise<void>;
32
+ candidates(indexKey: string, limit: number): Promise<StoredProfile[]>;
33
+ }
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ /**
3
+ * Redis-backed identity store for multi-instance deployments.
4
+ *
5
+ * Uses a minimal command surface so any ioredis-compatible client works.
6
+ * Every key carries a TTL; the similarity index is a capped sorted set
7
+ * scored by lastSeenAt.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.RedisIdentityStore = void 0;
11
+ class RedisIdentityStore {
12
+ redis;
13
+ prefix;
14
+ maxIndexMembers;
15
+ constructor(redis, options = {}) {
16
+ this.redis = redis;
17
+ this.prefix = options.keyPrefix ?? 'vdi:';
18
+ if (!/^[a-z0-9:._-]{1,64}$/i.test(this.prefix))
19
+ throw new Error('Invalid identity key prefix');
20
+ this.maxIndexMembers = options.maxIndexMembers ?? 500;
21
+ if (!Number.isSafeInteger(this.maxIndexMembers) || this.maxIndexMembers < 1 || this.maxIndexMembers > 10000) {
22
+ throw new Error('Invalid index bound');
23
+ }
24
+ }
25
+ profileKey(visitorId) {
26
+ return `${this.prefix}p:${visitorId}`;
27
+ }
28
+ indexKeyFor(indexKey) {
29
+ return `${this.prefix}i:${indexKey}`;
30
+ }
31
+ async getProfile(visitorId) {
32
+ const raw = await this.redis.get(this.profileKey(visitorId));
33
+ if (!raw || raw.length > 16384)
34
+ return undefined;
35
+ try {
36
+ const parsed = JSON.parse(raw);
37
+ if (parsed?.visitorId !== visitorId || typeof parsed.components !== 'object' || typeof parsed.indexKey !== 'string') {
38
+ return undefined;
39
+ }
40
+ return parsed;
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ }
46
+ async saveProfile(profile, ttlMs) {
47
+ await this.redis.set(this.profileKey(profile.visitorId), JSON.stringify(profile), 'PX', ttlMs);
48
+ const indexKey = this.indexKeyFor(profile.indexKey);
49
+ await this.redis.zadd(indexKey, profile.lastSeenAt, profile.visitorId);
50
+ await this.redis.pexpire(indexKey, ttlMs);
51
+ // Cap index cardinality; drop least-recent members beyond the bound.
52
+ await this.redis.zremrangebyrank(indexKey, 0, -this.maxIndexMembers - 1);
53
+ }
54
+ async deleteProfile(visitorId, indexKey) {
55
+ await this.redis.del(this.profileKey(visitorId));
56
+ if (indexKey)
57
+ await this.redis.zrem(this.indexKeyFor(indexKey), visitorId);
58
+ }
59
+ async candidates(indexKey, limit) {
60
+ const ids = await this.redis.zrevrange(this.indexKeyFor(indexKey), 0, Math.max(0, limit - 1));
61
+ const out = [];
62
+ for (const visitorId of ids.slice(0, 100)) {
63
+ const profile = await this.getProfile(visitorId);
64
+ if (profile)
65
+ out.push(profile);
66
+ }
67
+ return out;
68
+ }
69
+ }
70
+ exports.RedisIdentityStore = RedisIdentityStore;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Browser/device signal normalization for Valiron Device Identity.
3
+ *
4
+ * Two signal classes stay strictly separate in this package:
5
+ * - deterministic: the first-party, server-signed visitor cookie (cookie.ts)
6
+ * - probabilistic: the coarsened browser characteristics handled here
7
+ *
8
+ * Every probabilistic value is type-checked and clamped at the boundary.
9
+ * Raw values are used only to derive salted component hashes; the raw
10
+ * values themselves are never persisted by this package.
11
+ */
12
+ export declare const SIGNAL_SCHEMA_VERSION = 1;
13
+ export type RawSignals = Readonly<{
14
+ userAgent?: unknown;
15
+ languages?: unknown;
16
+ timezone?: unknown;
17
+ platform?: unknown;
18
+ hardwareConcurrency?: unknown;
19
+ deviceMemory?: unknown;
20
+ maxTouchPoints?: unknown;
21
+ screen?: unknown;
22
+ cookiesEnabled?: unknown;
23
+ doNotTrack?: unknown;
24
+ webdriver?: unknown;
25
+ }>;
26
+ export type ScreenSignals = Readonly<{
27
+ width: number;
28
+ height: number;
29
+ colorDepth: number;
30
+ pixelRatio: number;
31
+ }>;
32
+ export type NormalizedSignals = Readonly<{
33
+ schemaVersion: number;
34
+ uaFamily: string;
35
+ uaMajor: string;
36
+ languages: readonly string[];
37
+ timezone: string;
38
+ platform: string;
39
+ hardwareConcurrency: number;
40
+ deviceMemory: number;
41
+ maxTouchPoints: number;
42
+ screen?: ScreenSignals;
43
+ cookiesEnabled: boolean;
44
+ doNotTrack: boolean;
45
+ webdriver: boolean;
46
+ }>;
47
+ /** Strictly typed, bounded signals. Unknown or malformed input degrades to empty/coarse values, never throws. */
48
+ export declare function normalizeSignals(raw: RawSignals): NormalizedSignals;
49
+ /** The probabilistic components that participate in similarity scoring, in stable order. */
50
+ export declare function signalComponents(signals: NormalizedSignals): Readonly<Record<string, string>>;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ /**
3
+ * Browser/device signal normalization for Valiron Device Identity.
4
+ *
5
+ * Two signal classes stay strictly separate in this package:
6
+ * - deterministic: the first-party, server-signed visitor cookie (cookie.ts)
7
+ * - probabilistic: the coarsened browser characteristics handled here
8
+ *
9
+ * Every probabilistic value is type-checked and clamped at the boundary.
10
+ * Raw values are used only to derive salted component hashes; the raw
11
+ * values themselves are never persisted by this package.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.SIGNAL_SCHEMA_VERSION = void 0;
15
+ exports.normalizeSignals = normalizeSignals;
16
+ exports.signalComponents = signalComponents;
17
+ exports.SIGNAL_SCHEMA_VERSION = 1;
18
+ const MAX_UA = 512;
19
+ const MAX_LANGS = 8;
20
+ const MAX_LANG_LEN = 35;
21
+ const MAX_TZ = 64;
22
+ const MAX_PLATFORM = 64;
23
+ function str(value, max) {
24
+ if (typeof value !== 'string')
25
+ return '';
26
+ const trimmed = value.slice(0, max);
27
+ // Strip control characters; a signal string never carries markup.
28
+ // eslint-disable-next-line no-control-regex
29
+ return trimmed.replace(/[\x00-\x1f\x7f]/g, '');
30
+ }
31
+ function num(value, min, max) {
32
+ if (typeof value !== 'number' || !Number.isFinite(value))
33
+ return 0;
34
+ return Math.max(min, Math.min(max, Math.round(value)));
35
+ }
36
+ /** Coarse browser family + major version. The full UA string is never stored. */
37
+ function parseUa(ua) {
38
+ if (!ua)
39
+ return { family: '', major: '' };
40
+ const rules = [
41
+ [/edg(?:e|ios|a)?\/(\d{1,4})/i, 'edge'],
42
+ [/chrome\/(\d{1,4})/i, 'chrome'],
43
+ [/version\/(\d{1,4}).*safari/i, 'safari'],
44
+ [/firefox\/(\d{1,4})/i, 'firefox'],
45
+ ];
46
+ for (const [pattern, family] of rules) {
47
+ const match = ua.match(pattern);
48
+ if (match)
49
+ return { family, major: match[1] };
50
+ }
51
+ return { family: 'other', major: '' };
52
+ }
53
+ function normalizeLanguages(value) {
54
+ if (!Array.isArray(value))
55
+ return [];
56
+ const out = [];
57
+ for (const entry of value.slice(0, MAX_LANGS)) {
58
+ const lang = str(entry, MAX_LANG_LEN).toLowerCase();
59
+ if (/^[a-z0-9-]{2,35}$/.test(lang) && !out.includes(lang))
60
+ out.push(lang);
61
+ }
62
+ return out;
63
+ }
64
+ function normalizeScreen(value) {
65
+ if (!value || typeof value !== 'object' || Array.isArray(value))
66
+ return undefined;
67
+ const record = value;
68
+ const width = num(record.width, 0, 30000);
69
+ const height = num(record.height, 0, 30000);
70
+ if (!width || !height)
71
+ return undefined;
72
+ const colorDepth = num(record.colorDepth, 0, 64);
73
+ // Bucket pixel ratio; fractional precision adds uniqueness without recognition value.
74
+ const ratio = typeof record.pixelRatio === 'number' && Number.isFinite(record.pixelRatio)
75
+ ? Math.max(1, Math.min(4, Math.round(record.pixelRatio * 2) / 2))
76
+ : 0;
77
+ return { width, height, colorDepth, pixelRatio: ratio };
78
+ }
79
+ /** Strictly typed, bounded signals. Unknown or malformed input degrades to empty/coarse values, never throws. */
80
+ function normalizeSignals(raw) {
81
+ if (!raw || typeof raw !== 'object')
82
+ raw = {};
83
+ const ua = str(raw.userAgent, MAX_UA);
84
+ const { family, major } = parseUa(ua);
85
+ return {
86
+ schemaVersion: exports.SIGNAL_SCHEMA_VERSION,
87
+ uaFamily: family,
88
+ uaMajor: major,
89
+ languages: normalizeLanguages(raw.languages),
90
+ timezone: str(raw.timezone, MAX_TZ),
91
+ platform: str(raw.platform, MAX_PLATFORM),
92
+ hardwareConcurrency: num(raw.hardwareConcurrency, 0, 256),
93
+ deviceMemory: num(raw.deviceMemory, 0, 1024),
94
+ maxTouchPoints: num(raw.maxTouchPoints, 0, 256),
95
+ screen: normalizeScreen(raw.screen),
96
+ cookiesEnabled: raw.cookiesEnabled === true,
97
+ doNotTrack: raw.doNotTrack === true,
98
+ webdriver: raw.webdriver === true,
99
+ };
100
+ }
101
+ /** The probabilistic components that participate in similarity scoring, in stable order. */
102
+ function signalComponents(signals) {
103
+ const components = {
104
+ tz: signals.timezone,
105
+ lang: signals.languages[0] ?? '',
106
+ ua: signals.uaFamily ? `${signals.uaFamily}.${signals.uaMajor}` : '',
107
+ platform: signals.platform,
108
+ };
109
+ if (signals.screen) {
110
+ components.screen = `${signals.screen.width}x${signals.screen.height}`;
111
+ components.depth = `${signals.screen.colorDepth}@${signals.screen.pixelRatio}`;
112
+ }
113
+ if (signals.hardwareConcurrency)
114
+ components.cores = String(signals.hardwareConcurrency);
115
+ if (signals.deviceMemory)
116
+ components.mem = String(signals.deviceMemory);
117
+ if (signals.maxTouchPoints)
118
+ components.touch = String(signals.maxTouchPoints);
119
+ return components;
120
+ }