@valiron/crawler-protection 0.3.0 → 0.5.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,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,113 @@
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 activation_1 = require("../activation");
7
+ const collector_script_1 = require("./collector-script");
8
+ exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = '/api/valiron/device-identity';
9
+ let collectorCache;
10
+ /** The browser collector shipped with this package (public/collector.js). */
11
+ function deviceIdentityCollectorScript() {
12
+ if (collectorCache === undefined) {
13
+ collectorCache = collector_script_1.COLLECTOR_SCRIPT;
14
+ }
15
+ return collectorCache;
16
+ }
17
+ function sendJson(response, status, body, headers = {}) {
18
+ response.statusCode = status;
19
+ response.setHeader('Cache-Control', 'no-store');
20
+ response.setHeader('Content-Type', 'application/json; charset=utf-8');
21
+ for (const [name, value] of Object.entries(headers))
22
+ response.setHeader(name, value);
23
+ response.end(JSON.stringify(body));
24
+ }
25
+ function readBody(request, maxBytes) {
26
+ return new Promise((resolve, reject) => {
27
+ const chunks = [];
28
+ let size = 0;
29
+ request.on('data', (chunk) => {
30
+ size += chunk.length;
31
+ if (size > maxBytes) {
32
+ reject(new Error('body_too_large'));
33
+ request.destroy();
34
+ return;
35
+ }
36
+ chunks.push(chunk);
37
+ });
38
+ request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
39
+ request.on('error', reject);
40
+ });
41
+ }
42
+ function pathOf(request) {
43
+ const url = request.url ?? '';
44
+ const path = url.split('?')[0].replace(/\/+$/, '');
45
+ return path || '/';
46
+ }
47
+ /**
48
+ * Express-compatible middleware, also usable with a plain Node handler
49
+ * chain. Handles exactly two routes and delegates everything else:
50
+ * GET <basePath>/collector.js - the static browser collector
51
+ * POST <basePath>/identify - recognition; the response is { state } only
52
+ */
53
+ function createNodeDeviceIdentityMiddleware(config) {
54
+ const basePath = (config.basePath ?? exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH).replace(/\/+$/, '');
55
+ if (!basePath.startsWith('/'))
56
+ throw new Error('Invalid device identity base path');
57
+ const maxBodyBytes = config.maxBodyBytes ?? 4096;
58
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 256 || maxBodyBytes > 65536) {
59
+ throw new Error('Invalid device identity body limit');
60
+ }
61
+ return (request, response, next) => {
62
+ const path = pathOf(request);
63
+ if (request.method === 'GET' && path === `${basePath}/collector.js`) {
64
+ let script;
65
+ try {
66
+ script = deviceIdentityCollectorScript();
67
+ }
68
+ catch (error) {
69
+ next(error);
70
+ return;
71
+ }
72
+ response.statusCode = 200;
73
+ response.setHeader('Content-Type', 'application/javascript; charset=utf-8');
74
+ response.setHeader('Cache-Control', 'public, max-age=300');
75
+ response.end(script);
76
+ return;
77
+ }
78
+ if (path === `${basePath}/identify`) {
79
+ if (request.method !== 'POST') {
80
+ sendJson(response, 405, { error: 'method_not_allowed' }, { Allow: 'POST' });
81
+ return;
82
+ }
83
+ void (async () => {
84
+ let parsed;
85
+ try {
86
+ parsed = JSON.parse(await readBody(request, maxBodyBytes));
87
+ }
88
+ catch {
89
+ sendJson(response, 400, { error: 'invalid_body' });
90
+ return;
91
+ }
92
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
93
+ sendJson(response, 400, { error: 'invalid_body' });
94
+ return;
95
+ }
96
+ const { recognition, setCookie } = await config.identity.recognize({
97
+ cookieHeader: request.headers.cookie,
98
+ // Untrusted client input; only ever feeds similarity.
99
+ signals: (parsed.signals ?? {}),
100
+ });
101
+ config.onRecognition?.(recognition, request);
102
+ // The browser learns its state only. Echoing matched visitor ids or
103
+ // evidence would let a caller mimicking another browser's signals
104
+ // harvest that browser's identity.
105
+ sendJson(response, 200, { state: recognition.state }, { 'Set-Cookie': setCookie });
106
+ })().catch((error) => {
107
+ sendJson(response, error instanceof activation_1.CrawlerMonthlyLimitError ? 429 : 503, { error: error instanceof activation_1.CrawlerMonthlyLimitError ? "monthly_request_limit_exceeded" : "recognition_unavailable" });
108
+ });
109
+ return;
110
+ }
111
+ next();
112
+ };
113
+ }
@@ -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
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Profile persistence for Valiron Device Identity.
3
+ *
4
+ * A StoredProfile holds salted component hashes and coarse metadata only.
5
+ * Raw signal values, raw user agents, and IP addresses are never stored.
6
+ * Every entry carries a TTL; retention is a deployment decision enforced
7
+ * by the store, not by convention.
8
+ */
9
+ export type StoredProfile = Readonly<{
10
+ visitorId: string;
11
+ /** component name -> salted hash (see identity.ts) */
12
+ components: Readonly<Record<string, string>>;
13
+ /** salted hash of the (language | platform) pair - the recall filter for similarity candidates. Timezone is excluded on purpose so travelers stay findable. */
14
+ indexKey: string;
15
+ /** prior visitor id this browser was linked from via similarity, when known */
16
+ linkedFrom?: string;
17
+ createdAt: number;
18
+ lastSeenAt: number;
19
+ seenCount: number;
20
+ }>;
21
+ export interface IdentityStore {
22
+ getProfile(visitorId: string): Promise<StoredProfile | undefined>;
23
+ saveProfile(profile: StoredProfile, ttlMs: number): Promise<void>;
24
+ /** Data-subject deletion hook. Removing a profile removes both the id and its index entries. */
25
+ deleteProfile(visitorId: string, indexKey?: string): Promise<void>;
26
+ /** Up to `limit` profiles sharing an index key, most recently seen first. */
27
+ candidates(indexKey: string, limit: number): Promise<StoredProfile[]>;
28
+ }
29
+ /** In-memory store for tests and single-process pilots. Not multi-instance safe. */
30
+ export declare class MemoryIdentityStore implements IdentityStore {
31
+ private readonly now;
32
+ private readonly maxIndexMembers;
33
+ private profiles;
34
+ private index;
35
+ constructor(now?: () => number, maxIndexMembers?: number);
36
+ getProfile(visitorId: string): Promise<StoredProfile | undefined>;
37
+ saveProfile(profile: StoredProfile, ttlMs: number): Promise<void>;
38
+ deleteProfile(visitorId: string, indexKey?: string): Promise<void>;
39
+ candidates(indexKey: string, limit: number): Promise<StoredProfile[]>;
40
+ }
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ /**
3
+ * Profile persistence for Valiron Device Identity.
4
+ *
5
+ * A StoredProfile holds salted component hashes and coarse metadata only.
6
+ * Raw signal values, raw user agents, and IP addresses are never stored.
7
+ * Every entry carries a TTL; retention is a deployment decision enforced
8
+ * by the store, not by convention.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.MemoryIdentityStore = void 0;
12
+ /** In-memory store for tests and single-process pilots. Not multi-instance safe. */
13
+ class MemoryIdentityStore {
14
+ now;
15
+ maxIndexMembers;
16
+ profiles = new Map();
17
+ index = new Map(); // indexKey -> visitorId -> lastSeenAt
18
+ constructor(now = Date.now, maxIndexMembers = 500) {
19
+ this.now = now;
20
+ this.maxIndexMembers = maxIndexMembers;
21
+ }
22
+ async getProfile(visitorId) {
23
+ const entry = this.profiles.get(visitorId);
24
+ if (!entry)
25
+ return undefined;
26
+ if (entry.expiresAt <= this.now()) {
27
+ await this.deleteProfile(visitorId, entry.profile.indexKey);
28
+ return undefined;
29
+ }
30
+ return entry.profile;
31
+ }
32
+ async saveProfile(profile, ttlMs) {
33
+ this.profiles.set(profile.visitorId, { profile, expiresAt: this.now() + ttlMs });
34
+ let members = this.index.get(profile.indexKey);
35
+ if (!members) {
36
+ members = new Map();
37
+ this.index.set(profile.indexKey, members);
38
+ }
39
+ members.set(profile.visitorId, profile.lastSeenAt);
40
+ if (members.size > this.maxIndexMembers) {
41
+ const oldest = [...members.entries()].sort((a, b) => a[1] - b[1])[0];
42
+ members.delete(oldest[0]);
43
+ }
44
+ }
45
+ async deleteProfile(visitorId, indexKey) {
46
+ const existing = this.profiles.get(visitorId);
47
+ this.profiles.delete(visitorId);
48
+ const key = indexKey ?? existing?.profile.indexKey;
49
+ if (key)
50
+ this.index.get(key)?.delete(visitorId);
51
+ }
52
+ async candidates(indexKey, limit) {
53
+ const members = this.index.get(indexKey);
54
+ if (!members)
55
+ return [];
56
+ const ordered = [...members.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit);
57
+ const out = [];
58
+ for (const [visitorId] of ordered) {
59
+ const profile = await this.getProfile(visitorId);
60
+ if (profile)
61
+ out.push(profile);
62
+ }
63
+ return out;
64
+ }
65
+ }
66
+ exports.MemoryIdentityStore = MemoryIdentityStore;
package/dist/directory.js CHANGED
@@ -72,7 +72,7 @@ class CrawlerDirectory {
72
72
  if (totalCidrs > 100000)
73
73
  throw Error('Directory CIDR limit');
74
74
  // Keep official integrations authoritative; webhooks are outside crawler admission.
75
- const tokens = [...new Set(bot.user_agents.patterns.map(token).filter(Boolean))];
75
+ const tokens = [...new Set(bot.user_agents.patterns.map(token).filter((t) => Boolean(t) && !['mozilla', 'applewebkit', 'chrome', 'safari', 'compatible', 'bot', 'crawler'].includes(t)))];
76
76
  if (!tokens.length || bot.category === 'webhook' || tokens.some(t => (0, verification_1.crawlerClaim)(t + '/1.0') || /^(facebook|meta-)/.test(t)))
77
77
  continue;
78
78
  const docs = Array.isArray(bot.docs) ? bot.docs.filter(httpsUrl) : [];
@@ -81,10 +81,10 @@ class CrawlerDirectory {
81
81
  const hasCidrEvidence = [1, 2].includes(bot.tier) && Boolean(operatorUrl && docs.length) &&
82
82
  bot.verification.some((v) => v?.type === 'cidr_feed' && httpsUrl(v.url) || v?.type === 'static_cidrs' && Array.isArray(v.cidrs));
83
83
  const approval = (0, node_crypto_1.createHash)('sha256').update(JSON.stringify({ id: bot.id, operatorUrl, docs, category: bot.category,
84
- patterns: bot.user_agents.patterns, verification: bot.verification, tier: bot.tier })).digest('hex');
84
+ patterns: bot.user_agents.patterns, verification: bot.verification, tier: bot.tier, resolved_cidrs: [...cidrs].sort() })).digest('hex');
85
85
  const entry = { id: bot.id, name: bot.name, operatorUrl, docs, category: bot.category, tokens, approval, cidrs, hasCidrEvidence };
