@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,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
@@ -123,6 +123,9 @@ class CrawlerGuard {
123
123
  const classified = this.config.registry.classify(ip, input.userAgent);
124
124
  evidence = this.config.trustedEvidence?.(input.request, ip, input.userAgent) ?? (classified.claimedCrawler === 'bingbot' && (0, verification_1.crawlerClaim)(input.userAgent)?.provider === 'bing'
125
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
+ }
126
129
  const verified = evidence.state === 'verified';
127
130
  const provider = verified ? this.policy.providers[evidence.provider] : undefined;
128
131
  const crawlerRate = provider?.classes[evidence.crawlerClass];
@@ -165,6 +168,7 @@ class CrawlerGuard {
165
168
  (0, activation_1.assertActivation)(this.config.activation);
166
169
  details = { ...details, proposedAction: denied ? 'block' : result.allow ? 'allow' : 'limit' };
167
170
  if (result.allow || mode === 'observe') {
171
+ await this.config.activation.consume();
168
172
  const context = Object.freeze({ lane, principal: customer ? (0, admission_1.keyPart)(customer.principal) : undefined, ip, routeGroup: input.routeGroup, cost: input.cost, requestId,
169
173
  expiresAt: Math.min(this.policy.expiresAt, this.now() + this.policy.maxContextAgeMs),
170
174
  evidence: Object.freeze({ ...evidence }) });
@@ -176,8 +180,10 @@ class CrawlerGuard {
176
180
  }
177
181
  decision = { ...base, action: 'limit', reason: 'rate_budget_exhausted', retryAfterSeconds: result.retryAfterSeconds };
178
182
  }
179
- catch {
180
- decision = { ...base, action: 'unavailable', reason: 'admission_unavailable', retryAfterSeconds: 1 };
183
+ catch (error) {
184
+ decision = error instanceof activation_1.CrawlerMonthlyLimitError
185
+ ? { ...base, action: 'limit', reason: 'monthly_request_limit_exceeded', retryAfterSeconds: 60 }
186
+ : { ...base, action: 'unavailable', reason: 'admission_unavailable', retryAfterSeconds: 1 };
181
187
  }
182
188
  this.emit(decision, evidence, details);
183
189
  return { decision };
package/dist/index.d.ts CHANGED
@@ -14,4 +14,7 @@ export * from './onboarding';
14
14
  export * from './gateway';
15
15
  export * from './telemetry';
16
16
  export * from './directory';
17
+ export * from './webbotauth';
17
18
  export { createCrawlerActivation, activateCrawlerProtection, CRAWLER_ACTIVATION_ENDPOINT, type CrawlerActivation } from './activation';
19
+ export { DeviceIdentity, MemoryIdentityStore, RedisIdentityStore, createNodeDeviceIdentityMiddleware, deviceIdentityCollectorScript, serializeCookieClear, DEVICE_IDENTITY_DEFAULT_BASE_PATH, } from './device-identity';
20
+ export type { DeviceIdentityOptions, DeviceIdentityMiddlewareConfig, Recognition, RecognitionState, RecognizeResult, IdentityStore, StoredProfile, RawSignals, ScreenSignals, CookieOptions, VerifiedCookie, } from './device-identity';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.CRAWLER_ACTIVATION_ENDPOINT = exports.activateCrawlerProtection = exports.createCrawlerActivation = void 0;
17
+ exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = exports.serializeCookieClear = exports.deviceIdentityCollectorScript = exports.createNodeDeviceIdentityMiddleware = exports.RedisIdentityStore = exports.MemoryIdentityStore = exports.DeviceIdentity = exports.CRAWLER_ACTIVATION_ENDPOINT = exports.activateCrawlerProtection = exports.createCrawlerActivation = void 0;
18
18
  __exportStar(require("./ip"), exports);
19
19
  __exportStar(require("./verification"), exports);
20
20
  __exportStar(require("./admission"), exports);
@@ -31,7 +31,19 @@ __exportStar(require("./onboarding"), exports);
31
31
  __exportStar(require("./gateway"), exports);
32
32
  __exportStar(require("./telemetry"), exports);
33
33
  __exportStar(require("./directory"), exports);
34
+ __exportStar(require("./webbotauth"), exports);
34
35
  var activation_1 = require("./activation");
35
36
  Object.defineProperty(exports, "createCrawlerActivation", { enumerable: true, get: function () { return activation_1.createCrawlerActivation; } });
36
37
  Object.defineProperty(exports, "activateCrawlerProtection", { enumerable: true, get: function () { return activation_1.activateCrawlerProtection; } });
37
38
  Object.defineProperty(exports, "CRAWLER_ACTIVATION_ENDPOINT", { enumerable: true, get: function () { return activation_1.CRAWLER_ACTIVATION_ENDPOINT; } });
39
+ // Returning-browser recognition, folded into Crawler Protection so existing
40
+ // installs gain it without a second SDK. Evidence only: no fraud verdicts,
41
+ // no enforcement; collection activates only when the middleware is mounted.
42
+ var device_identity_1 = require("./device-identity");
43
+ Object.defineProperty(exports, "DeviceIdentity", { enumerable: true, get: function () { return device_identity_1.DeviceIdentity; } });
44
+ Object.defineProperty(exports, "MemoryIdentityStore", { enumerable: true, get: function () { return device_identity_1.MemoryIdentityStore; } });
45
+ Object.defineProperty(exports, "RedisIdentityStore", { enumerable: true, get: function () { return device_identity_1.RedisIdentityStore; } });
46
+ Object.defineProperty(exports, "createNodeDeviceIdentityMiddleware", { enumerable: true, get: function () { return device_identity_1.createNodeDeviceIdentityMiddleware; } });
47
+ Object.defineProperty(exports, "deviceIdentityCollectorScript", { enumerable: true, get: function () { return device_identity_1.deviceIdentityCollectorScript; } });
48
+ Object.defineProperty(exports, "serializeCookieClear", { enumerable: true, get: function () { return device_identity_1.serializeCookieClear; } });
49
+ Object.defineProperty(exports, "DEVICE_IDENTITY_DEFAULT_BASE_PATH", { enumerable: true, get: function () { return device_identity_1.DEVICE_IDENTITY_DEFAULT_BASE_PATH; } });
@@ -31,7 +31,8 @@ if lane == 'catalog' or lane == 'cache' or lane == 'gateway' then
31
31
  if state == 'open' then return 0 end
32
32
  if state == 'probe' then
33
33
  if lane == 'cache' then return 0 end
34
- for _,raw in ipairs(redis.call('HVALS',KEYS[1])) do
34
+ -- KEYS[1] is the pending-acquire cancellation key; KEYS[2] is inventory.
35
+ for _,raw in ipairs(redis.call('HVALS',KEYS[2])) do
35
36
  local held=cjson.decode(raw)
36
37
  if held.lane == lane then return 0 end
37
38
  end
package/dist/runtime.d.ts CHANGED
@@ -33,6 +33,7 @@ export declare function createCrawlerRuntime(input: {
33
33
  activation: Readonly<{
34
34
  tenant: string;
35
35
  start(): Promise<void>;
36
+ consume(): Promise<void>;
36
37
  refresh(): Promise<void>;
37
38
  stop(): void;
38
39
  status(): Readonly<{
@@ -3,9 +3,11 @@ export type CrawlerEvidence = Readonly<{
3
3
  claimedCrawler?: string;
4
4
  provider?: string;
5
5
  crawlerClass?: string;
6
- method?: 'published_cidr' | 'forward_confirmed_reverse_dns' | 'trusted_waf' | 'directory_cidr';
6
+ method?: 'published_cidr' | 'forward_confirmed_reverse_dns' | 'trusted_waf' | 'directory_cidr' | 'web_bot_auth';
7
7
  evidenceVersion?: string;
8
8
  expiresAt?: number;
9
+ /** Set only after a Web Bot Auth signature cryptographically verifies; a claimed URL is never reported. */
10
+ signerUrl?: string;
9
11
  }>;
10
12
  type Claim = {
11
13
  provider: string;
@@ -0,0 +1,70 @@
1
+ import type { CrawlerEvidence } from './verification';
2
+ /**
3
+ * Web Bot Auth (draft-ietf-webbotauth-httpsig-protocol) verification for
4
+ * crawlers and agents that cannot publish IP ranges.
5
+ *
6
+ * Scope and trust model:
7
+ * - A valid signature proves control of a pinned key for a Signature-Agent URL.
8
+ * It is not proof of good intent, of a recognized provider, or of admission.
9
+ * Budgets and policy still apply exactly as with IP/DNS verification.
10
+ * - Pin-only: keys come from operator-reviewed configuration. This module
11
+ * performs no network fetch, so a request can never steer this process into
12
+ * contacting an attacker-chosen directory URL. Dynamic resolution is
13
+ * deliberately omitted until it can ship with connect-time destination
14
+ * validation and bounded egress.
15
+ * - Freshness is not replay protection. The draft minimum coverage binds only
16
+ * @authority, so a captured signature can be replayed against this origin
17
+ * until `expires`. Verified signers remain subject to every budget, which
18
+ * bounds replay damage, and promotion to verified evidence is opt-in per
19
+ * signer. The optional 'strict' profile additionally requires @method and
20
+ * @path coverage; it is a Valiron profile stronger than the draft minimum,
21
+ * not a standard compliance claim.
22
+ */
23
+ export type WebBotAuthAgent = Readonly<{
24
+ provider: string;
25
+ crawlerClass: string;
26
+ /** Pinned Ed25519 JWKs (kty OKP, crv Ed25519) served by the signer URL. */
27
+ keys: readonly unknown[];
28
+ /** Opt-in: allow a valid signature to produce verified evidence. Default false:
29
+ * the authenticated signer is reported but admission stays on unverified budgets. */
30
+ promote?: boolean;
31
+ /** 'strict' additionally requires "@method" and "@path" coverage. Default draft minimum. */
32
+ profile?: 'standard' | 'strict';
33
+ }>;
34
+ type HeaderView = Readonly<{
35
+ method?: string;
36
+ url?: string;
37
+ headers?: Record<string, string | string[] | undefined>;
38
+ }>;
39
+ /** base64url JWK SHA-256 thumbprint for an Ed25519 OKP key (RFC 8037 Appendix A.3). */
40
+ export declare function ed25519Thumbprint(jwk: {
41
+ kty: string;
42
+ crv: string;
43
+ x: string;
44
+ }): string;
45
+ export declare class WebBotAuthVerifier {
46
+ private readonly agents;
47
+ private readonly now;
48
+ private readonly maxWindowMs;
49
+ private readonly skewMs;
50
+ constructor(options: {
51
+ agents: Readonly<Record<string, WebBotAuthAgent>>;
52
+ now?: () => number;
53
+ maxSignatureWindowMs?: number;
54
+ clockSkewMs?: number;
55
+ });
56
+ /**
57
+ * Compatible with CrawlerGuard's fallbackEvidence hook: pass the inbound request.
58
+ * Wired as fallbackEvidence, Web Bot Auth is consulted only when trusted/IP/DNS
59
+ * evidence did not verify, so an existing verified identity always stands.
60
+ * Returns undefined when the request carries no Web Bot Auth material, so the
61
+ * original evidence proceeds unchanged.
62
+ */
63
+ fallbackEvidence(request: unknown): CrawlerEvidence | undefined;
64
+ classify(request: HeaderView): CrawlerEvidence | undefined;
65
+ private verifyCandidate;
66
+ /** RFC 9421 signature base, rebuilt from the exact raw parameters the signer sent. */
67
+ private signatureBase;
68
+ private componentValue;
69
+ }
70
+ export {};
@@ -0,0 +1,323 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebBotAuthVerifier = void 0;
4
+ exports.ed25519Thumbprint = ed25519Thumbprint;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const MAX_HEADER = 8192;
7
+ const MAX_SIGNATURES = 4;
8
+ const MAX_AGENTS = 2000;
9
+ const MAX_KEYS = 16;
10
+ const DEFAULT_MAX_WINDOW_MS = 24 * 3600 * 1000; // draft recommends expires <= created + 24h
11
+ const DEFAULT_SKEW_MS = 60000;
12
+ const identityLabel = /^[a-z0-9_-]{1,64}$/;
13
+ function headerValue(headers, name) {
14
+ const value = headers?.[name];
15
+ const single = Array.isArray(value) ? (value.length === 1 ? value[0] : undefined) : value;
16
+ if (typeof single !== 'string' || single.length > MAX_HEADER)
17
+ return undefined;
18
+ return single;
19
+ }
20
+ /** Split on top-level separators, ignoring those inside strings or inner lists. */
21
+ function splitTopLevel(value, separator) {
22
+ const out = [];
23
+ let depth = 0, quoted = false, start = 0;
24
+ for (let i = 0; i < value.length; i++) {
25
+ const c = value[i];
26
+ if (quoted) {
27
+ if (c === '\\')
28
+ i++;
29
+ else if (c === '"')
30
+ quoted = false;
31
+ continue;
32
+ }
33
+ if (c === '"')
34
+ quoted = true;
35
+ else if (c === '(')
36
+ depth++;
37
+ else if (c === ')')
38
+ depth = Math.max(0, depth - 1);
39
+ else if (c === separator && depth === 0) {
40
+ out.push(value.slice(start, i));
41
+ start = i + 1;
42
+ }
43
+ }
44
+ out.push(value.slice(start));
45
+ return out.map(part => part.trim()).filter(Boolean);
46
+ }
47
+ function parseStringItem(value) {
48
+ if (value.length < 2 || value[0] !== '"' || value[value.length - 1] !== '"')
49
+ return undefined;
50
+ const inner = value.slice(1, -1);
51
+ if (!/^[ -~]*$/.test(inner))
52
+ return undefined;
53
+ return inner.replace(/\\(["\\])/g, '$1');
54
+ }
55
+ /** Parse one Signature-Input member: ("comp" "comp";key="label");created=...;expires=...;keyid="...";tag="..." */
56
+ function parseSignatureInputMember(label, raw) {
57
+ const close = raw.indexOf(')');
58
+ if (!raw.startsWith('(') || close < 0)
59
+ return undefined;
60
+ const inner = raw.slice(1, close);
61
+ const params = raw.slice(close + 1);
62
+ const components = [];
63
+ for (const item of splitTopLevel(inner, ' ')) {
64
+ const paramAt = item.indexOf(';');
65
+ const name = parseStringItem(paramAt === -1 ? item : item.slice(0, paramAt));
66
+ if (!name || name.length > 64)
67
+ return undefined;
68
+ let key;
69
+ if (paramAt !== -1) {
70
+ const match = /^;key=("(?:[^"\\]|\\.){1,64}")$/.exec(item.slice(paramAt));
71
+ if (!match)
72
+ return undefined; // only the key parameter is consumed here
73
+ key = parseStringItem(match[1]);
74
+ if (!key)
75
+ return undefined;
76
+ }
77
+ components.push({ id: name.toLowerCase(), key });
78
+ }
79
+ if (!components.length || components.length > 16)
80
+ return undefined;
81
+ const parsed = {};
82
+ for (const param of splitTopLevel(params.replace(/;/g, ','), ',')) {
83
+ if (!param)
84
+ continue;
85
+ const eq = param.indexOf('=');
86
+ if (eq < 1)
87
+ return undefined;
88
+ parsed[param.slice(0, eq).trim().toLowerCase()] = param.slice(eq + 1).trim();
89
+ }
90
+ const created = Number(parsed.created), expires = Number(parsed.expires);
91
+ const keyid = parsed.keyid ? parseStringItem(parsed.keyid) : undefined;
92
+ const tag = parsed.tag ? parseStringItem(parsed.tag) : undefined;
93
+ if (!Number.isSafeInteger(created) || !Number.isSafeInteger(expires) || !keyid || keyid.length > 64 || tag !== 'web-bot-auth')
94
+ return undefined;
95
+ return { label, raw: raw.trim(), components, created, expires, keyid, tag };
96
+ }
97
+ /** Signature-Agent members keyed by signature label, plus the legacy bare-string form. */
98
+ function parseSignatureAgent(header) {
99
+ const members = new Map();
100
+ if (header.startsWith('"')) {
101
+ const value = parseStringItem(header.trim());
102
+ return value ? new Map([['', value]]) : undefined; // legacy form; caller maps the covering label
103
+ }
104
+ for (const entry of splitTopLevel(header, ',')) {
105
+ const eq = entry.indexOf('=');
106
+ if (eq < 1)
107
+ return undefined;
108
+ const label = entry.slice(0, eq).trim();
109
+ let value = entry.slice(eq + 1).trim();
110
+ const semi = value.indexOf(';');
111
+ if (semi !== -1) {
112
+ value = value.slice(0, semi).trim();
113
+ continue;
114
+ } // members with parameters MUST be ignored
115
+ const url = parseStringItem(value);
116
+ if (!url)
117
+ return undefined;
118
+ members.set(label, url);
119
+ }
120
+ return members.size ? members : undefined;
121
+ }
122
+ function httpsAgentUrl(value) {
123
+ if (value.length > 2048)
124
+ return undefined;
125
+ try {
126
+ const url = new URL(value);
127
+ if (url.protocol !== 'https:' || url.username || url.password)
128
+ return undefined;
129
+ return url.href;
130
+ }
131
+ catch {
132
+ return undefined;
133
+ }
134
+ }
135
+ /** base64url JWK SHA-256 thumbprint for an Ed25519 OKP key (RFC 8037 Appendix A.3). */
136
+ function ed25519Thumbprint(jwk) {
137
+ const canonical = JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x });
138
+ return (0, node_crypto_1.createHash)('sha256').update(canonical, 'utf8').digest('base64url');
139
+ }
140
+ function pinKeys(keys) {
141
+ if (!Array.isArray(keys) || !keys.length || keys.length > MAX_KEYS)
142
+ throw new Error('Invalid pinned key set');
143
+ return keys.map(candidate => {
144
+ const jwk = candidate;
145
+ if (!jwk || jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(jwk.x)) {
146
+ throw new Error('Only Ed25519 OKP JWKs are supported');
147
+ }
148
+ const key = (0, node_crypto_1.createPublicKey)({ key: { kty: 'OKP', crv: 'Ed25519', x: jwk.x }, format: 'jwk' });
149
+ return { thumbprint: ed25519Thumbprint({ kty: 'OKP', crv: 'Ed25519', x: jwk.x }), key };
150
+ });
151
+ }
152
+ class WebBotAuthVerifier {
153
+ agents = new Map();
154
+ now;
155
+ maxWindowMs;
156
+ skewMs;
157
+ constructor(options) {
158
+ if (!options.agents || typeof options.agents !== 'object' || Array.isArray(options.agents) ||
159
+ Object.keys(options.agents).length > MAX_AGENTS)
160
+ throw new Error('Invalid Web Bot Auth agents');
161
+ this.now = options.now ?? Date.now;
162
+ this.maxWindowMs = options.maxSignatureWindowMs ?? DEFAULT_MAX_WINDOW_MS;
163
+ this.skewMs = options.clockSkewMs ?? DEFAULT_SKEW_MS;
164
+ if (!Number.isSafeInteger(this.maxWindowMs) || this.maxWindowMs < 1000 || this.maxWindowMs > DEFAULT_MAX_WINDOW_MS ||
165
+ !Number.isSafeInteger(this.skewMs) || this.skewMs < 0 || this.skewMs > 300000)
166
+ throw new Error('Invalid freshness bounds');
167
+ for (const [rawUrl, config] of Object.entries(options.agents)) {
168
+ const url = httpsAgentUrl(rawUrl);
169
+ if (!url || !config || !identityLabel.test(config.provider) || !identityLabel.test(config.crawlerClass) ||
170
+ (config.profile !== undefined && !['standard', 'strict'].includes(config.profile))) {
171
+ throw new Error('Invalid Web Bot Auth agent');
172
+ }
173
+ this.agents.set(url, { config: Object.freeze({ ...config }), keys: pinKeys(config.keys) });
174
+ }
175
+ }
176
+ /**
177
+ * Compatible with CrawlerGuard's fallbackEvidence hook: pass the inbound request.
178
+ * Wired as fallbackEvidence, Web Bot Auth is consulted only when trusted/IP/DNS
179
+ * evidence did not verify, so an existing verified identity always stands.
180
+ * Returns undefined when the request carries no Web Bot Auth material, so the
181
+ * original evidence proceeds unchanged.
182
+ */
183
+ fallbackEvidence(request) {
184
+ return this.classify(request);
185
+ }
186
+ classify(request) {
187
+ const signatureInput = headerValue(request?.headers, 'signature-input');
188
+ const signature = headerValue(request?.headers, 'signature');
189
+ const signatureAgent = headerValue(request?.headers, 'signature-agent');
190
+ if (signatureInput === undefined && signature === undefined && signatureAgent === undefined)
191
+ return undefined;
192
+ if (!signatureInput || !signature || !signatureAgent)
193
+ return { state: 'unverified' };
194
+ const agentUrls = parseSignatureAgent(signatureAgent);
195
+ if (!agentUrls)
196
+ return { state: 'unverified' };
197
+ const inputs = splitTopLevel(signatureInput, ',').slice(0, MAX_SIGNATURES + 1);
198
+ const signatures = splitTopLevel(signature, ',').slice(0, MAX_SIGNATURES + 1);
199
+ if (inputs.length > MAX_SIGNATURES || signatures.length > MAX_SIGNATURES)
200
+ return { state: 'unverified' };
201
+ const signatureValues = new Map();
202
+ for (const entry of signatures) {
203
+ const match = /^([a-z0-9.*-]{1,64})=:([A-Za-z0-9+/=_-]{1,4096}):$/.exec(entry);
204
+ if (!match)
205
+ return { state: 'unverified' };
206
+ signatureValues.set(match[1], match[2]);
207
+ }
208
+ for (const member of inputs) {
209
+ const eq = member.indexOf('=');
210
+ if (eq < 1)
211
+ continue;
212
+ const label = member.slice(0, eq).trim();
213
+ const params = parseSignatureInputMember(label, member.slice(eq + 1));
214
+ if (!params)
215
+ continue; // not a Web Bot Auth signature; another label may be
216
+ const outcome = this.verifyCandidate(request, params, agentUrls, signatureValues);
217
+ if (outcome)
218
+ return outcome;
219
+ }
220
+ return { state: 'unverified' };
221
+ }
222
+ verifyCandidate(request, params, agentUrls, signatureValues) {
223
+ // Required draft coverage: @authority plus the signature-agent member for this label.
224
+ const hasAuthority = params.components.some(c => c.id === '@authority' && !c.key);
225
+ const agentComponent = params.components.find(c => c.id === 'signature-agent' && c.key === params.label);
226
+ if (!hasAuthority || !agentComponent)
227
+ return undefined;
228
+ const rawUrl = agentUrls.get(params.label) ?? agentUrls.get(''); // legacy bare string
229
+ const url = rawUrl !== undefined ? httpsAgentUrl(rawUrl) : undefined;
230
+ if (!url)
231
+ return { state: 'unverified' };
232
+ const agent = this.agents.get(url);
233
+ if (!agent)
234
+ return { state: 'unverified' }; // unpinned signer: claim only, never privileged
235
+ const claimedCrawler = agent.config.crawlerClass;
236
+ const now = this.now();
237
+ // Freshness bounds the replay window; it is not replay protection.
238
+ if (params.expires * 1000 <= now - this.skewMs || params.created * 1000 > now + this.skewMs ||
239
+ (params.expires - params.created) * 1000 > this.maxWindowMs)
240
+ return { state: 'unverified', claimedCrawler };
241
+ if (agent.config.profile === 'strict' &&
242
+ !['@method', '@path'].every(id => params.components.some(c => c.id === id && !c.key))) {
243
+ return { state: 'claim_mismatch', claimedCrawler };
244
+ }
245
+ const key = agent.keys.find(candidate => candidate.thumbprint === params.keyid);
246
+ if (!key)
247
+ return { state: 'claim_mismatch', claimedCrawler }; // pinned set is evidence; a missing key fails
248
+ const signatureBase = this.signatureBase(request, params, url);
249
+ if (!signatureBase)
250
+ return { state: 'claim_mismatch', claimedCrawler };
251
+ const signatureBytes = Buffer.from(signatureValues.get(params.label) ?? '', 'base64');
252
+ if (!signatureBytes.length)
253
+ return { state: 'claim_mismatch', claimedCrawler };
254
+ let valid = false;
255
+ try {
256
+ valid = (0, node_crypto_1.verify)(null, Buffer.from(signatureBase, 'utf8'), key.key, signatureBytes);
257
+ }
258
+ catch {
259
+ valid = false;
260
+ }
261
+ if (!valid)
262
+ return { state: 'claim_mismatch', claimedCrawler };
263
+ if (agent.config.promote !== true) {
264
+ // Authenticated but not promoted: report the signer, keep unverified budgets.
265
+ return { state: 'unverified', claimedCrawler, signerUrl: url };
266
+ }
267
+ return {
268
+ state: 'verified', claimedCrawler, provider: agent.config.provider, crawlerClass: agent.config.crawlerClass,
269
+ method: 'web_bot_auth', evidenceVersion: 'webbotauth-pinned-v1', signerUrl: url,
270
+ expiresAt: params.expires * 1000,
271
+ };
272
+ }
273
+ /** RFC 9421 signature base, rebuilt from the exact raw parameters the signer sent. */
274
+ signatureBase(request, params, agentUrl) {
275
+ const lines = [];
276
+ for (const component of params.components) {
277
+ const serialized = this.componentValue(request, component, agentUrl);
278
+ if (serialized === undefined)
279
+ return undefined;
280
+ const identifier = component.key !== undefined ? `"${component.id}";key="${component.key}"` : `"${component.id}"`;
281
+ lines.push(`${identifier}: ${serialized}`);
282
+ }
283
+ lines.push(`"@signature-params": ${params.raw}`);
284
+ return lines.join('\n');
285
+ }
286
+ componentValue(request, component, agentUrl) {
287
+ if (component.id === 'signature-agent')
288
+ return component.key !== undefined ? `"${agentUrl}"` : undefined;
289
+ if (component.key !== undefined)
290
+ return undefined; // only signature-agent;key is supported
291
+ switch (component.id) {
292
+ case '@authority': {
293
+ const host = headerValue(request.headers, 'host')?.toLowerCase();
294
+ if (!host || host.length > 255 || /[\r\n]/.test(host))
295
+ return undefined;
296
+ return host;
297
+ }
298
+ case '@method': {
299
+ const method = request.method?.toLowerCase();
300
+ return method && /^[a-z]{1,16}$/.test(method) ? method : undefined;
301
+ }
302
+ case '@path': {
303
+ const path = request.url ?? '';
304
+ const queryAt = path.indexOf('?');
305
+ const value = queryAt === -1 ? path : path.slice(0, queryAt);
306
+ return value.startsWith('/') && value.length <= 4096 ? value : undefined;
307
+ }
308
+ case '@target-uri':
309
+ case '@scheme':
310
+ case '@request-target':
311
+ case '@query':
312
+ case '@status':
313
+ return undefined; // not reconstructible from the inbound view; treated as unverifiable
314
+ default: {
315
+ if (component.id.startsWith('@'))
316
+ return undefined;
317
+ const value = headerValue(request.headers, component.id);
318
+ return value !== undefined && !/[\r\n]/.test(value) ? value : undefined;
319
+ }
320
+ }
321
+ }
322
+ }
323
+ exports.WebBotAuthVerifier = WebBotAuthVerifier;