@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
@@ -0,0 +1,113 @@
1
+ export type CrawlerEvidence = Readonly<{
2
+ state: 'verified' | 'unverified' | 'claim_mismatch' | 'verification_unavailable';
3
+ claimedCrawler?: string;
4
+ provider?: string;
5
+ crawlerClass?: string;
6
+ method?: 'published_cidr' | 'forward_confirmed_reverse_dns' | 'trusted_waf' | 'directory_cidr';
7
+ evidenceVersion?: string;
8
+ expiresAt?: number;
9
+ }>;
10
+ type Claim = {
11
+ provider: string;
12
+ crawlerClass: string;
13
+ };
14
+ export declare function crawlerClaim(userAgent: string): Claim | undefined;
15
+ export type CidrSnapshot = {
16
+ provider: string;
17
+ crawlerClass: string;
18
+ version: string;
19
+ fetchedAt: number;
20
+ expiresAt: number;
21
+ cidrs: readonly string[];
22
+ };
23
+ export declare class CrawlerRegistry {
24
+ private readonly now;
25
+ private directory?;
26
+ setDirectory(directory: {
27
+ classify: (ip: string, ua: string) => CrawlerEvidence;
28
+ }): void;
29
+ private snapshots;
30
+ constructor(now?: () => number);
31
+ install(snapshot: CidrSnapshot): void;
32
+ classify(ip: string, ua: string): CrawlerEvidence;
33
+ }
34
+ /** Audited, fixed destinations. Feed refresh never follows redirects or accepts caller URLs. */
35
+ export declare const CRAWLER_FEEDS: Readonly<{
36
+ 'oai-searchbot': Readonly<{
37
+ provider: "openai";
38
+ url: "https://openai.com/searchbot.json";
39
+ }>;
40
+ gptbot: Readonly<{
41
+ provider: "openai";
42
+ url: "https://openai.com/gptbot.json";
43
+ }>;
44
+ 'chatgpt-user': Readonly<{
45
+ provider: "openai";
46
+ url: "https://openai.com/chatgpt-user.json";
47
+ }>;
48
+ googlebot: Readonly<{
49
+ provider: "google";
50
+ url: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json";
51
+ }>;
52
+ 'adsbot-google': Readonly<{
53
+ provider: "google";
54
+ url: "https://developers.google.com/static/crawling/ipranges/special-crawlers.json";
55
+ }>;
56
+ applebot: Readonly<{
57
+ provider: "apple";
58
+ url: "https://search.developer.apple.com/applebot.json";
59
+ }>;
60
+ duckduckbot: Readonly<{
61
+ provider: "duckduckgo";
62
+ url: "https://duckduckgo.com/duckduckbot.json";
63
+ }>;
64
+ perplexitybot: Readonly<{
65
+ provider: "perplexity";
66
+ url: "https://www.perplexity.ai/perplexitybot.json";
67
+ }>;
68
+ 'perplexity-user': Readonly<{
69
+ provider: "perplexity";
70
+ url: "https://www.perplexity.ai/perplexity-user.json";
71
+ }>;
72
+ }>;
73
+ export type CrawlerFeedId = keyof typeof CRAWLER_FEEDS;
74
+ export declare const OPENAI_FEEDS: Readonly<{
75
+ 'oai-searchbot': "https://openai.com/searchbot.json";
76
+ gptbot: "https://openai.com/gptbot.json";
77
+ 'chatgpt-user': "https://openai.com/chatgpt-user.json";
78
+ }>;
79
+ type FeedOptions = {
80
+ ttlMs: number;
81
+ fetch?: typeof fetch;
82
+ now?: () => number;
83
+ };
84
+ /** Invoke on a background schedule; never from an HTTP request handler. */
85
+ export declare function refreshCrawlerFeed(registry: CrawlerRegistry, crawler: CrawlerFeedId, options: FeedOptions): Promise<void>;
86
+ /** Backwards-compatible OpenAI-specific helper. */
87
+ export declare function refreshOpenAiFeed(registry: CrawlerRegistry, crawler: keyof typeof OPENAI_FEEDS, options: FeedOptions): Promise<void>;
88
+ /** Bounded batch refresh; one unavailable source does not prevent other sources updating. */
89
+ export declare function refreshCrawlerFeeds(registry: CrawlerRegistry, options: FeedOptions & {
90
+ concurrency?: number;
91
+ }): Promise<Record<CrawlerFeedId, 'updated' | 'unavailable'>>;
92
+ export type DnsLookup = (ip: string) => Promise<{
93
+ hostnames: string[];
94
+ addresses: string[];
95
+ ttlMs?: number;
96
+ }>;
97
+ export declare const bingDnsLookup: DnsLookup;
98
+ /** Cold requests are conservative. Background lookup is bounded and deduplicated. */
99
+ export declare class BingVerifier {
100
+ private readonly options;
101
+ private cache;
102
+ private pending;
103
+ constructor(options?: {
104
+ lookup?: DnsLookup;
105
+ now?: () => number;
106
+ maxEntries?: number;
107
+ maxConcurrent?: number;
108
+ });
109
+ classify(ip: string): CrawlerEvidence;
110
+ settled(): Promise<void>;
111
+ private verify;
112
+ }
113
+ export {};
@@ -0,0 +1,238 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BingVerifier = exports.bingDnsLookup = exports.OPENAI_FEEDS = exports.CRAWLER_FEEDS = exports.CrawlerRegistry = void 0;
4
+ exports.crawlerClaim = crawlerClaim;
5
+ exports.refreshCrawlerFeed = refreshCrawlerFeed;
6
+ exports.refreshOpenAiFeed = refreshOpenAiFeed;
7
+ exports.refreshCrawlerFeeds = refreshCrawlerFeeds;
8
+ const promises_1 = require("node:dns/promises");
9
+ const ip_1 = require("./ip");
10
+ const claims = [
11
+ [/\bbingbot\//i, { provider: 'bing', crawlerClass: 'bingbot' }],
12
+ [/\bOAI-SearchBot\//i, { provider: 'openai', crawlerClass: 'oai-searchbot' }],
13
+ [/\bGPTBot\//i, { provider: 'openai', crawlerClass: 'gptbot' }],
14
+ [/\bChatGPT-User\//i, { provider: 'openai', crawlerClass: 'chatgpt-user' }],
15
+ [/\bGooglebot\//i, { provider: 'google', crawlerClass: 'googlebot' }],
16
+ [/\bAdsBot-Google(?:-Mobile)?(?=[\s;)/]|$)/i, { provider: 'google', crawlerClass: 'adsbot-google' }],
17
+ [/\bApplebot\//i, { provider: 'apple', crawlerClass: 'applebot' }],
18
+ [/\bDuckDuckBot(?:-Https)?\//i, { provider: 'duckduckgo', crawlerClass: 'duckduckbot' }],
19
+ [/\bPerplexityBot\//i, { provider: 'perplexity', crawlerClass: 'perplexitybot' }],
20
+ [/\bPerplexity-User\//i, { provider: 'perplexity', crawlerClass: 'perplexity-user' }],
21
+ ];
22
+ function crawlerClaim(userAgent) {
23
+ if (userAgent.length > 2048)
24
+ return undefined;
25
+ const matches = claims.filter(([pattern]) => pattern.test(userAgent));
26
+ return matches.length === 1 ? { ...matches[0][1] } : undefined;
27
+ }
28
+ class CrawlerRegistry {
29
+ now;
30
+ directory;
31
+ setDirectory(directory) { this.directory = directory; }
32
+ snapshots = new Map();
33
+ constructor(now = Date.now) {
34
+ this.now = now;
35
+ }
36
+ install(snapshot) {
37
+ const allowed = claims.some(([, c]) => c.provider === snapshot.provider && c.crawlerClass === snapshot.crawlerClass);
38
+ if (!allowed || !snapshot.version || snapshot.version.length > 128 ||
39
+ !Number.isSafeInteger(snapshot.fetchedAt) || !Number.isSafeInteger(snapshot.expiresAt) ||
40
+ snapshot.fetchedAt > this.now() || snapshot.expiresAt <= this.now() ||
41
+ snapshot.expiresAt <= snapshot.fetchedAt || snapshot.expiresAt - snapshot.fetchedAt > 86400000) {
42
+ throw new Error('Invalid verification snapshot');
43
+ }
44
+ // Compile completely before replacing the last-known-good snapshot.
45
+ const { cidrs, ...metadata } = snapshot;
46
+ this.snapshots.set(snapshot.crawlerClass, { ...metadata, match: (0, ip_1.cidrMatcher)(cidrs) });
47
+ }
48
+ classify(ip, ua) {
49
+ const normalized = (0, ip_1.normalizeIp)(ip);
50
+ const claim = crawlerClaim(ua);
51
+ const external = this.directory?.classify(normalized, ua);
52
+ // Mixed identities never inherit a verified source's privilege.
53
+ if (external?.claimedCrawler && claims.some(([pattern]) => pattern.test(ua)))
54
+ return { state: 'unverified' };
55
+ if (!claim)
56
+ return external ?? { state: 'unverified' };
57
+ const claimedCrawler = claim.crawlerClass;
58
+ const snapshot = this.snapshots.get(claimedCrawler);
59
+ if (!snapshot || snapshot.expiresAt <= this.now())
60
+ return { state: 'verification_unavailable', claimedCrawler };
61
+ if (!snapshot.match(normalized))
62
+ return { state: 'claim_mismatch', claimedCrawler };
63
+ return { state: 'verified', claimedCrawler, provider: claim.provider, crawlerClass: claim.crawlerClass,
64
+ method: 'published_cidr', evidenceVersion: snapshot.version, expiresAt: snapshot.expiresAt };
65
+ }
66
+ }
67
+ exports.CrawlerRegistry = CrawlerRegistry;
68
+ /** Audited, fixed destinations. Feed refresh never follows redirects or accepts caller URLs. */
69
+ exports.CRAWLER_FEEDS = Object.freeze({
70
+ 'oai-searchbot': Object.freeze({ provider: 'openai', url: 'https://openai.com/searchbot.json' }),
71
+ gptbot: Object.freeze({ provider: 'openai', url: 'https://openai.com/gptbot.json' }),
72
+ 'chatgpt-user': Object.freeze({ provider: 'openai', url: 'https://openai.com/chatgpt-user.json' }),
73
+ googlebot: Object.freeze({ provider: 'google', url: 'https://developers.google.com/static/crawling/ipranges/common-crawlers.json' }),
74
+ 'adsbot-google': Object.freeze({ provider: 'google', url: 'https://developers.google.com/static/crawling/ipranges/special-crawlers.json' }),
75
+ applebot: Object.freeze({ provider: 'apple', url: 'https://search.developer.apple.com/applebot.json' }),
76
+ duckduckbot: Object.freeze({ provider: 'duckduckgo', url: 'https://duckduckgo.com/duckduckbot.json' }),
77
+ perplexitybot: Object.freeze({ provider: 'perplexity', url: 'https://www.perplexity.ai/perplexitybot.json' }),
78
+ 'perplexity-user': Object.freeze({ provider: 'perplexity', url: 'https://www.perplexity.ai/perplexity-user.json' }),
79
+ });
80
+ exports.OPENAI_FEEDS = Object.freeze({
81
+ 'oai-searchbot': exports.CRAWLER_FEEDS['oai-searchbot'].url,
82
+ gptbot: exports.CRAWLER_FEEDS.gptbot.url,
83
+ 'chatgpt-user': exports.CRAWLER_FEEDS['chatgpt-user'].url,
84
+ });
85
+ /** Invoke on a background schedule; never from an HTTP request handler. */
86
+ async function refreshCrawlerFeed(registry, crawler, options) {
87
+ if (!Object.hasOwn(exports.CRAWLER_FEEDS, crawler) || !Number.isSafeInteger(options.ttlMs) || options.ttlMs < 1000 || options.ttlMs > 86400000) {
88
+ throw new Error('Invalid feed configuration');
89
+ }
90
+ const source = exports.CRAWLER_FEEDS[crawler];
91
+ const response = await (options.fetch ?? fetch)(source.url, { redirect: 'error', signal: AbortSignal.timeout(5000) });
92
+ if (!response.ok || !response.body) {
93
+ await response.body?.cancel().catch(() => { });
94
+ throw new Error('Crawler feed unavailable');
95
+ }
96
+ const reader = response.body.getReader();
97
+ const chunks = [];
98
+ let size = 0;
99
+ try {
100
+ for (;;) {
101
+ const chunk = await reader.read();
102
+ if (chunk.done)
103
+ break;
104
+ size += chunk.value.length;
105
+ if (size > 1024 * 1024)
106
+ throw new Error('Crawler feed too large');
107
+ chunks.push(chunk.value);
108
+ }
109
+ }
110
+ finally {
111
+ await reader.cancel().catch(() => { });
112
+ reader.releaseLock();
113
+ }
114
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
115
+ if (!body || !Array.isArray(body.prefixes) || !body.prefixes.length || body.prefixes.length > 10000 ||
116
+ typeof body.creationTime !== 'string' || body.creationTime.length > 128)
117
+ throw new Error('Invalid crawler feed');
118
+ const cidrs = body.prefixes.map((entry) => {
119
+ if (!entry || typeof entry !== 'object')
120
+ throw new Error('Invalid prefix');
121
+ const record = entry;
122
+ const values = [record.ipv4Prefix, record.ipv6Prefix].filter(v => v !== undefined);
123
+ if (values.length !== 1 || typeof values[0] !== 'string')
124
+ throw new Error('Invalid prefix');
125
+ return values[0];
126
+ });
127
+ const fetchedAt = (options.now ?? Date.now)();
128
+ registry.install({ provider: source.provider, crawlerClass: crawler, version: body.creationTime,
129
+ fetchedAt, expiresAt: fetchedAt + options.ttlMs, cidrs });
130
+ }
131
+ /** Backwards-compatible OpenAI-specific helper. */
132
+ async function refreshOpenAiFeed(registry, crawler, options) {
133
+ if (!Object.hasOwn(exports.OPENAI_FEEDS, crawler))
134
+ throw new Error('Invalid feed configuration');
135
+ return refreshCrawlerFeed(registry, crawler, options);
136
+ }
137
+ /** Bounded batch refresh; one unavailable source does not prevent other sources updating. */
138
+ async function refreshCrawlerFeeds(registry, options) {
139
+ const concurrency = options.concurrency ?? 3;
140
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 8 ||
141
+ !Number.isSafeInteger(options.ttlMs) || options.ttlMs < 1000 || options.ttlMs > 86400000)
142
+ throw new Error('Invalid feed configuration');
143
+ const queue = Object.keys(exports.CRAWLER_FEEDS);
144
+ const results = {};
145
+ await Promise.all(Array.from({ length: concurrency }, async () => {
146
+ for (;;) {
147
+ const crawler = queue.shift();
148
+ if (!crawler)
149
+ return;
150
+ try {
151
+ await refreshCrawlerFeed(registry, crawler, options);
152
+ results[crawler] = 'updated';
153
+ }
154
+ catch {
155
+ results[crawler] = 'unavailable';
156
+ }
157
+ }
158
+ }));
159
+ return results;
160
+ }
161
+ const bingDnsLookup = async (ip) => {
162
+ const resolver = new promises_1.Resolver({ timeout: 1500, tries: 1 });
163
+ const timeout = setTimeout(() => resolver.cancel(), 4000);
164
+ try {
165
+ const hostnames = (await resolver.reverse(ip)).slice(0, 8).map(h => h.toLowerCase().replace(/\.$/, ''));
166
+ const approved = hostnames.filter(h => h.endsWith('.search.msn.com') && /^[a-z0-9.-]{1,253}$/.test(h));
167
+ const addresses = [];
168
+ const ttls = [];
169
+ // Bound actual DNS operations; do not follow arbitrary PTR names.
170
+ for (const name of approved.slice(0, 2)) {
171
+ const answers = await Promise.allSettled([resolver.resolve4(name, { ttl: true }), resolver.resolve6(name, { ttl: true })]);
172
+ for (const result of answers)
173
+ if (result.status === 'fulfilled')
174
+ for (const record of result.value) {
175
+ addresses.push(record.address);
176
+ if ((0, ip_1.normalizeIp)(record.address) === ip)
177
+ ttls.push(record.ttl * 1000);
178
+ }
179
+ }
180
+ return { hostnames: approved, addresses, ttlMs: Math.min(30000, ...ttls) };
181
+ }
182
+ finally {
183
+ clearTimeout(timeout);
184
+ }
185
+ };
186
+ exports.bingDnsLookup = bingDnsLookup;
187
+ /** Cold requests are conservative. Background lookup is bounded and deduplicated. */
188
+ class BingVerifier {
189
+ options;
190
+ cache = new Map();
191
+ pending = new Map();
192
+ constructor(options = {}) {
193
+ this.options = options;
194
+ for (const value of [options.maxEntries ?? 1000, options.maxConcurrent ?? 4]) {
195
+ if (!Number.isSafeInteger(value) || value < 1 || value > 10000)
196
+ throw new Error('Invalid DNS bounds');
197
+ }
198
+ }
199
+ classify(ip) {
200
+ ip = (0, ip_1.normalizeIp)(ip);
201
+ const now = (this.options.now ?? Date.now)();
202
+ const cached = this.cache.get(ip);
203
+ if (cached && cached.expiresAt > now)
204
+ return cached.evidence;
205
+ if (!this.pending.has(ip) && this.pending.size < (this.options.maxConcurrent ?? 4)) {
206
+ const job = this.verify(ip).finally(() => { this.pending.delete(ip); });
207
+ this.pending.set(ip, job);
208
+ }
209
+ return { state: 'verification_unavailable', claimedCrawler: 'bingbot' };
210
+ }
211
+ async settled() { await Promise.all(this.pending.values()); }
212
+ async verify(ip) {
213
+ let state = 'claim_mismatch';
214
+ let ttlMs = 30000;
215
+ try {
216
+ const result = await (this.options.lookup ?? exports.bingDnsLookup)(ip);
217
+ if (result.hostnames.some(h => h.toLowerCase().replace(/\.$/, '').endsWith('.search.msn.com')) &&
218
+ result.addresses.some(address => (0, ip_1.normalizeIp)(address) === ip))
219
+ state = 'verified';
220
+ if (result.ttlMs !== undefined)
221
+ ttlMs = Math.max(0, Math.min(30000, Number.isFinite(result.ttlMs) ? result.ttlMs : 0));
222
+ }
223
+ catch {
224
+ state = 'verification_unavailable';
225
+ }
226
+ // Node's reverse() does not expose PTR TTLs; cap positives at 30s and
227
+ // additionally honor shorter observed forward TTLs.
228
+ const expiresAt = (this.options.now ?? Date.now)() + (state === 'verified' ? ttlMs : 5000);
229
+ const evidence = state === 'verified'
230
+ ? { state, claimedCrawler: 'bingbot', provider: 'bing', crawlerClass: 'bingbot',
231
+ method: 'forward_confirmed_reverse_dns', evidenceVersion: 'bing-fcrdns-v1', expiresAt }
232
+ : { state, claimedCrawler: 'bingbot' };
233
+ if (this.cache.size >= (this.options.maxEntries ?? 1000))
234
+ this.cache.delete(this.cache.keys().next().value);
235
+ this.cache.set(ip, { evidence, expiresAt });
236
+ }
237
+ }
238
+ exports.BingVerifier = BingVerifier;
@@ -0,0 +1,21 @@
1
+ # Build from the repository root:
2
+ # docker build -f packages/valiron-crawler-protection/gateway/Dockerfile -t valiron-crawler-protection .
3
+ FROM node:22-bookworm-slim AS build
4
+ WORKDIR /workspace
5
+ RUN corepack enable
6
+ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml tsconfig.base.json ./
7
+ COPY packages/valiron-crawler-protection/package.json packages/valiron-crawler-protection/tsconfig.json ./packages/valiron-crawler-protection/
8
+ RUN pnpm install --frozen-lockfile --filter @valiron/crawler-protection --ignore-scripts
9
+ COPY packages/valiron-crawler-protection/src ./packages/valiron-crawler-protection/src
10
+ RUN pnpm --filter @valiron/crawler-protection build
11
+
12
+ FROM node:22-bookworm-slim
13
+ ENV NODE_ENV=production
14
+ WORKDIR /workspace
15
+ COPY --from=build /workspace/node_modules ./node_modules
16
+ COPY --from=build /workspace/packages/valiron-crawler-protection/node_modules ./packages/valiron-crawler-protection/node_modules
17
+ COPY --from=build /workspace/packages/valiron-crawler-protection/dist ./packages/valiron-crawler-protection/dist
18
+ COPY packages/valiron-crawler-protection/gateway/service.cjs packages/valiron-crawler-protection/gateway/admin.cjs packages/valiron-crawler-protection/gateway/directory.cjs ./packages/valiron-crawler-protection/gateway/
19
+ USER node
20
+ EXPOSE 8080
21
+ CMD ["node", "packages/valiron-crawler-protection/gateway/service.cjs"]
@@ -0,0 +1,107 @@
1
+ # Valiron Crawler Protection HTTP gateway
2
+
3
+ Run protection as a reverse proxy in front of an HTTP(S) origin. The origin can use any language or frontend framework; the Node.js requirement applies to this standalone service, not the website application. The in-process Node/Nuxt adapters remain available.
4
+
5
+ ```text
6
+ Visitor/crawler → CDN/WAF → Valiron gateway → private authenticated HTTP origin
7
+ ↕ ↕
8
+ shared Redis ← private operation API
9
+ ```
10
+
11
+ The gateway verifies supported crawler sources, applies the site's route/rate policy, and acquires shared origin-request capacity before forwarding. It buffers bounded request bodies before acquiring origin capacity (a shared per-process buffer ceiling is at least 32 MiB), streams response bodies, preserves application cookies/authorization, removes hop-by-hop and internal headers, accepts only configured public hosts, and forwards only to one configured origin. It does not follow origin redirects or select a destination from viewer input. Inventory explicit asset/API/page bypasses; unlisted routes fail closed. WebSocket upgrades, CONNECT tunnels and `Expect: 100-continue` are rejected rather than forwarded outside protection.
12
+
13
+ The gateway bounds HTTP origin concurrency. Individual database queries and background jobs require the private operation protocol below. Origin timeouts, incomplete responses and uncertain acquisition/release leave inventoried, nonexpiring holds. A browser disconnect does not release still-running origin work. Normal origin HTTP completion releases the HTTP hold, while each database hold has its own settlement.
14
+
15
+ ## Compatibility and verified coverage
16
+
17
+ The upstream must accept HTTP/1.1 over HTTP or HTTPS. The service's public listener is HTTP/1.1; use your existing TLS/CDN/reverse proxy for public HTTPS or viewer HTTP/2/HTTP/3. Framework choice does not change admission placement. Platforms that prohibit gateway routing or origin restrictions require a separate platform integration.
18
+
19
+ The work protocol is independent of the SQL/NoSQL driver: the application requests capacity, executes its own operation, and releases only after confirmed settlement. It does not install database instrumentation, resize connection pools or cancel queries automatically. Python/SQLite behind this gateway and Node/Nuxt/MariaDB with in-process admission are tested. Additional languages and drivers can implement the protocol but require integration and cancellation/settlement validation. Only the Python helper is currently included as a non-Node native client.
20
+
21
+ ## Run
22
+
23
+ The npm package includes `gateway/service.cjs`, `gateway/admin.cjs`, this guide and a standard-library Python integration. Install and run from your deployment directory (Node.js 22+):
24
+
25
+ ```sh
26
+ npm install @valiron/crawler-protection
27
+ node node_modules/@valiron/crawler-protection/gateway/service.cjs --check
28
+ node node_modules/@valiron/crawler-protection/gateway/service.cjs
29
+ ```
30
+
31
+ Use `node node_modules/@valiron/crawler-protection/gateway/admin.cjs` for the operator commands below. The Python helper is installed at `node_modules/@valiron/crawler-protection/integrations/python/valiron_crawler_protection.py`; copy it into your backend's server-only integration code if needed. Configure the required settings below before starting the service. The source-repository equivalents are:
32
+
33
+ ```sh
34
+ pnpm --filter @valiron/crawler-protection build
35
+ node packages/valiron-crawler-protection/gateway/service.cjs --check
36
+ node packages/valiron-crawler-protection/gateway/service.cjs
37
+ ```
38
+
39
+ Provision authoritative `noeviction` Redis, configure a schema-v1 exported site policy and supply server-only environment settings. `--check` validates without listening, connecting to Redis, activating policy or printing secrets. Build the supplied Dockerfile from the repository root to run the same service as a container. The Compose template keeps Redis and the work API off public host ports; attach the application to its separate private work network if it needs operation admission.
40
+
41
+ Required settings:
42
+
43
+ | Setting | Purpose |
44
+ | --- | --- |
45
+ | `CRAWLER_CONFIGURATION_FILE` | Exported site configuration, with actual inventoried routes and measured limits. |
46
+ | `REDIS_URL` | Authoritative shared Redis, with TLS for untrusted networks. |
47
+ | `CRAWLER_ORIGIN` | One fixed `http://` or `https://` origin, without path, credentials or query. |
48
+ | `CRAWLER_PUBLIC_HOSTS` | Comma-separated allowed public Host values (include nonstandard ports). |
49
+ | `CRAWLER_ORIGIN_SECRET` | Gateway-to-origin authentication secret; verify at the origin. |
50
+ | `CRAWLER_WORK_SECRET` | Authentication secret for the private operation API. |
51
+ | `CRAWLER_SIGNING_SECRET` | Request-capability signing secret shared only by gateway/work replicas. |
52
+ | `CRAWLER_INGRESS_MODE` | Explicit `direct` or `trusted-proxy`. Direct uses the socket peer, never forwarded headers. |
53
+
54
+ Use independent random secrets of at least 32 bytes. `trusted-proxy` additionally requires `CRAWLER_INGRESS_SECRET`, `CRAWLER_PROXY_CIDRS` and a reviewed `CRAWLER_PROXY_HOPS` topology (default zero). The last trusted proxy must overwrite `X-Valiron-Origin-Auth`, append a trustworthy client address to `X-Forwarded-For`, and be the only allowed ingress path. Do not use all-cloud CIDRs as crawler verification. Optional trusted AWS WAF Meta evidence requires `CRAWLER_META_WAF_RULES_VERSION` and `CRAWLER_REJECT_VIEWER_WAF_HEADERS=true`, only after installing the documented spoof-rejection rules.
55
+
56
+ The public listener defaults to port `8080`; the work API defaults to `127.0.0.1:8081`. Configure `PORT`, `CRAWLER_GATEWAY_BIND`, `CRAWLER_WORK_PORT` and `CRAWLER_WORK_BIND` for your private network. If work calls cross machines, terminate TLS on its private authenticated ingress. `CRAWLER_MAX_BODY_BYTES` defaults to 8 MiB and `CRAWLER_ORIGIN_TIMEOUT_MS` to 30 seconds. Public protocol defaults to HTTPS; set `CRAWLER_PUBLIC_PROTOCOL=http` only for an HTTP test deployment.
57
+
58
+ Lock down the origin: allow the gateway's network identity and check `X-Valiron-Origin-Auth` in constant time before rendering/query execution. An origin that remains directly accessible without that check bypasses protection. The proxy replaces viewer-supplied forwarding/Valiron headers and sends a signed `X-Valiron-Request-Token` only to protected origin requests. Never reflect that token, the origin secret or release capabilities in page bodies, logs, frontend bundles or public response headers.
59
+
60
+ Policy control remains explicit. Use the private `gateway/admin.cjs` with the same configuration to inspect, initialize, pause, activate and resume. Initialization requires a new/drained namespace, `--confirmed-drained` and an evidence file (`CRAWLER_EVIDENCE_FILE`). Initialization creates paused state; resume separately. After crashes/timeouts, pause, stop affected origin/DB work, inspect exact orphan hold IDs and reconcile only those IDs with fresh drain evidence. Services never automatically reset holds, initialize policy or resume on startup. See [decisions and recovery](https://www.valiron.co/docs/crawler-protection/operations) for recovery steps.
61
+
62
+ The nine OpenAI, Googlebot/AdsBot, Applebot, DuckDuckBot and Perplexity feed snapshots refresh in the background with at most three simultaneous fetches; Bing uses bounded forward-confirmed reverse DNS. Missing/expired evidence remains conservative. Ordinary visitors are not classified as human from cookies or user-agent. Reserved customer lanes need a real server-validated grant through the runtime customer hook; the default standalone command does not elevate arbitrary cookies to shopper status.
63
+
64
+ ## Private language-neutral work protocol
65
+
66
+ Any server language can call these endpoints. The machine-readable contract is [work-api.openapi.json](work-api.openapi.json). They are not public customer dashboard APIs. Scope the private listener/credentials to one site's deployment. Do not proxy these paths through the public origin gateway.
67
+
68
+ `POST /v1/work/acquire`, with `Authorization: Bearer <work-secret>` and JSON:
69
+
70
+ ```json
71
+ {"requestToken":"<gateway-signed header>","method":"GET","path":"/products/ring?metal=gold"}
72
+ ```
73
+
74
+ Use the original public method and exact raw path/query. The server verifies the signed request, tenant/policy, recipient, path/method and expiry, then atomically checks shared parent fanout and query concurrency. On success, the response is `{"permit":{"id":"...","secret":"..."}}`. Start the query only after HTTP 200 and a structurally valid work permit. The Python client validates permit fields and requires a positive release acknowledgement. Authentication failures return 401/403; unavailable/exhausted work returns 503. Never retry an ambiguous acquisition automatically: an inventoried hold may already exist.
75
+
76
+ `POST /v1/work/release`, with the same authentication:
77
+
78
+ ```json
79
+ {"permit":{"id":"<returned-id>","secret":"<returned-secret>"},"settled":true}
80
+ ```
81
+
82
+ Release only when the query actually stopped. A timeout/disconnect alone is not settlement. Capabilities can be released by another worker, even after request/policy expiry; releases are idempotent. Missing release, process death or a lost response retains capacity for explicit operator reconciliation. The private API has no automatic expiry, reset or public administrative endpoint.
83
+
84
+ For Python synchronous SQLite/DB drivers, use `integrations/python/valiron_crawler_protection.py`:
85
+
86
+ ```python
87
+ # client is configured with the private endpoint and server secrets.
88
+ if not client.authenticate_origin(request.headers):
89
+ reject_request()
90
+ with client.database(request.headers, request.method, request.raw_path):
91
+ rows = database.execute(query).fetchall()
92
+ ```
93
+
94
+ For asynchronous drivers, acquire explicitly and release after confirmed query cancellation/completion. The context manager assumes that returning or raising means the statement stopped. Apply the same protocol in PHP, Java, Go, Ruby or any other HTTP-capable backend; it does not require a Node SDK inside that application.
95
+
96
+ Hosted platforms must let you route traffic through this gateway and restrict the origin to it. A platform that prevents those controls needs a platform integration; universal routing cannot be imposed by an SDK. CDN cache hits that never reach the gateway remain outside its origin counters. Existing authorization, WAF, connection pools, query timeouts and background-job safeguards remain necessary.
97
+
98
+
99
+ Optional hosted telemetry: set `CRAWLER_TELEMETRY_URL` to `https://valiron-edge-proxy.onrender.com/operator/crawlers/telemetry`, `CRAWLER_TELEMETRY_API_KEY` to a server-side Pro operator API key, and `CRAWLER_SITE_ID` to a stable site label. Use the account tenant from the validated configuration export. Every gateway process gets a new random reporting instance ID. Initial samples establish a counter baseline; subsequent background uploads power rolling 24-hour dashboard analytics, shared capacity and monitoring alerts. Admission continues independently when telemetry is unavailable. Keep keys out of browser code and uploaded configuration. See the public Crawler Protection guide for retention, missing-data semantics and bounds.
100
+
101
+ ## Additional crawler directory
102
+
103
+ The gateway refreshes the independent Verified Bots Directory at `https://verifiedbots.dev/data/all.json` alongside official feeds. Discovery alone grants no identity privilege. Run `node gateway/directory.cjs > directory-review.json`, review operator documentation and network scope, and put selected bot IDs and their approval hashes into a JSON file. Mount that file read-only, set `CRAWLER_DIRECTORY_APPROVALS_FILE`, and restart the gateway. The default Compose template does not mount the file. Configure each returned provider/class in site policy and complete the normal policy activation/recovery procedure.
104
+
105
+ Identity metadata changes invalidate approval. Unapproved, unsupported, stale or unverifiable entries retain conservative limits; even approved CIDR identities need explicit customer budgets. Remote regex, feed URLs, DNS and signature recipes are never executed. Directory evidence is labeled `directory_cidr` and is distinct from official feeds. Download failures log `crawler_directory_unavailable`. Data expires within one hour and at most 48 hours after catalog generation. See the public crawler guide for validation bounds and in-process setup.
106
+
107
+ Attribution: Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev), CC-BY-4.0.
@@ -0,0 +1,34 @@
1
+ // Private operator CLI. No administrative HTTP routes are installed.
2
+ const { readFile } = require('node:fs/promises');
3
+ const Redis = require('ioredis');
4
+ const { compileCrawlerConfiguration, ManagedRedisAdmission } = require('../dist');
5
+ async function main() {
6
+ const [action, argument] = process.argv.slice(2);
7
+ if (!['inspect', 'initialize', 'pause', 'resume', 'activate', 'reconcile', 'circuit'].includes(action)) throw Error('Unknown operator action');
8
+ const configuration = JSON.parse(await readFile(process.env.CRAWLER_CONFIGURATION_FILE, 'utf8'));
9
+ // Expiry must not prevent inspection/pause/exact-ID recovery. This compiler clock
10
+ // is used only to read the immutable policy; no request runtime is constructed.
11
+ const recovery = ['inspect', 'pause', 'reconcile'].includes(action);
12
+ const expires = configuration?.policy?.expiresAt;
13
+ const now = recovery && Number.isSafeInteger(expires) ? Math.min(Date.now(), expires - 1) : Date.now();
14
+ const compiled = compileCrawlerConfiguration(configuration, now);
15
+ const redis = new Redis(process.env.REDIS_URL, { lazyConnect: true, enableOfflineQueue: false, retryStrategy: null,
16
+ maxRetriesPerRequest: 0, connectTimeout: 1000, commandTimeout: 1000 });
17
+ redis.on('error', () => {});
18
+ const store = new ManagedRedisAdmission(redis, compiled.configuration.tenant, compiled.policy, 1500);
19
+ await redis.connect();
20
+ const proof = async () => {
21
+ if (!process.argv.includes('--confirmed-drained')) throw Error('Confirm that workers AND origin/DB work have stopped');
22
+ return { confirmedDrained: true, evidence: (await readFile(process.env.CRAWLER_EVIDENCE_FILE, 'utf8')).trim() };
23
+ };
24
+ try {
25
+ if (action === 'inspect') console.log(JSON.stringify(await store.inspect(), null, 2));
26
+ if (action === 'initialize') await store.initialize(await proof());
27
+ if (action === 'pause') await store.pause();
28
+ if (action === 'resume') await store.resume();
29
+ if (action === 'activate') await store.activate(argument);
30
+ if (action === 'reconcile') await store.reconcile(JSON.parse(await readFile(argument, 'utf8')), await proof());
31
+ if (action === 'circuit') await store.catalogCircuit(argument, (await proof()).evidence);
32
+ } finally { redis.disconnect(); }
33
+ }
34
+ main().catch(error => { console.error(error.message); process.exitCode = 1; });
@@ -0,0 +1,40 @@
1
+ # Supply gateway.env, site.json and a private recovery-evidence.txt on the operator's host.
2
+ # The site's origin must authenticate the gateway and be unreachable through a bypass path.
3
+ services:
4
+ gateway:
5
+ build:
6
+ context: ../../..
7
+ dockerfile: packages/valiron-crawler-protection/gateway/Dockerfile
8
+ env_file: gateway.env
9
+ environment:
10
+ CRAWLER_CONFIGURATION_FILE: /configuration/site.json
11
+ CRAWLER_EVIDENCE_FILE: /configuration/recovery-evidence.txt
12
+ REDIS_URL: redis://redis:6379
13
+ CRAWLER_WORK_BIND: 0.0.0.0
14
+ ports:
15
+ - "127.0.0.1:8080:8080"
16
+ volumes:
17
+ - ./site.json:/configuration/site.json:ro
18
+ - ./recovery-evidence.txt:/configuration/recovery-evidence.txt:ro
19
+ networks: [ingress, admission, work]
20
+ depends_on:
21
+ redis:
22
+ condition: service_healthy
23
+ redis:
24
+ image: redis:7.4-alpine
25
+ command: [redis-server, --appendonly, "yes", --maxmemory, 256mb, --maxmemory-policy, noeviction]
26
+ volumes: ["admission-data:/data"]
27
+ networks: [admission]
28
+ healthcheck:
29
+ test: [CMD, redis-cli, ping]
30
+ interval: 5s
31
+ timeout: 2s
32
+ retries: 5
33
+ networks:
34
+ ingress: {}
35
+ admission:
36
+ internal: true
37
+ work:
38
+ internal: true
39
+ volumes:
40
+ admission-data: {}
@@ -0,0 +1,10 @@
1
+ // Review metadata and official documentation before copying approval hashes into configuration.
2
+ const { CrawlerDirectory, refreshCrawlerDirectory, CRAWLER_DIRECTORY_ATTRIBUTION } = require('../dist');
3
+ async function main() {
4
+ const directory = new CrawlerDirectory();
5
+ await refreshCrawlerDirectory(directory);
6
+ console.log(JSON.stringify({ attribution: CRAWLER_DIRECTORY_ATTRIBUTION,
7
+ instructions: 'Review operator documentation and network scope. Approve selected IDs only; configure provider/class budgets separately.',
8
+ bots: directory.review() }, null, 2));
9
+ }
10
+ if (require.main === module) main().catch(error => { console.error(error.message); process.exitCode = 1; });