@valiron/crawler-protection 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +217 -2
  2. package/dist/adapters.d.ts +29 -0
  3. package/dist/adapters.js +69 -0
  4. package/dist/admission.d.ts +62 -0
  5. package/dist/admission.js +188 -0
  6. package/dist/cache.d.ts +42 -0
  7. package/dist/cache.js +130 -0
  8. package/dist/configuration.d.ts +54 -0
  9. package/dist/configuration.js +223 -0
  10. package/dist/directory.d.ts +36 -0
  11. package/dist/directory.js +155 -0
  12. package/dist/gateway.d.ts +31 -0
  13. package/dist/gateway.js +341 -0
  14. package/dist/guard.d.ts +108 -0
  15. package/dist/guard.js +278 -0
  16. package/dist/index.d.ts +16 -0
  17. package/dist/index.js +32 -0
  18. package/dist/internal.d.ts +29 -0
  19. package/dist/internal.js +50 -0
  20. package/dist/ip.d.ts +18 -0
  21. package/dist/ip.js +81 -0
  22. package/dist/meta.d.ts +13 -0
  23. package/dist/meta.js +34 -0
  24. package/dist/onboarding.d.ts +56 -0
  25. package/dist/onboarding.js +60 -0
  26. package/dist/operations.d.ts +60 -0
  27. package/dist/operations.js +149 -0
  28. package/dist/reporting.d.ts +44 -0
  29. package/dist/reporting.js +72 -0
  30. package/dist/runtime.d.ts +44 -0
  31. package/dist/runtime.js +66 -0
  32. package/dist/telemetry.d.ts +16 -0
  33. package/dist/telemetry.js +61 -0
  34. package/dist/verification.d.ts +113 -0
  35. package/dist/verification.js +238 -0
  36. package/gateway/Dockerfile +21 -0
  37. package/gateway/README.md +107 -0
  38. package/gateway/admin.cjs +34 -0
  39. package/gateway/compose.yaml +40 -0
  40. package/gateway/directory.cjs +10 -0
  41. package/gateway/service.cjs +91 -0
  42. package/gateway/work-api.openapi.json +186 -0
  43. package/integrations/python/valiron_crawler_protection.py +90 -0
  44. package/package.json +57 -4
