@valiron/crawler-protection 0.0.0-stage → 0.2.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 (46) hide show
  1. package/README.md +223 -2
  2. package/dist/activation.d.ts +25 -0
  3. package/dist/activation.js +121 -0
  4. package/dist/adapters.d.ts +29 -0
  5. package/dist/adapters.js +69 -0
  6. package/dist/admission.d.ts +62 -0
  7. package/dist/admission.js +188 -0
  8. package/dist/cache.d.ts +42 -0
  9. package/dist/cache.js +130 -0
  10. package/dist/configuration.d.ts +54 -0
  11. package/dist/configuration.js +223 -0
  12. package/dist/directory.d.ts +36 -0
  13. package/dist/directory.js +155 -0
  14. package/dist/gateway.d.ts +31 -0
  15. package/dist/gateway.js +352 -0
  16. package/dist/guard.d.ts +110 -0
  17. package/dist/guard.js +294 -0
  18. package/dist/index.d.ts +17 -0
  19. package/dist/index.js +37 -0
  20. package/dist/internal.d.ts +29 -0
  21. package/dist/internal.js +50 -0
  22. package/dist/ip.d.ts +18 -0
  23. package/dist/ip.js +81 -0
  24. package/dist/meta.d.ts +13 -0
  25. package/dist/meta.js +34 -0
  26. package/dist/onboarding.d.ts +56 -0
  27. package/dist/onboarding.js +60 -0
  28. package/dist/operations.d.ts +60 -0
  29. package/dist/operations.js +149 -0
  30. package/dist/reporting.d.ts +44 -0
  31. package/dist/reporting.js +72 -0
  32. package/dist/runtime.d.ts +56 -0
  33. package/dist/runtime.js +69 -0
  34. package/dist/telemetry.d.ts +16 -0
  35. package/dist/telemetry.js +61 -0
  36. package/dist/verification.d.ts +113 -0
  37. package/dist/verification.js +238 -0
  38. package/gateway/Dockerfile +21 -0
  39. package/gateway/README.md +110 -0
  40. package/gateway/admin.cjs +34 -0
  41. package/gateway/compose.yaml +40 -0
  42. package/gateway/directory.cjs +10 -0
  43. package/gateway/service.cjs +97 -0
  44. package/gateway/work-api.openapi.json +186 -0
  45. package/integrations/python/valiron_crawler_protection.py +90 -0
  46. package/package.json +57 -4
