@valiron/crawler-protection 0.7.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 +11 -0
- package/README.md +24 -4
- package/dist/cf.d.ts +27 -0
- package/dist/cf.js +53 -0
- package/dist/directory-fetch.d.ts +37 -0
- package/dist/directory-fetch.js +231 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/request-log.d.ts +52 -0
- package/dist/request-log.js +128 -0
- 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 +2 -2
- package/package.json +6 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.8.0 (2026-11-23)
|
|
4
|
+
|
|
5
|
+
- Add the `@valiron/crawler-protection/request-log` subpath export, so the request logger can be imported without the rest of the runtime (for example in Next.js `proxy.ts`).
|
|
6
|
+
|
|
7
|
+
- Add `CrawlerRegistry.snapshot(crawlerClass)`, which returns the installed, unexpired official prefixes and version exactly as verification uses them (frozen; `undefined` once expired), and `verifiableCrawlers()`, the read-only verifiable crawler catalog. Valiron uses them to compile verified-crawler rules for Cloudflare and AWS WAF from the same evidence as runtime verification.
|
|
8
|
+
- Runtime activation now requires a Pro account with the Crawler Protection add-on, or Enterprise (enforced by the hosted activation endpoint; no SDK API change).
|
|
9
|
+
- Add `createCrawlerRequestLog`: passive request logging for Valiron's observability (Pro), for sites that cannot share CDN/WAF logs. It records after responses finish (Node middleware, `recordFetch`, or `record`) and uploads gzip NDJSON in the background to a per-connection `/ingest/crawler/logs/<id>` endpoint with a `vcl_` token. It never blocks or delays requests and needs no Redis, operator API key or activation. Query strings are stripped and only User-Agent is collected from headers. Bounded memory buffer, retries on 429/5xx, HTTPS-only endpoint, no redirects.
|
|
10
|
+
- Add `createCloudflareWafEvidence`: a `trusted_waf` evidence source for Cloudflare Bot Management verified-bot categories, attesting a spoof-resistant edge-to-origin path (viewer-supplied `cf-verified-bot-category` headers rejected before insertion). Verified evidence maps configured categories to crawler classes and intentionally leaves `provider` unset.
|
|
11
|
+
- Add opt-in dynamic Web Bot Auth directory resolution: `WebBotAuthVerifier` accepts a `dynamicDirectory` resolver (`createCachingDirectoryResolver`, `fetchDirectoryKeys`) used only by the async `classifyDynamic()`. HTTPS-only, no redirects, all resolved IPs validated against private/special ranges and pinned into the TLS connect, 5-second timeout, 64 KB body, 16-key cap, URL-keyed cache with in-flight dedupe. Dynamically resolved signers get the neutral `webbotauth-dynamic` class and `promote: false`; the synchronous `classify()` stays pin-only and never touches the network.
|
|
12
|
+
|
|
3
13
|
## 0.7.0
|
|
4
14
|
|
|
5
15
|
- Add opt-in hosted crawler access controls, request budget reductions and observe/enforce mode, bounded by installed policy ceilings.
|
|
@@ -39,3 +49,4 @@ All notable changes to `@valiron/crawler-protection` are documented here. The pr
|
|
|
39
49
|
|
|
40
50
|
- External signer interoperability for Web Bot Auth is untested; real-world coverage depends on which signing providers operators pin keys for. The protocol is an active IETF draft - expect wire-format changes before RFC publication.
|
|
41
51
|
|
|
52
|
+
|
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 or crawler signup is required. SDK 0.3.0+ requires
|
|
7
|
+
Integration for [Valiron Crawler Protection](https://www.valiron.co/docs/crawler-protection). Protects origin work in customer infrastructure. No blockchain or crawler signup is required. SDK 0.3.0+ requires an operator API key for a Pro account with the Crawler Protection add-on (or Enterprise) 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
|
|
|
@@ -20,7 +20,26 @@ Implemented:
|
|
|
20
20
|
- Node middleware and a structural Nuxt/Nitro server middleware adapter. Unknown callers retain baseline limits.
|
|
21
21
|
- Noncacheable 429/503 responses, policy/evidence expiry and conservative dependency-failure handling.
|
|
22
22
|
|
|
23
|
-
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
|
+
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. Cloudflare Bot Management is a second opt-in `trusted_waf` source through `createCloudflareWafEvidence`: it maps configured `cf.verified_bot_category` values to crawler classes only across an attested edge-to-origin path where viewer-supplied `cf-verified-bot-category` headers are rejected before the trusted value is inserted, and it intentionally leaves `provider` unset because Cloudflare attests the category, not the operator identity. Header spoofing without a network match does not receive verified allowances.
|
|
24
|
+
|
|
25
|
+
## Observability request log (no runtime required)
|
|
26
|
+
|
|
27
|
+
For Valiron's read-only observability (Pro) on sites that cannot share CDN, WAF or server logs. Requires 0.8.0+. `createCrawlerRequestLog` records request metadata after each response finishes and uploads it in the background. It never blocks, delays or changes a request, and it does not need Redis, an operator API key or account activation. Create an **SDK request log** connection in Dashboard → Crawler Protection → Connect traffic for the endpoint and `vcl_` token.
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
import { createCrawlerRequestLog } from '@valiron/crawler-protection';
|
|
31
|
+
|
|
32
|
+
const requestLog = createCrawlerRequestLog({
|
|
33
|
+
endpoint: process.env.VALIRON_REQUEST_LOG_URL!, // https://…/ingest/crawler/logs/<connection-id>
|
|
34
|
+
token: process.env.VALIRON_REQUEST_LOG_TOKEN!, // vcl_…
|
|
35
|
+
clientIp: (req) => req.socket.remoteAddress, // trusted client address for your proxy topology
|
|
36
|
+
});
|
|
37
|
+
app.use(requestLog.middleware()); // Express/Connect/Node
|
|
38
|
+
// Fetch-style runtimes: requestLog.recordFetch(request, response, { ip, startedAt });
|
|
39
|
+
// Shutdown: await requestLog.stop();
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Query strings are removed, and User-Agent is the only header collected. Records are buffered in memory (`maxBuffer`, default 20,000), uploaded as gzip NDJSON every `flushIntervalMs` (default 10 seconds, up to 5,000 per upload), and retried after network errors, 429 and 5xx. Overflow is counted in `stats().dropped`. The endpoint must be HTTPS (or loopback HTTP) with the exact ingestion path; redirects are refused. See [request log for sites without log access](https://www.valiron.co/docs/crawler-protection/observability#request-log-for-sites-without-log-access).
|
|
24
43
|
|
|
25
44
|
## Returning-browser recognition (optional, observe-only)
|
|
26
45
|
|
|
@@ -84,7 +103,7 @@ pnpm test:crawlers:service
|
|
|
84
103
|
|
|
85
104
|
The Redis and service tests start temporary Redis processes and loopback Python/SQLite origins with generated fixture credentials. `redis-server` and Python 3 must be installed. External verification-feed egress is disabled in service lifecycle fixtures; no customer URLs or production databases are used. The Python unit suite uses local HTTP fixtures only for deliberate authentication/error/redirect cases. The package is distributed through npm as `@valiron/crawler-protection`.
|
|
86
105
|
|
|
87
|
-
Website availability: **
|
|
106
|
+
Website availability: observability and setup with **Pro**; runtime and edge enforcement with the **Crawler Protection add-on** (USD 29.99/month on top of Pro) or **Enterprise**, within each plan’s usage allowance. Dashboard → Crawler Protection offers authenticated configuration validation/export and integration guidance. Optional `createCrawlerTelemetry` reporting adds hosted rolling origin analytics, shared capacity, instance status and dashboard monitoring alerts. It does not deploy customer infrastructure. Optional 0.7.0+ managed controls support dashboard publishing/rollback within installed ceilings, bounded opt-in decision logs and separately configured email/webhook alerts. See the public integration guide for telemetry setup, retention and measurement limits.
|
|
88
107
|
|
|
89
108
|
## Release CI coverage
|
|
90
109
|
|
|
@@ -321,7 +340,7 @@ The standalone gateway and `createCrawlerRuntime()` do not automatically enable
|
|
|
321
340
|
|
|
322
341
|
Trust boundaries, deliberately stricter than the draft minimum:
|
|
323
342
|
|
|
324
|
-
- Pin-only key sources. The
|
|
343
|
+
- Pin-only key sources by default. The synchronous `classify()` performs no network fetch, so a request cannot steer verification into contacting an attacker-chosen directory URL. Dynamic directory resolution is a separate opt-in: construct the verifier with a `dynamicDirectory` resolver (for example `createCachingDirectoryResolver`) and call the async `classifyDynamic()`. Resolution is HTTPS-only with no redirects, validates every resolved IP against private and special ranges (any failure poisons the whole fetch; the validated set is pinned into the TLS connect so re-resolution cannot rebind), and is bounded (5-second timeout, 64 KB body, 16 keys, URL-keyed cache with in-flight dedupe). A hostile or broken directory degrades to unpinned and never throws. Dynamically resolved signers are registered with the neutral class `webbotauth-dynamic` and `promote: false`: a valid signature authenticates the signer URL but produces no verified evidence on first sight. Promotion remains an explicit operator decision.
|
|
325
344
|
- A valid signature is proof of key control, not good intent or authorization. Unpinned signer URLs stay unverified, and pinned-but-not-promoted signers keep unverified budgets while telemetry records the authenticated `signerUrl`. Promotion is an explicit per-signer opt-in.
|
|
326
345
|
- Freshness is not replay protection. The draft's minimum coverage binds only `@authority`, so a captured signature can be replayed against this origin until `expires` (bounded to the draft's recommended 24-hour maximum, configurable down). Verified signers remain subject to every budget, which bounds replay damage; `profile: 'strict'` additionally requires `@method` and `@path` coverage. The strict profile is a Valiron-specific strengthening, not a standard compliance claim.
|
|
327
346
|
- The protocol is a draft. Verification is signature-only and tolerates non-Web-Bot-Auth signatures on the same request; expect wire-format changes before RFC publication.
|
|
@@ -422,3 +441,4 @@ Owner dashboard sessions authenticate:
|
|
|
422
441
|
- `GET /operator/crawlers/control/deliveries?site=...`: recent delivery statuses.
|
|
423
442
|
|
|
424
443
|
These controls do not enable paid request overages or change plan allowances. Database utilization, SQL query counts and money saved are not inferred from blocked requests.
|
|
444
|
+
|
package/dist/cf.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'node:http';
|
|
2
|
+
import { type CrawlerEvidence } from './verification';
|
|
3
|
+
/** Trust Cloudflare verified-bot detection only across an authenticated, spoof-resistant edge→origin path.
|
|
4
|
+
*
|
|
5
|
+
* Prerequisites the operator attests to by constructing this source:
|
|
6
|
+
* - A Cloudflare rule (Transform Rule or WAF custom rule, earliest phase) REJECTS
|
|
7
|
+
* viewer-supplied cf-verified-bot-category headers BEFORE the trusted value is
|
|
8
|
+
* inserted, so a client can never smuggle its own category upstream.
|
|
9
|
+
* - The trusted header is inserted ONLY when cf.bot_management.verified_bot is true
|
|
10
|
+
* AND cf.verified_bot_category matches one of the configured category names.
|
|
11
|
+
* Verified-bot detection is a Bot Management feature; without that entitlement the
|
|
12
|
+
* field is never populated and this source must not be configured.
|
|
13
|
+
*
|
|
14
|
+
* What a verified result means: Cloudflare attests the request came from a bot it
|
|
15
|
+
* has verified, in the given category. It does NOT identify the provider or the
|
|
16
|
+
* individual bot, so provider is intentionally left unset; when the User-Agent
|
|
17
|
+
* maps to a known crawler claim, that claim is reported as claimedCrawler only.
|
|
18
|
+
*/
|
|
19
|
+
export declare function createCloudflareWafEvidence(config: {
|
|
20
|
+
authenticatedClientIp: (request: IncomingMessage) => string;
|
|
21
|
+
/** Operator attestation that the prerequisite edge rules are installed. */
|
|
22
|
+
rejectViewerCfHeaders: true;
|
|
23
|
+
rulesVersion: string;
|
|
24
|
+
/** Cloudflare cf.verified_bot_category values mapped to Valiron crawler classes. */
|
|
25
|
+
categories: Readonly<Record<string, string>>;
|
|
26
|
+
now?: () => number;
|
|
27
|
+
}): (request: unknown, ip: string, userAgent: string) => CrawlerEvidence | undefined;
|
package/dist/cf.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createCloudflareWafEvidence = createCloudflareWafEvidence;
|
|
4
|
+
const ip_1 = require("./ip");
|
|
5
|
+
const verification_1 = require("./verification");
|
|
6
|
+
const identityLabel = /^[a-z0-9_-]{1,64}$/;
|
|
7
|
+
const MAX_CATEGORIES = 64;
|
|
8
|
+
/** Trust Cloudflare verified-bot detection only across an authenticated, spoof-resistant edge→origin path.
|
|
9
|
+
*
|
|
10
|
+
* Prerequisites the operator attests to by constructing this source:
|
|
11
|
+
* - A Cloudflare rule (Transform Rule or WAF custom rule, earliest phase) REJECTS
|
|
12
|
+
* viewer-supplied cf-verified-bot-category headers BEFORE the trusted value is
|
|
13
|
+
* inserted, so a client can never smuggle its own category upstream.
|
|
14
|
+
* - The trusted header is inserted ONLY when cf.bot_management.verified_bot is true
|
|
15
|
+
* AND cf.verified_bot_category matches one of the configured category names.
|
|
16
|
+
* Verified-bot detection is a Bot Management feature; without that entitlement the
|
|
17
|
+
* field is never populated and this source must not be configured.
|
|
18
|
+
*
|
|
19
|
+
* What a verified result means: Cloudflare attests the request came from a bot it
|
|
20
|
+
* has verified, in the given category. It does NOT identify the provider or the
|
|
21
|
+
* individual bot, so provider is intentionally left unset; when the User-Agent
|
|
22
|
+
* maps to a known crawler claim, that claim is reported as claimedCrawler only.
|
|
23
|
+
*/
|
|
24
|
+
function createCloudflareWafEvidence(config) {
|
|
25
|
+
if (config.rejectViewerCfHeaders !== true || !config.rulesVersion || config.rulesVersion.length > 128 ||
|
|
26
|
+
!config.categories || typeof config.categories !== 'object' || Array.isArray(config.categories)) {
|
|
27
|
+
throw new Error('Verified Cloudflare WAF configuration required');
|
|
28
|
+
}
|
|
29
|
+
const categories = Object.entries(config.categories);
|
|
30
|
+
if (!categories.length || categories.length > MAX_CATEGORIES ||
|
|
31
|
+
categories.some(([category, crawlerClass]) => !category.length || category.length > 128 || /[\r\n]/.test(category) || !identityLabel.test(crawlerClass))) {
|
|
32
|
+
throw new Error('Invalid Cloudflare category mapping');
|
|
33
|
+
}
|
|
34
|
+
const mapping = new Map(categories);
|
|
35
|
+
return (request, ip, userAgent) => {
|
|
36
|
+
if (!request)
|
|
37
|
+
return undefined;
|
|
38
|
+
const req = request;
|
|
39
|
+
if ((0, ip_1.normalizeIp)(config.authenticatedClientIp(req)) !== (0, ip_1.normalizeIp)(ip))
|
|
40
|
+
throw new Error('WAF client mismatch');
|
|
41
|
+
const value = req.headers['cf-verified-bot-category'];
|
|
42
|
+
if (value === undefined)
|
|
43
|
+
return undefined;
|
|
44
|
+
const crawlerClass = typeof value === 'string' ? mapping.get(value) : undefined;
|
|
45
|
+
if (!crawlerClass)
|
|
46
|
+
return { state: 'claim_mismatch' };
|
|
47
|
+
return Object.freeze({
|
|
48
|
+
state: 'verified', crawlerClass, method: 'trusted_waf',
|
|
49
|
+
claimedCrawler: (0, verification_1.crawlerClaim)(userAgent)?.crawlerClass,
|
|
50
|
+
evidenceVersion: config.rulesVersion, expiresAt: (config.now ?? Date.now)() + 10000,
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type ResolvedAddress = Readonly<{
|
|
2
|
+
address: string;
|
|
3
|
+
family: number;
|
|
4
|
+
}>;
|
|
5
|
+
export type DirectoryDnsLookup = (hostname: string) => Promise<readonly ResolvedAddress[]>;
|
|
6
|
+
export type HttpGet = (url: URL, options: {
|
|
7
|
+
addresses: readonly ResolvedAddress[];
|
|
8
|
+
timeoutMs: number;
|
|
9
|
+
maxBytes: number;
|
|
10
|
+
}) => Promise<{
|
|
11
|
+
status: number;
|
|
12
|
+
body: string;
|
|
13
|
+
}>;
|
|
14
|
+
export declare function isPublicIpAddress(address: string): boolean;
|
|
15
|
+
export declare const defaultDnsLookup: DirectoryDnsLookup;
|
|
16
|
+
/** Real transport: connects only to the pre-validated address set, no redirects. */
|
|
17
|
+
export declare const defaultHttpGet: HttpGet;
|
|
18
|
+
export type DirectoryFetchOptions = Readonly<{
|
|
19
|
+
dnsLookup?: DirectoryDnsLookup;
|
|
20
|
+
httpGet?: HttpGet;
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
maxBytes?: number;
|
|
23
|
+
}>;
|
|
24
|
+
/**
|
|
25
|
+
* Fetch and structurally validate a signer's key directory.
|
|
26
|
+
* Returns the JWK array, or undefined on any network, policy, or shape failure.
|
|
27
|
+
* Never throws: a hostile or broken directory degrades to "unpinned signer".
|
|
28
|
+
*/
|
|
29
|
+
export declare function fetchDirectoryKeys(agentUrl: string, options?: DirectoryFetchOptions): Promise<readonly unknown[] | undefined>;
|
|
30
|
+
/** URL-keyed cache over fetchDirectoryKeys: one in-flight or fresh entry per signer URL. */
|
|
31
|
+
export declare function createCachingDirectoryResolver(options?: DirectoryFetchOptions & {
|
|
32
|
+
cacheTtlMs?: number;
|
|
33
|
+
now?: () => number;
|
|
34
|
+
}): {
|
|
35
|
+
resolve: (agentUrl: string) => Promise<readonly unknown[] | undefined>;
|
|
36
|
+
size: () => number;
|
|
37
|
+
};
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.defaultHttpGet = exports.defaultDnsLookup = void 0;
|
|
7
|
+
exports.isPublicIpAddress = isPublicIpAddress;
|
|
8
|
+
exports.fetchDirectoryKeys = fetchDirectoryKeys;
|
|
9
|
+
exports.createCachingDirectoryResolver = createCachingDirectoryResolver;
|
|
10
|
+
const node_dns_1 = __importDefault(require("node:dns"));
|
|
11
|
+
const node_https_1 = __importDefault(require("node:https"));
|
|
12
|
+
const node_net_1 = __importDefault(require("node:net"));
|
|
13
|
+
/**
|
|
14
|
+
* Opt-in dynamic key resolution for Web Bot Auth signer directories.
|
|
15
|
+
*
|
|
16
|
+
* The pinned-key model in webbotauth.ts never touches the network, so a request
|
|
17
|
+
* can never steer this process into contacting an attacker-chosen URL. This
|
|
18
|
+
* module relaxes that deliberately and only under these bounds:
|
|
19
|
+
*
|
|
20
|
+
* - HTTPS only; no redirects; the exact configured URL is the only origin.
|
|
21
|
+
* - Every resolved IP address is validated before connecting: any private,
|
|
22
|
+
* loopback, link-local, CGNAT, multicast, reserved, or IPv4-mapped/private
|
|
23
|
+
* IPv6 result aborts the fetch. All addresses are checked, so DNS returning
|
|
24
|
+
* one public decoy alongside an internal target fails closed. The validated
|
|
25
|
+
* address set is pinned into the TLS connect, so a re-resolution between
|
|
26
|
+
* validation and connect cannot change the destination (no TOCTOU rebinding).
|
|
27
|
+
* - 5s total timeout, 64KB response cap, at most 16 keys per directory.
|
|
28
|
+
* - Results are cached per URL; callers key trust by JWK thumbprint downstream.
|
|
29
|
+
* - A dynamically resolved signer is registered WITHOUT promotion: a valid
|
|
30
|
+
* signature authenticates the signer URL, it never produces verified
|
|
31
|
+
* evidence on first sight. Promotion stays an operator decision.
|
|
32
|
+
*/
|
|
33
|
+
const DEFAULT_TIMEOUT_MS = 5000;
|
|
34
|
+
const MAX_TIMEOUT_MS = 10000;
|
|
35
|
+
const DEFAULT_MAX_BYTES = 64 * 1024;
|
|
36
|
+
const HARD_MAX_BYTES = 128 * 1024;
|
|
37
|
+
const MAX_KEYS = 16;
|
|
38
|
+
const DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000;
|
|
39
|
+
const MAX_CACHE_ENTRIES = 2000;
|
|
40
|
+
function isPublicIpAddress(address) {
|
|
41
|
+
const family = node_net_1.default.isIP(address);
|
|
42
|
+
if (family === 4)
|
|
43
|
+
return isPublicIpv4(address);
|
|
44
|
+
if (family === 6)
|
|
45
|
+
return isPublicIpv6(address);
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
function isPublicIpv4(address) {
|
|
49
|
+
const parts = address.split('.').map(part => Number(part));
|
|
50
|
+
if (parts.length !== 4 || parts.some(part => !Number.isInteger(part) || part < 0 || part > 255))
|
|
51
|
+
return false;
|
|
52
|
+
const [a, b] = parts;
|
|
53
|
+
if (a === 0 || a === 10 || a === 127)
|
|
54
|
+
return false; // current-net, private, loopback
|
|
55
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
56
|
+
return false; // CGNAT 100.64/10
|
|
57
|
+
if (a === 169 && b === 254)
|
|
58
|
+
return false; // link-local
|
|
59
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
60
|
+
return false; // private 172.16/12
|
|
61
|
+
if (a === 192 && b === 168)
|
|
62
|
+
return false; // private
|
|
63
|
+
if (a === 192 && b === 0)
|
|
64
|
+
return false; // IETF protocol assignments (incl. TEST-NET-1)
|
|
65
|
+
if (a === 198 && (b === 18 || b === 19))
|
|
66
|
+
return false; // benchmarking
|
|
67
|
+
if (a === 198 && b === 51 && parts[2] === 100)
|
|
68
|
+
return false; // TEST-NET-2
|
|
69
|
+
if (a === 203 && b === 0 && parts[2] === 113)
|
|
70
|
+
return false; // TEST-NET-3
|
|
71
|
+
if (a >= 224)
|
|
72
|
+
return false; // multicast + reserved + broadcast
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
function isPublicIpv6(address) {
|
|
76
|
+
const n = address.toLowerCase();
|
|
77
|
+
// IPv4-mapped forms: validate the embedded address; hex-form mapped is rejected.
|
|
78
|
+
const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(n);
|
|
79
|
+
if (mapped)
|
|
80
|
+
return isPublicIpv4(mapped[1]);
|
|
81
|
+
if (n.startsWith('::ffff:'))
|
|
82
|
+
return false;
|
|
83
|
+
// Allow only global unicast 2000::/3, minus ranges that embed or stand in for non-public space.
|
|
84
|
+
if (!/^[23]/.test(n))
|
|
85
|
+
return false;
|
|
86
|
+
if (/^2001:0{0,4}:/.test(n))
|
|
87
|
+
return false; // 2001::/32 TEREDO embeds IPv4
|
|
88
|
+
if (/^2001:0{0,3}db8/.test(n))
|
|
89
|
+
return false; // 2001:db8::/32 documentation
|
|
90
|
+
if (n.startsWith('2002:'))
|
|
91
|
+
return false; // 6to4 embeds IPv4
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
const defaultDnsLookup = async (hostname) => {
|
|
95
|
+
const results = await node_dns_1.default.promises.lookup(hostname, { all: true, verbatim: true });
|
|
96
|
+
return results.map(({ address, family }) => ({ address, family }));
|
|
97
|
+
};
|
|
98
|
+
exports.defaultDnsLookup = defaultDnsLookup;
|
|
99
|
+
/** Real transport: connects only to the pre-validated address set, no redirects. */
|
|
100
|
+
const defaultHttpGet = (url, { addresses, timeoutMs, maxBytes }) => new Promise((resolve, reject) => {
|
|
101
|
+
let settled = false;
|
|
102
|
+
const fail = (error) => { if (!settled) {
|
|
103
|
+
settled = true;
|
|
104
|
+
request.destroy();
|
|
105
|
+
reject(error);
|
|
106
|
+
} };
|
|
107
|
+
let index = 0;
|
|
108
|
+
const attempt = () => {
|
|
109
|
+
const target = addresses[index];
|
|
110
|
+
request = node_https_1.default.request({
|
|
111
|
+
protocol: 'https:', host: url.hostname, port: url.port || 443,
|
|
112
|
+
path: url.pathname + url.search, method: 'GET',
|
|
113
|
+
servername: url.hostname, // SNI keeps the real hostname; the IP is pinned below.
|
|
114
|
+
lookup: (_hostname, _options, callback) => callback(null, target.address, target.family),
|
|
115
|
+
timeout: timeoutMs,
|
|
116
|
+
headers: { accept: 'application/json', 'user-agent': 'valiron-crawler-protection/1' },
|
|
117
|
+
}, response => {
|
|
118
|
+
const chunks = [];
|
|
119
|
+
let received = 0;
|
|
120
|
+
response.on('data', (chunk) => {
|
|
121
|
+
received += chunk.length;
|
|
122
|
+
if (received > maxBytes) {
|
|
123
|
+
fail(new Error('Directory response too large'));
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
chunks.push(chunk);
|
|
127
|
+
});
|
|
128
|
+
response.on('end', () => {
|
|
129
|
+
if (settled)
|
|
130
|
+
return;
|
|
131
|
+
settled = true;
|
|
132
|
+
resolve({ status: response.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') });
|
|
133
|
+
});
|
|
134
|
+
response.on('error', fail);
|
|
135
|
+
});
|
|
136
|
+
request.on('timeout', () => fail(new Error('Directory fetch timed out')));
|
|
137
|
+
request.on('error', () => {
|
|
138
|
+
index += 1;
|
|
139
|
+
if (index < addresses.length)
|
|
140
|
+
attempt();
|
|
141
|
+
else
|
|
142
|
+
fail(new Error('Directory fetch failed'));
|
|
143
|
+
});
|
|
144
|
+
request.end();
|
|
145
|
+
};
|
|
146
|
+
let request;
|
|
147
|
+
attempt();
|
|
148
|
+
});
|
|
149
|
+
exports.defaultHttpGet = defaultHttpGet;
|
|
150
|
+
/**
|
|
151
|
+
* Fetch and structurally validate a signer's key directory.
|
|
152
|
+
* Returns the JWK array, or undefined on any network, policy, or shape failure.
|
|
153
|
+
* Never throws: a hostile or broken directory degrades to "unpinned signer".
|
|
154
|
+
*/
|
|
155
|
+
async function fetchDirectoryKeys(agentUrl, options) {
|
|
156
|
+
if (typeof agentUrl !== 'string' || agentUrl.length > 2048)
|
|
157
|
+
return undefined;
|
|
158
|
+
let url;
|
|
159
|
+
try {
|
|
160
|
+
url = new URL(agentUrl);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
if (url.protocol !== 'https:' || url.username || url.password)
|
|
166
|
+
return undefined;
|
|
167
|
+
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
168
|
+
const maxBytes = options?.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
169
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 500 || timeoutMs > MAX_TIMEOUT_MS ||
|
|
170
|
+
!Number.isSafeInteger(maxBytes) || maxBytes < 1024 || maxBytes > HARD_MAX_BYTES)
|
|
171
|
+
return undefined;
|
|
172
|
+
const dnsLookup = options?.dnsLookup ?? exports.defaultDnsLookup;
|
|
173
|
+
const httpGet = options?.httpGet ?? exports.defaultHttpGet;
|
|
174
|
+
try {
|
|
175
|
+
const addresses = await dnsLookup(url.hostname);
|
|
176
|
+
if (!addresses.length || addresses.length > 32)
|
|
177
|
+
return undefined;
|
|
178
|
+
if (addresses.some(({ address, family }) => (family !== 4 && family !== 6) || !isPublicIpAddress(address))) {
|
|
179
|
+
return undefined; // any private/special address fails the whole fetch
|
|
180
|
+
}
|
|
181
|
+
const response = await httpGet(url, { addresses, timeoutMs, maxBytes });
|
|
182
|
+
if (response.status !== 200 || response.body.length > maxBytes)
|
|
183
|
+
return undefined; // redirects never followed
|
|
184
|
+
const parsed = JSON.parse(response.body);
|
|
185
|
+
const keys = parsed.keys;
|
|
186
|
+
if (!Array.isArray(keys) || !keys.length || keys.length > MAX_KEYS)
|
|
187
|
+
return undefined;
|
|
188
|
+
for (const candidate of keys) {
|
|
189
|
+
const jwk = candidate;
|
|
190
|
+
if (!jwk || jwk.kty !== 'OKP' || jwk.crv !== 'Ed25519' || typeof jwk.x !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(jwk.x)) {
|
|
191
|
+
return undefined; // one bad key poisons the directory
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return Object.freeze(keys.slice());
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/** URL-keyed cache over fetchDirectoryKeys: one in-flight or fresh entry per signer URL. */
|
|
201
|
+
function createCachingDirectoryResolver(options) {
|
|
202
|
+
const now = options?.now ?? Date.now;
|
|
203
|
+
const cacheTtlMs = options?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
204
|
+
if (!Number.isSafeInteger(cacheTtlMs) || cacheTtlMs < 1000 || cacheTtlMs > 3600000) {
|
|
205
|
+
throw new Error('Invalid directory cache TTL');
|
|
206
|
+
}
|
|
207
|
+
const cache = new Map();
|
|
208
|
+
const inflight = new Map();
|
|
209
|
+
return {
|
|
210
|
+
resolve(agentUrl) {
|
|
211
|
+
const cached = cache.get(agentUrl);
|
|
212
|
+
if (cached && cached.expiresAt > now())
|
|
213
|
+
return Promise.resolve(cached.keys);
|
|
214
|
+
const pending = inflight.get(agentUrl);
|
|
215
|
+
if (pending)
|
|
216
|
+
return pending;
|
|
217
|
+
const task = fetchDirectoryKeys(agentUrl, options).then(keys => {
|
|
218
|
+
inflight.delete(agentUrl);
|
|
219
|
+
if (keys) {
|
|
220
|
+
if (cache.size >= MAX_CACHE_ENTRIES)
|
|
221
|
+
cache.clear();
|
|
222
|
+
cache.set(agentUrl, { keys, expiresAt: now() + cacheTtlMs });
|
|
223
|
+
}
|
|
224
|
+
return keys;
|
|
225
|
+
}, () => { inflight.delete(agentUrl); return undefined; });
|
|
226
|
+
inflight.set(agentUrl, task);
|
|
227
|
+
return task;
|
|
228
|
+
},
|
|
229
|
+
size: () => cache.size,
|
|
230
|
+
};
|
|
231
|
+
}
|
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,10 @@ 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';
|
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; } });
|
|
@@ -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/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. |
|
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": {
|