@valiron/crawler-protection 0.6.0 → 0.8.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/CHANGELOG.md +20 -0
- package/README.md +112 -4
- package/dist/cf.d.ts +27 -0
- package/dist/cf.js +53 -0
- package/dist/configuration.d.ts +1 -0
- package/dist/configuration.js +3 -2
- package/dist/controls.d.ts +90 -0
- package/dist/controls.js +339 -0
- package/dist/directory-fetch.d.ts +37 -0
- package/dist/directory-fetch.js +231 -0
- package/dist/guard.d.ts +2 -0
- package/dist/guard.js +16 -8
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/onboarding.d.ts +1 -1
- package/dist/request-log.d.ts +52 -0
- package/dist/request-log.js +128 -0
- package/dist/runtime.d.ts +29 -0
- package/dist/runtime.js +5 -1
- package/dist/telemetry.js +3 -1
- package/dist/verification.d.ts +12 -0
- package/dist/verification.js +18 -2
- package/dist/webbotauth.d.ts +23 -5
- package/dist/webbotauth.js +47 -0
- package/gateway/README.md +6 -2
- package/gateway/service.cjs +8 -4
- package/package.json +6 -2
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export * from './adapters';
|
|
|
6
6
|
export * from "./operations";
|
|
7
7
|
export * from './internal';
|
|
8
8
|
export * from './meta';
|
|
9
|
+
export * from './cf';
|
|
9
10
|
export * from './cache';
|
|
10
11
|
export * from './configuration';
|
|
11
12
|
export * from './reporting';
|
|
@@ -13,8 +14,11 @@ export * from './runtime';
|
|
|
13
14
|
export * from './onboarding';
|
|
14
15
|
export * from './gateway';
|
|
15
16
|
export * from './telemetry';
|
|
17
|
+
export * from './request-log';
|
|
16
18
|
export * from './directory';
|
|
17
19
|
export * from './webbotauth';
|
|
20
|
+
export * from './directory-fetch';
|
|
18
21
|
export { CrawlerMonthlyLimitError, createCrawlerActivation, activateCrawlerProtection, CRAWLER_ACTIVATION_ENDPOINT, type CrawlerActivation } from './activation';
|
|
19
22
|
export { DeviceIdentity, MemoryIdentityStore, RedisIdentityStore, createNodeDeviceIdentityMiddleware, deviceIdentityCollectorScript, serializeCookieClear, DEVICE_IDENTITY_DEFAULT_BASE_PATH, } from './device-identity';
|
|
20
23
|
export type { DeviceIdentityOptions, DeviceIdentityMiddlewareConfig, Recognition, RecognitionState, RecognizeResult, IdentityStore, StoredProfile, RawSignals, ScreenSignals, CookieOptions, VerifiedCookie, } from './device-identity';
|
|
24
|
+
export * from './controls';
|
package/dist/index.js
CHANGED
|
@@ -23,6 +23,7 @@ __exportStar(require("./adapters"), exports);
|
|
|
23
23
|
__exportStar(require("./operations"), exports);
|
|
24
24
|
__exportStar(require("./internal"), exports);
|
|
25
25
|
__exportStar(require("./meta"), exports);
|
|
26
|
+
__exportStar(require("./cf"), exports);
|
|
26
27
|
__exportStar(require("./cache"), exports);
|
|
27
28
|
__exportStar(require("./configuration"), exports);
|
|
28
29
|
__exportStar(require("./reporting"), exports);
|
|
@@ -30,8 +31,10 @@ __exportStar(require("./runtime"), exports);
|
|
|
30
31
|
__exportStar(require("./onboarding"), exports);
|
|
31
32
|
__exportStar(require("./gateway"), exports);
|
|
32
33
|
__exportStar(require("./telemetry"), exports);
|
|
34
|
+
__exportStar(require("./request-log"), exports);
|
|
33
35
|
__exportStar(require("./directory"), exports);
|
|
34
36
|
__exportStar(require("./webbotauth"), exports);
|
|
37
|
+
__exportStar(require("./directory-fetch"), exports);
|
|
35
38
|
var activation_1 = require("./activation");
|
|
36
39
|
Object.defineProperty(exports, "CrawlerMonthlyLimitError", { enumerable: true, get: function () { return activation_1.CrawlerMonthlyLimitError; } });
|
|
37
40
|
Object.defineProperty(exports, "createCrawlerActivation", { enumerable: true, get: function () { return activation_1.createCrawlerActivation; } });
|
|
@@ -48,3 +51,4 @@ Object.defineProperty(exports, "createNodeDeviceIdentityMiddleware", { enumerabl
|
|
|
48
51
|
Object.defineProperty(exports, "deviceIdentityCollectorScript", { enumerable: true, get: function () { return device_identity_1.deviceIdentityCollectorScript; } });
|
|
49
52
|
Object.defineProperty(exports, "serializeCookieClear", { enumerable: true, get: function () { return device_identity_1.serializeCookieClear; } });
|
|
50
53
|
Object.defineProperty(exports, "DEVICE_IDENTITY_DEFAULT_BASE_PATH", { enumerable: true, get: function () { return device_identity_1.DEVICE_IDENTITY_DEFAULT_BASE_PATH; } });
|
|
54
|
+
__exportStar(require("./controls"), exports);
|
package/dist/onboarding.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export declare function planCrawlerRollout(configuration: unknown, baseline?: Ca
|
|
|
19
19
|
enforceGroups: readonly string[];
|
|
20
20
|
inventory: {
|
|
21
21
|
id: string;
|
|
22
|
-
kind: "
|
|
22
|
+
kind: "protected" | "bypass";
|
|
23
23
|
methods: readonly string[];
|
|
24
24
|
path: string;
|
|
25
25
|
}[];
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
/**
|
|
3
|
+
* Passive request logging for Valiron Crawler Protection observability.
|
|
4
|
+
*
|
|
5
|
+
* For sites that cannot share CDN/WAF logs. It records request metadata after
|
|
6
|
+
* the response is sent and uploads it in the background. It never blocks,
|
|
7
|
+
* delays, challenges or rate-limits a request, needs no Redis, and does not
|
|
8
|
+
* require account activation. Query strings, headers other than User-Agent,
|
|
9
|
+
* cookies and bodies are never collected. Client IPs are sent over HTTPS so
|
|
10
|
+
* Valiron can verify crawler identity; Valiron stores only a keyed hash.
|
|
11
|
+
*/
|
|
12
|
+
export type RequestLogEntry = {
|
|
13
|
+
method: string;
|
|
14
|
+
path: string;
|
|
15
|
+
status?: number;
|
|
16
|
+
host?: string;
|
|
17
|
+
userAgent?: string;
|
|
18
|
+
ip?: string;
|
|
19
|
+
durationMs?: number;
|
|
20
|
+
bytes?: number;
|
|
21
|
+
cache?: 'hit' | 'miss' | 'bypass';
|
|
22
|
+
requestId?: string;
|
|
23
|
+
at?: number;
|
|
24
|
+
};
|
|
25
|
+
export type RequestLogOptions = {
|
|
26
|
+
/** Connection endpoint from the dashboard: https://…/ingest/crawler/logs/<connection-id> */
|
|
27
|
+
endpoint: string;
|
|
28
|
+
/** Connection token (vcl_…), shown once when the connection is created. */
|
|
29
|
+
token: string;
|
|
30
|
+
/** Must select a trusted client address for your proxy topology (see cloudFrontClientIp). */
|
|
31
|
+
clientIp?: (request: IncomingMessage) => string | undefined;
|
|
32
|
+
/** 0 < sampleRate <= 1. Sampled traffic is shown as sampled coverage. */
|
|
33
|
+
sampleRate?: number;
|
|
34
|
+
flushIntervalMs?: number;
|
|
35
|
+
maxBuffer?: number;
|
|
36
|
+
fetch?: typeof fetch;
|
|
37
|
+
onError?: (error: unknown) => void;
|
|
38
|
+
};
|
|
39
|
+
export declare function createCrawlerRequestLog(options: RequestLogOptions): {
|
|
40
|
+
record: (entry: RequestLogEntry) => void;
|
|
41
|
+
recordFetch: (request: Request, response: Pick<Response, "status">, extra?: {
|
|
42
|
+
ip?: string;
|
|
43
|
+
startedAt?: number;
|
|
44
|
+
}) => void;
|
|
45
|
+
middleware: () => (request: IncomingMessage, response: ServerResponse, next?: (error?: unknown) => void) => void;
|
|
46
|
+
flush: () => Promise<void>;
|
|
47
|
+
stats: () => {
|
|
48
|
+
buffered: number;
|
|
49
|
+
dropped: number;
|
|
50
|
+
};
|
|
51
|
+
stop(): Promise<void>;
|
|
52
|
+
};
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createCrawlerRequestLog = createCrawlerRequestLog;
|
|
4
|
+
const node_zlib_1 = require("node:zlib");
|
|
5
|
+
const ENDPOINT_PATH = /^\/ingest\/crawler\/logs\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6
|
+
function createCrawlerRequestLog(options) {
|
|
7
|
+
const url = new URL(options.endpoint);
|
|
8
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
9
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || url.username || url.password || url.search || url.hash || !ENDPOINT_PATH.test(url.pathname)) {
|
|
10
|
+
throw new Error('Invalid request-log endpoint');
|
|
11
|
+
}
|
|
12
|
+
if (!/^vcl_[A-Za-z0-9_-]{43}$/.test(options.token))
|
|
13
|
+
throw new Error('Invalid request-log token');
|
|
14
|
+
const sampleRate = options.sampleRate ?? 1;
|
|
15
|
+
const flushIntervalMs = options.flushIntervalMs ?? 10000;
|
|
16
|
+
const maxBuffer = options.maxBuffer ?? 20000;
|
|
17
|
+
if (!(sampleRate > 0 && sampleRate <= 1))
|
|
18
|
+
throw new Error('Invalid sample rate');
|
|
19
|
+
if (!Number.isSafeInteger(flushIntervalMs) || flushIntervalMs < 1000 || flushIntervalMs > 300000)
|
|
20
|
+
throw new Error('Invalid flush interval');
|
|
21
|
+
if (!Number.isSafeInteger(maxBuffer) || maxBuffer < 100 || maxBuffer > 200000)
|
|
22
|
+
throw new Error('Invalid buffer bound');
|
|
23
|
+
let buffer = [];
|
|
24
|
+
let dropped = 0, busy = false, stopped = false;
|
|
25
|
+
const report = (error) => { try {
|
|
26
|
+
options.onError?.(error);
|
|
27
|
+
}
|
|
28
|
+
catch { /* never throw into the app */ } };
|
|
29
|
+
function record(entry) {
|
|
30
|
+
try {
|
|
31
|
+
if (stopped || (sampleRate < 1 && Math.random() >= sampleRate))
|
|
32
|
+
return;
|
|
33
|
+
if (buffer.length >= maxBuffer) {
|
|
34
|
+
dropped++;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const path = typeof entry.path === 'string' ? entry.path.split(/[?#]/, 1)[0].slice(0, 2048) : '';
|
|
38
|
+
if (!path)
|
|
39
|
+
return;
|
|
40
|
+
buffer.push(JSON.stringify({
|
|
41
|
+
timestamp: new Date(entry.at ?? Date.now()).toISOString(), host: entry.host?.slice(0, 253), method: entry.method?.slice(0, 16), path,
|
|
42
|
+
status: entry.status, user_agent: entry.userAgent?.slice(0, 1024), client_ip: entry.ip?.slice(0, 64),
|
|
43
|
+
duration_ms: entry.durationMs === undefined ? undefined : Math.max(0, Math.round(entry.durationMs)), bytes: entry.bytes,
|
|
44
|
+
cache: entry.cache, request_id: entry.requestId?.slice(0, 128), sample_rate: sampleRate < 1 ? sampleRate : undefined,
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
report(error);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
async function flush() {
|
|
52
|
+
if (busy || !buffer.length)
|
|
53
|
+
return;
|
|
54
|
+
busy = true;
|
|
55
|
+
const batch = buffer.splice(0, 5000);
|
|
56
|
+
try {
|
|
57
|
+
const body = (0, node_zlib_1.gzipSync)(batch.join('\n'));
|
|
58
|
+
const response = await (options.fetch ?? fetch)(url, {
|
|
59
|
+
method: 'POST', body, redirect: 'error', signal: AbortSignal.timeout(10000),
|
|
60
|
+
headers: { Authorization: 'Bearer ' + options.token, 'Content-Type': 'application/x-ndjson', 'Content-Encoding': 'gzip' },
|
|
61
|
+
});
|
|
62
|
+
await response.body?.cancel().catch(() => { });
|
|
63
|
+
// 4xx other than 429 means the payload or credential is unusable: do not retry forever.
|
|
64
|
+
if (!response.ok && (response.status === 429 || response.status >= 500))
|
|
65
|
+
throw new Error('Request log unavailable');
|
|
66
|
+
if (!response.ok)
|
|
67
|
+
report(new Error('Request log rejected: ' + response.status));
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
// Keep records for the next attempt, within the buffer bound.
|
|
71
|
+
const room = Math.max(0, maxBuffer - buffer.length);
|
|
72
|
+
dropped += Math.max(0, batch.length - room);
|
|
73
|
+
buffer = batch.slice(0, room).concat(buffer);
|
|
74
|
+
report(error);
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
busy = false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const timer = setInterval(() => void flush(), flushIntervalMs);
|
|
81
|
+
timer.unref?.();
|
|
82
|
+
/** Express/Connect/Node middleware. Calls next() immediately; records after the response finishes. */
|
|
83
|
+
function middleware() {
|
|
84
|
+
return (request, response, next) => {
|
|
85
|
+
const started = performance.now();
|
|
86
|
+
try {
|
|
87
|
+
response.once('finish', () => {
|
|
88
|
+
let ip;
|
|
89
|
+
try {
|
|
90
|
+
ip = options.clientIp ? options.clientIp(request) : undefined;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
ip = undefined;
|
|
94
|
+
}
|
|
95
|
+
const length = Number(response.getHeader('content-length'));
|
|
96
|
+
record({ method: request.method ?? 'GET', path: request.url ?? '/', host: typeof request.headers.host === 'string' ? request.headers.host.replace(/:\d+$/, '') : undefined,
|
|
97
|
+
status: response.statusCode, userAgent: typeof request.headers['user-agent'] === 'string' ? request.headers['user-agent'] : undefined, ip,
|
|
98
|
+
durationMs: performance.now() - started, bytes: Number.isFinite(length) ? length : undefined });
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
report(error);
|
|
103
|
+
}
|
|
104
|
+
next?.();
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** Fetch-style runtimes (Next.js middleware, Hono, Workers with nodejs_compat). */
|
|
108
|
+
function recordFetch(request, response, extra = {}) {
|
|
109
|
+
try {
|
|
110
|
+
const u = new URL(request.url);
|
|
111
|
+
record({ method: request.method, path: u.pathname, host: u.hostname, status: response.status, userAgent: request.headers.get('user-agent') ?? undefined,
|
|
112
|
+
ip: extra.ip, durationMs: extra.startedAt === undefined ? undefined : Date.now() - extra.startedAt });
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
report(error);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
record, recordFetch, middleware, flush,
|
|
120
|
+
stats: () => ({ buffered: buffer.length, dropped }),
|
|
121
|
+
async stop() { stopped = true; clearInterval(timer); while (buffer.length && !busy) {
|
|
122
|
+
const before = buffer.length;
|
|
123
|
+
await flush();
|
|
124
|
+
if (buffer.length >= before)
|
|
125
|
+
break;
|
|
126
|
+
} },
|
|
127
|
+
};
|
|
128
|
+
}
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { createCrawlerControlClient } from './controls';
|
|
1
2
|
import type { IncomingMessage } from 'node:http';
|
|
2
3
|
import { CrawlerGuard, type RequestContext } from './guard';
|
|
3
4
|
import { ManagedRedisAdmission } from './operations';
|
|
@@ -17,6 +18,7 @@ export declare function createCrawlerRuntime(input: {
|
|
|
17
18
|
bing?: BingVerifier;
|
|
18
19
|
customer?: GuardDependencies['customer'];
|
|
19
20
|
trustedEvidence?: GuardDependencies['trustedEvidence'];
|
|
21
|
+
controlClient?: ReturnType<typeof createCrawlerControlClient>;
|
|
20
22
|
onDecision?: GuardDependencies['onDecision'];
|
|
21
23
|
now?: () => number;
|
|
22
24
|
timeoutMs?: number;
|
|
@@ -41,6 +43,33 @@ export declare function createCrawlerRuntime(input: {
|
|
|
41
43
|
expiresAt?: number;
|
|
42
44
|
}>;
|
|
43
45
|
}>;
|
|
46
|
+
controlClient: {
|
|
47
|
+
configurationId: string;
|
|
48
|
+
refresh: () => Promise<void>;
|
|
49
|
+
record: (decision: import("./admission").Decision, evidence?: import("./verification").CrawlerEvidence, details?: import("./guard").DecisionDetails) => void;
|
|
50
|
+
current(): Readonly<{
|
|
51
|
+
mode: "observe" | "enforce";
|
|
52
|
+
enforceGroups?: readonly string[];
|
|
53
|
+
defaultAction: "budget" | "deny";
|
|
54
|
+
unverifiedAction: "budget" | "deny";
|
|
55
|
+
rules: readonly import("./configuration").CrawlerAccessRule[];
|
|
56
|
+
rates: Readonly<{
|
|
57
|
+
global?: import("./controls").ControlRate;
|
|
58
|
+
unknown?: import("./controls").ControlRate;
|
|
59
|
+
perIp?: import("./controls").ControlRate;
|
|
60
|
+
routes?: Readonly<Record<string, import("./controls").ControlRate>>;
|
|
61
|
+
providers?: Readonly<Record<string, import("./controls").ControlRate>>;
|
|
62
|
+
}>;
|
|
63
|
+
logging: boolean;
|
|
64
|
+
}>;
|
|
65
|
+
status(): {
|
|
66
|
+
error?: "unavailable" | "rejected" | undefined;
|
|
67
|
+
revision: number;
|
|
68
|
+
mode: "observe" | "enforce";
|
|
69
|
+
active: boolean;
|
|
70
|
+
};
|
|
71
|
+
start(): () => void;
|
|
72
|
+
} | undefined;
|
|
44
73
|
nodeMiddleware: (request: import("./adapters").GuardedRequest, response: import("http").ServerResponse, next: (error?: unknown) => void) => void;
|
|
45
74
|
nuxtMiddleware: (event: {
|
|
46
75
|
node: {
|
package/dist/runtime.js
CHANGED
|
@@ -14,15 +14,19 @@ const activation_1 = require("./activation");
|
|
|
14
14
|
function createCrawlerRuntime(input) {
|
|
15
15
|
const compiled = (0, configuration_1.compileCrawlerConfiguration)(input.configuration, (input.now ?? Date.now)());
|
|
16
16
|
(0, activation_1.validateActivation)(input.activation, compiled.configuration.tenant);
|
|
17
|
+
if (input.controlClient && input.controlClient.configurationId !== compiled.fingerprint)
|
|
18
|
+
throw Error('Crawler control configuration mismatch');
|
|
17
19
|
const store = new operations_1.ManagedRedisAdmission(input.redis, compiled.configuration.tenant, compiled.policy, input.timeoutMs);
|
|
18
20
|
const report = new reporting_1.CrawlerReport(compiled.policy, 1024, compiled.configuration.crawlerAccess);
|
|
19
21
|
const access = compiled.configuration.crawlerAccess ?? [];
|
|
20
22
|
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(),
|
|
23
|
+
controls: input.controlClient?.current,
|
|
21
24
|
unverifiedAccess: compiled.configuration.unverifiedAccess,
|
|
22
25
|
customer: input.customer, trustedEvidence: input.trustedEvidence, now: input.now,
|
|
23
26
|
crawlerAccess: (e, group) => access.find(rule => rule.provider === e.provider && rule.crawlerClass === e.crawlerClass && rule.groups.includes(group))?.action ?? compiled.configuration.crawlerAccessDefault ?? 'budget',
|
|
24
27
|
onDecision: (decision, evidence, details) => {
|
|
25
28
|
report.decision(decision, evidence, details);
|
|
29
|
+
input.controlClient?.record(decision, evidence, details);
|
|
26
30
|
return input.onDecision?.(decision, evidence, details);
|
|
27
31
|
},
|
|
28
32
|
});
|
|
@@ -48,7 +52,7 @@ function createCrawlerRuntime(input) {
|
|
|
48
52
|
throw error;
|
|
49
53
|
}
|
|
50
54
|
}
|
|
51
|
-
return Object.freeze({ compiled, store, guard, report, activation: input.activation,
|
|
55
|
+
return Object.freeze({ compiled, store, guard, report, activation: input.activation, controlClient: input.controlClient,
|
|
52
56
|
nodeMiddleware: (0, adapters_1.createNodeCrawlerMiddleware)(adapter), nuxtMiddleware: (0, adapters_1.createNuxtCrawlerMiddleware)(adapter),
|
|
53
57
|
withDatabaseAdmission: (context, operation) => work('database', context, operation),
|
|
54
58
|
withRenderingAdmission: (context, operation) => work('render', context, operation),
|
package/dist/telemetry.js
CHANGED
|
@@ -33,8 +33,10 @@ function createCrawlerTelemetry(input) {
|
|
|
33
33
|
}
|
|
34
34
|
catch { /* Report unavailable capacity without changing admission. */ }
|
|
35
35
|
const snapshot = runtime.report.snapshot();
|
|
36
|
+
const control = runtime.controlClient?.status();
|
|
36
37
|
const body = JSON.stringify({ site: input.site, instance, sequence: ++sequence, tenant: runtime.compiled.configuration.tenant,
|
|
37
|
-
configurationId: runtime.compiled.fingerprint, mode: runtime.compiled.configuration.rollout.mode,
|
|
38
|
+
configurationId: runtime.compiled.fingerprint, mode: control?.mode ?? runtime.compiled.configuration.rollout.mode,
|
|
39
|
+
...(control ? { control: { revision: control.revision, active: control.active } } : {}),
|
|
38
40
|
overflow: snapshot.overflow + snapshot.series.slice(256).reduce((n, s) => n + s.count, 0),
|
|
39
41
|
series: snapshot.series.slice(0, 256).map(({ tags, count, durationMs }) => ({ tags, count, durationMs })), capacity });
|
|
40
42
|
if (Buffer.byteLength(body) > 262144)
|
package/dist/verification.d.ts
CHANGED
|
@@ -13,6 +13,12 @@ type Claim = {
|
|
|
13
13
|
provider: string;
|
|
14
14
|
crawlerClass: string;
|
|
15
15
|
};
|
|
16
|
+
/** Verifiable crawler classes, in matching order. Read-only. */
|
|
17
|
+
export declare function verifiableCrawlers(): readonly {
|
|
18
|
+
provider: string;
|
|
19
|
+
crawlerClass: string;
|
|
20
|
+
pattern: RegExp;
|
|
21
|
+
}[];
|
|
16
22
|
export declare function crawlerClaim(userAgent: string): Claim | undefined;
|
|
17
23
|
export type CidrSnapshot = {
|
|
18
24
|
provider: string;
|
|
@@ -31,6 +37,12 @@ export declare class CrawlerRegistry {
|
|
|
31
37
|
private snapshots;
|
|
32
38
|
constructor(now?: () => number);
|
|
33
39
|
install(snapshot: CidrSnapshot): void;
|
|
40
|
+
/**
|
|
41
|
+
* The installed, unexpired official prefixes for one crawler class, exactly as
|
|
42
|
+
* verification uses them. Lets other enforcement targets (for example edge WAF
|
|
43
|
+
* IP lists) apply the same evidence instead of a User-Agent-only rule.
|
|
44
|
+
*/
|
|
45
|
+
snapshot(crawlerClass: string): CidrSnapshot | undefined;
|
|
34
46
|
classify(ip: string, ua: string): CrawlerEvidence;
|
|
35
47
|
}
|
|
36
48
|
/** Audited, fixed destinations. Feed refresh never follows redirects or accepts caller URLs. */
|
package/dist/verification.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.BingVerifier = exports.bingDnsLookup = exports.OPENAI_FEEDS = exports.CRAWLER_FEEDS = exports.CrawlerRegistry = void 0;
|
|
4
|
+
exports.verifiableCrawlers = verifiableCrawlers;
|
|
4
5
|
exports.crawlerClaim = crawlerClaim;
|
|
5
6
|
exports.refreshCrawlerFeed = refreshCrawlerFeed;
|
|
6
7
|
exports.refreshOpenAiFeed = refreshOpenAiFeed;
|
|
@@ -24,6 +25,10 @@ const claims = [
|
|
|
24
25
|
[/\bPerplexityBot\//i, { provider: 'perplexity', crawlerClass: 'perplexitybot' }],
|
|
25
26
|
[/\bPerplexity-User\//i, { provider: 'perplexity', crawlerClass: 'perplexity-user' }],
|
|
26
27
|
];
|
|
28
|
+
/** Verifiable crawler classes, in matching order. Read-only. */
|
|
29
|
+
function verifiableCrawlers() {
|
|
30
|
+
return claims.map(([pattern, c]) => ({ ...c, pattern: new RegExp(pattern.source, pattern.flags) }));
|
|
31
|
+
}
|
|
27
32
|
function crawlerClaim(userAgent) {
|
|
28
33
|
if (userAgent.length > 2048)
|
|
29
34
|
return undefined;
|
|
@@ -47,8 +52,19 @@ class CrawlerRegistry {
|
|
|
47
52
|
throw new Error('Invalid verification snapshot');
|
|
48
53
|
}
|
|
49
54
|
// Compile completely before replacing the last-known-good snapshot.
|
|
50
|
-
const
|
|
51
|
-
this.snapshots.set(snapshot.crawlerClass, { ...
|
|
55
|
+
const cidrs = Object.freeze([...snapshot.cidrs]);
|
|
56
|
+
this.snapshots.set(snapshot.crawlerClass, { ...snapshot, cidrs, match: (0, ip_1.cidrMatcher)(cidrs) });
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The installed, unexpired official prefixes for one crawler class, exactly as
|
|
60
|
+
* verification uses them. Lets other enforcement targets (for example edge WAF
|
|
61
|
+
* IP lists) apply the same evidence instead of a User-Agent-only rule.
|
|
62
|
+
*/
|
|
63
|
+
snapshot(crawlerClass) {
|
|
64
|
+
const s = this.snapshots.get(crawlerClass);
|
|
65
|
+
if (!s || s.expiresAt <= this.now())
|
|
66
|
+
return undefined;
|
|
67
|
+
return { provider: s.provider, crawlerClass: s.crawlerClass, version: s.version, fetchedAt: s.fetchedAt, expiresAt: s.expiresAt, cidrs: s.cidrs };
|
|
52
68
|
}
|
|
53
69
|
classify(ip, ua) {
|
|
54
70
|
const normalized = (0, ip_1.normalizeIp)(ip);
|
package/dist/webbotauth.d.ts
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
import type { CrawlerEvidence } from './verification';
|
|
2
|
+
/** Opt-in dynamic directory resolver; see directory-fetch.ts for the required bounds. */
|
|
3
|
+
export type DirectoryKeyResolver = Readonly<{
|
|
4
|
+
resolve: (agentUrl: string) => Promise<readonly unknown[] | undefined>;
|
|
5
|
+
}>;
|
|
2
6
|
/**
|
|
3
7
|
* Web Bot Auth (draft-ietf-webbotauth-httpsig-protocol) verification for
|
|
4
8
|
* crawlers and agents that cannot publish IP ranges.
|
|
@@ -7,11 +11,12 @@ import type { CrawlerEvidence } from './verification';
|
|
|
7
11
|
* - A valid signature proves control of a pinned key for a Signature-Agent URL.
|
|
8
12
|
* It is not proof of good intent, of a recognized provider, or of admission.
|
|
9
13
|
* Budgets and policy still apply exactly as with IP/DNS verification.
|
|
10
|
-
* - Pin-only: keys come from operator-reviewed configuration.
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
14
|
+
* - Pin-only by default: keys come from operator-reviewed configuration. Dynamic
|
|
15
|
+
* resolution is opt-in via `dynamicDirectory` + `classifyDynamic` and must go
|
|
16
|
+
* through a resolver with connect-time destination validation and bounded
|
|
17
|
+
* egress (see directory-fetch.ts). A dynamically resolved signer is registered
|
|
18
|
+
* WITHOUT promotion: a valid signature authenticates the signer URL but never
|
|
19
|
+
* produces verified evidence on first sight; promotion stays operator-decided.
|
|
15
20
|
* - Freshness is not replay protection. The draft minimum coverage binds only
|
|
16
21
|
* @authority, so a captured signature can be replayed against this origin
|
|
17
22
|
* until `expires`. Verified signers remain subject to every budget, which
|
|
@@ -44,11 +49,14 @@ export declare function ed25519Thumbprint(jwk: {
|
|
|
44
49
|
}): string;
|
|
45
50
|
export declare class WebBotAuthVerifier {
|
|
46
51
|
private readonly agents;
|
|
52
|
+
private readonly dynamicDirectory?;
|
|
47
53
|
private readonly now;
|
|
48
54
|
private readonly maxWindowMs;
|
|
49
55
|
private readonly skewMs;
|
|
50
56
|
constructor(options: {
|
|
51
57
|
agents: Readonly<Record<string, WebBotAuthAgent>>;
|
|
58
|
+
/** Opt-in: resolves keys for unpinned signer URLs via classifyDynamic only. */
|
|
59
|
+
dynamicDirectory?: DirectoryKeyResolver;
|
|
52
60
|
now?: () => number;
|
|
53
61
|
maxSignatureWindowMs?: number;
|
|
54
62
|
clockSkewMs?: number;
|
|
@@ -61,6 +69,16 @@ export declare class WebBotAuthVerifier {
|
|
|
61
69
|
* original evidence proceeds unchanged.
|
|
62
70
|
*/
|
|
63
71
|
fallbackEvidence(request: unknown): CrawlerEvidence | undefined;
|
|
72
|
+
/**
|
|
73
|
+
* Async classification that may resolve keys for unpinned signer URLs through
|
|
74
|
+
* the configured dynamicDirectory resolver. The sync classify() never touches
|
|
75
|
+
* the network; callers that did not opt in keep that guarantee by never
|
|
76
|
+
* calling this method. Dynamically resolved agents are registered with the
|
|
77
|
+
* neutral provider/crawlerClass 'webbotauth-dynamic' and promote: false.
|
|
78
|
+
*/
|
|
79
|
+
classifyDynamic(request: HeaderView): Promise<CrawlerEvidence | undefined>;
|
|
80
|
+
/** Signer URLs carried by the request, validated to https; never trusted, only resolvable. */
|
|
81
|
+
private extractSignerUrls;
|
|
64
82
|
classify(request: HeaderView): CrawlerEvidence | undefined;
|
|
65
83
|
private verifyCandidate;
|
|
66
84
|
/** RFC 9421 signature base, rebuilt from the exact raw parameters the signer sent. */
|
package/dist/webbotauth.js
CHANGED
|
@@ -151,6 +151,7 @@ function pinKeys(keys) {
|
|
|
151
151
|
}
|
|
152
152
|
class WebBotAuthVerifier {
|
|
153
153
|
agents = new Map();
|
|
154
|
+
dynamicDirectory;
|
|
154
155
|
now;
|
|
155
156
|
maxWindowMs;
|
|
156
157
|
skewMs;
|
|
@@ -158,6 +159,7 @@ class WebBotAuthVerifier {
|
|
|
158
159
|
if (!options.agents || typeof options.agents !== 'object' || Array.isArray(options.agents) ||
|
|
159
160
|
Object.keys(options.agents).length > MAX_AGENTS)
|
|
160
161
|
throw new Error('Invalid Web Bot Auth agents');
|
|
162
|
+
this.dynamicDirectory = options.dynamicDirectory;
|
|
161
163
|
this.now = options.now ?? Date.now;
|
|
162
164
|
this.maxWindowMs = options.maxSignatureWindowMs ?? DEFAULT_MAX_WINDOW_MS;
|
|
163
165
|
this.skewMs = options.clockSkewMs ?? DEFAULT_SKEW_MS;
|
|
@@ -183,6 +185,51 @@ class WebBotAuthVerifier {
|
|
|
183
185
|
fallbackEvidence(request) {
|
|
184
186
|
return this.classify(request);
|
|
185
187
|
}
|
|
188
|
+
/**
|
|
189
|
+
* Async classification that may resolve keys for unpinned signer URLs through
|
|
190
|
+
* the configured dynamicDirectory resolver. The sync classify() never touches
|
|
191
|
+
* the network; callers that did not opt in keep that guarantee by never
|
|
192
|
+
* calling this method. Dynamically resolved agents are registered with the
|
|
193
|
+
* neutral provider/crawlerClass 'webbotauth-dynamic' and promote: false.
|
|
194
|
+
*/
|
|
195
|
+
async classifyDynamic(request) {
|
|
196
|
+
const outcome = this.classify(request);
|
|
197
|
+
if (!this.dynamicDirectory || outcome?.state === 'verified')
|
|
198
|
+
return outcome;
|
|
199
|
+
for (const url of this.extractSignerUrls(request)) {
|
|
200
|
+
if (this.agents.has(url) || this.agents.size >= MAX_AGENTS)
|
|
201
|
+
continue;
|
|
202
|
+
const keys = await this.dynamicDirectory.resolve(url);
|
|
203
|
+
if (!keys)
|
|
204
|
+
continue;
|
|
205
|
+
try {
|
|
206
|
+
this.agents.set(url, {
|
|
207
|
+
config: Object.freeze({ provider: 'webbotauth-dynamic', crawlerClass: 'webbotauth-dynamic', keys, promote: false }),
|
|
208
|
+
keys: pinKeys(keys),
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
continue;
|
|
213
|
+
} // a malformed directory simply leaves the signer unpinned
|
|
214
|
+
}
|
|
215
|
+
return this.classify(request);
|
|
216
|
+
}
|
|
217
|
+
/** Signer URLs carried by the request, validated to https; never trusted, only resolvable. */
|
|
218
|
+
extractSignerUrls(request) {
|
|
219
|
+
const signatureAgent = headerValue(request?.headers, 'signature-agent');
|
|
220
|
+
if (!signatureAgent)
|
|
221
|
+
return [];
|
|
222
|
+
const agentUrls = parseSignatureAgent(signatureAgent);
|
|
223
|
+
if (!agentUrls)
|
|
224
|
+
return [];
|
|
225
|
+
const urls = [];
|
|
226
|
+
for (const rawUrl of agentUrls.values()) {
|
|
227
|
+
const url = httpsAgentUrl(rawUrl);
|
|
228
|
+
if (url && !urls.includes(url) && urls.length < MAX_SIGNATURES)
|
|
229
|
+
urls.push(url);
|
|
230
|
+
}
|
|
231
|
+
return urls;
|
|
232
|
+
}
|
|
186
233
|
classify(request) {
|
|
187
234
|
const signatureInput = headerValue(request?.headers, 'signature-input');
|
|
188
235
|
const signature = headerValue(request?.headers, 'signature');
|
package/gateway/README.md
CHANGED
|
@@ -38,13 +38,13 @@ node packages/valiron-crawler-protection/gateway/service.cjs --check
|
|
|
38
38
|
node packages/valiron-crawler-protection/gateway/service.cjs
|
|
39
39
|
```
|
|
40
40
|
|
|
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
|
|
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 account (Pro with the Crawler Protection add-on, or Enterprise) 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.
|
|
42
42
|
|
|
43
43
|
Required settings (SDK 0.3.0+):
|
|
44
44
|
|
|
45
45
|
| Setting | Purpose |
|
|
46
46
|
| --- | --- |
|
|
47
|
-
| `VALIRON_API_KEY` | Server-side
|
|
47
|
+
| `VALIRON_API_KEY` | Server-side operator (Pro with the Crawler Protection add-on, or Enterprise) API key. The exported tenant must belong to its account. Startup requires successful activation; refresh runs every minute, with a five-minute maximum lease. |
|
|
48
48
|
| `CRAWLER_CONFIGURATION_FILE` | Exported site configuration, with actual inventoried routes and measured limits. |
|
|
49
49
|
| `REDIS_URL` | Authoritative shared Redis, with TLS for untrusted networks. |
|
|
50
50
|
| `CRAWLER_ORIGIN` | One fixed `http://` or `https://` origin, without path, credentials or query. |
|
|
@@ -114,3 +114,7 @@ Attribution: Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev),
|
|
|
114
114
|
The gateway refreshes official OpenAI, Anthropic and Google agent/fetcher feeds in the background. Configure explicit `crawlerAccess` allowances and set `crawlerAccessDefault` to `deny` to reject other verified crawlers on protected groups. Each allowance still needs matching provider/class budgets. Optional `unverifiedAccess: "deny"` also rejects anonymous humans, spoofed claims and unavailable verifications; retain `"budget"` for ordinary anonymous storefront traffic unless an independent customer-grant integration is in place. Existing configurations keep their previous behavior.
|
|
115
115
|
|
|
116
116
|
See the [complete configuration fragment and provider boundaries](https://valiron.co/docs/agents/CRAWLER-PROTECTION.md#allow-selected-ai-services). Google-agent verification does not identify every Gemini interaction. Claude-Agent browser access requires its separately reviewed directory identity; static address changes require review against Anthropic’s official publication. Regenerate directory approval hashes when upgrading to this behavior.
|
|
117
|
+
|
|
118
|
+
## Managed dashboard controls (0.7.0+)
|
|
119
|
+
|
|
120
|
+
After deploying the management backend and migration, set `CRAWLER_MANAGED_CONTROLS=true` and a stable `CRAWLER_SITE_ID` in gateway.env. Keep `VALIRON_API_KEY` server-side. The gateway registers its validated installation, polls controls every 30 seconds and acknowledges applied revisions. The dashboard can publish access rules and tighter request budgets within installed ceilings, view bounded opt-in decisions and configure optional alerts. Match the telemetry site ID. Control leases expire within five minutes; catalog traffic fails closed when no valid lease remains. This does not initialize Redis, raise work limits or replace deployment/recovery. See [Dashboard controls](https://www.valiron.co/docs/crawler-protection/controls).
|
package/gateway/service.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const { readFile } = require('node:fs/promises');
|
|
2
2
|
const Redis = require('ioredis');
|
|
3
|
-
const { createCrawlerRuntime, createCrawlerTelemetry, createCrawlerGateway, createCrawlerWorkServer, InternalAdmission, normalizeIp,
|
|
3
|
+
const { createCrawlerRuntime, createCrawlerControlClient, createCrawlerTelemetry, createCrawlerGateway, createCrawlerWorkServer, InternalAdmission, normalizeIp,
|
|
4
4
|
createCrawlerActivation, createCloudFrontClientIpResolver, createAwsWafMetaEvidence, refreshCrawlerFeeds, CrawlerRegistry, CrawlerDirectory, refreshCrawlerDirectory } = require('../dist');
|
|
5
5
|
|
|
6
6
|
function required(name) {
|
|
@@ -35,11 +35,12 @@ async function load() {
|
|
|
35
35
|
endpoint: process.env.VALIRON_CRAWLER_ACTIVATION_URL,
|
|
36
36
|
onError: () => console.error(JSON.stringify({ event: 'crawler_activation_unavailable' })),
|
|
37
37
|
});
|
|
38
|
-
const
|
|
39
|
-
|
|
38
|
+
const controlClient = process.env.CRAWLER_MANAGED_CONTROLS === 'true' ? createCrawlerControlClient({ configuration, apiKey: required('VALIRON_API_KEY'), site: required('CRAWLER_SITE_ID') }) : undefined;
|
|
39
|
+
const runtime = createCrawlerRuntime({ controlClient, activation, configuration, redis, clientIp, registry, trustedEvidence, timeoutMs: 1500 });
|
|
40
|
+
return { runtime, redis, clientIp, registry, directory, controlClient };
|
|
40
41
|
}
|
|
41
42
|
async function main() {
|
|
42
|
-
const { runtime, redis, clientIp, registry, directory } = await load();
|
|
43
|
+
const { runtime, redis, clientIp, registry, directory, controlClient } = await load();
|
|
43
44
|
const originSecret = required('CRAWLER_ORIGIN_SECRET');
|
|
44
45
|
const apiSecret = required('CRAWLER_WORK_SECRET');
|
|
45
46
|
const signingSecret = required('CRAWLER_SIGNING_SECRET');
|
|
@@ -60,6 +61,8 @@ async function main() {
|
|
|
60
61
|
const work = createCrawlerWorkServer({ runtime, channel, apiSecret });
|
|
61
62
|
if (process.argv.includes('--check')) { console.log(JSON.stringify({ valid: true, configurationId: runtime.compiled.fingerprint })); redis.disconnect(); return; }
|
|
62
63
|
await runtime.activation.start();
|
|
64
|
+
await controlClient?.refresh();
|
|
65
|
+
const stopControls = controlClient?.start();
|
|
63
66
|
await redis.connect();
|
|
64
67
|
// Never initialize/resume from a service startup: recovery remains an explicit operator action.
|
|
65
68
|
const listen = (server, port, host) => new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
|
|
@@ -87,6 +90,7 @@ async function main() {
|
|
|
87
90
|
const shutdown = () => {
|
|
88
91
|
runtime.activation.stop();
|
|
89
92
|
telemetry?.stop();
|
|
93
|
+
stopControls?.();
|
|
90
94
|
clearInterval(interval);
|
|
91
95
|
gateway.close(() => { work.close(() => redis.disconnect()); });
|
|
92
96
|
setTimeout(() => process.exit(1), 30000).unref();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@valiron/crawler-protection",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Valiron Crawler Protection: HTTP gateway and shared workload admission for any website backend",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
".": {
|
|
9
9
|
"types": "./dist/index.d.ts",
|
|
10
10
|
"default": "./dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./request-log": {
|
|
13
|
+
"types": "./dist/request-log.d.ts",
|
|
14
|
+
"default": "./dist/request-log.js"
|
|
11
15
|
}
|
|
12
16
|
},
|
|
13
17
|
"files": [
|
|
@@ -51,7 +55,7 @@
|
|
|
51
55
|
"homepage": "https://www.valiron.co/docs/crawler-protection",
|
|
52
56
|
"repository": {
|
|
53
57
|
"type": "git",
|
|
54
|
-
"url": "https://github.com/vatsashah45/Valiron.git",
|
|
58
|
+
"url": "git+https://github.com/vatsashah45/Valiron.git",
|
|
55
59
|
"directory": "packages/valiron-crawler-protection"
|
|
56
60
|
},
|
|
57
61
|
"publishConfig": {
|