@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,91 @@
1
+ const { readFile } = require('node:fs/promises');
2
+ const Redis = require('ioredis');
3
+ const { createCrawlerRuntime, createCrawlerTelemetry, createCrawlerGateway, createCrawlerWorkServer, InternalAdmission, normalizeIp,
4
+ createCloudFrontClientIpResolver, createAwsWafMetaEvidence, refreshCrawlerFeeds, CrawlerRegistry, CrawlerDirectory, refreshCrawlerDirectory } = require('../dist');
5
+
6
+ function required(name) {
7
+ const value = process.env[name];
8
+ if (!value) throw Error(`${name} is required`);
9
+ return value;
10
+ }
11
+ function integer(name, fallback, min, max) {
12
+ const value = Number(process.env[name] ?? fallback);
13
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw Error(`Invalid ${name}`);
14
+ return value;
15
+ }
16
+ async function load() {
17
+ const configuration = JSON.parse(await readFile(required('CRAWLER_CONFIGURATION_FILE'), 'utf8'));
18
+ const mode = required('CRAWLER_INGRESS_MODE');
19
+ if (!['direct', 'trusted-proxy'].includes(mode)) throw Error('Choose direct or trusted-proxy ingress explicitly');
20
+ const clientIp = mode === 'direct' ? request => normalizeIp(request.socket.remoteAddress ?? '') : createCloudFrontClientIpResolver({
21
+ originSecret: required('CRAWLER_INGRESS_SECRET'), trustedProxyCidrs: required('CRAWLER_PROXY_CIDRS').split(',').map(v => v.trim()),
22
+ additionalProxyHops: integer('CRAWLER_PROXY_HOPS', 0, 0, 8),
23
+ });
24
+ const redis = new Redis(required('REDIS_URL'), { lazyConnect: true, enableOfflineQueue: false, retryStrategy: null,
25
+ maxRetriesPerRequest: 0, connectTimeout: 1000, commandTimeout: 1000 });
26
+ redis.on('error', () => {});
27
+ const trustedEvidence = process.env.CRAWLER_META_WAF_RULES_VERSION ? createAwsWafMetaEvidence({ authenticatedClientIp: clientIp,
28
+ rejectViewerWafHeaders: process.env.CRAWLER_REJECT_VIEWER_WAF_HEADERS === 'true', rulesVersion: process.env.CRAWLER_META_WAF_RULES_VERSION }) : undefined;
29
+ if (trustedEvidence && mode !== 'trusted-proxy') throw Error('WAF evidence requires authenticated proxy ingress');
30
+ const registry = new CrawlerRegistry();
31
+ const directory = new CrawlerDirectory(process.env.CRAWLER_DIRECTORY_APPROVALS_FILE
32
+ ? JSON.parse(await readFile(process.env.CRAWLER_DIRECTORY_APPROVALS_FILE, 'utf8')) : {});
33
+ registry.setDirectory(directory);
34
+ const runtime = createCrawlerRuntime({ configuration, redis, clientIp, registry, trustedEvidence, timeoutMs: 1500 });
35
+ return { runtime, redis, clientIp, registry, directory };
36
+ }
37
+ async function main() {
38
+ const { runtime, redis, clientIp, registry, directory } = await load();
39
+ const originSecret = required('CRAWLER_ORIGIN_SECRET');
40
+ const apiSecret = required('CRAWLER_WORK_SECRET');
41
+ const signingSecret = required('CRAWLER_SIGNING_SECRET');
42
+ const secrets = [originSecret, apiSecret, signingSecret, ...(process.env.CRAWLER_INGRESS_SECRET ? [process.env.CRAWLER_INGRESS_SECRET] : [])];
43
+ if (new Set(secrets).size !== secrets.length) throw Error('Use independent ingress, origin, work API and signing secrets');
44
+ const channel = new InternalAdmission({ issuer: runtime.compiled.configuration.tenant + ':gateway', audience: runtime.compiled.configuration.tenant + ':work', activeKey: 'current', keys: { current: signingSecret } });
45
+ const gateway = createCrawlerGateway({ runtime, clientIp, requestChannel: channel, origin: required('CRAWLER_ORIGIN'), originSecret,
46
+ publicHosts: required('CRAWLER_PUBLIC_HOSTS').split(',').map(v => v.trim()),
47
+ maxBodyBytes: integer('CRAWLER_MAX_BODY_BYTES', 8388608, 1, 1073741824),
48
+ upstreamTimeoutMs: integer('CRAWLER_ORIGIN_TIMEOUT_MS', 30000, 1, 300000),
49
+ publicProtocol: process.env.CRAWLER_PUBLIC_PROTOCOL === 'http' ? 'http' : 'https',
50
+ onOrphan: event => console.error(JSON.stringify({ event: 'origin_hold_requires_inspection', ...event })),
51
+ });
52
+ const telemetry = process.env.CRAWLER_TELEMETRY_URL ? createCrawlerTelemetry({ runtime, endpoint: process.env.CRAWLER_TELEMETRY_URL,
53
+ apiKey: required('CRAWLER_TELEMETRY_API_KEY'), site: required('CRAWLER_SITE_ID'),
54
+ onError: () => console.error(JSON.stringify({ event: 'crawler_telemetry_unavailable' })),
55
+ }) : undefined;
56
+ const work = createCrawlerWorkServer({ runtime, channel, apiSecret });
57
+ if (process.argv.includes('--check')) { console.log(JSON.stringify({ valid: true, configurationId: runtime.compiled.fingerprint })); redis.disconnect(); return; }
58
+ await redis.connect();
59
+ // Never initialize/resume from a service startup: recovery remains an explicit operator action.
60
+ const listen = (server, port, host) => new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
61
+ let refreshing = false;
62
+ async function refresh() {
63
+ if (refreshing) return;
64
+ refreshing = true;
65
+ try {
66
+ const [results] = await Promise.all([
67
+ refreshCrawlerFeeds(registry, { ttlMs: 3600000, concurrency: 3 }),
68
+ refreshCrawlerDirectory(directory).catch(() => console.error(JSON.stringify({ event: 'crawler_directory_unavailable' }))),
69
+ ]);
70
+ const unavailable = Object.keys(results).filter(key => results[key] === 'unavailable');
71
+ if (unavailable.length) console.error(JSON.stringify({ event: 'crawler_feeds_unavailable', sources: unavailable }));
72
+ }
73
+ finally { refreshing = false; }
74
+ }
75
+ // Registry snapshots refresh in the background; missing/expired evidence stays conservative.
76
+ // The registry is shared with the runtime, rather than rebuilt per request.
77
+ await listen(work, integer('CRAWLER_WORK_PORT', 8081, 1, 65535), process.env.CRAWLER_WORK_BIND ?? '127.0.0.1');
78
+ await listen(gateway, integer('PORT', 8080, 1, 65535), process.env.CRAWLER_GATEWAY_BIND ?? '0.0.0.0');
79
+ const interval = setInterval(() => void refresh(), 300000); interval.unref(); void refresh();
80
+ console.log(JSON.stringify({ event: 'crawler_gateway_listening', configurationId: runtime.compiled.fingerprint }));
81
+ void telemetry?.flush();
82
+ const shutdown = () => {
83
+ telemetry?.stop();
84
+ clearInterval(interval);
85
+ gateway.close(() => { work.close(() => redis.disconnect()); });
86
+ setTimeout(() => process.exit(1), 30000).unref();
87
+ };
88
+ process.once('SIGTERM', shutdown); process.once('SIGINT', shutdown);
89
+ }
90
+ if (require.main === module) main().catch(error => { console.error(error.message); process.exit(1); });
91
+ module.exports = { load };
@@ -0,0 +1,186 @@
1
+ {
2
+ "openapi": "3.1.0",
3
+ "info": {
4
+ "title": "Valiron Crawler Protection Private Work API",
5
+ "version": "1.0.0",
6
+ "description": "Private per-deployment server-to-server protocol. A successful acquire must precede the operation. Release only after confirmed settlement; holds never expire automatically. Request capabilities bind the original method and raw path/query. No public/admin endpoints are installed."
7
+ },
8
+ "paths": {
9
+ "/v1/work/acquire": {
10
+ "post": {
11
+ "operationId": "acquireCrawlerWork",
12
+ "security": [
13
+ {
14
+ "workService": []
15
+ }
16
+ ],
17
+ "requestBody": {
18
+ "required": true,
19
+ "content": {
20
+ "application/json": {
21
+ "schema": {
22
+ "type": "object",
23
+ "additionalProperties": false,
24
+ "required": [
25
+ "requestToken",
26
+ "method",
27
+ "path"
28
+ ],
29
+ "properties": {
30
+ "requestToken": {
31
+ "type": "string",
32
+ "maxLength": 8192
33
+ },
34
+ "method": {
35
+ "type": "string",
36
+ "pattern": "^[A-Z]{3,10}$"
37
+ },
38
+ "path": {
39
+ "type": "string",
40
+ "maxLength": 4096,
41
+ "pattern": "^/"
42
+ }
43
+ }
44
+ }
45
+ }
46
+ }
47
+ },
48
+ "responses": {
49
+ "200": {
50
+ "description": "Success",
51
+ "content": {
52
+ "application/json": {
53
+ "schema": {
54
+ "type": "object",
55
+ "required": [
56
+ "permit"
57
+ ],
58
+ "properties": {
59
+ "permit": {
60
+ "$ref": "#/components/schemas/WorkPermit"
61
+ }
62
+ }
63
+ }
64
+ }
65
+ }
66
+ },
67
+ "400": {
68
+ "description": "Invalid input or settlement missing"
69
+ },
70
+ "401": {
71
+ "description": "Service authentication required"
72
+ },
73
+ "403": {
74
+ "description": "Invalid request capability"
75
+ },
76
+ "413": {
77
+ "description": "Request body exceeds 16 KiB"
78
+ },
79
+ "415": {
80
+ "description": "JSON content type required"
81
+ },
82
+ "503": {
83
+ "description": "Admission unavailable or capacity exhausted; do not automatically retry an ambiguous acquire"
84
+ }
85
+ }
86
+ }
87
+ },
88
+ "/v1/work/release": {
89
+ "post": {
90
+ "operationId": "releaseCrawlerWork",
91
+ "security": [
92
+ {
93
+ "workService": []
94
+ }
95
+ ],
96
+ "requestBody": {
97
+ "required": true,
98
+ "content": {
99
+ "application/json": {
100
+ "schema": {
101
+ "type": "object",
102
+ "additionalProperties": false,
103
+ "required": [
104
+ "permit",
105
+ "settled"
106
+ ],
107
+ "properties": {
108
+ "permit": {
109
+ "$ref": "#/components/schemas/WorkPermit"
110
+ },
111
+ "settled": {
112
+ "type": "boolean",
113
+ "const": true
114
+ }
115
+ }
116
+ }
117
+ }
118
+ }
119
+ },
120
+ "responses": {
121
+ "200": {
122
+ "description": "Success",
123
+ "content": {
124
+ "application/json": {
125
+ "schema": {
126
+ "type": "object",
127
+ "properties": {
128
+ "released": {
129
+ "const": true
130
+ }
131
+ }
132
+ }
133
+ }
134
+ }
135
+ },
136
+ "400": {
137
+ "description": "Invalid input or settlement missing"
138
+ },
139
+ "401": {
140
+ "description": "Service authentication required"
141
+ },
142
+ "403": {
143
+ "description": "Invalid request capability"
144
+ },
145
+ "413": {
146
+ "description": "Request body exceeds 16 KiB"
147
+ },
148
+ "415": {
149
+ "description": "JSON content type required"
150
+ },
151
+ "503": {
152
+ "description": "Admission unavailable or capacity exhausted; do not automatically retry an ambiguous acquire"
153
+ }
154
+ }
155
+ }
156
+ }
157
+ },
158
+ "components": {
159
+ "securitySchemes": {
160
+ "workService": {
161
+ "type": "http",
162
+ "scheme": "bearer"
163
+ }
164
+ },
165
+ "schemas": {
166
+ "WorkPermit": {
167
+ "type": "object",
168
+ "additionalProperties": false,
169
+ "required": [
170
+ "id",
171
+ "secret"
172
+ ],
173
+ "properties": {
174
+ "id": {
175
+ "type": "string",
176
+ "format": "uuid"
177
+ },
178
+ "secret": {
179
+ "type": "string",
180
+ "pattern": "^[A-Za-z0-9_-]{43}$"
181
+ }
182
+ }
183
+ }
184
+ }
185
+ }
186
+ }
@@ -0,0 +1,90 @@
1
+ """Standard-library client for Valiron's private work-admission HTTP protocol.
2
+
3
+ Never expose credentials or request capabilities in browser code. No acquire retries:
4
+ an ambiguous response can leave a real, intentionally nonexpiring capacity hold.
5
+ """
6
+ import contextlib
7
+ import hmac
8
+ import json
9
+ import re
10
+ import urllib.error
11
+ import urllib.parse
12
+ import urllib.request
13
+
14
+
15
+ class AdmissionUnavailable(RuntimeError):
16
+ pass
17
+
18
+
19
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
20
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
21
+ return None
22
+
23
+
24
+ class CrawlerProtection:
25
+ def __init__(self, endpoint, api_secret, origin_secret, timeout=2):
26
+ url = urllib.parse.urlsplit(endpoint)
27
+ if (url.scheme not in ("http", "https") or not url.hostname or url.username
28
+ or url.password or url.path not in ("", "/") or url.query or url.fragment):
29
+ raise ValueError("A fixed private work endpoint is required")
30
+ if min(len(api_secret.encode()), len(origin_secret.encode())) < 32 or not 0 < timeout <= 30:
31
+ raise ValueError("Private secrets and a bounded timeout are required")
32
+ self.endpoint, self.api_secret, self.origin_secret = endpoint.rstrip("/"), api_secret, origin_secret
33
+ self.timeout = timeout
34
+ # Do not send private credentials through environment-configured HTTP proxies.
35
+ self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect())
36
+
37
+ def authenticate_origin(self, headers):
38
+ supplied = headers.get("X-Valiron-Origin-Auth", "")
39
+ return hmac.compare_digest(supplied.encode(), self.origin_secret.encode())
40
+
41
+ def _post(self, path, value):
42
+ request = urllib.request.Request(self.endpoint + path, data=json.dumps(value).encode(), method="POST",
43
+ headers={"Authorization": "Bearer " + self.api_secret, "Content-Type": "application/json"})
44
+ try:
45
+ with self.opener.open(request, timeout=self.timeout) as response:
46
+ raw = response.read(16385)
47
+ if len(raw) > 16384:
48
+ raise ValueError("Work admission response too large")
49
+ result = json.loads(raw)
50
+ if not isinstance(result, dict):
51
+ raise ValueError("Invalid work admission response")
52
+ return result
53
+ except urllib.error.HTTPError as error:
54
+ # open() raises before the response context manager is entered.
55
+ # Close failed/redirect responses rather than leaking their socket.
56
+ error.close()
57
+ raise AdmissionUnavailable("Work admission unavailable") from error
58
+ except (OSError, ValueError) as error:
59
+ raise AdmissionUnavailable("Work admission unavailable") from error
60
+
61
+ def acquire(self, headers, method, path):
62
+ if not self.authenticate_origin(headers):
63
+ raise AdmissionUnavailable("Request did not come through the gateway")
64
+ result = self._post("/v1/work/acquire", {"requestToken": headers.get("X-Valiron-Request-Token", ""),
65
+ "method": method, "path": path})
66
+ permit = result.get("permit")
67
+ if (not isinstance(permit, dict) or set(permit) != {"id", "secret"}
68
+ or not isinstance(permit.get("id"), str) or not re.fullmatch(r"[a-f0-9-]{36}", permit["id"])
69
+ or not isinstance(permit.get("secret"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{43}", permit["secret"])):
70
+ raise AdmissionUnavailable("Invalid work permit")
71
+ return permit
72
+
73
+ def release(self, permit):
74
+ """Call only after the operation actually stopped, even when the browser disconnected."""
75
+ if self._post("/v1/work/release", {"permit": permit, "settled": True}).get("released") is not True:
76
+ raise AdmissionUnavailable("Release was not acknowledged")
77
+
78
+ @contextlib.contextmanager
79
+ def database(self, headers, method, path):
80
+ """For synchronous operations: completion/exception must mean the query has stopped.
81
+
82
+ Async drivers that leave server-side queries running after a timeout must use
83
+ acquire/release explicitly and retain the hold until cancellation is confirmed.
84
+ A failed release is surfaced rather than silently claiming settlement.
85
+ """
86
+ permit = self.acquire(headers, method, path)
87
+ try:
88
+ yield
89
+ finally:
90
+ self.release(permit)
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@valiron/crawler-protection",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Valiron Crawler Protection: HTTP gateway and shared workload admission for any website backend",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md",
16
+ "gateway/service.cjs",
17
+ "gateway/admin.cjs",
18
+ "gateway/directory.cjs",
19
+ "gateway/Dockerfile",
20
+ "gateway/compose.yaml",
21
+ "gateway/README.md",
22
+ "gateway/work-api.openapi.json",
23
+ "integrations/python/valiron_crawler_protection.py"
24
+ ],
25
+ "engines": {
26
+ "node": ">=22"
27
+ },
28
+ "scripts": {
29
+ "build": "tsc -p tsconfig.json",
30
+ "test": "pnpm build && node --test test/*.test.cjs",
31
+ "test:redis": "pnpm build && node --test test/*.redis.cjs",
32
+ "test:stack": "pnpm build && node --test test/pilot.stack.cjs",
33
+ "start:gateway": "node gateway/service.cjs",
34
+ "test:gateway": "pnpm build && node --test test/gateway.redis.cjs",
35
+ "test:service": "pnpm build && node --test test/*.process.cjs",
36
+ "test:python": "python3 -B -m unittest discover -s test -p 'test_python_*.py'",
37
+ "prepack": "pnpm build"
38
+ },
39
+ "dependencies": {
40
+ "ipaddr.js": "2.2.0",
41
+ "ioredis": "5.8.2"
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "24.10.1",
45
+ "typescript": "5.9.3"
46
+ },
47
+ "license": "UNLICENSED",
48
+ "author": "Valiron",
49
+ "homepage": "https://www.valiron.co/docs/crawler-protection",
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "https://github.com/vatsashah45/Valiron.git",
53
+ "directory": "packages/valiron-crawler-protection"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public",
57
+ "registry": "https://registry.npmjs.org/"
58
+ }
59
+ }