package/dist/cache.js ADDED
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CatalogCache = void 0;
4
+ const admission_1 = require("./admission");
5
+ /** Public catalog HTML only. Personalized requests bypass before reading shared state. */
6
+ class CatalogCache {
7
+ config;
8
+ constructor(config) {
9
+ this.config = config;
10
+ for (const n of [config.freshMs, config.staleMs, config.maxBytes, config.maxEntries, config.maxRegenerations])
11
+ if (!Number.isSafeInteger(n) || n < 1 || n > 1e8)
12
+ throw new Error('Invalid cache bound');
13
+ if (!config.namespace || config.namespace.length > 128 || config.freshMs + config.staleMs > 86400000)
14
+ throw new Error('Invalid cache lifetime');
15
+ if (config.trackingKeys?.some(k => config.queryKeys.includes(k)))
16
+ throw new Error('Ambiguous cache key');
17
+ // Snapshot mutable config arrays so callers cannot alter canonicalization later.
18
+ this.config = { ...config, queryKeys: [...config.queryKeys], trackingKeys: [...config.trackingKeys ?? []] };
19
+ }
20
+ emit(event) {
21
+ try {
22
+ void Promise.resolve(this.config.onEvent?.(event)).catch(() => { });
23
+ }
24
+ catch { /* reporting cannot change access */ }
25
+ }
26
+ prefix() { return `valiron:catalog:{${(0, admission_1.keyPart)(this.config.namespace)}}:`; }
27
+ key(input) {
28
+ const h = Object.fromEntries(Object.entries(input.headers).map(([k, v]) => [k.toLowerCase(), v]));
29
+ if (!['GET', 'HEAD'].includes(input.method) || h.cookie || h.authorization || h.range || h['cache-control']?.includes('no-cache'))
30
+ return undefined;
31
+ const url = new URL(input.url, 'https://catalog.invalid');
32
+ if (url.origin !== 'https://catalog.invalid')
33
+ return undefined;
34
+ for (const key of [...url.searchParams.keys()]) {
35
+ if (this.config.trackingKeys?.includes(key))
36
+ url.searchParams.delete(key);
37
+ else if (!this.config.queryKeys.includes(key))
38
+ return undefined;
39
+ }
40
+ url.searchParams.sort();
41
+ return (0, admission_1.keyPart)(url.pathname + url.search);
42
+ }
43
+ cacheable(r) {
44
+ const h = Object.fromEntries(Object.entries(r.headers).map(([k, v]) => [k.toLowerCase(), v]));
45
+ return r.status === 200 && !h['set-cookie'] && !/private|no-store|no-cache/i.test(h['cache-control'] ?? '') &&
46
+ !h.vary && /^text\/html\b/i.test(h['content-type'] ?? '') && Buffer.byteLength(JSON.stringify(r)) <= this.config.maxBytes;
47
+ }
48
+ async get(input,
49
+ /** Must admit the request BEFORE SSR, and admit every DB operation. */
50
+ admittedLoader,
51
+ /** Required for background stale refresh; otherwise stale is served without refresh. */
52
+ background) {
53
+ const key = this.key(input);
54
+ if (!key) {
55
+ this.emit('bypass');
56
+ return admittedLoader();
57
+ }
58
+ const prefix = this.prefix();
59
+ // All cache I/O is bounded by the Redis client's command timeout; failures fail closed on misses.
60
+ const raw = await this.config.redis.eval(`return redis.call('GET',KEYS[1])`, 1, prefix + key);
61
+ const entry = typeof raw === 'string' ? JSON.parse(raw) : undefined;
62
+ const now = Date.now();
63
+ if (entry && now < entry.freshUntil) {
64
+ this.emit('fresh_hit');
65
+ return entry.response;
66
+ }
67
+ // A HEAD handler may return an empty body. It may reuse a GET representation,
68
+ // but must never populate or regenerate that representation from a HEAD loader.
69
+ if (input.method === 'HEAD') {
70
+ if (entry && now < entry.staleUntil) {
71
+ this.emit('stale_hit');
72
+ return entry.response;
73
+ }
74
+ this.emit('bypass');
75
+ return admittedLoader();
76
+ }
77
+ this.emit(entry && now < entry.staleUntil ? 'stale_hit' : 'miss');
78
+ const regenerate = async () => {
79
+ const release = await this.config.admission.acquire([
80
+ { key: 'cache-key:' + key, limit: 1 }, { key: 'cache-regeneration', limit: this.config.maxRegenerations },
81
+ ], { lane: 'cache', requestId: key });
82
+ if (!release) {
83
+ this.emit('regeneration_busy');
84
+ return undefined;
85
+ }
86
+ try {
87
+ // Double-check after acquiring the lock; a competing regeneration may have just finished.
88
+ const existing = await this.config.redis.eval(`return redis.call('GET',KEYS[1])`, 1, prefix + key);
89
+ if (typeof existing === 'string') {
90
+ const fresh = JSON.parse(existing);
91
+ if (Date.now() < fresh.freshUntil)
92
+ return fresh.response;
93
+ }
94
+ const response = await admittedLoader();
95
+ if (this.cacheable(response)) {
96
+ const at = Date.now();
97
+ const value = { response, freshUntil: at + this.config.freshMs, staleUntil: at + this.config.freshMs + this.config.staleMs };
98
+ const stored = await this.config.redis.eval(`
99
+ local clock=redis.call('TIME') local now=tonumber(clock[1])*1000+tonumber(clock[2])/1000
100
+ redis.call('ZREMRANGEBYSCORE',KEYS[2],'-inf',now)
101
+ if redis.call('ZSCORE',KEYS[2],KEYS[1]) or redis.call('ZCARD',KEYS[2]) < tonumber(ARGV[3]) then
102
+ redis.call('SET',KEYS[1],ARGV[1],'PX',ARGV[2]) redis.call('ZADD',KEYS[2],now+tonumber(ARGV[2]),KEYS[1])
103
+ return 1
104
+ end return 0`, 2, prefix + key, prefix + 'index', JSON.stringify(value), this.config.freshMs + this.config.staleMs, this.config.maxEntries);
105
+ this.emit(Number(stored) === 1 ? 'stored' : 'storage_skipped');
106
+ }
107
+ else
108
+ this.emit('uncacheable');
109
+ return response;
110
+ }
111
+ catch (error) {
112
+ this.emit('error');
113
+ throw error;
114
+ }
115
+ finally {
116
+ await release();
117
+ }
118
+ };
119
+ if (entry && now < entry.staleUntil) {
120
+ if (background)
121
+ background(regenerate().then(() => { }, () => { }));
122
+ return entry.response;
123
+ }
124
+ const result = await regenerate();
125
+ if (!result)
126
+ return { status: 503, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', 'retry-after': '1' }, body: '{"code":"CACHE_REGENERATION_BUSY"}' };
127
+ return result;
128
+ }
129
+ }
130
+ exports.CatalogCache = CatalogCache;
@@ -0,0 +1,54 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import { type GuardPolicy } from './guard';
3
+ export type RouteInventoryEntry = Readonly<{
4
+ id: string;
5
+ path: string;
6
+ methods: readonly string[];
7
+ } & ({
8
+ kind: 'protected';
9
+ group: string;
10
+ } | {
11
+ kind: 'bypass';
12
+ })>;
13
+ export type CrawlerAccessRule = Readonly<{
14
+ provider: string;
15
+ crawlerClass: string;
16
+ groups: readonly string[];
17
+ action: 'budget' | 'deny';
18
+ }>;
19
+ export type CatalogCacheSettings = Readonly<{
20
+ groups: readonly string[];
21
+ queryKeys: readonly string[];
22
+ trackingKeys: readonly string[];
23
+ freshMs: number;
24
+ staleMs: number;
25
+ maxBytes: number;
26
+ maxEntries: number;
27
+ maxRegenerations: number;
28
+ }>;
29
+ export type CrawlerConfiguration = Readonly<{
30
+ schemaVersion: 1;
31
+ tenant: string;
32
+ policy: Omit<GuardPolicy, 'configurationId' | 'rollout'>;
33
+ inventory: readonly RouteInventoryEntry[];
34
+ rollout: NonNullable<GuardPolicy['rollout']>;
35
+ crawlerAccess?: readonly CrawlerAccessRule[];
36
+ cache?: CatalogCacheSettings;
37
+ }>;
38
+ export type ResolvedRoute = {
39
+ kind: 'protected';
40
+ id: string;
41
+ group: string;
42
+ cost: number;
43
+ } | {
44
+ kind: 'bypass';
45
+ id: string;
46
+ };
47
+ export type CompiledCrawlerConfiguration = Readonly<{
48
+ configuration: CrawlerConfiguration;
49
+ policy: GuardPolicy;
50
+ fingerprint: string;
51
+ resolve: (request: Pick<IncomingMessage, 'method' | 'url'>) => ResolvedRoute;
52
+ }>;
53
+ /** Strict JSON-compatible schema v1. Unknown fields, overlapping routes and missing groups reject. */
54
+ export declare function compileCrawlerConfiguration(input: unknown, now?: number): CompiledCrawlerConfiguration;
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compileCrawlerConfiguration = compileCrawlerConfiguration;
4
+ const guard_1 = require("./guard");
5
+ const operations_1 = require("./operations");
6
+ const label = /^[a-zA-Z0-9_-]{1,64}$/;
7
+ function object(value, keys, where) {
8
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !keys.includes(key)))
9
+ throw new Error('Invalid ' + where + ' fields');
10
+ }
11
+ function labels(value, where) {
12
+ if (!Array.isArray(value) || value.length > 128 || new Set(value).size !== value.length || value.some(v => typeof v !== 'string' || !label.test(v)))
13
+ throw new Error('Invalid ' + where);
14
+ }
15
+ function rate(value) { object(value, ['capacity', 'refillPerSecond'], 'rate'); }
16
+ function jsonData(input) {
17
+ let count = 0;
18
+ const visiting = new Set();
19
+ function visit(value, depth) {
20
+ if (++count > 20000 || depth > 32)
21
+ throw new Error('Configuration nesting/size exceeded');
22
+ if (value === null || typeof value === 'boolean')
23
+ return;
24
+ if (typeof value === 'string' && value.length <= 262144)
25
+ return;
26
+ if (typeof value === 'number' && Number.isFinite(value))
27
+ return;
28
+ if (!value || typeof value !== 'object' || visiting.has(value) || Object.getOwnPropertySymbols(value).length)
29
+ throw new Error('Configuration must be finite JSON data');
30
+ if (!Array.isArray(value) && ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
31
+ throw new Error('Configuration must use plain JSON objects');
32
+ if (Array.isArray(value) && Object.keys(value).length !== value.length)
33
+ throw new Error('Sparse/extended configuration arrays are invalid');
34
+ visiting.add(value);
35
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
36
+ if (Array.isArray(value) && key === 'length')
37
+ continue;
38
+ if (descriptor.get || descriptor.set || !descriptor.enumerable)
39
+ throw new Error('Configuration accessors are invalid');
40
+ visit(descriptor.value, depth + 1);
41
+ }
42
+ visiting.delete(value);
43
+ }
44
+ visit(input, 0);
45
+ }
46
+ function freeze(value) {
47
+ if (value && typeof value === 'object') {
48
+ for (const v of Object.values(value))
49
+ freeze(v);
50
+ Object.freeze(value);
51
+ }
52
+ return value;
53
+ }
54
+ function segments(path, pattern) {
55
+ if (typeof path !== 'string' || !path.startsWith('/') || path.startsWith('//') || path.length > 4096 || /[\\?#\s\x00-\x1f\x7f]/.test(path) || path.includes('//'))
56
+ throw new Error('Invalid route path');
57
+ const parts = path.replace(/\/$/, '').slice(1).split('/').filter(Boolean);
58
+ if (parts.length > 64)
59
+ throw new Error('Too many route segments');
60
+ return parts.map((part, i) => {
61
+ if (pattern && (part === '**' || /^:[a-zA-Z][a-zA-Z0-9_]*$/.test(part))) {
62
+ if (part === '**' && i !== parts.length - 1)
63
+ throw new Error('Wildcard must be terminal');
64
+ return part;
65
+ }
66
+ const decoded = decodeURIComponent(part);
67
+ if (decoded === '.' || decoded === '..' || /[%?#\\/\x00-\x20\x7f]/.test(decoded) || (pattern && /[%*:]/.test(part)))
68
+ throw new Error('Ambiguous route path');
69
+ return decoded;
70
+ });
71
+ }
72
+ function overlaps(a, b) {
73
+ for (let i = 0;; i++) {
74
+ if (a[i] === '**' || b[i] === '**')
75
+ return true;
76
+ if (a[i] === undefined || b[i] === undefined)
77
+ return a[i] === b[i];
78
+ if (!a[i].startsWith(':') && !b[i].startsWith(':') && a[i] !== b[i])
79
+ return false;
80
+ }
81
+ }
82
+ function matches(pattern, path) {
83
+ for (let i = 0;; i++) {
84
+ if (pattern[i] === '**')
85
+ return true;
86
+ if (pattern[i] === undefined || path[i] === undefined)
87
+ return pattern[i] === path[i];
88
+ if (!pattern[i].startsWith(':') && pattern[i] !== path[i])
89
+ return false;
90
+ }
91
+ }
92
+ /** Strict JSON-compatible schema v1. Unknown fields, overlapping routes and missing groups reject. */
93
+ function compileCrawlerConfiguration(input, now = Date.now()) {
94
+ // Reject non-JSON fields rather than silently dropping callbacks/undefined during serialization.
95
+ jsonData(input);
96
+ const encoded = JSON.stringify(input);
97
+ if (!encoded || Buffer.byteLength(encoded) > 262144)
98
+ throw new Error('Configuration too large');
99
+ const c = JSON.parse(encoded);
100
+ object(c, ['schemaVersion', 'tenant', 'policy', 'inventory', 'rollout', 'crawlerAccess', 'cache'], 'configuration');
101
+ if (c.schemaVersion !== 1 || typeof c.tenant !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(c.tenant))
102
+ throw new Error('Invalid configuration version or tenant');
103
+ object(c.policy, ['version', 'expiresAt', 'globalRate', 'unknownRate', 'perIpRate', 'providers', 'globalWorkLimit', 'unknownWorkLimit', 'providerWorkLimit', 'localWorkLimit', 'customers', 'maxOperationsPerRequest', 'maxContextAgeMs', 'routes'], 'policy');
104
+ for (const r of [c.policy.globalRate, c.policy.unknownRate, c.policy.perIpRate])
105
+ rate(r);
106
+ object(c.policy.providers, Object.keys(c.policy.providers ?? {}), 'providers');
107
+ if (Object.keys(c.policy.providers).length > 32)
108
+ throw new Error('Too many providers');
109
+ for (const [name, provider] of Object.entries(c.policy.providers)) {
110
+ if (!label.test(name))
111
+ throw new Error('Invalid provider');
112
+ object(provider, ['rate', 'classes'], 'provider');
113
+ rate(provider.rate);
114
+ object(provider.classes, Object.keys(provider.classes ?? {}), 'crawler classes');
115
+ if (Object.keys(provider.classes).length > 32)
116
+ throw new Error('Too many crawler classes');
117
+ for (const [name, value] of Object.entries(provider.classes)) {
118
+ if (!label.test(name))
119
+ throw new Error('Invalid crawler class');
120
+ rate(value);
121
+ }
122
+ }
123
+ object(c.policy.routes, Object.keys(c.policy.routes ?? {}), 'route groups');
124
+ for (const route of Object.values(c.policy.routes)) {
125
+ object(route, ['cost', 'rate', 'customerLane'], 'route group');
126
+ rate(route.rate);
127
+ if (route.customerLane !== undefined && route.customerLane !== 'checkout')
128
+ throw new Error('Invalid customer lane');
129
+ }
130
+ if (c.policy.customers) {
131
+ object(c.policy.customers, ['shopperReserve', 'checkoutReserve', 'shopperRate', 'checkoutRate'], 'customers');
132
+ rate(c.policy.customers.shopperRate);
133
+ rate(c.policy.customers.checkoutRate);
134
+ }
135
+ object(c.rollout, ['mode', 'enforceGroups', 'safetyRate', 'safetyPerIpRate'], 'rollout');
136
+ labels(c.rollout.enforceGroups, 'enforcement groups');
137
+ rate(c.rollout.safetyRate);
138
+ rate(c.rollout.safetyPerIpRate);
139
+ const fingerprint = (0, operations_1.policyFingerprint)(c);
140
+ const policy = { ...c.policy, rollout: c.rollout, configurationId: fingerprint };
141
+ (0, guard_1.validateGuardPolicy)(policy);
142
+ if (!Number.isSafeInteger(now) || policy.expiresAt <= now)
143
+ throw new Error('Configuration policy expired');
144
+ if (!Array.isArray(c.inventory) || !c.inventory.length || c.inventory.length > 128)
145
+ throw new Error('Invalid route inventory');
146
+ const ids = new Set();
147
+ const groups = new Set();
148
+ const inventory = c.inventory.map((entry) => {
149
+ object(entry, ['id', 'path', 'methods', 'kind', 'group'], 'inventory entry');
150
+ if (typeof entry.id !== 'string' || !label.test(entry.id) || ids.has(entry.id))
151
+ throw new Error('Invalid or duplicate route ID');
152
+ ids.add(entry.id);
153
+ labels(entry.methods, 'HTTP methods');
154
+ if (!entry.methods.length || entry.methods.some((m) => !['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'].includes(m)))
155
+ throw new Error('Invalid HTTP methods');
156
+ if (entry.methods.includes('GET') && !entry.methods.includes('HEAD'))
157
+ throw new Error('GET inventory must include HEAD');
158
+ if (entry.kind === 'protected') {
159
+ if (typeof entry.group !== 'string' || !Object.hasOwn(policy.routes, entry.group))
160
+ throw new Error('Missing route policy');
161
+ groups.add(entry.group);
162
+ }
163
+ else if (entry.kind !== 'bypass' || entry.group !== undefined)
164
+ throw new Error('Invalid route kind');
165
+ return { entry: entry, parts: segments(entry.path, true) };
166
+ });
167
+ for (let i = 0; i < inventory.length; i++)
168
+ for (let j = i + 1; j < inventory.length; j++) {
169
+ if (inventory[i].entry.methods.some(m => inventory[j].entry.methods.includes(m)) && overlaps(inventory[i].parts, inventory[j].parts))
170
+ throw new Error('Overlapping route inventory');
171
+ }
172
+ if (Object.keys(policy.routes).some(group => !groups.has(group)))
173
+ throw new Error('Policy group missing from route inventory');
174
+ if (c.crawlerAccess !== undefined) {
175
+ if (!Array.isArray(c.crawlerAccess) || c.crawlerAccess.length > 128)
176
+ throw new Error('Invalid crawler access rules');
177
+ const seen = new Set();
178
+ for (const rule of c.crawlerAccess) {
179
+ object(rule, ['provider', 'crawlerClass', 'groups', 'action'], 'crawler access');
180
+ if (typeof rule.provider !== 'string' || !label.test(rule.provider) || typeof rule.crawlerClass !== 'string' || !label.test(rule.crawlerClass) || !['budget', 'deny'].includes(rule.action))
181
+ throw new Error('Invalid crawler access');
182
+ labels(rule.groups, 'crawler route groups');
183
+ if (!rule.groups.length || rule.groups.some((group) => !groups.has(group)))
184
+ throw new Error('Invalid crawler access groups');
185
+ for (const group of rule.groups) {
186
+ const key = JSON.stringify([rule.provider, rule.crawlerClass, group]);
187
+ if (seen.has(key))
188
+ throw new Error('Duplicate crawler access rule');
189
+ seen.add(key);
190
+ }
191
+ }
192
+ }
193
+ if (c.cache !== undefined) {
194
+ object(c.cache, ['groups', 'queryKeys', 'trackingKeys', 'freshMs', 'staleMs', 'maxBytes', 'maxEntries', 'maxRegenerations'], 'cache');
195
+ labels(c.cache.groups, 'cache groups');
196
+ labels(c.cache.queryKeys, 'cache query keys');
197
+ labels(c.cache.trackingKeys, 'cache tracking keys');
198
+ if (!c.cache.groups.length || c.cache.groups.some((group) => !groups.has(group) || policy.routes[group].customerLane === 'checkout'))
199
+ throw new Error('Invalid public cache groups');
200
+ if (c.cache.queryKeys.some((key) => c.cache.trackingKeys.includes(key)))
201
+ throw new Error('Overlapping cache query keys');
202
+ for (const key of ['freshMs', 'staleMs', 'maxBytes', 'maxEntries', 'maxRegenerations'])
203
+ if (!Number.isSafeInteger(c.cache[key]) || c.cache[key] < 1 || c.cache[key] > 1e8)
204
+ throw new Error('Invalid cache bound');
205
+ if (c.cache.freshMs + c.cache.staleMs > 86400000)
206
+ throw new Error('Cache lifetime exceeds one day');
207
+ }
208
+ freeze(c);
209
+ freeze(policy);
210
+ return Object.freeze({ configuration: c, policy, fingerprint,
211
+ resolve(request) {
212
+ const url = request.url ?? '';
213
+ if (url.length > 8192 || /[\x00-\x20\x7f#]/.test(url))
214
+ throw new Error('Invalid request target');
215
+ const path = segments(url.split('?')[0], false);
216
+ const found = inventory.find(r => r.entry.methods.includes(request.method ?? '') && matches(r.parts, path));
217
+ if (!found)
218
+ throw new Error('Route absent from inventory');
219
+ const r = found.entry;
220
+ return r.kind === 'bypass' ? { kind: 'bypass', id: r.id } : { kind: 'protected', id: r.id, group: r.group, cost: policy.routes[r.group].cost };
221
+ },
222
+ });
223
+ }
@@ -0,0 +1,36 @@
1
+ import { type CrawlerEvidence } from './verification';
2
+ export declare const CRAWLER_DIRECTORY_URL = "https://verifiedbots.dev/data/all.json";
3
+ export declare const CRAWLER_DIRECTORY_ATTRIBUTION = "Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev), CC-BY-4.0";
4
+ export type DirectoryReview = Readonly<{
5
+ id: string;
6
+ name: string;
7
+ provider: string;
8
+ crawlerClass: string;
9
+ operatorUrl: string;
10
+ docs: readonly string[];
11
+ category: string;
12
+ tokens: readonly string[];
13
+ approval: string;
14
+ cidrCount: number;
15
+ eligible: boolean;
16
+ approved: boolean;
17
+ }>;
18
+ /** An external catalog is discovery data. CIDR identity requires a locally reviewed metadata hash. */
19
+ export declare class CrawlerDirectory {
20
+ private readonly now;
21
+ private entries;
22
+ private matchers;
23
+ private generatedAt;
24
+ private expiresAt;
25
+ private version;
26
+ private approvals;
27
+ constructor(approvals?: Readonly<Record<string, string>>, now?: () => number);
28
+ install(data: unknown, ttlMs?: number): void;
29
+ review(): DirectoryReview[];
30
+ classify(ip: string, ua: string): CrawlerEvidence;
31
+ }
32
+ /** Fetch one fixed public URL in the background; no directory-provided URL is ever fetched. */
33
+ export declare function refreshCrawlerDirectory(directory: CrawlerDirectory, options?: {
34
+ fetch?: typeof fetch;
35
+ ttlMs?: number;
36
+ }): Promise<void>;
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CrawlerDirectory = exports.CRAWLER_DIRECTORY_ATTRIBUTION = exports.CRAWLER_DIRECTORY_URL = void 0;
4
+ exports.refreshCrawlerDirectory = refreshCrawlerDirectory;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const ip_1 = require("./ip");
7
+ const verification_1 = require("./verification");
8
+ exports.CRAWLER_DIRECTORY_URL = 'https://verifiedbots.dev/data/all.json';
9
+ exports.CRAWLER_DIRECTORY_ATTRIBUTION = 'Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev), CC-BY-4.0';
10
+ const MAX_AGE = 48 * 3600000;
11
+ const label = /^[a-z0-9][a-z0-9_-]{0,53}$/;
12
+ // Never execute remotely supplied regex. Accept only literal names with optional version suffixes.
13
+ function token(pattern) {
14
+ if (typeof pattern !== 'string' || pattern.length > 128)
15
+ return;
16
+ const value = pattern.replace(/\\\\/g, '\\').replace(/\/(?:\\d|\[\\d\.\]\+)$/, '');
17
+ return /^[a-zA-Z][a-zA-Z0-9 _.-]{2,95}$/.test(value) ? value.toLowerCase() : undefined;
18
+ }
19
+ function hasToken(ua, value) {
20
+ let at = -1;
21
+ while ((at = ua.indexOf(value, at + 1)) !== -1) {
22
+ const before = ua[at - 1], after = ua[at + value.length];
23
+ if ((!before || !/[a-z0-9_.-]/.test(before)) && (!after || !/[a-z0-9_.-]/.test(after)))
24
+ return true;
25
+ }
26
+ return false;
27
+ }
28
+ function httpsUrl(value) {
29
+ if (typeof value !== 'string' || value.length > 2048)
30
+ return false;
31
+ try {
32
+ const u = new URL(value);
33
+ return u.protocol === 'https:' && !u.username && !u.password;
34
+ }
35
+ catch {
36
+ return false;
37
+ }
38
+ }
39
+ /** An external catalog is discovery data. CIDR identity requires a locally reviewed metadata hash. */
40
+ class CrawlerDirectory {
41
+ now;
42
+ entries = [];
43
+ matchers = new Map();
44
+ generatedAt = 0;
45
+ expiresAt = 0;
46
+ version = '';
47
+ approvals;
48
+ constructor(approvals = {}, now = Date.now) {
49
+ this.now = now;
50
+ if (!approvals || typeof approvals !== 'object' || Array.isArray(approvals) || Object.keys(approvals).length > 2000 ||
51
+ Object.entries(approvals).some(([id, hash]) => !label.test(id) || typeof hash !== 'string' || !/^[a-f0-9]{64}$/.test(hash)))
52
+ throw Error('Invalid directory approvals');
53
+ this.approvals = Object.freeze({ ...approvals });
54
+ }
55
+ install(data, ttlMs = 3600000) {
56
+ const body = data;
57
+ const now = this.now(), generatedAt = Date.parse(body?.generated_at);
58
+ if (!Number.isSafeInteger(ttlMs) || ttlMs < 1000 || ttlMs > 86400000 || body?.project !== 'Verified Bots Directory' ||
59
+ typeof body.generated_at !== 'string' || body.generated_at.length > 64 || !Array.isArray(body.bots) || !body.bots.length || body.bots.length > 2000 || body.count !== body.bots.length ||
60
+ !Number.isFinite(generatedAt) || generatedAt > now || now - generatedAt >= MAX_AGE || generatedAt < this.generatedAt)
61
+ throw Error('Invalid or stale directory');
62
+ const ids = new Set(), entries = [], matchers = new Map();
63
+ let totalCidrs = 0;
64
+ for (const bot of body.bots) {
65
+ if (!bot || !label.test(bot.id) || ids.has(bot.id) || typeof bot.name !== 'string' || bot.name.length > 256 ||
66
+ !Array.isArray(bot.user_agents?.patterns) || bot.user_agents.patterns.length > 32 ||
67
+ !Array.isArray(bot.verification) || bot.verification.length > 16 || !Array.isArray(bot.resolved_cidrs) || bot.resolved_cidrs.length > 10000 ||
68
+ bot.resolved_cidrs.some((v) => typeof v !== 'string') || typeof bot.category !== 'string')
69
+ throw Error('Invalid directory entry');
70
+ ids.add(bot.id);
71
+ totalCidrs += bot.resolved_cidrs.length;
72
+ if (totalCidrs > 100000)
73
+ throw Error('Directory CIDR limit');
74
+ // Keep official integrations authoritative; webhooks are outside crawler admission.
75
+ const tokens = [...new Set(bot.user_agents.patterns.map(token).filter(Boolean))];
76
+ if (!tokens.length || bot.category === 'webhook' || tokens.some(t => (0, verification_1.crawlerClaim)(t + '/1.0') || /^(facebook|meta-)/.test(t)))
77
+ continue;
78
+ const docs = Array.isArray(bot.docs) ? bot.docs.filter(httpsUrl) : [];
79
+ const operatorUrl = httpsUrl(bot.operator?.url) ? bot.operator.url : '';
80
+ const cidrs = bot.resolved_cidrs;
81
+ const hasCidrEvidence = [1, 2].includes(bot.tier) && Boolean(operatorUrl && docs.length) &&
82
+ bot.verification.some((v) => v?.type === 'cidr_feed' && httpsUrl(v.url) || v?.type === 'static_cidrs' && Array.isArray(v.cidrs));
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');
85
+ const entry = { id: bot.id, name: bot.name, operatorUrl, docs, category: bot.category, tokens, approval, cidrs, hasCidrEvidence };
86
+ entries.push(entry);
87
+ if (hasCidrEvidence && cidrs.length && this.approvals[bot.id] === approval) {
88
+ // Reject broad network claims, including IPv4-mapped IPv6. The strict matcher validates syntax too.
89
+ for (const range of cidrs) {
90
+ const [ip, bits] = range.split('/');
91
+ const normalized = (0, ip_1.normalizeIp)(ip);
92
+ if ((normalized.includes(':') && Number(bits) < 32) || (!normalized.includes(':') && (ip.includes(':') || Number(bits) < 8)))
93
+ throw Error('Overbroad directory CIDR');
94
+ }
95
+ matchers.set(bot.id, (0, ip_1.cidrMatcher)(cidrs));
96
+ }
97
+ }
98
+ // Commit only after every accepted entry has passed validation; failures preserve original expiry.
99
+ this.entries = entries;
100
+ this.matchers = matchers;
101
+ this.generatedAt = generatedAt;
102
+ this.expiresAt = Math.min(now + ttlMs, generatedAt + MAX_AGE);
103
+ this.version = body.generated_at;
104
+ }
105
+ review() {
106
+ return this.entries.map(e => ({ id: e.id, name: e.name, provider: 'directory-' + e.id, crawlerClass: e.id,
107
+ operatorUrl: e.operatorUrl, docs: [...e.docs], category: e.category, tokens: [...e.tokens], approval: e.approval,
108
+ cidrCount: e.cidrs.length, eligible: e.hasCidrEvidence && e.cidrs.length > 0, approved: this.matchers.has(e.id) && this.expiresAt > this.now() }));
109
+ }
110
+ classify(ip, ua) {
111
+ if (ua.length > 2048)
112
+ return { state: 'unverified' };
113
+ const lower = ua.toLowerCase();
114
+ const matches = this.entries.filter(e => e.tokens.some(t => hasToken(lower, t)));
115
+ if (matches.length > 1)
116
+ return { state: 'unverified', claimedCrawler: 'ambiguous-directory' };
117
+ if (!matches.length)
118
+ return { state: 'unverified' };
119
+ const entry = matches[0], claimedCrawler = entry.id;
120
+ const matcher = this.matchers.get(entry.id);
121
+ if (!matcher || this.expiresAt <= this.now())
122
+ return { state: 'verification_unavailable', claimedCrawler };
123
+ if (!matcher((0, ip_1.normalizeIp)(ip)))
124
+ return { state: 'claim_mismatch', claimedCrawler };
125
+ return { state: 'verified', claimedCrawler, provider: 'directory-' + entry.id, crawlerClass: entry.id,
126
+ method: 'directory_cidr', evidenceVersion: this.version, expiresAt: this.expiresAt };
127
+ }
128
+ }
129
+ exports.CrawlerDirectory = CrawlerDirectory;
130
+ /** Fetch one fixed public URL in the background; no directory-provided URL is ever fetched. */
131
+ async function refreshCrawlerDirectory(directory, options = {}) {
132
+ const response = await (options.fetch ?? fetch)(exports.CRAWLER_DIRECTORY_URL, { redirect: 'error', signal: AbortSignal.timeout(10000) });
133
+ if (!response.ok || !response.body) {
134
+ await response.body?.cancel().catch(() => { });
135
+ throw Error('Crawler directory unavailable');
136
+ }
137
+ const reader = response.body.getReader(), chunks = [];
138
+ let size = 0;
139
+ try {
140
+ for (;;) {
141
+ const chunk = await reader.read();
142
+ if (chunk.done)
143
+ break;
144
+ size += chunk.value.length;
145
+ if (size > 4 * 1024 * 1024)
146
+ throw Error('Crawler directory too large');
147
+ chunks.push(chunk.value);
148
+ }
149
+ }
150
+ finally {
151
+ await reader.cancel().catch(() => { });
152
+ reader.releaseLock();
153
+ }
154
+ directory.install(JSON.parse(Buffer.concat(chunks).toString('utf8')), options.ttlMs);
155
+ }
@@ -0,0 +1,31 @@
1
+ import { type IncomingMessage, type ServerResponse } from 'node:http';
2
+ import { InternalAdmission } from './internal';
3
+ import { createCrawlerRuntime } from './runtime';
4
+ type Runtime = ReturnType<typeof createCrawlerRuntime>;
5
+ /** Fixed-origin HTTP reverse proxy. The origin's language/framework is not involved in admission. */
6
+ export declare function createCrawlerGateway(input: {
7
+ runtime: Runtime;
8
+ origin: string;
9
+ publicHosts: readonly string[];
10
+ originSecret: string;
11
+ clientIp: (request: IncomingMessage) => string;
12
+ publicProtocol?: 'http' | 'https';
13
+ requestChannel?: InternalAdmission;
14
+ maxBodyBytes?: number;
15
+ upstreamTimeoutMs?: number;
16
+ maxConnections?: number;
17
+ onOrphan?: (event: {
18
+ requestId: string;
19
+ reason: string;
20
+ }) => void;
21
+ }): import("http").Server<typeof IncomingMessage, typeof ServerResponse>;
22
+ /** Private language-neutral operation admission. Deploy on a private listener, never route through the public gateway. */
23
+ export declare function createCrawlerWorkServer(input: {
24
+ runtime: Runtime;
25
+ channel: InternalAdmission;
26
+ apiSecret: string;
27
+ maxConnections?: number;
28
+ }): import("http").Server<typeof IncomingMessage, typeof ServerResponse>;
29
+ /** Origin middleware can compare this header in any language; network-restrict the origin as well. */
30
+ export declare function authenticateGatewayOrigin(request: IncomingMessage, originSecret: string): boolean;
31
+ export {};