86
86
  entries.push(entry);
87
- if (hasCidrEvidence && cidrs.length && this.approvals[bot.id] === approval) {
87
+ if (hasCidrEvidence && cidrs.length) {
88
88
  // Reject broad network claims, including IPv4-mapped IPv6. The strict matcher validates syntax too.
89
89
  for (const range of cidrs) {
90
90
  const [ip, bits] = range.split('/');
@@ -92,7 +92,9 @@ class CrawlerDirectory {
92
92
  if ((normalized.includes(':') && Number(bits) < 32) || (!normalized.includes(':') && (ip.includes(':') || Number(bits) < 8)))
93
93
  throw Error('Overbroad directory CIDR');
94
94
  }
95
- matchers.set(bot.id, (0, ip_1.cidrMatcher)(cidrs));
95
+ const matcher = (0, ip_1.cidrMatcher)(cidrs);
96
+ if (this.approvals[bot.id] === approval)
97
+ matchers.set(bot.id, matcher);
96
98
  }
97
99
  }
98
100
  // Commit only after every accepted entry has passed validation; failures preserve original expiry.
package/dist/guard.d.ts CHANGED
@@ -86,6 +86,11 @@ export declare class CrawlerGuard {
86
86
  principal: string;
87
87
  } | undefined>;
88
88
  trustedEvidence?: (request: unknown, ip: string, userAgent: string) => CrawlerEvidence | undefined;
89
+ /** Consulted only when trusted/IP/DNS evidence did not verify. Existing verified
90
+ identities always win; a fallback result can never replace them. Web Bot Auth
91
+ wires in here so signed crawlers outside the approved lists get a verification
92
+ path without taking precedence over established source verification. */
93
+ fallbackEvidence?: (request: unknown, ip: string, userAgent: string) => CrawlerEvidence | undefined;
89
94
  crawlerAccess?: (evidence: CrawlerEvidence, routeGroup: string) => 'budget' | 'deny';
90
95
  onDecision?: (decision: Readonly<Decision>, evidence?: CrawlerEvidence, details?: DecisionDetails) => void;
91
96
  });