@@ -0,0 +1,188 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AdmissionError = exports.RedisAdmission = void 0;
4
+ exports.keyPart = keyPart;
5
+ exports.withWorkSlot = withWorkSlot;
6
+ const node_os_1 = require("node:os");
7
+ const node_crypto_1 = require("node:crypto");
8
+ // All buckets use one server timestamp and commit only if every bucket admits.
9
+ const RATE = `
10
+ -- ADMISSION
11
+ local clock = redis.call('TIME')
12
+ local now = tonumber(clock[1]) * 1000 + tonumber(clock[2]) / 1000
13
+ local values = {}
14
+ local retry = 0
15
+ for i,key in ipairs(KEYS) do
16
+ local offset = (i-1)*3
17
+ local cap = tonumber(ARGV[offset+1])
18
+ local refill = tonumber(ARGV[offset+2])
19
+ local cost = tonumber(ARGV[offset+3])
20
+ local old = redis.call('HMGET', key, 'tokens', 'at')
21
+ local available = cap
22
+ if old[1] then available = math.min(cap, tonumber(old[1]) + math.max(0,now-tonumber(old[2]))*refill/1000) end
23
+ values[i] = available-cost
24
+ if available < cost then retry = math.max(retry, math.ceil((cost-available)/refill)) end
25
+ end
26
+ if retry > 0 then return {0, retry} end
27
+ for i,key in ipairs(KEYS) do
28
+ local offset = (i-1)*3
29
+ redis.call('HSET', key, 'tokens', values[i], 'at', now)
30
+ redis.call('PEXPIRE', key, math.ceil(tonumber(ARGV[offset+1])/tonumber(ARGV[offset+2])*1000)+1000)
31
+ end
32
+ return {1,0}
33
+ `;
34
+ // Slots intentionally have no TTL: a crashed process cannot silently free slots
35
+ // while its DB query may still be alive. Reconcile orphaned holds after draining.
36
+ const ACQUIRE = `
37
+ -- ADMISSION
38
+ -- WORK_ACQUIRE
39
+ local inventory = table.remove(KEYS,1)
40
+ local metadata = cjson.decode(table.remove(ARGV,1))
41
+ if redis.call('HLEN',inventory) >= 10000 then return 0 end
42
+ for i,key in ipairs(KEYS) do
43
+ if redis.call('HLEN',key) >= tonumber(ARGV[i+1]) then return 0 end
44
+ end
45
+ local clock = redis.call('TIME')
46
+ metadata.acquiredAt = tonumber(clock[1])*1000+math.floor(tonumber(clock[2])/1000)
47
+ metadata.keys = KEYS
48
+ for i,key in ipairs(KEYS) do redis.call('HSET',key,ARGV[1],1) end
49
+ redis.call('HSET',inventory,ARGV[1],cjson.encode(metadata))
50
+ return 1
51
+ `;
52
+ const RELEASE_PERMIT = `
53
+ local raw=redis.call('HGET',KEYS[1],ARGV[1])
54
+ if not raw then return 1 end
55
+ local record=cjson.decode(raw)
56
+ if record.releaseHash ~= ARGV[2] then return redis.error_reply('Invalid release capability') end
57
+ for _,key in ipairs(record.keys) do
58
+ if string.sub(key,1,string.len(ARGV[3])) ~= ARGV[3] then return redis.error_reply('Invalid hold key') end
59
+ end
60
+ for _,key in ipairs(record.keys) do redis.call('HDEL',key,ARGV[1]) end
61
+ redis.call('HDEL',KEYS[1],ARGV[1])
62
+ return 1
63
+ `;
64
+ function positive(value, integer = false) {
65
+ if (!Number.isFinite(value) || value <= 0 || value > 1e9 || (integer && !Number.isSafeInteger(value))) {
66
+ throw new Error('Invalid admission limit');
67
+ }
68
+ }
69
+ function keyPart(input) {
70
+ return (0, node_crypto_1.createHash)('sha256').update(input).digest('hex');
71
+ }
72
+ class RedisAdmission {
73
+ redis;
74
+ timeoutMs;
75
+ prefix;
76
+ constructor(redis, tenant, timeoutMs = 250) {
77
+ this.redis = redis;
78
+ this.timeoutMs = timeoutMs;
79
+ if (!tenant || tenant.length > 128)
80
+ throw new Error('Invalid tenant');
81
+ positive(timeoutMs, true);
82
+ this.prefix = `valiron:crawler:{${keyPart(tenant)}}:`;
83
+ }
84
+ keys(stage, names) {
85
+ if (!names.length || names.length > 16 || new Set(names).size !== names.length || names.some(k => !k || k.length > 512)) {
86
+ throw new Error('Invalid admission keys');
87
+ }
88
+ return names.map(name => this.prefix + stage + ':' + keyPart(name));
89
+ }
90
+ async run(script, keys, args) {
91
+ let timer;
92
+ try {
93
+ return await Promise.race([
94
+ this.redis.eval(script, keys.length, ...keys, ...args),
95
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Admission dependency timeout')), this.timeoutMs); }),
96
+ ]);
97
+ }
98
+ finally {
99
+ if (timer)
100
+ clearTimeout(timer);
101
+ }
102
+ }
103
+ async consume(buckets) {
104
+ for (const b of buckets) {
105
+ positive(b.capacity);
106
+ positive(b.refillPerSecond);
107
+ positive(b.cost);
108
+ if (b.cost > b.capacity || b.capacity / b.refillPerSecond > 86400)
109
+ throw new Error('Unserviceable bucket');
110
+ }
111
+ const keys = this.keys('rate', buckets.map(b => b.key));
112
+ const result = await this.run(RATE, keys, buckets.flatMap(b => [b.capacity, b.refillPerSecond, b.cost]));
113
+ if (!Array.isArray(result) || result.length !== 2 || ![0, 1].includes(Number(result[0])) ||
114
+ !Number.isFinite(Number(result[1])))
115
+ throw new Error('Invalid admission response');
116
+ return { allow: Number(result[0]) === 1, retryAfterSeconds: Math.min(86400, Math.max(1, Number(result[1]))) };
117
+ }
118
+ /** A transferable release capability; no TTL or automatic disconnect recovery. */
119
+ async acquirePermit(slots, metadata = {}) {
120
+ slots.forEach(s => positive(s.limit, true));
121
+ const fields = Object.fromEntries(Object.entries(metadata).filter(([, value]) => value !== undefined));
122
+ if (Object.keys(fields).some(key => !['requestId', 'lane'].includes(key)) ||
123
+ Object.values(fields).some(v => typeof v !== 'string' || v.length > 128))
124
+ throw new Error('Invalid hold metadata');
125
+ const keys = this.keys('work', slots.map(s => s.key));
126
+ const id = (0, node_crypto_1.randomUUID)();
127
+ const secret = (0, node_crypto_1.randomBytes)(32).toString('base64url');
128
+ const result = Number(await this.run(ACQUIRE, [this.prefix + 'holds', ...keys], [JSON.stringify({ ...fields,
129
+ slots: slots.map(s => s.key), owner: (0, node_os_1.hostname)() + ':' + process.pid + ':' + id, releaseHash: keyPart(secret) }), id, ...slots.map(s => s.limit)]));
130
+ if (result === 0)
131
+ return undefined;
132
+ if (result !== 1)
133
+ throw new Error('Invalid lease response');
134
+ return Object.freeze({ id, secret });
135
+ }
136
+ /** May run on another worker. Only the capability holder may release after confirmed settlement. */
137
+ async releasePermit(permit) {
138
+ if (!permit || !/^[a-f0-9-]{36}$/.test(permit.id) || !/^[A-Za-z0-9_-]{43}$/.test(permit.secret))
139
+ throw new Error('Invalid work permit');
140
+ await this.run(RELEASE_PERMIT, [this.prefix + 'holds'], [permit.id, keyPart(permit.secret), this.prefix + 'work:']);
141
+ }
142
+ async acquire(slots, metadata = {}) {
143
+ const permit = await this.acquirePermit(slots, metadata);
144
+ if (!permit)
145
+ return undefined;
146
+ let released = false;
147
+ return async () => {
148
+ if (released)
149
+ return;
150
+ await this.releasePermit(permit);
151
+ released = true;
152
+ };
153
+ }
154
+ }
155
+ exports.RedisAdmission = RedisAdmission;
156
+ class AdmissionError extends Error {
157
+ decision;
158
+ constructor(decision) {
159
+ super(decision.reason);
160
+ this.decision = decision;
161
+ }
162
+ }
163
+ exports.AdmissionError = AdmissionError;
164
+ /** Release after actual operation settlement, never after HTTP disconnect/timeout. */
165
+ async function withWorkSlot(input, operation) {
166
+ const requestId = input.requestId ?? (0, node_crypto_1.randomUUID)();
167
+ let release;
168
+ try {
169
+ release = await input.store.acquire(input.slots, { requestId, lane: input.lane });
170
+ }
171
+ catch {
172
+ throw new AdmissionError({ action: 'unavailable', reason: 'work_store_unavailable', requestId,
173
+ policyVersion: input.policyVersion, retryAfterSeconds: 1 });
174
+ }
175
+ if (!release)
176
+ throw new AdmissionError({ action: 'unavailable', reason: 'work_capacity_exhausted', requestId,
177
+ policyVersion: input.policyVersion, retryAfterSeconds: 1 });
178
+ try {
179
+ return await operation();
180
+ }
181
+ finally {
182
+ // Preserve the operation outcome. A failed release leaves a conservative hold.
183
+ await release().catch(() => { try {
184
+ input.onReleaseFailure?.();
185
+ }
186
+ catch { /* preserve operation outcome */ } });
187
+ }
188
+ }
@@ -0,0 +1,42 @@
1
+ import { type RedisEval } from './admission';
2
+ import { ManagedRedisAdmission } from './operations';
3
+ export type CacheEvent = 'bypass' | 'fresh_hit' | 'stale_hit' | 'miss' | 'regeneration_busy' | 'stored' | 'storage_skipped' | 'uncacheable' | 'error';
4
+ export type PublicResponse = {
5
+ status: number;
6
+ headers: Record<string, string>;
7
+ body: string;
8
+ };
9
+ /** Public catalog HTML only. Personalized requests bypass before reading shared state. */
10
+ export declare class CatalogCache {
11
+ private readonly config;
12
+ constructor(config: {
13
+ onEvent?: (event: CacheEvent) => void;
14
+ redis: RedisEval;
15
+ admission: ManagedRedisAdmission;
16
+ namespace: string;
17
+ queryKeys: readonly string[];
18
+ trackingKeys?: readonly string[];
19
+ freshMs: number;
20
+ staleMs: number;
21
+ maxBytes: number;
22
+ maxEntries: number;
23
+ maxRegenerations: number;
24
+ });
25
+ private emit;
26
+ private prefix;
27
+ key(input: {
28
+ method: string;
29
+ url: string;
30
+ headers: Record<string, string | undefined>;
31
+ }): string | undefined;
32
+ private cacheable;
33
+ get(input: {
34
+ method: string;
35
+ url: string;
36
+ headers: Record<string, string | undefined>;
37
+ },
38
+ /** Must admit the request BEFORE SSR, and admit every DB operation. */
39
+ admittedLoader: () => Promise<PublicResponse>,
40
+ /** Required for background stale refresh; otherwise stale is served without refresh. */
41
+ background?: (work: Promise<void>) => void): Promise<PublicResponse>;
42
+ }
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>;