@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,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 {};
@@ -0,0 +1,352 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCrawlerGateway = createCrawlerGateway;
4
+ exports.createCrawlerWorkServer = createCrawlerWorkServer;
5
+ exports.authenticateGatewayOrigin = authenticateGatewayOrigin;
6
+ const node_http_1 = require("node:http");
7
+ const node_https_1 = require("node:https");
8
+ const node_crypto_1 = require("node:crypto");
9
+ const ip_1 = require("./ip");
10
+ const admission_1 = require("./admission");
11
+ const adapters_1 = require("./adapters");
12
+ const operations_1 = require("./operations");
13
+ const activation_1 = require("./activation");
14
+ const hopByHop = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
15
+ function cleanHeaders(headers) {
16
+ const nominated = new Set((headers.connection ?? '').toLowerCase().split(',').map(v => v.trim()));
17
+ return Object.fromEntries(Object.entries(headers).filter(([name]) => !hopByHop.has(name) && !nominated.has(name) &&
18
+ !name.startsWith('x-valiron-') && !name.startsWith('x-forwarded-') && !name.startsWith('x-amzn-waf-') &&
19
+ !['forwarded', 'x-real-ip', 'client-ip', 'true-client-ip', 'cf-connecting-ip', 'fastly-client-ip', 'host', 'expect'].includes(name)));
20
+ }
21
+ function secret(value) {
22
+ if (typeof value !== 'string' || Buffer.byteLength(value) < 32 || value.length > 1024 || /[\r\n]/.test(value))
23
+ throw new Error('A private 32+ byte secret is required');
24
+ return Buffer.from(value);
25
+ }
26
+ function equal(supplied, expected) {
27
+ const actual = typeof supplied === 'string' ? Buffer.from(supplied) : Buffer.alloc(0);
28
+ return actual.length === expected.length && (0, node_crypto_1.timingSafeEqual)(actual, expected);
29
+ }
30
+ function fail(response, status, code) {
31
+ if (response.destroyed || response.writableEnded)
32
+ return;
33
+ if (response.headersSent) {
34
+ response.destroy();
35
+ return;
36
+ }
37
+ response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
38
+ response.end(JSON.stringify({ code }));
39
+ }
40
+ /** Fixed-origin HTTP reverse proxy. The origin's language/framework is not involved in admission. */
41
+ function createCrawlerGateway(input) {
42
+ const origin = new URL(input.origin);
43
+ secret(input.originSecret);
44
+ if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash)
45
+ throw new Error('A fixed HTTP(S) origin without a path is required');
46
+ if (!input.publicHosts.length || input.publicHosts.some(h => !/^[a-zA-Z0-9.:[\]-]+$/.test(h) || h.length > 255))
47
+ throw new Error('Explicit public hosts required');
48
+ const hosts = new Set(input.publicHosts.map(h => h.toLowerCase()));
49
+ const maxBody = input.maxBodyBytes ?? 8 * 1024 * 1024;
50
+ const timeout = input.upstreamTimeoutMs ?? 30000;
51
+ const maxConnections = input.maxConnections ?? 256;
52
+ if (!Number.isSafeInteger(maxBody) || maxBody < 1 || maxBody > 1024 * 1024 * 1024 || !Number.isSafeInteger(timeout) || timeout < 1 || timeout > 300000 ||
53
+ !Number.isSafeInteger(maxConnections) || maxConnections < 1 || maxConnections > 10000)
54
+ throw new Error('Invalid gateway bounds');
55
+ const runtime = input.runtime;
56
+ const policy = runtime.compiled.policy;
57
+ let active = 0;
58
+ let bufferedBytes = 0;
59
+ const bufferCeiling = Math.max(maxBody, 32 * 1024 * 1024);
60
+ const server = (0, node_http_1.createServer)({ maxHeaderSize: 32768, requestTimeout: timeout, headersTimeout: Math.min(timeout, 10000) }, (request, response) => {
61
+ request.on('error', () => { });
62
+ response.on('error', () => response.destroy());
63
+ if (active >= maxConnections) {
64
+ fail(response, 503, 'GATEWAY_BUSY');
65
+ return;
66
+ }
67
+ active++;
68
+ let done = false;
69
+ let reservedBytes = 0;
70
+ const releaseBuffer = () => { bufferedBytes -= reservedBytes; reservedBytes = 0; };
71
+ const finish = () => { if (!done) {
72
+ done = true;
73
+ releaseBuffer();
74
+ active--;
75
+ } };
76
+ void (async () => {
77
+ const host = request.headers.host?.toLowerCase();
78
+ if (!host || !hosts.has(host) || !request.url?.startsWith('/') || request.url.startsWith('//') || request.headers.upgrade || request.method === 'CONNECT') {
79
+ fail(response, 400, 'INVALID_GATEWAY_REQUEST');
80
+ finish();
81
+ return;
82
+ }
83
+ const length = request.headers['content-length'];
84
+ if (length && (!/^\d+$/.test(length) || Number(length) > maxBody)) {
85
+ fail(response, 413, 'REQUEST_TOO_LARGE');
86
+ finish();
87
+ return;
88
+ }
89
+ let ip;
90
+ try {
91
+ ip = (0, ip_1.normalizeIp)(input.clientIp(request));
92
+ }
93
+ catch {
94
+ fail(response, 503, 'UNTRUSTED_INGRESS');
95
+ finish();
96
+ return;
97
+ }
98
+ // Finish bounded uploads before acquiring an origin hold. A slow/aborted viewer
99
+ // must never strand capacity for work that has not even been sent to the origin.
100
+ const payload = await new Promise((resolve, reject) => {
101
+ const chunks = [];
102
+ const cleanup = () => { clearTimeout(readTimer); request.off('data', data); request.off('end', ended); request.off('error', errored); request.off('aborted', aborted); };
103
+ const rejectBody = (code) => { cleanup(); request.resume(); reject(new Error(code)); };
104
+ const data = (chunk) => {
105
+ if (reservedBytes + chunk.length > maxBody) {
106
+ rejectBody('REQUEST_TOO_LARGE');
107
+ return;
108
+ }
109
+ if (bufferedBytes + chunk.length > bufferCeiling) {
110
+ rejectBody('GATEWAY_BODY_BUSY');
111
+ return;
112
+ }
113
+ reservedBytes += chunk.length;
114
+ bufferedBytes += chunk.length;
115
+ chunks.push(chunk);
116
+ };
117
+ const ended = () => { cleanup(); resolve(Buffer.concat(chunks)); };
118
+ const errored = () => rejectBody('INCOMPLETE_REQUEST');
119
+ const aborted = () => rejectBody('INCOMPLETE_REQUEST');
120
+ const readTimer = setTimeout(() => rejectBody('REQUEST_BODY_TIMEOUT'), timeout);
121
+ request.on('data', data);
122
+ request.once('end', ended);
123
+ request.once('error', errored);
124
+ request.once('aborted', aborted);
125
+ });
126
+ await new Promise((resolve, reject) => {
127
+ const closed = () => resolve();
128
+ response.once('finish', closed);
129
+ response.once('close', closed);
130
+ runtime.nodeMiddleware(request, response, error => {
131
+ response.off('finish', closed);
132
+ response.off('close', closed);
133
+ if (error)
134
+ reject(error);
135
+ else
136
+ resolve();
137
+ });
138
+ });
139
+ if (response.writableEnded || response.destroyed) {
140
+ finish();
141
+ return;
142
+ }
143
+ const context = request.valironCrawler;
144
+ let permit;
145
+ if (context) {
146
+ const slots = [{ key: 'gateway:global', limit: policy.globalWorkLimit }];
147
+ if (policy.customers) {
148
+ if (context.lane !== 'checkout')
149
+ slots.push({ key: 'gateway:non-checkout', limit: policy.globalWorkLimit - policy.customers.checkoutReserve });
150
+ if (context.lane !== 'checkout' && context.lane !== 'shopper')
151
+ slots.push({ key: 'gateway:catalog', limit: policy.globalWorkLimit - policy.customers.checkoutReserve - policy.customers.shopperReserve });
152
+ }
153
+ if (context.lane === 'catalog') {
154
+ const evidence = context.evidence;
155
+ const verified = evidence.state === 'verified' && Boolean(policy.providers[evidence.provider]?.classes[evidence.crawlerClass]);
156
+ slots.push(verified ? { key: 'gateway:provider:' + evidence.provider, limit: policy.providerWorkLimit } : { key: 'gateway:unknown', limit: policy.unknownWorkLimit });
157
+ }
158
+ permit = await runtime.store.acquirePermit(slots, { requestId: context.requestId, lane: context.lane === 'catalog' ? 'gateway' : context.lane });
159
+ if (!permit) {
160
+ runtime.report.gateway(context.routeGroup, 'rejected');
161
+ fail(response, 503, 'ORIGIN_CAPACITY_EXHAUSTED');
162
+ finish();
163
+ return;
164
+ }
165
+ }
166
+ if (context) {
167
+ try {
168
+ (0, activation_1.assertActivation)(runtime.activation);
169
+ }
170
+ catch (error) {
171
+ if (permit)
172
+ await runtime.store.releasePermit(permit);
173
+ throw error;
174
+ }
175
+ }
176
+ if (context)
177
+ runtime.report.gateway(context.routeGroup, 'admitted');
178
+ const headers = cleanHeaders(request.headers);
179
+ headers.host = host;
180
+ headers['x-forwarded-host'] = host;
181
+ headers['x-forwarded-for'] = ip;
182
+ headers['content-length'] = String(payload.length);
183
+ headers['x-forwarded-proto'] = input.publicProtocol ?? 'https';
184
+ headers['x-valiron-origin-auth'] = input.originSecret;
185
+ if (context && input.requestChannel)
186
+ headers['x-valiron-request-token'] = runtime.guard.forward(context, input.requestChannel, { method: request.method, path: request.url });
187
+ const orphan = (reason) => {
188
+ if (permit) {
189
+ runtime.report.gateway(context.routeGroup, 'orphan');
190
+ try {
191
+ input.onOrphan?.({ requestId: context.requestId, reason });
192
+ }
193
+ catch { /* reporting must not release uncertain work */ }
194
+ }
195
+ };
196
+ // Use a fixed hostname and an origin-form path, never resolve a viewer-supplied URL.
197
+ const upstream = (origin.protocol === 'https:' ? node_https_1.request : node_http_1.request)({ protocol: origin.protocol, hostname: origin.hostname.replace(/^\[|\]$/g, ''),
198
+ port: origin.port || undefined, method: request.method, path: request.url, headers, agent: false });
199
+ upstream.once('finish', releaseBuffer);
200
+ let settled = false;
201
+ const failed = (reason, status = 502) => {
202
+ if (settled)
203
+ return;
204
+ settled = true;
205
+ clearTimeout(timer);
206
+ orphan(reason);
207
+ upstream.destroy();
208
+ fail(response, status, reason);
209
+ request.resume();
210
+ finish();
211
+ };
212
+ const timer = setTimeout(() => failed('ORIGIN_TIMEOUT', 504), timeout);
213
+ upstream.on('error', () => failed('ORIGIN_CONNECTION_FAILED'));
214
+ upstream.once('response', originResponse => {
215
+ const forwarded = cleanHeaders(originResponse.headers);
216
+ if (!response.destroyed)
217
+ response.writeHead(originResponse.statusCode ?? 502, forwarded);
218
+ // Continue draining the origin after a viewer disconnect. Disconnect never releases a hold.
219
+ originResponse.on('data', chunk => {
220
+ if (!settled && !response.destroyed && !response.writableEnded && !response.write(chunk))
221
+ originResponse.pause();
222
+ });
223
+ response.on('drain', () => originResponse.resume());
224
+ response.on('close', () => originResponse.resume());
225
+ originResponse.once('error', () => failed('INCOMPLETE_ORIGIN_RESPONSE'));
226
+ originResponse.once('aborted', () => failed('INCOMPLETE_ORIGIN_RESPONSE'));
227
+ originResponse.once('end', () => {
228
+ if (settled)
229
+ return;
230
+ if (!originResponse.complete || !upstream.writableFinished || !request.complete) {
231
+ failed('INCOMPLETE_ORIGIN_RESPONSE');
232
+ return;
233
+ }
234
+ settled = true;
235
+ clearTimeout(timer);
236
+ // This bounds completed HTTP work only. DB/background work requires operation admission.
237
+ if (context)
238
+ runtime.report.gateway(context.routeGroup, 'completed');
239
+ void (permit ? runtime.store.releasePermit(permit) : Promise.resolve()).catch(() => orphan('ORIGIN_RELEASE_FAILED')).finally(() => {
240
+ response.end();
241
+ finish();
242
+ });
243
+ });
244
+ });
245
+ upstream.end(payload);
246
+ })().catch(error => {
247
+ if (error instanceof admission_1.AdmissionError)
248
+ (0, adapters_1.sendDenial)(response, error.decision);
249
+ else {
250
+ const status = { REQUEST_TOO_LARGE: 413, GATEWAY_BODY_BUSY: 503, INCOMPLETE_REQUEST: 400, REQUEST_BODY_TIMEOUT: 408 };
251
+ const code = error instanceof Error && Object.hasOwn(status, error.message) ? error.message : 'GATEWAY_UNAVAILABLE';
252
+ fail(response, status[code] ?? 503, code);
253
+ }
254
+ finish();
255
+ });
256
+ });
257
+ server.maxConnections = maxConnections;
258
+ server.on('connect', (_request, socket) => socket.destroy());
259
+ server.on('upgrade', (_request, socket) => socket.end('HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\n\r\n'));
260
+ server.on('checkContinue', (request, response) => { fail(response, 417, 'EXPECT_NOT_SUPPORTED'); });
261
+ return server;
262
+ }
263
+ /** Private language-neutral operation admission. Deploy on a private listener, never route through the public gateway. */
264
+ function createCrawlerWorkServer(input) {
265
+ const auth = Buffer.concat([Buffer.from('Bearer '), secret(input.apiSecret)]);
266
+ const runtime = input.runtime;
267
+ const policy = (0, operations_1.policyFingerprint)(runtime.compiled.policy);
268
+ const server = (0, node_http_1.createServer)({ maxHeaderSize: 16384, requestTimeout: 5000, headersTimeout: 5000 }, (request, response) => {
269
+ void (async () => {
270
+ if (!equal(request.headers.authorization, auth)) {
271
+ fail(response, 401, 'AUTHENTICATION_REQUIRED');
272
+ return;
273
+ }
274
+ if (request.method !== 'POST' || !['/v1/work/acquire', '/v1/work/release'].includes(request.url ?? '')) {
275
+ fail(response, 404, 'NOT_FOUND');
276
+ return;
277
+ }
278
+ if (!/^application\/json(?:;|$)/i.test(request.headers['content-type'] ?? '')) {
279
+ fail(response, 415, 'JSON_REQUIRED');
280
+ return;
281
+ }
282
+ const chunks = [];
283
+ let size = 0;
284
+ for await (const chunk of request) {
285
+ size += chunk.length;
286
+ if (size > 16384) {
287
+ fail(response, 413, 'REQUEST_TOO_LARGE');
288
+ return;
289
+ }
290
+ chunks.push(chunk);
291
+ }
292
+ let body;
293
+ try {
294
+ body = JSON.parse(Buffer.concat(chunks).toString());
295
+ if (!body || Array.isArray(body) || typeof body !== 'object')
296
+ throw Error();
297
+ }
298
+ catch {
299
+ fail(response, 400, 'INVALID_JSON');
300
+ return;
301
+ }
302
+ let result;
303
+ if (request.url === '/v1/work/acquire') {
304
+ if (Object.keys(body).some(k => !['requestToken', 'method', 'path'].includes(k))) {
305
+ fail(response, 400, 'INVALID_FIELDS');
306
+ return;
307
+ }
308
+ let claims;
309
+ try {
310
+ claims = input.channel.verify(body.requestToken, { method: body.method, path: body.path }, policy);
311
+ }
312
+ catch {
313
+ fail(response, 403, 'INVALID_REQUEST_CAPABILITY');
314
+ return;
315
+ }
316
+ // Generate a unique child; Redis atomically applies the parent's total fanout across all broker replicas.
317
+ const target = { method: 'POST', path: '/v1/work/acquire' };
318
+ const child = input.channel.sign(claims.context, policy, target);
319
+ const context = runtime.guard.acceptInternal(child, input.channel, target);
320
+ try {
321
+ result = { permit: await runtime.guard.acquireRemoteDatabaseAdmission(context) };
322
+ runtime.report.databasePermit(context.routeGroup, 'admitted');
323
+ }
324
+ catch (error) {
325
+ runtime.report.databasePermit(context.routeGroup, 'rejected');
326
+ throw error;
327
+ }
328
+ }
329
+ else {
330
+ if (body.settled !== true || Object.keys(body).some(k => !['permit', 'settled'].includes(k))) {
331
+ fail(response, 400, 'SETTLEMENT_REQUIRED');
332
+ return;
333
+ }
334
+ await runtime.store.releasePermit(body.permit);
335
+ result = { released: true };
336
+ }
337
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
338
+ response.end(JSON.stringify(result));
339
+ })().catch(error => {
340
+ if (error instanceof admission_1.AdmissionError)
341
+ (0, adapters_1.sendDenial)(response, error.decision);
342
+ else
343
+ fail(response, 503, 'WORK_ADMISSION_UNAVAILABLE');
344
+ });
345
+ });
346
+ server.maxConnections = input.maxConnections ?? 128;
347
+ return server;
348
+ }
349
+ /** Origin middleware can compare this header in any language; network-restrict the origin as well. */
350
+ function authenticateGatewayOrigin(request, originSecret) {
351
+ return equal(request.headers['x-valiron-origin-auth'], secret(originSecret));
352
+ }
@@ -0,0 +1,110 @@
1
+ import { InternalAdmission, type InternalTarget } from './internal';
2
+ import { type CrawlerActivation } from './activation';
3
+ import { BingVerifier, CrawlerRegistry, type CrawlerEvidence } from './verification';
4
+ import { RedisAdmission, type Decision, type WorkPermit } from './admission';
5
+ type Rate = Readonly<{
6
+ capacity: number;
7
+ refillPerSecond: number;
8
+ }>;
9
+ export type GuardPolicy = Readonly<{
10
+ version: string;
11
+ expiresAt: number;
12
+ /** Binds the full compiled deployment configuration to managed policy activation. */
13
+ configurationId?: string;
14
+ rollout?: Readonly<{
15
+ mode: 'observe' | 'enforce';
16
+ enforceGroups: readonly string[];
17
+ safetyRate: Rate;
18
+ safetyPerIpRate: Rate;
19
+ }>;
20
+ globalRate: Rate;
21
+ unknownRate: Rate;
22
+ perIpRate: Rate;
23
+ providers: Readonly<Record<string, Readonly<{
24
+ rate: Rate;
25
+ classes: Readonly<Record<string, Rate>>;
26
+ }>>>;
27
+ globalWorkLimit: number;
28
+ unknownWorkLimit: number;
29
+ providerWorkLimit: number;
30
+ localWorkLimit: number;
31
+ /** Reserved capacity is usable only by a server-validated customer flow. */
32
+ customers?: Readonly<{
33
+ shopperReserve: number;
34
+ checkoutReserve: number;
35
+ shopperRate: Rate;
36
+ checkoutRate: Rate;
37
+ }>;
38
+ maxOperationsPerRequest: number;
39
+ maxContextAgeMs: number;
40
+ routes: Readonly<Record<string, Readonly<{
41
+ cost: number;
42
+ rate: Rate;
43
+ customerLane?: 'checkout';
44
+ }>>>;
45
+ }>;
46
+ export type RequestContext = Readonly<{
47
+ ip: string;
48
+ routeGroup: string;
49
+ cost: number;
50
+ requestId: string;
51
+ evidence: CrawlerEvidence;
52
+ expiresAt: number;
53
+ lane?: 'catalog' | 'shopper' | 'checkout';
54
+ principal?: string;
55
+ }>;
56
+ export type DecisionDetails = Readonly<{
57
+ routeGroup?: string;
58
+ lane?: string;
59
+ mode?: 'observe' | 'enforce';
60
+ proposedAction?: Decision['action'];
61
+ }>;
62
+ export type AdmissionResult = {
63
+ decision: Decision;
64
+ context?: RequestContext;
65
+ };
66
+ /** Shared runtime validation used by the guard and configuration compiler. */
67
+ export declare function validateGuardPolicy(p: GuardPolicy): void;
68
+ export declare class CrawlerGuard {
69
+ private readonly config;
70
+ private readonly policy;
71
+ private localWork;
72
+ private localRender;
73
+ private readonly contexts;
74
+ private readonly children;
75
+ private readonly operations;
76
+ constructor(config: {
77
+ activation: CrawlerActivation;
78
+ policy: GuardPolicy;
79
+ registry: CrawlerRegistry;
80
+ bing: BingVerifier;
81
+ store: RedisAdmission;
82
+ now?: () => number;
83
+ /** Must validate a real server-side session/cart/checkout grant. No UA or cookie presence shortcuts. */
84
+ customer?: (request: unknown, routeGroup: string) => Promise<{
85
+ lane: 'shopper' | 'checkout';
86
+ principal: string;
87
+ } | undefined>;
88
+ trustedEvidence?: (request: unknown, ip: string, userAgent: string) => CrawlerEvidence | undefined;
89
+ crawlerAccess?: (evidence: CrawlerEvidence, routeGroup: string) => 'budget' | 'deny';
90
+ onDecision?: (decision: Readonly<Decision>, evidence?: CrawlerEvidence, details?: DecisionDetails) => void;
91
+ });
92
+ private now;
93
+ private emit;
94
+ admit(input: {
95
+ ip: string;
96
+ userAgent: string;
97
+ routeGroup: string;
98
+ cost: number;
99
+ request?: unknown;
100
+ }): Promise<AdmissionResult>;
101
+ forward(context: RequestContext, channel: InternalAdmission, target: InternalTarget): string;
102
+ acceptInternal(token: string, channel: InternalAdmission, target: InternalTarget): RequestContext;
103
+ /** Bound SSR separately from DB operations; retain the hold until the render/fetches settle. */
104
+ withRenderingAdmission<T>(context: RequestContext, operation: () => Promise<T>): Promise<T>;
105
+ private databaseSlots;
106
+ /** HTTP work broker: shared Redis caps replace a process-affine callback/local counter. */
107
+ acquireRemoteDatabaseAdmission(context: RequestContext): Promise<WorkPermit>;
108
+ withDatabaseAdmission<T>(context: RequestContext, operation: () => Promise<T>): Promise<T>;
109
+ }
110
+ export {};