@valiron/crawler-protection 0.1.0 → 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.
- package/README.md +10 -4
- package/dist/activation.d.ts +25 -0
- package/dist/activation.js +121 -0
- package/dist/gateway.js +11 -0
- package/dist/guard.d.ts +2 -0
- package/dist/guard.js +18 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +5 -0
- package/dist/runtime.d.ts +12 -0
- package/dist/runtime.js +5 -2
- package/gateway/README.md +5 -2
- package/gateway/service.cjs +9 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Install the integration package from npm: `npm install @valiron/crawler-protecti
|
|
|
4
4
|
|
|
5
5
|
**Any HTTP backend:** deploy the [standalone HTTP gateway](gateway/README.md) before your origin, with shared route/rate/origin-concurrency admission. PHP, Python, Ruby, Java, Go and other HTTP backends do not need to install a Node SDK. Use the private work-admission protocol around individual database operations; a standard-library Python client is included. Node/Nuxt in-process adapters remain available. SQLite and MariaDB are tested; other SQL/NoSQL drivers require integration and confirmed-settlement validation. The gateway alone does not automatically instrument queries or connection pools. Gateway deployment requires control of routing and origin access; hosted platforms that prevent those controls need a platform integration.
|
|
6
6
|
|
|
7
|
-
Integration for [Valiron Crawler Protection](https://www.valiron.co/docs/crawler-protection). Protects origin work in customer infrastructure. No blockchain, hosted
|
|
7
|
+
Integration for [Valiron Crawler Protection](https://www.valiron.co/docs/crawler-protection). Protects origin work in customer infrastructure. No blockchain, per-request hosted round trip or crawler signup is required. SDK 0.2.0+ requires a Pro/Enterprise operator API key at startup and refreshes a short-lived account lease in the background.
|
|
8
8
|
|
|
9
9
|
Customer-facing behavior and integration contracts are documented in the [controlled crawler access guide](https://www.valiron.co/docs/agents/CRAWLER-PROTECTION.md). Install it with `npm install @valiron/crawler-protection`; it is separate from `@valiron/sdk`.
|
|
10
10
|
|
|
@@ -21,6 +21,10 @@ Implemented:
|
|
|
21
21
|
|
|
22
22
|
This is an origin admission library, not a complete bot detector. A matching user-agent and source network establish provenance, not human identity or proven crawler intent. Meta classes can use verified AWS WAF evidence over a protected ingress path; no Meta CIDR/ASN verifier is assumed. Header spoofing without a network match does not receive verified allowances.
|
|
23
23
|
|
|
24
|
+
## Paid-account activation
|
|
25
|
+
|
|
26
|
+
Sign up at Valiron, upgrade to Pro (or Enterprise), and create an operator API key in Dashboard → API Keys. Keep it server-side as `VALIRON_API_KEY`. Use your dashboard-exported `operator_<account ID>` tenant. `activateCrawlerProtection()` obtains a five-minute lease and refreshes every minute; pass its handle to the runtime/guard. Missing, invalid, unpaid or revoked credentials cannot activate the supported SDK. Startup/background refresh use HTTPS; request-time checks are local. Outages never extend a lease. After revocation/expiry, new protected work stops, while confirmed releases and recovery remain available. Call `activation.stop()` on shutdown. The public SDK is modifiable; these checks are not tamper-proof and do not retroactively restrict version 0.1.0. Deploy the account activation endpoint before upgrading clients.
|
|
27
|
+
|
|
24
28
|
## Install and validate inside this workspace
|
|
25
29
|
|
|
26
30
|
```sh
|
|
@@ -55,7 +59,8 @@ Both gateway matrix results and the Nuxt/MariaDB job feed the aggregate `CI requ
|
|
|
55
59
|
The recommended managed integration is `compileCrawlerConfiguration()` / `createCrawlerRuntime()`. Schema version 1 validates immutable site policy, explicit route/method inventory, staged rollout, verified crawler rules and public cache settings. Unknown or overlapping paths reject; GET includes HEAD. No customer-specific route logic is built into the engine.
|
|
56
60
|
|
|
57
61
|
```ts
|
|
58
|
-
const
|
|
62
|
+
const activation = await activateCrawlerProtection({ apiKey: process.env.VALIRON_API_KEY!, tenant: siteConfiguration.tenant });
|
|
63
|
+
const runtime = createCrawlerRuntime({ activation,
|
|
59
64
|
configuration: siteConfiguration, redis, clientIp: trustedClientIp,
|
|
60
65
|
customer: validateShoppingGrant,
|
|
61
66
|
});
|
|
@@ -80,7 +85,7 @@ The following uses illustrative low fixture values. Production limits, context l
|
|
|
80
85
|
```ts
|
|
81
86
|
import Redis from 'ioredis';
|
|
82
87
|
import {
|
|
83
|
-
BingVerifier, CrawlerGuard, CrawlerRegistry, RedisAdmission,
|
|
88
|
+
activateCrawlerProtection, BingVerifier, CrawlerGuard, CrawlerRegistry, RedisAdmission,
|
|
84
89
|
refreshCrawlerFeeds, createCloudFrontClientIpResolver,
|
|
85
90
|
} from '@valiron/crawler-protection';
|
|
86
91
|
|
|
@@ -97,7 +102,8 @@ redis.on('error', reportDependencyError);
|
|
|
97
102
|
|
|
98
103
|
const registry = new CrawlerRegistry();
|
|
99
104
|
const rate = { capacity: 10, refillPerSecond: 1 };
|
|
100
|
-
const
|
|
105
|
+
const activation = await activateCrawlerProtection({ apiKey: process.env.VALIRON_API_KEY!, tenant: process.env.VALIRON_TENANT! });
|
|
106
|
+
const guard = new CrawlerGuard({ activation,
|
|
101
107
|
registry,
|
|
102
108
|
bing: new BingVerifier(),
|
|
103
109
|
store: new RedisAdmission(redis, 'customer-tenant-id', 250),
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Paid-account activation. Lease checks are local; only startup/background refresh use HTTP. */
|
|
2
|
+
export declare const CRAWLER_ACTIVATION_ENDPOINT = "https://valiron-edge-proxy.onrender.com/operator/crawlers/activation";
|
|
3
|
+
export type CrawlerActivation = Readonly<{
|
|
4
|
+
tenant: string;
|
|
5
|
+
start(): Promise<void>;
|
|
6
|
+
refresh(): Promise<void>;
|
|
7
|
+
stop(): void;
|
|
8
|
+
status(): Readonly<{
|
|
9
|
+
active: boolean;
|
|
10
|
+
expiresAt?: number;
|
|
11
|
+
}>;
|
|
12
|
+
}>;
|
|
13
|
+
export declare function validateActivation(value: CrawlerActivation, tenant?: string): void;
|
|
14
|
+
export declare function assertActivation(value: CrawlerActivation): void;
|
|
15
|
+
export declare function createCrawlerActivation(input: {
|
|
16
|
+
apiKey: string;
|
|
17
|
+
tenant: string;
|
|
18
|
+
endpoint?: string;
|
|
19
|
+
/** Custom transport supports owned fixtures. Never send production keys to an untrusted transport. */
|
|
20
|
+
fetch?: typeof fetch;
|
|
21
|
+
onError?: () => void;
|
|
22
|
+
now?: () => number;
|
|
23
|
+
monotonicNow?: () => number;
|
|
24
|
+
}): CrawlerActivation;
|
|
25
|
+
export declare function activateCrawlerProtection(input: Parameters<typeof createCrawlerActivation>[0]): Promise<CrawlerActivation>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CRAWLER_ACTIVATION_ENDPOINT = void 0;
|
|
4
|
+
exports.validateActivation = validateActivation;
|
|
5
|
+
exports.assertActivation = assertActivation;
|
|
6
|
+
exports.createCrawlerActivation = createCrawlerActivation;
|
|
7
|
+
exports.activateCrawlerProtection = activateCrawlerProtection;
|
|
8
|
+
/** Paid-account activation. Lease checks are local; only startup/background refresh use HTTP. */
|
|
9
|
+
exports.CRAWLER_ACTIVATION_ENDPOINT = 'https://valiron-edge-proxy.onrender.com/operator/crawlers/activation';
|
|
10
|
+
const activations = new WeakMap();
|
|
11
|
+
function validateActivation(value, tenant) {
|
|
12
|
+
if (!value || !activations.has(value) || (tenant !== undefined && value.tenant !== tenant))
|
|
13
|
+
throw Error('Crawler Protection requires account-bound Pro activation');
|
|
14
|
+
}
|
|
15
|
+
function assertActivation(value) {
|
|
16
|
+
validateActivation(value);
|
|
17
|
+
if (!activations.get(value).active())
|
|
18
|
+
throw Error('Crawler Protection Pro activation unavailable');
|
|
19
|
+
}
|
|
20
|
+
function createCrawlerActivation(input) {
|
|
21
|
+
input = { ...input };
|
|
22
|
+
if (typeof input.apiKey !== 'string' || !/^val_op_[a-zA-Z0-9_-]{1,200}$/.test(input.apiKey) ||
|
|
23
|
+
typeof input.tenant !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(input.tenant))
|
|
24
|
+
throw Error('A Valiron operator API key and tenant are required');
|
|
25
|
+
const url = new URL(input.endpoint ?? exports.CRAWLER_ACTIVATION_ENDPOINT);
|
|
26
|
+
const fixture = url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
27
|
+
if (url.href !== exports.CRAWLER_ACTIVATION_ENDPOINT && (!fixture || url.pathname !== '/operator/crawlers/activation' || url.username || url.password || url.search || url.hash))
|
|
28
|
+
throw Error('Invalid Crawler Protection activation endpoint');
|
|
29
|
+
const now = input.now ?? Date.now, monotonic = input.monotonicNow ?? (() => performance.now());
|
|
30
|
+
let expiresAt = 0, deadline = 0, stopped = false, pending;
|
|
31
|
+
let timer;
|
|
32
|
+
const active = () => !stopped && expiresAt > now() && deadline > monotonic();
|
|
33
|
+
const invalidate = () => { expiresAt = 0; deadline = 0; };
|
|
34
|
+
async function exchange() {
|
|
35
|
+
if (stopped)
|
|
36
|
+
throw Error('Crawler activation stopped');
|
|
37
|
+
const sent = monotonic();
|
|
38
|
+
try {
|
|
39
|
+
const response = await (input.fetch ?? fetch)(url, { method: 'POST', redirect: 'error',
|
|
40
|
+
headers: { Authorization: 'Bearer ' + input.apiKey, 'Content-Type': 'application/json' },
|
|
41
|
+
body: JSON.stringify({ tenant: input.tenant }), signal: AbortSignal.timeout(5000) });
|
|
42
|
+
if (!response.ok) {
|
|
43
|
+
if ([401, 403].includes(response.status))
|
|
44
|
+
invalidate();
|
|
45
|
+
await response.body?.cancel();
|
|
46
|
+
throw Error('Crawler activation unavailable');
|
|
47
|
+
}
|
|
48
|
+
// Reject malformed success replies rather than retaining an earlier entitlement.
|
|
49
|
+
let value;
|
|
50
|
+
try {
|
|
51
|
+
const reader = response.body?.getReader();
|
|
52
|
+
if (!reader)
|
|
53
|
+
throw Error();
|
|
54
|
+
let bytes = 0;
|
|
55
|
+
const chunks = [];
|
|
56
|
+
try {
|
|
57
|
+
while (true) {
|
|
58
|
+
const { done, value: chunk } = await reader.read();
|
|
59
|
+
if (done)
|
|
60
|
+
break;
|
|
61
|
+
bytes += chunk.length;
|
|
62
|
+
if (bytes > 4096) {
|
|
63
|
+
await reader.cancel();
|
|
64
|
+
throw Error();
|
|
65
|
+
}
|
|
66
|
+
chunks.push(chunk);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
reader.releaseLock();
|
|
71
|
+
}
|
|
72
|
+
value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
73
|
+
if (!value || Object.keys(value).some(k => !['feature', 'tenant', 'plan', 'issuedAt', 'expiresAt'].includes(k)) ||
|
|
74
|
+
value.feature !== 'crawler_protection' || value.tenant !== input.tenant || !['pro', 'enterprise'].includes(value.plan) ||
|
|
75
|
+
!Number.isSafeInteger(value.issuedAt) || !Number.isSafeInteger(value.expiresAt) ||
|
|
76
|
+
value.issuedAt > now() + 30000 || value.issuedAt < now() - 30000 || value.expiresAt <= now() ||
|
|
77
|
+
value.expiresAt <= value.issuedAt || value.expiresAt - value.issuedAt > 300000)
|
|
78
|
+
throw Error();
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
invalidate();
|
|
82
|
+
throw Error('Invalid crawler activation response');
|
|
83
|
+
}
|
|
84
|
+
if (stopped)
|
|
85
|
+
throw Error('Crawler activation stopped');
|
|
86
|
+
expiresAt = value.expiresAt;
|
|
87
|
+
// A clock rollback or slow refresh cannot extend a lease beyond five monotonic minutes.
|
|
88
|
+
deadline = Math.min(sent + 300000, monotonic() + Math.min(300000, expiresAt - now()));
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
try {
|
|
92
|
+
input.onError?.();
|
|
93
|
+
}
|
|
94
|
+
catch { /* Logging cannot extend access. */ }
|
|
95
|
+
throw Error('Crawler Protection Pro activation unavailable');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const refresh = () => {
|
|
99
|
+
if (!pending)
|
|
100
|
+
pending = exchange().finally(() => { pending = undefined; });
|
|
101
|
+
return pending;
|
|
102
|
+
};
|
|
103
|
+
const activation = Object.freeze({ tenant: input.tenant, refresh,
|
|
104
|
+
async start() {
|
|
105
|
+
await refresh();
|
|
106
|
+
if (!timer && !stopped) {
|
|
107
|
+
timer = setInterval(() => { void refresh().catch(() => { }); }, 60000);
|
|
108
|
+
timer.unref();
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
stop() { stopped = true; invalidate(); clearInterval(timer); },
|
|
112
|
+
status() { return Object.freeze({ active: active(), ...(expiresAt ? { expiresAt } : {}) }); },
|
|
113
|
+
});
|
|
114
|
+
activations.set(activation, { active });
|
|
115
|
+
return activation;
|
|
116
|
+
}
|
|
117
|
+
async function activateCrawlerProtection(input) {
|
|
118
|
+
const activation = createCrawlerActivation(input);
|
|
119
|
+
await activation.start();
|
|
120
|
+
return activation;
|
|
121
|
+
}
|
package/dist/gateway.js
CHANGED
|
@@ -10,6 +10,7 @@ const ip_1 = require("./ip");
|
|
|
10
10
|
const admission_1 = require("./admission");
|
|
11
11
|
const adapters_1 = require("./adapters");
|
|
12
12
|
const operations_1 = require("./operations");
|
|
13
|
+
const activation_1 = require("./activation");
|
|
13
14
|
const hopByHop = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'proxy-connection', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
|
|
14
15
|
function cleanHeaders(headers) {
|
|
15
16
|
const nominated = new Set((headers.connection ?? '').toLowerCase().split(',').map(v => v.trim()));
|
|
@@ -162,6 +163,16 @@ function createCrawlerGateway(input) {
|
|
|
162
163
|
return;
|
|
163
164
|
}
|
|
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
|
+
}
|
|
165
176
|
if (context)
|
|
166
177
|
runtime.report.gateway(context.routeGroup, 'admitted');
|
|
167
178
|
const headers = cleanHeaders(request.headers);
|
package/dist/guard.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { InternalAdmission, type InternalTarget } from './internal';
|
|
2
|
+
import { type CrawlerActivation } from './activation';
|
|
2
3
|
import { BingVerifier, CrawlerRegistry, type CrawlerEvidence } from './verification';
|
|
3
4
|
import { RedisAdmission, type Decision, type WorkPermit } from './admission';
|
|
4
5
|
type Rate = Readonly<{
|
|
@@ -73,6 +74,7 @@ export declare class CrawlerGuard {
|
|
|
73
74
|
private readonly children;
|
|
74
75
|
private readonly operations;
|
|
75
76
|
constructor(config: {
|
|
77
|
+
activation: CrawlerActivation;
|
|
76
78
|
policy: GuardPolicy;
|
|
77
79
|
registry: CrawlerRegistry;
|
|
78
80
|
bing: BingVerifier;
|
package/dist/guard.js
CHANGED
|
@@ -4,6 +4,7 @@ exports.CrawlerGuard = void 0;
|
|
|
4
4
|
exports.validateGuardPolicy = validateGuardPolicy;
|
|
5
5
|
const operations_1 = require("./operations");
|
|
6
6
|
const node_crypto_1 = require("node:crypto");
|
|
7
|
+
const activation_1 = require("./activation");
|
|
7
8
|
const ip_1 = require("./ip");
|
|
8
9
|
const verification_1 = require("./verification");
|
|
9
10
|
const admission_1 = require("./admission");
|
|
@@ -81,6 +82,7 @@ class CrawlerGuard {
|
|
|
81
82
|
operations = new WeakMap();
|
|
82
83
|
constructor(config) {
|
|
83
84
|
this.config = config;
|
|
85
|
+
(0, activation_1.validateActivation)(config.activation);
|
|
84
86
|
this.policy = structuredClone(config.policy);
|
|
85
87
|
validateGuardPolicy(this.policy);
|
|
86
88
|
}
|
|
@@ -99,6 +101,7 @@ class CrawlerGuard {
|
|
|
99
101
|
let details = { routeGroup: input.routeGroup };
|
|
100
102
|
let decision;
|
|
101
103
|
try {
|
|
104
|
+
(0, activation_1.assertActivation)(this.config.activation);
|
|
102
105
|
if (this.policy.expiresAt <= this.now())
|
|
103
106
|
throw new Error('Expired policy');
|
|
104
107
|
const ip = (0, ip_1.normalizeIp)(input.ip);
|
|
@@ -159,6 +162,7 @@ class CrawlerGuard {
|
|
|
159
162
|
b.key = 'observe:' + b.key;
|
|
160
163
|
// Route costs are selected by trusted integration code, never request input.
|
|
161
164
|
const result = await this.config.store.consume(buckets);
|
|
165
|
+
(0, activation_1.assertActivation)(this.config.activation);
|
|
162
166
|
details = { ...details, proposedAction: denied ? 'block' : result.allow ? 'allow' : 'limit' };
|
|
163
167
|
if (result.allow || mode === 'observe') {
|
|
164
168
|
const context = Object.freeze({ lane, principal: customer ? (0, admission_1.keyPart)(customer.principal) : undefined, ip, routeGroup: input.routeGroup, cost: input.cost, requestId,
|
|
@@ -179,11 +183,13 @@ class CrawlerGuard {
|
|
|
179
183
|
return { decision };
|
|
180
184
|
}
|
|
181
185
|
forward(context, channel, target) {
|
|
186
|
+
(0, activation_1.assertActivation)(this.config.activation);
|
|
182
187
|
if (!(this.config.store instanceof operations_1.ManagedRedisAdmission) || !this.contexts.has(context) || context.expiresAt <= this.now())
|
|
183
188
|
throw new Error('Invalid parent context');
|
|
184
189
|
return channel.sign(context, (0, operations_1.policyFingerprint)(this.policy), target);
|
|
185
190
|
}
|
|
186
191
|
acceptInternal(token, channel, target) {
|
|
192
|
+
(0, activation_1.assertActivation)(this.config.activation);
|
|
187
193
|
if (!(this.config.store instanceof operations_1.ManagedRedisAdmission) || this.policy.expiresAt <= this.now())
|
|
188
194
|
throw new Error('Managed active policy required');
|
|
189
195
|
const claims = channel.verify(token, target, (0, operations_1.policyFingerprint)(this.policy));
|
|
@@ -195,6 +201,7 @@ class CrawlerGuard {
|
|
|
195
201
|
}
|
|
196
202
|
/** Bound SSR separately from DB operations; retain the hold until the render/fetches settle. */
|
|
197
203
|
async withRenderingAdmission(context, operation) {
|
|
204
|
+
(0, activation_1.assertActivation)(this.config.activation);
|
|
198
205
|
const p = this.policy;
|
|
199
206
|
if (!this.contexts.has(context) || context.expiresAt <= this.now() || p.expiresAt <= this.now() || this.localRender >= p.localWorkLimit)
|
|
200
207
|
throw new admission_1.AdmissionError({ action: 'unavailable', reason: 'render_unavailable', requestId: context?.requestId ?? (0, node_crypto_1.randomUUID)(), policyVersion: p.version });
|
|
@@ -208,7 +215,7 @@ class CrawlerGuard {
|
|
|
208
215
|
this.localRender++;
|
|
209
216
|
try {
|
|
210
217
|
return await (0, admission_1.withWorkSlot)({ store: this.config.store, slots, requestId: context.requestId, policyVersion: p.version, lane: 'render',
|
|
211
|
-
onReleaseFailure: () => this.emit({ action: 'unavailable', reason: 'render_release_failed', requestId: context.requestId, policyVersion: p.version }) }, operation);
|
|
218
|
+
onReleaseFailure: () => this.emit({ action: 'unavailable', reason: 'render_release_failed', requestId: context.requestId, policyVersion: p.version }) }, async () => { (0, activation_1.assertActivation)(this.config.activation); return operation(); });
|
|
212
219
|
}
|
|
213
220
|
finally {
|
|
214
221
|
this.localRender--;
|
|
@@ -233,6 +240,7 @@ class CrawlerGuard {
|
|
|
233
240
|
}
|
|
234
241
|
/** HTTP work broker: shared Redis caps replace a process-affine callback/local counter. */
|
|
235
242
|
async acquireRemoteDatabaseAdmission(context) {
|
|
243
|
+
(0, activation_1.assertActivation)(this.config.activation);
|
|
236
244
|
const p = this.policy;
|
|
237
245
|
if (!(this.config.store instanceof operations_1.ManagedRedisAdmission) || !this.contexts.has(context) || p.expiresAt <= this.now() || context.expiresAt <= this.now())
|
|
238
246
|
throw new admission_1.AdmissionError({ action: 'unavailable', reason: 'invalid_remote_context', requestId: context?.requestId ?? (0, node_crypto_1.randomUUID)(), policyVersion: p.version });
|
|
@@ -242,9 +250,17 @@ class CrawlerGuard {
|
|
|
242
250
|
const permit = await this.config.store.acquirePermit(this.databaseSlots(context), { requestId: context.requestId, lane: context.lane ?? 'catalog' });
|
|
243
251
|
if (!permit)
|
|
244
252
|
throw new admission_1.AdmissionError({ action: 'unavailable', reason: 'work_capacity_exhausted', requestId: context.requestId, policyVersion: p.version, retryAfterSeconds: 1 });
|
|
253
|
+
try {
|
|
254
|
+
(0, activation_1.assertActivation)(this.config.activation);
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
await this.config.store.releasePermit(permit);
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
245
260
|
return permit;
|
|
246
261
|
}
|
|
247
262
|
async withDatabaseAdmission(context, operation) {
|
|
263
|
+
(0, activation_1.assertActivation)(this.config.activation);
|
|
248
264
|
const p = this.policy;
|
|
249
265
|
if (!this.contexts.has(context) || p.expiresAt <= this.now() || context.expiresAt <= this.now() || this.localWork >= p.localWorkLimit ||
|
|
250
266
|
(this.operations.get(context) ?? Infinity) >= p.maxOperationsPerRequest) {
|
|
@@ -268,7 +284,7 @@ class CrawlerGuard {
|
|
|
268
284
|
try {
|
|
269
285
|
return await (0, admission_1.withWorkSlot)({ store: this.config.store, requestId: context.requestId, policyVersion: p.version, lane: context.lane ?? 'catalog',
|
|
270
286
|
onReleaseFailure: () => this.emit({ action: 'unavailable', reason: 'work_release_failed', requestId: context.requestId, policyVersion: p.version }),
|
|
271
|
-
slots }, operation);
|
|
287
|
+
slots }, async () => { (0, activation_1.assertActivation)(this.config.activation); return operation(); });
|
|
272
288
|
}
|
|
273
289
|
finally {
|
|
274
290
|
this.localWork--;
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -14,6 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.CRAWLER_ACTIVATION_ENDPOINT = exports.activateCrawlerProtection = exports.createCrawlerActivation = void 0;
|
|
17
18
|
__exportStar(require("./ip"), exports);
|
|
18
19
|
__exportStar(require("./verification"), exports);
|
|
19
20
|
__exportStar(require("./admission"), exports);
|
|
@@ -30,3 +31,7 @@ __exportStar(require("./onboarding"), exports);
|
|
|
30
31
|
__exportStar(require("./gateway"), exports);
|
|
31
32
|
__exportStar(require("./telemetry"), exports);
|
|
32
33
|
__exportStar(require("./directory"), exports);
|
|
34
|
+
var activation_1 = require("./activation");
|
|
35
|
+
Object.defineProperty(exports, "createCrawlerActivation", { enumerable: true, get: function () { return activation_1.createCrawlerActivation; } });
|
|
36
|
+
Object.defineProperty(exports, "activateCrawlerProtection", { enumerable: true, get: function () { return activation_1.activateCrawlerProtection; } });
|
|
37
|
+
Object.defineProperty(exports, "CRAWLER_ACTIVATION_ENDPOINT", { enumerable: true, get: function () { return activation_1.CRAWLER_ACTIVATION_ENDPOINT; } });
|
package/dist/runtime.d.ts
CHANGED
|
@@ -5,11 +5,13 @@ import { type RedisEval } from './admission';
|
|
|
5
5
|
import { CrawlerRegistry, BingVerifier } from './verification';
|
|
6
6
|
import { type PublicResponse } from './cache';
|
|
7
7
|
import { CrawlerReport } from './reporting';
|
|
8
|
+
import { type CrawlerActivation } from './activation';
|
|
8
9
|
type GuardDependencies = ConstructorParameters<typeof CrawlerGuard>[0];
|
|
9
10
|
/** Assemble framework-independent enforcement from one validated deployment configuration. */
|
|
10
11
|
export declare function createCrawlerRuntime(input: {
|
|
11
12
|
configuration: unknown;
|
|
12
13
|
redis: RedisEval;
|
|
14
|
+
activation: CrawlerActivation;
|
|
13
15
|
clientIp: (request: IncomingMessage) => string;
|
|
14
16
|
registry?: CrawlerRegistry;
|
|
15
17
|
bing?: BingVerifier;
|
|
@@ -28,6 +30,16 @@ export declare function createCrawlerRuntime(input: {
|
|
|
28
30
|
store: ManagedRedisAdmission;
|
|
29
31
|
guard: CrawlerGuard;
|
|
30
32
|
report: CrawlerReport;
|
|
33
|
+
activation: Readonly<{
|
|
34
|
+
tenant: string;
|
|
35
|
+
start(): Promise<void>;
|
|
36
|
+
refresh(): Promise<void>;
|
|
37
|
+
stop(): void;
|
|
38
|
+
status(): Readonly<{
|
|
39
|
+
active: boolean;
|
|
40
|
+
expiresAt?: number;
|
|
41
|
+
}>;
|
|
42
|
+
}>;
|
|
31
43
|
nodeMiddleware: (request: import("./adapters").GuardedRequest, response: import("http").ServerResponse, next: (error?: unknown) => void) => void;
|
|
32
44
|
nuxtMiddleware: (event: {
|
|
33
45
|
node: {
|
package/dist/runtime.js
CHANGED
|
@@ -9,13 +9,15 @@ const configuration_1 = require("./configuration");
|
|
|
9
9
|
const cache_1 = require("./cache");
|
|
10
10
|
const reporting_1 = require("./reporting");
|
|
11
11
|
const adapters_1 = require("./adapters");
|
|
12
|
+
const activation_1 = require("./activation");
|
|
12
13
|
/** Assemble framework-independent enforcement from one validated deployment configuration. */
|
|
13
14
|
function createCrawlerRuntime(input) {
|
|
14
15
|
const compiled = (0, configuration_1.compileCrawlerConfiguration)(input.configuration, (input.now ?? Date.now)());
|
|
16
|
+
(0, activation_1.validateActivation)(input.activation, compiled.configuration.tenant);
|
|
15
17
|
const store = new operations_1.ManagedRedisAdmission(input.redis, compiled.configuration.tenant, compiled.policy, input.timeoutMs);
|
|
16
18
|
const report = new reporting_1.CrawlerReport(compiled.policy, 1024, compiled.configuration.crawlerAccess);
|
|
17
19
|
const access = compiled.configuration.crawlerAccess ?? [];
|
|
18
|
-
const guard = new guard_1.CrawlerGuard({ policy: compiled.policy, store, registry: input.registry ?? new verification_1.CrawlerRegistry(), bing: input.bing ?? new verification_1.BingVerifier(),
|
|
20
|
+
const guard = new guard_1.CrawlerGuard({ activation: input.activation, policy: compiled.policy, store, registry: input.registry ?? new verification_1.CrawlerRegistry(), bing: input.bing ?? new verification_1.BingVerifier(),
|
|
19
21
|
customer: input.customer, trustedEvidence: input.trustedEvidence, now: input.now,
|
|
20
22
|
crawlerAccess: (e, group) => access.find(rule => rule.provider === e.provider && rule.crawlerClass === e.crawlerClass && rule.groups.includes(group))?.action ?? 'budget',
|
|
21
23
|
onDecision: (decision, evidence, details) => {
|
|
@@ -45,13 +47,14 @@ function createCrawlerRuntime(input) {
|
|
|
45
47
|
throw error;
|
|
46
48
|
}
|
|
47
49
|
}
|
|
48
|
-
return Object.freeze({ compiled, store, guard, report,
|
|
50
|
+
return Object.freeze({ compiled, store, guard, report, activation: input.activation,
|
|
49
51
|
nodeMiddleware: (0, adapters_1.createNodeCrawlerMiddleware)(adapter), nuxtMiddleware: (0, adapters_1.createNuxtCrawlerMiddleware)(adapter),
|
|
50
52
|
withDatabaseAdmission: (context, operation) => work('database', context, operation),
|
|
51
53
|
withRenderingAdmission: (context, operation) => work('render', context, operation),
|
|
52
54
|
/** Loader must perform page admission and wrap render/DB work. This wrapper authenticates every request, including hits. */
|
|
53
55
|
async publicResponse(request, admittedLoader, background) {
|
|
54
56
|
input.clientIp(request);
|
|
57
|
+
(0, activation_1.assertActivation)(input.activation);
|
|
55
58
|
const route = compiled.resolve(request);
|
|
56
59
|
if (route.kind !== 'protected')
|
|
57
60
|
throw new Error('Public cache requires a protected inventoried route');
|
package/gateway/README.md
CHANGED
|
@@ -12,6 +12,8 @@ The gateway verifies supported crawler sources, applies the site's route/rate po
|
|
|
12
12
|
|
|
13
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
14
|
|
|
15
|
+
After lease expiry or an observed revoked/unpaid key, new protected work fails closed. Existing work can settle and the private release API remains available. Activation does not initialize or resume Redis admission. Explicit static bypasses remain usable. Deploy the hosted activation endpoint before upgrading clients from 0.1.0.
|
|
16
|
+
|
|
15
17
|
## Compatibility and verified coverage
|
|
16
18
|
|
|
17
19
|
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.
|
|
@@ -36,12 +38,13 @@ node packages/valiron-crawler-protection/gateway/service.cjs --check
|
|
|
36
38
|
node packages/valiron-crawler-protection/gateway/service.cjs
|
|
37
39
|
```
|
|
38
40
|
|
|
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.
|
|
41
|
+
Provision authoritative `noeviction` Redis, configure a schema-v1 exported site policy and supply server-only environment settings. `--check` validates configuration and API-key syntax without listening, connecting to Redis, checking the subscription online, activating policy or printing secrets. Normal startup checks the current Pro/Enterprise account before listening. 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
42
|
|
|
41
|
-
Required settings:
|
|
43
|
+
Required settings (SDK 0.2.0+):
|
|
42
44
|
|
|
43
45
|
| Setting | Purpose |
|
|
44
46
|
| --- | --- |
|
|
47
|
+
| `VALIRON_API_KEY` | Server-side Pro/Enterprise operator API key. The exported tenant must belong to its account. Startup requires successful activation; refresh runs every minute, with a five-minute maximum lease. |
|
|
45
48
|
| `CRAWLER_CONFIGURATION_FILE` | Exported site configuration, with actual inventoried routes and measured limits. |
|
|
46
49
|
| `REDIS_URL` | Authoritative shared Redis, with TLS for untrusted networks. |
|
|
47
50
|
| `CRAWLER_ORIGIN` | One fixed `http://` or `https://` origin, without path, credentials or query. |
|
package/gateway/service.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const { readFile } = require('node:fs/promises');
|
|
2
2
|
const Redis = require('ioredis');
|
|
3
3
|
const { createCrawlerRuntime, createCrawlerTelemetry, createCrawlerGateway, createCrawlerWorkServer, InternalAdmission, normalizeIp,
|
|
4
|
-
createCloudFrontClientIpResolver, createAwsWafMetaEvidence, refreshCrawlerFeeds, CrawlerRegistry, CrawlerDirectory, refreshCrawlerDirectory } = require('../dist');
|
|
4
|
+
createCrawlerActivation, createCloudFrontClientIpResolver, createAwsWafMetaEvidence, refreshCrawlerFeeds, CrawlerRegistry, CrawlerDirectory, refreshCrawlerDirectory } = require('../dist');
|
|
5
5
|
|
|
6
6
|
function required(name) {
|
|
7
7
|
const value = process.env[name];
|
|
@@ -31,7 +31,11 @@ async function load() {
|
|
|
31
31
|
const directory = new CrawlerDirectory(process.env.CRAWLER_DIRECTORY_APPROVALS_FILE
|
|
32
32
|
? JSON.parse(await readFile(process.env.CRAWLER_DIRECTORY_APPROVALS_FILE, 'utf8')) : {});
|
|
33
33
|
registry.setDirectory(directory);
|
|
34
|
-
const
|
|
34
|
+
const activation = createCrawlerActivation({ apiKey: required('VALIRON_API_KEY'), tenant: configuration.tenant,
|
|
35
|
+
endpoint: process.env.VALIRON_CRAWLER_ACTIVATION_URL,
|
|
36
|
+
onError: () => console.error(JSON.stringify({ event: 'crawler_activation_unavailable' })),
|
|
37
|
+
});
|
|
38
|
+
const runtime = createCrawlerRuntime({ activation, configuration, redis, clientIp, registry, trustedEvidence, timeoutMs: 1500 });
|
|
35
39
|
return { runtime, redis, clientIp, registry, directory };
|
|
36
40
|
}
|
|
37
41
|
async function main() {
|
|
@@ -50,11 +54,12 @@ async function main() {
|
|
|
50
54
|
onOrphan: event => console.error(JSON.stringify({ event: 'origin_hold_requires_inspection', ...event })),
|
|
51
55
|
});
|
|
52
56
|
const telemetry = process.env.CRAWLER_TELEMETRY_URL ? createCrawlerTelemetry({ runtime, endpoint: process.env.CRAWLER_TELEMETRY_URL,
|
|
53
|
-
apiKey: required('
|
|
57
|
+
apiKey: process.env.CRAWLER_TELEMETRY_API_KEY ?? required('VALIRON_API_KEY'), site: required('CRAWLER_SITE_ID'),
|
|
54
58
|
onError: () => console.error(JSON.stringify({ event: 'crawler_telemetry_unavailable' })),
|
|
55
59
|
}) : undefined;
|
|
56
60
|
const work = createCrawlerWorkServer({ runtime, channel, apiSecret });
|
|
57
61
|
if (process.argv.includes('--check')) { console.log(JSON.stringify({ valid: true, configurationId: runtime.compiled.fingerprint })); redis.disconnect(); return; }
|
|
62
|
+
await runtime.activation.start();
|
|
58
63
|
await redis.connect();
|
|
59
64
|
// Never initialize/resume from a service startup: recovery remains an explicit operator action.
|
|
60
65
|
const listen = (server, port, host) => new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
|
|
@@ -80,6 +85,7 @@ async function main() {
|
|
|
80
85
|
console.log(JSON.stringify({ event: 'crawler_gateway_listening', configurationId: runtime.compiled.fingerprint }));
|
|
81
86
|
void telemetry?.flush();
|
|
82
87
|
const shutdown = () => {
|
|
88
|
+
runtime.activation.stop();
|
|
83
89
|
telemetry?.stop();
|
|
84
90
|
clearInterval(interval);
|
|
85
91
|
gateway.close(() => { work.close(() => redis.disconnect()); });
|
package/package.json
CHANGED