package/dist/guard.js CHANGED
@@ -111,7 +111,6 @@ class CrawlerGuard {
111
111
  if (!Object.hasOwn(this.policy.routes, input.routeGroup) || input.cost !== this.policy.routes[input.routeGroup].cost) {
112
112
  throw new Error('Unconfigured route cost');
113
113
  }
114
- await this.config.activation.consume();
115
114
  let customer = this.policy.customers && this.config.customer ? await this.config.customer(input.request, input.routeGroup) : undefined;
116
115
  if (customer && (!['shopper', 'checkout'].includes(customer.lane) || !customer.principal || customer.principal.length > 256))
117
116
  throw new Error('Invalid customer grant');
@@ -124,6 +123,9 @@ class CrawlerGuard {
124
123
  const classified = this.config.registry.classify(ip, input.userAgent);
125
124
  evidence = this.config.trustedEvidence?.(input.request, ip, input.userAgent) ?? (classified.claimedCrawler === 'bingbot' && (0, verification_1.crawlerClaim)(input.userAgent)?.provider === 'bing'
126
125
  ? this.config.bing.classify(ip) : classified);
126
+ if (evidence.state !== 'verified' && this.config.fallbackEvidence) {
127
+ evidence = this.config.fallbackEvidence(input.request, ip, input.userAgent) ?? evidence;
128
+ }
127
129
  const verified = evidence.state === 'verified';
128
130
  const provider = verified ? this.policy.providers[evidence.provider] : undefined;
129
131
  const crawlerRate = provider?.classes[evidence.crawlerClass];
@@ -166,6 +168,7 @@ class CrawlerGuard {
166
168
  (0, activation_1.assertActivation)(this.config.activation);
167
169
  details = { ...details, proposedAction: denied ? 'block' : result.allow ? 'allow' : 'limit' };
168
170
  if (result.allow || mode === 'observe') {
171
+ await this.config.activation.consume();
169
172
  const context = Object.freeze({ lane, principal: customer ? (0, admission_1.keyPart)(customer.principal) : undefined, ip, routeGroup: input.routeGroup, cost: input.cost, requestId,
170
173
  expiresAt: Math.min(this.policy.expiresAt, this.now() + this.policy.maxContextAgeMs),
171
174
  evidence: Object.freeze({ ...evidence }) });