@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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
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
|
+
|
|
13
|
+
## 0.7.0
|
|
14
|
+
|
|
15
|
+
- Add opt-in hosted crawler access controls, request budget reductions and observe/enforce mode, bounded by installed policy ceilings.
|
|
16
|
+
- Add owner-session publishing and rollback, short runtime policy leases and per-instance revision acknowledgments.
|
|
17
|
+
- Add separately enabled recent decision logs without raw IPs, URLs, user agents or caller identifiers.
|
|
18
|
+
- Gateway supports `CRAWLER_MANAGED_CONTROLS=true`; existing static integrations retain their behavior.
|
|
19
|
+
- Requires the management backend and database migration before managed controls are enabled.
|
|
20
|
+
|
|
21
|
+
|
|
3
22
|
All notable changes to `@valiron/crawler-protection` are documented here. The project uses semantic versioning.
|
|
4
23
|
|
|
5
24
|
## 0.6.0 (2026-11-12)
|
|
@@ -30,3 +49,4 @@ All notable changes to `@valiron/crawler-protection` are documented here. The pr
|
|
|
30
49
|
|
|
31
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.
|
|
32
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.
|
|
@@ -334,3 +353,92 @@ Trust boundaries, deliberately stricter than the draft minimum:
|
|
|
334
353
|
## Upgrade to 0.6.0
|
|
335
354
|
|
|
336
355
|
Install `@valiron/crawler-protection@^0.6.0` for official Anthropic and Google agent/Notebook verification and explicit default-deny controls. Existing configurations retain their budget defaults. Review and regenerate directory approvals before deploying; static addresses remain pinned, while reviewed feed-backed recipes can refresh addresses. Migrate any overlapping directory-based Claude crawler and supported Google agent/Notebook rules to the built-in IDs. See the included CHANGELOG and [selected AI service guide](https://www.valiron.co/docs/crawler-protection/policies#allow-selected-ai-services) for the complete configuration and anonymous-visitor boundaries.
|
|
356
|
+
|
|
357
|
+
## Dashboard controls
|
|
358
|
+
|
|
359
|
+
Managed controls require Crawler Protection SDK/gateway **0.7.0+**, the management backend and its database migration. Existing static runtimes and aggregate telemetry do not automatically enable this feature. The dashboard does not install software, deploy infrastructure or increase database capacity.
|
|
360
|
+
|
|
361
|
+
### Connect a gateway
|
|
362
|
+
|
|
363
|
+
Keep the existing validated installation configuration, Redis and operator API key. Add these server-side variables and restart your gateway:
|
|
364
|
+
|
|
365
|
+
```dotenv
|
|
366
|
+
VALIRON_API_KEY=<your-server-side-operator-key>
|
|
367
|
+
CRAWLER_SITE_ID=storefront
|
|
368
|
+
CRAWLER_MANAGED_CONTROLS=true
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
Use the same site ID for controls and telemetry. Continue `CRAWLER_TELEMETRY_URL` reporting for aggregate analytics and traffic alerts. On first successful control report, the installation registers with its current crawler access and mode, preserving a partial `enforceGroups` rollout. Selecting a new mode in Crawler controls applies that mode to all configured route groups. Decision logging and outbound alerts start disabled. All instances sharing a site must use the same base configuration. Managed registration accepts at most 64 KiB of compact configuration JSON, 16 sites per account and 64 runtime instances per site in 24 hours.
|
|
372
|
+
|
|
373
|
+
### Connect Node middleware
|
|
374
|
+
|
|
375
|
+
```ts
|
|
376
|
+
import { createCrawlerControlClient, createCrawlerRuntime } from '@valiron/crawler-protection';
|
|
377
|
+
|
|
378
|
+
const controls = createCrawlerControlClient({
|
|
379
|
+
configuration, // your validated deployment configuration
|
|
380
|
+
apiKey: process.env.VALIRON_API_KEY!,
|
|
381
|
+
site: process.env.CRAWLER_SITE_ID!,
|
|
382
|
+
});
|
|
383
|
+
await controls.refresh();
|
|
384
|
+
const stopControls = controls.start();
|
|
385
|
+
const runtime = createCrawlerRuntime({
|
|
386
|
+
configuration, redis, activation, clientIp, registry,
|
|
387
|
+
controlClient: controls,
|
|
388
|
+
});
|
|
389
|
+
// Mount runtime.nodeMiddleware/runtime.nuxtMiddleware before protected work.
|
|
390
|
+
// Keep your existing database/render admission wrappers and telemetry.
|
|
391
|
+
// On shutdown: stopControls(); telemetry.stop(); activation.stop();
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
The control client uses its fixed hosted endpoint by default. An optional `endpoint` must be trusted HTTPS (HTTP is accepted only for loopback tests), end in `/operator/crawlers/control/runtime`, and contain no credentials, query or fragment. Do not accept this value from website visitors. `status()` reports the locally held revision and lease availability. `refresh()` records failures in status; `current()` throws when no valid policy is available.
|
|
395
|
+
|
|
396
|
+
### Choose access and budgets
|
|
397
|
+
|
|
398
|
+
Open **Crawler Protection → Crawler controls**, select a registered site, edit and **Publish changes**:
|
|
399
|
+
|
|
400
|
+
- Choose **Allow within limits** or **Block** for each installed crawler class and route group. Search, user fetches and training are separate identities. Allowing a class still requires its configured verifier and available budget; it does not grant every browser identifying itself as that service access.
|
|
401
|
+
- Set the fallback for other verified crawlers. Unverified traffic has a separate control: it includes ordinary anonymous visitors, so blocking it can block people. Independently authenticated shopper/checkout grants retain their own lanes.
|
|
402
|
+
- Reduce global, source, route or per-IP credits within the installed ceilings. Credits follow configured route costs; they are not necessarily one credit per request. Unknown traffic remains no more privileged than reduced provider budgets. Work-pool/concurrency ceilings, customer reservations, source verifiers and routing remain installation settings.
|
|
403
|
+
- **Observe** reports proposed access/rate denials while preserving hard safety and workload limits. **Enforce** applies access/rate decisions to catalog traffic. Review measured headroom before switching.
|
|
404
|
+
|
|
405
|
+
Customer publishing requires the owner's authenticated dashboard session. Authorized platform admins can also make customer-scoped changes through the admin workspace, with a required reason and atomic audit record; customer history labels those revisions Valiron support. Runtime operator API keys cannot publish, change alert destinations or read owner logs. Settings and the last 20 revisions are durable and account/site scoped. Concurrent edits use revision checks; refresh and review a conflicting revision rather than overwriting it. Rollback publishes the selected settings as a new increasing revision.
|
|
406
|
+
|
|
407
|
+
### Know whether a revision is active
|
|
408
|
+
|
|
409
|
+
Runtimes poll every 30 seconds and report their previously applied revision before receiving an update. The dashboard distinguishes the desired revision from acknowledgment by instances with reports within the five-minute lease window. An acknowledgment is a runtime report, not independent deployment attestation. Instances may temporarily use different revisions during propagation; the installed safety ceilings remain the upper bound.
|
|
410
|
+
|
|
411
|
+
Control fetching runs in the background; it adds no hosted network call to the per-request control decision. It does not remove the existing hosted monthly quota admission call. Transient update failures retain the current policy only to its original expiry, at most five minutes. Authentication/configuration rejection invalidates the local policy immediately. Without a valid managed policy, new catalog admissions fail closed; authenticated customer grants remain independent. Already running work must still settle and release normally.
|
|
412
|
+
|
|
413
|
+
Changing routes, source candidates, work ceilings or the base configuration requires a planned installation update. Stop the old deployment, validate a replacement in Setup, use **Version history → Replace the installed configuration**, and deploy that exact file. Adoption resets access to the new installation defaults in observation mode, disables decision logging, clears logs and replaces version history. Old configuration fingerprints are rejected. This can interrupt traffic; use a maintenance window. A runtime API key cannot silently overwrite the site's installed configuration.
|
|
414
|
+
|
|
415
|
+
### Inspect recent decisions
|
|
416
|
+
|
|
417
|
+
**Decision logs** is separately enabled in Crawler controls. It retains up to 1,000 decisions per site for 24 hours, with source/class, route group, action, reason, verification state, runtime time, server receipt time and generated event ID. No raw IPs, URLs, user agents, credentials or caller-supplied request identifiers are collected by this log buffer. These coarse dimensions can still be business-sensitive; access is account scoped.
|
|
418
|
+
|
|
419
|
+
Each process buffers up to 1,000 events, uploads at most 100 per control report, and drops new events when full. Retry event IDs are deduplicated in storage. This is a bounded recent sample, not a complete audit archive. The dashboard shows runtime drop indications; aggregate Traffic & analytics remains the source of reported totals. Filter by source, route or decision and export the matching rows. Disabling logging clears retained events and buffers once runtimes receive the update. Runtime clocks can differ; server receipt time controls retention.
|
|
420
|
+
|
|
421
|
+
### Configure notifications
|
|
422
|
+
|
|
423
|
+
**Alerts** can send email to the account email address and/or a public HTTPS webhook, only after the owner saves enabled destinations. Email requires server-side `RESEND_API_KEY` and optional `CRAWLER_ALERT_EMAIL_FROM`; the UI shows when email is unavailable. Webhooks must use public HTTPS on port 443 without URL credentials. DNS is resolved and checked again for each delivery, pinned to the checked public address; redirects are not followed.
|
|
424
|
+
|
|
425
|
+
Available triggers are runtime reporting absent for two minutes and a configured threshold of limited/blocked requests in the current fixed five-minute reporting window. The latter requires aggregate telemetry using the same site ID; it is not computed from sampled decision logs. Checks run about once a minute in bounded worker batches, so notifications can be delayed. A per-destination/type cooldown is configurable from 15 minutes to 24 hours. Delivery attempts and status are visible; failures retry up to three times. Deliveries are retained for seven days. These notifications supplement existing infrastructure alarms and do not change policy or reclaim workload holds.
|
|
426
|
+
|
|
427
|
+
Webhook bodies contain `id`, `type` (`crawler.stale` or `crawler.blocked`), `site`, `occurredAt` and a fixed message. Delivery is not signed; treat it as a notification and confirm incidents in the authenticated dashboard before taking privileged actions. Receivers should deduplicate by `id`: failures after delivery can produce retries. Turning destinations off or changing settings cancels queued deliveries on their next check; it cannot retract a delivery already in flight.
|
|
428
|
+
|
|
429
|
+
### Management endpoints
|
|
430
|
+
|
|
431
|
+
All responses are private and noncacheable. API keys authenticate only `POST /operator/crawlers/control/runtime`, which registers/updates a site, receives a five-minute policy lease and uploads bounded decisions. A configuration fingerprint mismatch returns 409; excessively frequent reports or cardinality limits return 429.
|
|
432
|
+
|
|
433
|
+
Owner dashboard sessions authenticate:
|
|
434
|
+
|
|
435
|
+
- `GET /operator/crawlers/control`: registered sites, installed ceilings, desired settings and runtime acknowledgments.
|
|
436
|
+
- `POST /operator/crawlers/control/publish?site=...`: `{ expectedRevision, settings }` or `{ expectedRevision, rollbackRevision }`.
|
|
437
|
+
- `POST /operator/crawlers/control/adopt?site=...`: `{ expectedRevision, configuration }` for a planned installation replacement.
|
|
438
|
+
- `GET /operator/crawlers/control/history?site=...`: last 20 revisions.
|
|
439
|
+
- `GET /operator/crawlers/control/logs?site=...`: bounded recent decisions.
|
|
440
|
+
- `POST /operator/crawlers/control/alerts?site=...`: `{ expectedVersion, settings }` to configure destinations/triggers.
|
|
441
|
+
- `GET /operator/crawlers/control/deliveries?site=...`: recent delivery statuses.
|
|
442
|
+
|
|
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
|
+
}
|
package/dist/configuration.d.ts
CHANGED
|
@@ -52,5 +52,6 @@ export type CompiledCrawlerConfiguration = Readonly<{
|
|
|
52
52
|
fingerprint: string;
|
|
53
53
|
resolve: (request: Pick<IncomingMessage, 'method' | 'url'>) => ResolvedRoute;
|
|
54
54
|
}>;
|
|
55
|
+
export declare function assertCrawlerJsonData(input: unknown): void;
|
|
55
56
|
/** Strict JSON-compatible schema v1. Unknown fields, overlapping routes and missing groups reject. */
|
|
56
57
|
export declare function compileCrawlerConfiguration(input: unknown, now?: number): CompiledCrawlerConfiguration;
|
package/dist/configuration.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertCrawlerJsonData = assertCrawlerJsonData;
|
|
3
4
|
exports.compileCrawlerConfiguration = compileCrawlerConfiguration;
|
|
4
5
|
const guard_1 = require("./guard");
|
|
5
6
|
const operations_1 = require("./operations");
|
|
@@ -13,7 +14,7 @@ function labels(value, where) {
|
|
|
13
14
|
throw new Error('Invalid ' + where);
|
|
14
15
|
}
|
|
15
16
|
function rate(value) { object(value, ['capacity', 'refillPerSecond'], 'rate'); }
|
|
16
|
-
function
|
|
17
|
+
function assertCrawlerJsonData(input) {
|
|
17
18
|
let count = 0;
|
|
18
19
|
const visiting = new Set();
|
|
19
20
|
function visit(value, depth) {
|
|
@@ -92,7 +93,7 @@ function matches(pattern, path) {
|
|
|
92
93
|
/** Strict JSON-compatible schema v1. Unknown fields, overlapping routes and missing groups reject. */
|
|
93
94
|
function compileCrawlerConfiguration(input, now = Date.now()) {
|
|
94
95
|
// Reject non-JSON fields rather than silently dropping callbacks/undefined during serialization.
|
|
95
|
-
|
|
96
|
+
assertCrawlerJsonData(input);
|
|
96
97
|
const encoded = JSON.stringify(input);
|
|
97
98
|
if (!encoded || Buffer.byteLength(encoded) > 262144)
|
|
98
99
|
throw new Error('Configuration too large');
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { Decision } from "./admission";
|
|
2
|
+
import type { CrawlerEvidence } from "./verification";
|
|
3
|
+
import type { DecisionDetails } from "./guard";
|
|
4
|
+
import type { GuardPolicy } from "./guard";
|
|
5
|
+
import type { CrawlerAccessRule } from "./configuration";
|
|
6
|
+
export type ControlRate = Readonly<{
|
|
7
|
+
capacity: number;
|
|
8
|
+
refillPerSecond: number;
|
|
9
|
+
}>;
|
|
10
|
+
export type CrawlerControls = Readonly<{
|
|
11
|
+
mode: "observe" | "enforce";
|
|
12
|
+
enforceGroups?: readonly string[];
|
|
13
|
+
defaultAction: "budget" | "deny";
|
|
14
|
+
unverifiedAction: "budget" | "deny";
|
|
15
|
+
rules: readonly CrawlerAccessRule[];
|
|
16
|
+
rates: Readonly<{
|
|
17
|
+
global?: ControlRate;
|
|
18
|
+
unknown?: ControlRate;
|
|
19
|
+
perIp?: ControlRate;
|
|
20
|
+
routes?: Readonly<Record<string, ControlRate>>;
|
|
21
|
+
providers?: Readonly<Record<string, ControlRate>>;
|
|
22
|
+
}>;
|
|
23
|
+
logging: boolean;
|
|
24
|
+
}>;
|
|
25
|
+
/** Dashboard controls cannot increase locally installed request ceilings or alter work pools. */
|
|
26
|
+
export declare function validateCrawlerControls(raw: unknown, policy: GuardPolicy): CrawlerControls;
|
|
27
|
+
export declare function defaultCrawlerControls(configuration: {
|
|
28
|
+
policy: GuardPolicy;
|
|
29
|
+
rollout?: {
|
|
30
|
+
mode: "observe" | "enforce";
|
|
31
|
+
enforceGroups?: readonly string[];
|
|
32
|
+
};
|
|
33
|
+
crawlerAccess?: readonly CrawlerAccessRule[];
|
|
34
|
+
crawlerAccessDefault?: "budget" | "deny";
|
|
35
|
+
unverifiedAccess?: "budget" | "deny";
|
|
36
|
+
}): CrawlerControls;
|
|
37
|
+
export type CrawlerDecisionLog = {
|
|
38
|
+
id: string;
|
|
39
|
+
at: number;
|
|
40
|
+
group: string;
|
|
41
|
+
provider: string;
|
|
42
|
+
crawlerClass: string;
|
|
43
|
+
action: Decision["action"];
|
|
44
|
+
reason: string;
|
|
45
|
+
verification: string;
|
|
46
|
+
mode: string;
|
|
47
|
+
};
|
|
48
|
+
/** Separate opt-in bounded log buffer; never retains IP, URL, user agent or caller request IDs. */
|
|
49
|
+
export declare function createCrawlerDecisionBuffer(policy: GuardPolicy, enabled: () => boolean, now?: () => number): {
|
|
50
|
+
record(decision: Decision, evidence?: CrawlerEvidence, details?: DecisionDetails): void;
|
|
51
|
+
batch(): CrawlerDecisionLog[];
|
|
52
|
+
ack(ids: readonly string[]): void;
|
|
53
|
+
clear(): void;
|
|
54
|
+
dropped(): number;
|
|
55
|
+
};
|
|
56
|
+
/** Memory-only short lease. Dashboard sessions alone publish; requests use cached controls. */
|
|
57
|
+
export declare function createCrawlerControlClient(input: {
|
|
58
|
+
apiKey: string;
|
|
59
|
+
site: string;
|
|
60
|
+
configuration: unknown;
|
|
61
|
+
endpoint?: string;
|
|
62
|
+
fetch?: typeof fetch;
|
|
63
|
+
now?: () => number;
|
|
64
|
+
}): {
|
|
65
|
+
configurationId: string;
|
|
66
|
+
refresh: () => Promise<void>;
|
|
67
|
+
record: (decision: Decision, evidence?: CrawlerEvidence, details?: DecisionDetails) => void;
|
|
68
|
+
current(): Readonly<{
|
|
69
|
+
mode: "observe" | "enforce";
|
|
70
|
+
enforceGroups?: readonly string[];
|
|
71
|
+
defaultAction: "budget" | "deny";
|
|
72
|
+
unverifiedAction: "budget" | "deny";
|
|
73
|
+
rules: readonly CrawlerAccessRule[];
|
|
74
|
+
rates: Readonly<{
|
|
75
|
+
global?: ControlRate;
|
|
76
|
+
unknown?: ControlRate;
|
|
77
|
+
perIp?: ControlRate;
|
|
78
|
+
routes?: Readonly<Record<string, ControlRate>>;
|
|
79
|
+
providers?: Readonly<Record<string, ControlRate>>;
|
|
80
|
+
}>;
|
|
81
|
+
logging: boolean;
|
|
82
|
+
}>;
|
|
83
|
+
status(): {
|
|
84
|
+
error?: "unavailable" | "rejected" | undefined;
|
|
85
|
+
revision: number;
|
|
86
|
+
mode: "observe" | "enforce";
|
|
87
|
+
active: boolean;
|
|
88
|
+
};
|
|
89
|
+
start(): () => void;
|
|
90
|
+
};
|