@valiron/crawler-protection 0.5.0 → 0.7.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 +41 -0
- package/README.md +96 -3
- package/dist/configuration.d.ts +3 -0
- package/dist/configuration.js +8 -3
- package/dist/controls.d.ts +90 -0
- package/dist/controls.js +339 -0
- package/dist/directory.d.ts +1 -0
- package/dist/directory.js +24 -15
- package/dist/guard.d.ts +3 -0
- package/dist/guard.js +19 -7
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/onboarding.d.ts +3 -1
- package/dist/onboarding.js +3 -1
- package/dist/runtime.d.ts +29 -0
- package/dist/runtime.js +7 -2
- package/dist/telemetry.js +3 -1
- package/dist/verification.d.ts +20 -0
- package/dist/verification.js +10 -0
- package/gateway/README.md +12 -2
- package/gateway/service.cjs +8 -4
- package/package.json +2 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.7.0
|
|
4
|
+
|
|
5
|
+
- Add opt-in hosted crawler access controls, request budget reductions and observe/enforce mode, bounded by installed policy ceilings.
|
|
6
|
+
- Add owner-session publishing and rollback, short runtime policy leases and per-instance revision acknowledgments.
|
|
7
|
+
- Add separately enabled recent decision logs without raw IPs, URLs, user agents or caller identifiers.
|
|
8
|
+
- Gateway supports `CRAWLER_MANAGED_CONTROLS=true`; existing static integrations retain their behavior.
|
|
9
|
+
- Requires the management backend and database migration before managed controls are enabled.
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
All notable changes to `@valiron/crawler-protection` are documented here. The project uses semantic versioning.
|
|
13
|
+
|
|
14
|
+
## 0.6.0 (2026-11-12)
|
|
15
|
+
|
|
16
|
+
- Added official feed verification for Anthropic’s `ClaudeBot`, `Claude-SearchBot`, `Claude-User`, Google-Agent and Gemini Notebook, keeping training/search/user-fetch policies separate.
|
|
17
|
+
- Added optional `crawlerAccessDefault` and `unverifiedAccess` settings. Default-deny verified crawler access requires explicit group-specific allowances; denying unverified traffic also denies anonymous humans. Existing configurations retain budget-based defaults.
|
|
18
|
+
- Directory bare IP addresses normalize to host prefixes, and invalid or overly broad range sets disable only the affected identity. Feed-backed approval hashes survive range rotation; static recipes remain range-pinned. Existing approval hashes must be reviewed and regenerated.
|
|
19
|
+
- Added regression coverage for provider spoofing, feed expiry, address rotation, access defaults, observation reporting and real Redis enforcement.
|
|
20
|
+
|
|
21
|
+
## 0.5.0 (2026-11-10)
|
|
22
|
+
|
|
23
|
+
- Browser recognition now requires an account-bound `activation` handle. Create it with a website-issued operator API key and pass it to `DeviceIdentity`; each recognition call obtains hosted bot-quota admission before storing evidence. This is a breaking constructor change for 0.4.x recognition integrations.
|
|
24
|
+
- Browser middleware maps quota exhaustion to 429 and unavailable activation/admission to 503.
|
|
25
|
+
- Hosted Pro overage accounting and explicit subscription enrollment support additional calls at 0.001 each in the subscription currency; the gateway and guard use their existing hosted admission protocol. Enabling paid overages is separate from installing this package.
|
|
26
|
+
|
|
27
|
+
## 0.4.0 (2026-11-09)
|
|
28
|
+
|
|
29
|
+
### Added
|
|
30
|
+
|
|
31
|
+
- **Returning-browser recognition** (optional, observe-only): `DeviceIdentity`, `RedisIdentityStore` / in-memory store, and `createNodeDeviceIdentityMiddleware`, folded in from the former standalone `@valiron/device-identity` package. Deterministic recognition via a first-party server-signed cookie (`exact`) stays strictly separate from probabilistic coarsened-signal matching (`similar`). Recognition is evidence only: no risk score, no block decision, no enforcement hook. Privacy properties are enforced in code (salted per-component hashes, bounded retention, cookie carries a random id + HMAC only, `forget()` deletion hook). See the README's "Returning-browser recognition" section for the production policy decisions each deployment must make explicitly.
|
|
32
|
+
- **Web Bot Auth verification** (opt-in, draft protocol): `WebBotAuthVerifier` verifies draft-ietf-webbotauth-httpsig-protocol signatures as a third evidence path, wired through the guard's `fallbackEvidence` hook. Pin-only Ed25519 key sources (no network fetch), per-signer promotion opt-in, freshness bounds configurable up to the draft's recommended 24-hour maximum, and a Valiron-specific `strict` profile requiring `@method` and `@path` coverage.
|
|
33
|
+
|
|
34
|
+
### Fixed
|
|
35
|
+
|
|
36
|
+
- `deviceIdentityCollectorScript()` no longer reads `public/collector.js` from disk at runtime. The collector is embedded in the built package as a string, so bundled consumers (verified against Next.js 16 dev/Turbopack and production builds) serve it without `serverExternalPackages`, asset copying, or working-directory assumptions. Previously such consumers got `ENOENT` and a 500 on the collector route. A regression test asserts the embedded script stays byte-identical to `public/collector.js`.
|
|
37
|
+
|
|
38
|
+
### Notes
|
|
39
|
+
|
|
40
|
+
- 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
|
+
|
package/README.md
CHANGED
|
@@ -11,8 +11,9 @@ Customer-facing behavior and integration contracts are documented in the [contro
|
|
|
11
11
|
Implemented:
|
|
12
12
|
|
|
13
13
|
- Strict client IP parsing and an authenticated CloudFront origin-header adapter; never trusts the leftmost forwarded value.
|
|
14
|
+
- Official IP verification for OpenAI search/user/training crawlers, Anthropic search/user/training crawlers, Google-hosted agents and Gemini Notebook; each class remains subject to configured budgets.
|
|
15
|
+
- Explicit `crawlerAccessDefault` and `unverifiedAccess` controls for opt-in default-deny access, independent of authenticated shopper lanes. See [AI service access](https://valiron.co/docs/agents/CRAWLER-PROTECTION.md#allow-selected-ai-services).
|
|
14
16
|
- Broader directory discovery with reviewed metadata approvals, distinct third-party CIDR evidence, and conservative fallback; see [directory setup](https://valiron.co/docs/agents/CRAWLER-PROTECTION.md#broader-crawler-directory).
|
|
15
|
-
- Official CIDR verification for OpenAI, Googlebot/AdsBot, Applebot, DuckDuckBot and Perplexity search/user-fetch classes, with bounded background refresh from an immutable nine-feed catalog.
|
|
16
17
|
- Bing forward-confirmed reverse DNS with deduplicated, concurrency-limited cold lookups and a bounded cache.
|
|
17
18
|
- Atomic Redis token buckets across global, route, IP, provider and crawler-class budgets.
|
|
18
19
|
- Shared DB work slots, local concurrency limits, short-lived guard-owned request contexts and per-request operation bounds.
|
|
@@ -83,7 +84,7 @@ pnpm test:crawlers:service
|
|
|
83
84
|
|
|
84
85
|
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`.
|
|
85
86
|
|
|
86
|
-
Website availability: **Free, Pro and 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
|
|
87
|
+
Website availability: **Free, Pro and 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.
|
|
87
88
|
|
|
88
89
|
## Release CI coverage
|
|
89
90
|
|
|
@@ -288,7 +289,7 @@ Run unit/Redis tests, then the [isolated stack fixture](fixtures/README.md). It
|
|
|
288
289
|
|
|
289
290
|
Real Meta fetch/ad diagnostics, customer-specific AWS label configuration, production policy/telemetry delivery and customer budgets remain external rollout work. The temporary website lab is still the earlier public-document experiment; this stack milestone is not automatically enabled on valiron.co or another site.
|
|
290
291
|
|
|
291
|
-
Directory data attribution: Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev), CC-BY-4.0. Directory membership does not grant access. Run `node gateway/directory.cjs` to review candidates; mount selected approval hashes using `CRAWLER_DIRECTORY_APPROVALS_FILE`, then configure explicit site budgets.
|
|
292
|
+
Directory data attribution: Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev), CC-BY-4.0. Directory membership does not grant access. Bare IPs become host ranges; invalid/broad range sets disable only the affected entry. Feed-backed approval hashes survive address rotation; static ranges and changed identity metadata require review. Existing approval files need regenerated hashes after this update. Run `node gateway/directory.cjs` to review candidates; mount selected approval hashes using `CRAWLER_DIRECTORY_APPROVALS_FILE`, then configure explicit site budgets.
|
|
292
293
|
|
|
293
294
|
Monthly bot quotas require Crawler SDK 0.3.0 or later. Upgrade existing 0.2.x deployments to use Free accounts and hosted per-request quota admission. Earlier public SDK versions are not retroactively metered.
|
|
294
295
|
|
|
@@ -329,3 +330,95 @@ Trust boundaries, deliberately stricter than the draft minimum:
|
|
|
329
330
|
## Request usage
|
|
330
331
|
|
|
331
332
|
[Dashboard → Usage](https://www.valiron.co/dashboard/usage) shows account-wide monthly crawler requests, remaining allowance, additional calls and estimated request-overage charges. It refreshes every 15 seconds while visible. Free includes 10,000; Pro includes 100,000 and separately opted-in additional requests at 0.001 each in the accepted subscription currency. Middleware has a separate allowance and opt-in. Traffic charts come from optional runtime telemetry; billing counts come from hosted admission.
|
|
333
|
+
|
|
334
|
+
## Upgrade to 0.6.0
|
|
335
|
+
|
|
336
|
+
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.
|
|
337
|
+
|
|
338
|
+
## Dashboard controls
|
|
339
|
+
|
|
340
|
+
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.
|
|
341
|
+
|
|
342
|
+
### Connect a gateway
|
|
343
|
+
|
|
344
|
+
Keep the existing validated installation configuration, Redis and operator API key. Add these server-side variables and restart your gateway:
|
|
345
|
+
|
|
346
|
+
```dotenv
|
|
347
|
+
VALIRON_API_KEY=<your-server-side-operator-key>
|
|
348
|
+
CRAWLER_SITE_ID=storefront
|
|
349
|
+
CRAWLER_MANAGED_CONTROLS=true
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
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.
|
|
353
|
+
|
|
354
|
+
### Connect Node middleware
|
|
355
|
+
|
|
356
|
+
```ts
|
|
357
|
+
import { createCrawlerControlClient, createCrawlerRuntime } from '@valiron/crawler-protection';
|
|
358
|
+
|
|
359
|
+
const controls = createCrawlerControlClient({
|
|
360
|
+
configuration, // your validated deployment configuration
|
|
361
|
+
apiKey: process.env.VALIRON_API_KEY!,
|
|
362
|
+
site: process.env.CRAWLER_SITE_ID!,
|
|
363
|
+
});
|
|
364
|
+
await controls.refresh();
|
|
365
|
+
const stopControls = controls.start();
|
|
366
|
+
const runtime = createCrawlerRuntime({
|
|
367
|
+
configuration, redis, activation, clientIp, registry,
|
|
368
|
+
controlClient: controls,
|
|
369
|
+
});
|
|
370
|
+
// Mount runtime.nodeMiddleware/runtime.nuxtMiddleware before protected work.
|
|
371
|
+
// Keep your existing database/render admission wrappers and telemetry.
|
|
372
|
+
// On shutdown: stopControls(); telemetry.stop(); activation.stop();
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
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.
|
|
376
|
+
|
|
377
|
+
### Choose access and budgets
|
|
378
|
+
|
|
379
|
+
Open **Crawler Protection → Crawler controls**, select a registered site, edit and **Publish changes**:
|
|
380
|
+
|
|
381
|
+
- 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.
|
|
382
|
+
- 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.
|
|
383
|
+
- 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.
|
|
384
|
+
- **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.
|
|
385
|
+
|
|
386
|
+
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.
|
|
387
|
+
|
|
388
|
+
### Know whether a revision is active
|
|
389
|
+
|
|
390
|
+
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.
|
|
391
|
+
|
|
392
|
+
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.
|
|
393
|
+
|
|
394
|
+
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.
|
|
395
|
+
|
|
396
|
+
### Inspect recent decisions
|
|
397
|
+
|
|
398
|
+
**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.
|
|
399
|
+
|
|
400
|
+
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.
|
|
401
|
+
|
|
402
|
+
### Configure notifications
|
|
403
|
+
|
|
404
|
+
**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.
|
|
405
|
+
|
|
406
|
+
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.
|
|
407
|
+
|
|
408
|
+
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.
|
|
409
|
+
|
|
410
|
+
### Management endpoints
|
|
411
|
+
|
|
412
|
+
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.
|
|
413
|
+
|
|
414
|
+
Owner dashboard sessions authenticate:
|
|
415
|
+
|
|
416
|
+
- `GET /operator/crawlers/control`: registered sites, installed ceilings, desired settings and runtime acknowledgments.
|
|
417
|
+
- `POST /operator/crawlers/control/publish?site=...`: `{ expectedRevision, settings }` or `{ expectedRevision, rollbackRevision }`.
|
|
418
|
+
- `POST /operator/crawlers/control/adopt?site=...`: `{ expectedRevision, configuration }` for a planned installation replacement.
|
|
419
|
+
- `GET /operator/crawlers/control/history?site=...`: last 20 revisions.
|
|
420
|
+
- `GET /operator/crawlers/control/logs?site=...`: bounded recent decisions.
|
|
421
|
+
- `POST /operator/crawlers/control/alerts?site=...`: `{ expectedVersion, settings }` to configure destinations/triggers.
|
|
422
|
+
- `GET /operator/crawlers/control/deliveries?site=...`: recent delivery statuses.
|
|
423
|
+
|
|
424
|
+
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.
|
package/dist/configuration.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export type CrawlerConfiguration = Readonly<{
|
|
|
33
33
|
inventory: readonly RouteInventoryEntry[];
|
|
34
34
|
rollout: NonNullable<GuardPolicy['rollout']>;
|
|
35
35
|
crawlerAccess?: readonly CrawlerAccessRule[];
|
|
36
|
+
crawlerAccessDefault?: 'budget' | 'deny';
|
|
37
|
+
unverifiedAccess?: 'budget' | 'deny';
|
|
36
38
|
cache?: CatalogCacheSettings;
|
|
37
39
|
}>;
|
|
38
40
|
export type ResolvedRoute = {
|
|
@@ -50,5 +52,6 @@ export type CompiledCrawlerConfiguration = Readonly<{
|
|
|
50
52
|
fingerprint: string;
|
|
51
53
|
resolve: (request: Pick<IncomingMessage, 'method' | 'url'>) => ResolvedRoute;
|
|
52
54
|
}>;
|
|
55
|
+
export declare function assertCrawlerJsonData(input: unknown): void;
|
|
53
56
|
/** Strict JSON-compatible schema v1. Unknown fields, overlapping routes and missing groups reject. */
|
|
54
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,12 +93,12 @@ 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');
|
|
99
100
|
const c = JSON.parse(encoded);
|
|
100
|
-
object(c, ['schemaVersion', 'tenant', 'policy', 'inventory', 'rollout', 'crawlerAccess', 'cache'], 'configuration');
|
|
101
|
+
object(c, ['schemaVersion', 'tenant', 'policy', 'inventory', 'rollout', 'crawlerAccess', 'crawlerAccessDefault', 'unverifiedAccess', 'cache'], 'configuration');
|
|
101
102
|
if (c.schemaVersion !== 1 || typeof c.tenant !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(c.tenant))
|
|
102
103
|
throw new Error('Invalid configuration version or tenant');
|
|
103
104
|
object(c.policy, ['version', 'expiresAt', 'globalRate', 'unknownRate', 'perIpRate', 'providers', 'globalWorkLimit', 'unknownWorkLimit', 'providerWorkLimit', 'localWorkLimit', 'customers', 'maxOperationsPerRequest', 'maxContextAgeMs', 'routes'], 'policy');
|
|
@@ -171,6 +172,10 @@ function compileCrawlerConfiguration(input, now = Date.now()) {
|
|
|
171
172
|
}
|
|
172
173
|
if (Object.keys(policy.routes).some(group => !groups.has(group)))
|
|
173
174
|
throw new Error('Policy group missing from route inventory');
|
|
175
|
+
for (const key of ['crawlerAccessDefault', 'unverifiedAccess']) {
|
|
176
|
+
if (c[key] !== undefined && !['budget', 'deny'].includes(c[key]))
|
|
177
|
+
throw new Error('Invalid ' + key);
|
|
178
|
+
}
|
|
174
179
|
if (c.crawlerAccess !== undefined) {
|
|
175
180
|
if (!Array.isArray(c.crawlerAccess) || c.crawlerAccess.length > 128)
|
|
176
181
|
throw new Error('Invalid crawler access rules');
|
|
@@ -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
|
+
};
|
package/dist/controls.js
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateCrawlerControls = validateCrawlerControls;
|
|
4
|
+
exports.defaultCrawlerControls = defaultCrawlerControls;
|
|
5
|
+
exports.createCrawlerDecisionBuffer = createCrawlerDecisionBuffer;
|
|
6
|
+
exports.createCrawlerControlClient = createCrawlerControlClient;
|
|
7
|
+
const node_crypto_1 = require("node:crypto");
|
|
8
|
+
const configuration_1 = require("./configuration");
|
|
9
|
+
const label = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
10
|
+
function object(v, keys, name) {
|
|
11
|
+
if (!v ||
|
|
12
|
+
typeof v !== "object" ||
|
|
13
|
+
Array.isArray(v) ||
|
|
14
|
+
Object.keys(v).some((k) => !keys.includes(k)))
|
|
15
|
+
throw Error("Invalid " + name);
|
|
16
|
+
}
|
|
17
|
+
/** Dashboard controls cannot increase locally installed request ceilings or alter work pools. */
|
|
18
|
+
function validateCrawlerControls(raw, policy) {
|
|
19
|
+
(0, configuration_1.assertCrawlerJsonData)(raw);
|
|
20
|
+
const encoded = JSON.stringify(raw);
|
|
21
|
+
if (!encoded || Buffer.byteLength(encoded) > 32768)
|
|
22
|
+
throw Error("Controls too large");
|
|
23
|
+
const c = JSON.parse(encoded);
|
|
24
|
+
object(c, [
|
|
25
|
+
"mode",
|
|
26
|
+
"enforceGroups",
|
|
27
|
+
"defaultAction",
|
|
28
|
+
"unverifiedAction",
|
|
29
|
+
"rules",
|
|
30
|
+
"rates",
|
|
31
|
+
"logging",
|
|
32
|
+
], "controls");
|
|
33
|
+
if (!["observe", "enforce"].includes(c.mode) ||
|
|
34
|
+
!["budget", "deny"].includes(c.defaultAction) ||
|
|
35
|
+
!["budget", "deny"].includes(c.unverifiedAction) ||
|
|
36
|
+
typeof c.logging !== "boolean")
|
|
37
|
+
throw Error("Invalid control defaults");
|
|
38
|
+
if (c.enforceGroups !== undefined &&
|
|
39
|
+
(c.mode !== "enforce" ||
|
|
40
|
+
!Array.isArray(c.enforceGroups) ||
|
|
41
|
+
!c.enforceGroups.length ||
|
|
42
|
+
c.enforceGroups.length > 128 ||
|
|
43
|
+
new Set(c.enforceGroups).size !== c.enforceGroups.length ||
|
|
44
|
+
c.enforceGroups.some((g) => typeof g !== "string" || !Object.hasOwn(policy.routes, g))))
|
|
45
|
+
throw Error("Invalid enforcement groups");
|
|
46
|
+
if (!Array.isArray(c.rules) || c.rules.length > 128)
|
|
47
|
+
throw Error("Invalid crawler rules");
|
|
48
|
+
const seen = new Set();
|
|
49
|
+
for (const r of c.rules) {
|
|
50
|
+
object(r, ["provider", "crawlerClass", "groups", "action"], "rule");
|
|
51
|
+
if (typeof r.provider !== "string" ||
|
|
52
|
+
typeof r.crawlerClass !== "string" ||
|
|
53
|
+
!label.test(r.provider) ||
|
|
54
|
+
!label.test(r.crawlerClass) ||
|
|
55
|
+
(r.action !== "deny" &&
|
|
56
|
+
(!Object.hasOwn(policy.providers, r.provider) ||
|
|
57
|
+
!Object.hasOwn(policy.providers[r.provider].classes, r.crawlerClass))) ||
|
|
58
|
+
!["budget", "deny"].includes(r.action) ||
|
|
59
|
+
!Array.isArray(r.groups) ||
|
|
60
|
+
!r.groups.length ||
|
|
61
|
+
r.groups.length > 128 ||
|
|
62
|
+
new Set(r.groups).size !== r.groups.length)
|
|
63
|
+
throw Error("Unknown crawler or invalid rule");
|
|
64
|
+
for (const group of r.groups) {
|
|
65
|
+
if (typeof group !== "string" || !Object.hasOwn(policy.routes, group))
|
|
66
|
+
throw Error("Unknown route group");
|
|
67
|
+
const id = JSON.stringify([r.provider, r.crawlerClass, group]);
|
|
68
|
+
if (seen.has(id))
|
|
69
|
+
throw Error("Duplicate crawler rule");
|
|
70
|
+
seen.add(id);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
object(c.rates, ["global", "unknown", "perIp", "routes", "providers"], "rates");
|
|
74
|
+
const maxCost = Math.max(...Object.values(policy.routes).map((r) => r.cost));
|
|
75
|
+
const check = (r, ceiling, minimumCost = maxCost) => {
|
|
76
|
+
object(r, ["capacity", "refillPerSecond"], "rate");
|
|
77
|
+
if (!Number.isFinite(r.capacity) ||
|
|
78
|
+
r.capacity < minimumCost ||
|
|
79
|
+
!Number.isFinite(r.refillPerSecond) ||
|
|
80
|
+
r.refillPerSecond <= 0 ||
|
|
81
|
+
r.capacity > ceiling.capacity ||
|
|
82
|
+
r.refillPerSecond > ceiling.refillPerSecond ||
|
|
83
|
+
r.capacity / r.refillPerSecond > 86400)
|
|
84
|
+
throw Error("Rate exceeds installed ceiling or is invalid");
|
|
85
|
+
};
|
|
86
|
+
for (const [key, ceiling] of Object.entries({
|
|
87
|
+
global: policy.globalRate,
|
|
88
|
+
unknown: policy.unknownRate,
|
|
89
|
+
perIp: policy.perIpRate,
|
|
90
|
+
}))
|
|
91
|
+
if (c.rates[key] !== undefined)
|
|
92
|
+
check(c.rates[key], ceiling);
|
|
93
|
+
for (const key of ["routes", "providers"])
|
|
94
|
+
if (c.rates[key] !== undefined) {
|
|
95
|
+
const allowed = key === "routes" ? policy.routes : policy.providers;
|
|
96
|
+
object(c.rates[key], Object.keys(allowed), key);
|
|
97
|
+
for (const [id, r] of Object.entries(c.rates[key])) {
|
|
98
|
+
if (!label.test(id))
|
|
99
|
+
throw Error("Invalid rate identity");
|
|
100
|
+
check(r, allowed[id].rate, key === "routes" ? policy.routes[id].cost : maxCost);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
function freeze(v) {
|
|
104
|
+
if (v && typeof v === "object") {
|
|
105
|
+
Object.values(v).forEach(freeze);
|
|
106
|
+
Object.freeze(v);
|
|
107
|
+
}
|
|
108
|
+
return v;
|
|
109
|
+
}
|
|
110
|
+
return freeze(c);
|
|
111
|
+
}
|
|
112
|
+
function defaultCrawlerControls(configuration) {
|
|
113
|
+
return validateCrawlerControls({
|
|
114
|
+
mode: configuration.rollout?.mode ?? "observe",
|
|
115
|
+
...(configuration.rollout?.mode === "enforce" &&
|
|
116
|
+
configuration.rollout.enforceGroups &&
|
|
117
|
+
configuration.rollout.enforceGroups.length <
|
|
118
|
+
Object.keys(configuration.policy.routes).length
|
|
119
|
+
? { enforceGroups: configuration.rollout.enforceGroups }
|
|
120
|
+
: {}),
|
|
121
|
+
defaultAction: configuration.crawlerAccessDefault ?? "budget",
|
|
122
|
+
unverifiedAction: configuration.unverifiedAccess ?? "budget",
|
|
123
|
+
rules: configuration.crawlerAccess ?? [],
|
|
124
|
+
rates: {},
|
|
125
|
+
logging: false,
|
|
126
|
+
}, configuration.policy);
|
|
127
|
+
}
|
|
128
|
+
/** Separate opt-in bounded log buffer; never retains IP, URL, user agent or caller request IDs. */
|
|
129
|
+
function createCrawlerDecisionBuffer(policy, enabled, now = Date.now) {
|
|
130
|
+
const rows = [];
|
|
131
|
+
let dropped = 0;
|
|
132
|
+
return {
|
|
133
|
+
record(decision, evidence, details) {
|
|
134
|
+
if (!enabled() ||
|
|
135
|
+
!details?.routeGroup ||
|
|
136
|
+
!Object.hasOwn(policy.routes, details.routeGroup))
|
|
137
|
+
return;
|
|
138
|
+
const provider = evidence?.state === "verified" &&
|
|
139
|
+
evidence.provider &&
|
|
140
|
+
Object.hasOwn(policy.providers, evidence.provider)
|
|
141
|
+
? evidence.provider
|
|
142
|
+
: "other";
|
|
143
|
+
const crawlerClass = provider !== "other" &&
|
|
144
|
+
evidence?.crawlerClass &&
|
|
145
|
+
Object.hasOwn(policy.providers[provider].classes, evidence.crawlerClass)
|
|
146
|
+
? evidence.crawlerClass
|
|
147
|
+
: "other";
|
|
148
|
+
if (rows.length >= 1000) {
|
|
149
|
+
dropped++;
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
rows.push({
|
|
153
|
+
id: (0, node_crypto_1.randomUUID)(),
|
|
154
|
+
at: now(),
|
|
155
|
+
group: details.routeGroup,
|
|
156
|
+
provider,
|
|
157
|
+
crawlerClass,
|
|
158
|
+
action: ["allow", "block", "limit", "unavailable"].includes(decision.action)
|
|
159
|
+
? decision.action
|
|
160
|
+
: "unavailable",
|
|
161
|
+
reason: [
|
|
162
|
+
"within_budget",
|
|
163
|
+
"observation_within_safety",
|
|
164
|
+
"crawler_policy_denied",
|
|
165
|
+
"safety_budget_exhausted",
|
|
166
|
+
"rate_budget_exhausted",
|
|
167
|
+
"admission_unavailable",
|
|
168
|
+
].includes(decision.reason)
|
|
169
|
+
? decision.reason
|
|
170
|
+
: "other",
|
|
171
|
+
verification: evidence &&
|
|
172
|
+
[
|
|
173
|
+
"verified",
|
|
174
|
+
"unverified",
|
|
175
|
+
"claim_mismatch",
|
|
176
|
+
"verification_unavailable",
|
|
177
|
+
].includes(evidence.state)
|
|
178
|
+
? evidence.state
|
|
179
|
+
: "verification_unavailable",
|
|
180
|
+
mode: details.mode === "observe" ? "observe" : "enforce",
|
|
181
|
+
});
|
|
182
|
+
},
|
|
183
|
+
batch() {
|
|
184
|
+
return rows.slice(0, 100);
|
|
185
|
+
},
|
|
186
|
+
ack(ids) {
|
|
187
|
+
const set = new Set(ids);
|
|
188
|
+
for (let i = rows.length - 1; i >= 0; i--)
|
|
189
|
+
if (set.has(rows[i].id))
|
|
190
|
+
rows.splice(i, 1);
|
|
191
|
+
},
|
|
192
|
+
clear() {
|
|
193
|
+
rows.length = 0;
|
|
194
|
+
},
|
|
195
|
+
dropped() {
|
|
196
|
+
return dropped;
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/** Memory-only short lease. Dashboard sessions alone publish; requests use cached controls. */
|
|
201
|
+
function createCrawlerControlClient(input) {
|
|
202
|
+
const compiled = (0, configuration_1.compileCrawlerConfiguration)(input.configuration, (input.now ?? Date.now)());
|
|
203
|
+
if (!/^val_op_[a-zA-Z0-9_-]{1,200}$/.test(input.apiKey) ||
|
|
204
|
+
!label.test(input.site))
|
|
205
|
+
throw Error("Invalid control identity");
|
|
206
|
+
const url = new URL(input.endpoint ??
|
|
207
|
+
"https://valiron-edge-proxy.onrender.com/operator/crawlers/control/runtime");
|
|
208
|
+
if ((url.protocol !== "https:" &&
|
|
209
|
+
!(url.protocol === "http:" &&
|
|
210
|
+
["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) ||
|
|
211
|
+
url.pathname !== "/operator/crawlers/control/runtime" ||
|
|
212
|
+
url.username ||
|
|
213
|
+
url.password ||
|
|
214
|
+
url.search ||
|
|
215
|
+
url.hash)
|
|
216
|
+
throw Error("Invalid control endpoint");
|
|
217
|
+
const instance = (0, node_crypto_1.randomUUID)();
|
|
218
|
+
let lastMode = compiled.configuration.rollout.mode;
|
|
219
|
+
let value, revision = 0, expiresAt = 0, deadline = 0, busy = false, stopped = false, error;
|
|
220
|
+
const now = input.now ?? Date.now;
|
|
221
|
+
const logs = createCrawlerDecisionBuffer(compiled.policy, () => active() && !!value?.logging, now);
|
|
222
|
+
const active = () => !!value && expiresAt > now() && deadline > performance.now() && !stopped;
|
|
223
|
+
async function refresh() {
|
|
224
|
+
if (busy || stopped)
|
|
225
|
+
return;
|
|
226
|
+
busy = true;
|
|
227
|
+
const sent = performance.now();
|
|
228
|
+
const batch = logs.batch();
|
|
229
|
+
try {
|
|
230
|
+
const response = await (input.fetch ?? fetch)(url, {
|
|
231
|
+
method: "POST",
|
|
232
|
+
headers: {
|
|
233
|
+
Authorization: "Bearer " + input.apiKey,
|
|
234
|
+
"Content-Type": "application/json",
|
|
235
|
+
},
|
|
236
|
+
body: JSON.stringify({
|
|
237
|
+
site: input.site,
|
|
238
|
+
instance,
|
|
239
|
+
configuration: compiled.configuration,
|
|
240
|
+
configurationId: compiled.fingerprint,
|
|
241
|
+
revision: active() ? revision : 0,
|
|
242
|
+
logs: batch,
|
|
243
|
+
dropped: logs.dropped(),
|
|
244
|
+
}),
|
|
245
|
+
redirect: "error",
|
|
246
|
+
signal: AbortSignal.timeout(5000),
|
|
247
|
+
});
|
|
248
|
+
if (!response.ok) {
|
|
249
|
+
if ([401, 403, 404, 409].includes(response.status)) {
|
|
250
|
+
value = undefined;
|
|
251
|
+
expiresAt = 0;
|
|
252
|
+
}
|
|
253
|
+
await response.body?.cancel();
|
|
254
|
+
throw Error();
|
|
255
|
+
}
|
|
256
|
+
const reader = response.body?.getReader();
|
|
257
|
+
if (!reader)
|
|
258
|
+
throw Error();
|
|
259
|
+
let size = 0;
|
|
260
|
+
const chunks = [];
|
|
261
|
+
try {
|
|
262
|
+
for (;;) {
|
|
263
|
+
const part = await reader.read();
|
|
264
|
+
if (part.done)
|
|
265
|
+
break;
|
|
266
|
+
size += part.value.length;
|
|
267
|
+
if (size > 65536)
|
|
268
|
+
throw Error();
|
|
269
|
+
chunks.push(part.value);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
finally {
|
|
273
|
+
await reader.cancel().catch(() => { });
|
|
274
|
+
reader.releaseLock();
|
|
275
|
+
}
|
|
276
|
+
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
277
|
+
object(body, ["revision", "configurationId", "expiresAt", "settings"], "control response");
|
|
278
|
+
if (body.configurationId !== compiled.fingerprint ||
|
|
279
|
+
!Number.isSafeInteger(body.revision) ||
|
|
280
|
+
body.revision < revision ||
|
|
281
|
+
body.revision < 1 ||
|
|
282
|
+
!Number.isSafeInteger(body.expiresAt) ||
|
|
283
|
+
body.expiresAt <= now() ||
|
|
284
|
+
body.expiresAt > now() + 300000)
|
|
285
|
+
throw Error();
|
|
286
|
+
const checked = validateCrawlerControls(body.settings, compiled.policy);
|
|
287
|
+
if (value &&
|
|
288
|
+
body.revision === revision &&
|
|
289
|
+
JSON.stringify(checked) !== JSON.stringify(value))
|
|
290
|
+
throw Error();
|
|
291
|
+
if (stopped)
|
|
292
|
+
return;
|
|
293
|
+
value = checked;
|
|
294
|
+
lastMode = checked.mode;
|
|
295
|
+
revision = body.revision;
|
|
296
|
+
expiresAt = body.expiresAt;
|
|
297
|
+
deadline = sent + Math.min(300000, expiresAt - now());
|
|
298
|
+
error = undefined;
|
|
299
|
+
logs.ack(batch.map((row) => row.id));
|
|
300
|
+
if (!checked.logging)
|
|
301
|
+
logs.clear();
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
error = value ? "rejected" : "unavailable";
|
|
305
|
+
}
|
|
306
|
+
finally {
|
|
307
|
+
busy = false;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
configurationId: compiled.fingerprint,
|
|
312
|
+
refresh,
|
|
313
|
+
record: logs.record,
|
|
314
|
+
current() {
|
|
315
|
+
if (!active())
|
|
316
|
+
throw Error("Crawler controls unavailable");
|
|
317
|
+
return value;
|
|
318
|
+
},
|
|
319
|
+
status() {
|
|
320
|
+
return {
|
|
321
|
+
revision,
|
|
322
|
+
mode: lastMode,
|
|
323
|
+
active: active(),
|
|
324
|
+
...(error ? { error } : {}),
|
|
325
|
+
};
|
|
326
|
+
},
|
|
327
|
+
start() {
|
|
328
|
+
const timer = setInterval(() => void refresh(), 30000);
|
|
329
|
+
timer.unref();
|
|
330
|
+
if (!value)
|
|
331
|
+
void refresh();
|
|
332
|
+
return () => {
|
|
333
|
+
stopped = true;
|
|
334
|
+
logs.clear();
|
|
335
|
+
clearInterval(timer);
|
|
336
|
+
};
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
}
|
package/dist/directory.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export type DirectoryReview = Readonly<{
|
|
|
14
14
|
cidrCount: number;
|
|
15
15
|
eligible: boolean;
|
|
16
16
|
approved: boolean;
|
|
17
|
+
rangeError?: string;
|
|
17
18
|
}>;
|
|
18
19
|
/** An external catalog is discovery data. CIDR identity requires a locally reviewed metadata hash. */
|
|
19
20
|
export declare class CrawlerDirectory {
|
package/dist/directory.js
CHANGED
|
@@ -73,29 +73,38 @@ class CrawlerDirectory {
|
|
|
73
73
|
throw Error('Directory CIDR limit');
|
|
74
74
|
// Keep official integrations authoritative; webhooks are outside crawler admission.
|
|
75
75
|
const tokens = [...new Set(bot.user_agents.patterns.map(token).filter((t) => Boolean(t) && !['mozilla', 'applewebkit', 'chrome', 'safari', 'compatible', 'bot', 'crawler'].includes(t)))];
|
|
76
|
-
if (!tokens.length || bot.category === 'webhook' || tokens.
|
|
76
|
+
if (!tokens.length || bot.category === 'webhook' || tokens.every(t => (0, verification_1.crawlerClaim)(t + '/1.0') || /^(facebook|meta-)/.test(t)))
|
|
77
77
|
continue;
|
|
78
78
|
const docs = Array.isArray(bot.docs) ? bot.docs.filter(httpsUrl) : [];
|
|
79
79
|
const operatorUrl = httpsUrl(bot.operator?.url) ? bot.operator.url : '';
|
|
80
|
-
|
|
80
|
+
// Bare addresses denote single hosts, never an implicit subnet.
|
|
81
|
+
const cidrs = bot.resolved_cidrs.map((range) => range.includes('/') ? range :
|
|
82
|
+
range + (range.includes(':') ? '/128' : '/32'));
|
|
81
83
|
const hasCidrEvidence = [1, 2].includes(bot.tier) && Boolean(operatorUrl && docs.length) &&
|
|
82
84
|
bot.verification.some((v) => v?.type === 'cidr_feed' && httpsUrl(v.url) || v?.type === 'static_cidrs' && Array.isArray(v.cidrs));
|
|
83
85
|
const approval = (0, node_crypto_1.createHash)('sha256').update(JSON.stringify({ id: bot.id, operatorUrl, docs, category: bot.category,
|
|
84
|
-
patterns: bot.user_agents.patterns, verification: bot.verification, tier: bot.tier,
|
|
85
|
-
|
|
86
|
-
|
|
86
|
+
patterns: bot.user_agents.patterns, verification: bot.verification, tier: bot.tier,
|
|
87
|
+
...(bot.verification.some((v) => v?.type === 'static_cidrs') ? { resolved_cidrs: [...cidrs].sort() } : {}) })).digest('hex');
|
|
88
|
+
const entry = { id: bot.id, name: bot.name, operatorUrl, docs, category: bot.category, tokens: tokens.filter(t => !(0, verification_1.crawlerClaim)(t + '/1.0') && !/^(facebook|meta-)/.test(t)), approval, cidrs, hasCidrEvidence };
|
|
87
89
|
if (hasCidrEvidence && cidrs.length) {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
90
|
+
try {
|
|
91
|
+
for (const range of cidrs) {
|
|
92
|
+
const [ip, bits] = range.split('/');
|
|
93
|
+
const normalized = (0, ip_1.normalizeIp)(ip);
|
|
94
|
+
if ((normalized.includes(':') && Number(bits) < 32) || (!normalized.includes(':') && (ip.includes(':') || Number(bits) < 8)))
|
|
95
|
+
throw Error('Overbroad directory CIDR');
|
|
96
|
+
}
|
|
97
|
+
const matcher = (0, ip_1.cidrMatcher)(cidrs);
|
|
98
|
+
if (this.approvals[bot.id] === approval)
|
|
99
|
+
matchers.set(bot.id, matcher);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// Reject this identity's entire range set, without disabling unrelated identities.
|
|
103
|
+
entry.hasCidrEvidence = false;
|
|
104
|
+
entry.rangeError = 'invalid_or_overbroad_ranges';
|
|
94
105
|
}
|
|
95
|
-
const matcher = (0, ip_1.cidrMatcher)(cidrs);
|
|
96
|
-
if (this.approvals[bot.id] === approval)
|
|
97
|
-
matchers.set(bot.id, matcher);
|
|
98
106
|
}
|
|
107
|
+
entries.push(entry);
|
|
99
108
|
}
|
|
100
109
|
// Commit only after every accepted entry has passed validation; failures preserve original expiry.
|
|
101
110
|
this.entries = entries;
|
|
@@ -107,7 +116,7 @@ class CrawlerDirectory {
|
|
|
107
116
|
review() {
|
|
108
117
|
return this.entries.map(e => ({ id: e.id, name: e.name, provider: 'directory-' + e.id, crawlerClass: e.id,
|
|
109
118
|
operatorUrl: e.operatorUrl, docs: [...e.docs], category: e.category, tokens: [...e.tokens], approval: e.approval,
|
|
110
|
-
cidrCount: e.cidrs.length, eligible: e.hasCidrEvidence && e.cidrs.length > 0, approved: this.matchers.has(e.id) && this.expiresAt > this.now() }));
|
|
119
|
+
cidrCount: e.cidrs.length, eligible: e.hasCidrEvidence && e.cidrs.length > 0, approved: this.matchers.has(e.id) && this.expiresAt > this.now(), ...(e.rangeError ? { rangeError: e.rangeError } : {}) }));
|
|
111
120
|
}
|
|
112
121
|
classify(ip, ua) {
|
|
113
122
|
if (ua.length > 2048)
|
package/dist/guard.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CrawlerControls } from './controls';
|
|
1
2
|
import { InternalAdmission, type InternalTarget } from './internal';
|
|
2
3
|
import { type CrawlerActivation } from './activation';
|
|
3
4
|
import { BingVerifier, CrawlerRegistry, type CrawlerEvidence } from './verification';
|
|
@@ -91,6 +92,8 @@ export declare class CrawlerGuard {
|
|
|
91
92
|
wires in here so signed crawlers outside the approved lists get a verification
|
|
92
93
|
path without taking precedence over established source verification. */
|
|
93
94
|
fallbackEvidence?: (request: unknown, ip: string, userAgent: string) => CrawlerEvidence | undefined;
|
|
95
|
+
controls?: () => CrawlerControls;
|
|
96
|
+
unverifiedAccess?: 'budget' | 'deny';
|
|
94
97
|
crawlerAccess?: (evidence: CrawlerEvidence, routeGroup: string) => 'budget' | 'deny';
|
|
95
98
|
onDecision?: (decision: Readonly<Decision>, evidence?: CrawlerEvidence, details?: DecisionDetails) => void;
|
|
96
99
|
});
|
package/dist/guard.js
CHANGED
|
@@ -82,6 +82,8 @@ class CrawlerGuard {
|
|
|
82
82
|
operations = new WeakMap();
|
|
83
83
|
constructor(config) {
|
|
84
84
|
this.config = config;
|
|
85
|
+
if (config.unverifiedAccess !== undefined && !['budget', 'deny'].includes(config.unverifiedAccess))
|
|
86
|
+
throw new Error('Invalid unverifiedAccess');
|
|
85
87
|
(0, activation_1.validateActivation)(config.activation);
|
|
86
88
|
this.policy = structuredClone(config.policy);
|
|
87
89
|
validateGuardPolicy(this.policy);
|
|
@@ -116,10 +118,14 @@ class CrawlerGuard {
|
|
|
116
118
|
throw new Error('Invalid customer grant');
|
|
117
119
|
if (customer?.lane === 'checkout' && this.policy.routes[input.routeGroup].customerLane !== 'checkout')
|
|
118
120
|
customer = { ...customer, lane: 'shopper' };
|
|
121
|
+
const controls = customer ? undefined : this.config.controls?.();
|
|
119
122
|
const lane = customer?.lane ?? 'catalog';
|
|
120
123
|
const rollout = this.policy.rollout;
|
|
121
|
-
const
|
|
124
|
+
const originalMode = customer || !rollout || (rollout.mode === 'enforce' && rollout.enforceGroups.includes(input.routeGroup)) ? 'enforce' : 'observe';
|
|
125
|
+
const mode = customer ? 'enforce' : controls ? (controls.mode === 'enforce' && (!controls.enforceGroups || controls.enforceGroups.includes(input.routeGroup)) ? 'enforce' : 'observe') : originalMode;
|
|
122
126
|
details = { routeGroup: input.routeGroup, lane, mode };
|
|
127
|
+
const rates = controls?.rates;
|
|
128
|
+
const minimum = (a, b) => ({ capacity: Math.min(a.capacity, b?.capacity ?? a.capacity), refillPerSecond: Math.min(a.refillPerSecond, b?.refillPerSecond ?? a.refillPerSecond) });
|
|
123
129
|
const classified = this.config.registry.classify(ip, input.userAgent);
|
|
124
130
|
evidence = this.config.trustedEvidence?.(input.request, ip, input.userAgent) ?? (classified.claimedCrawler === 'bingbot' && (0, verification_1.crawlerClaim)(input.userAgent)?.provider === 'bing'
|
|
125
131
|
? this.config.bing.classify(ip) : classified);
|
|
@@ -132,20 +138,26 @@ class CrawlerGuard {
|
|
|
132
138
|
// Known source without an explicit allowance gets the conservative policy.
|
|
133
139
|
const privileged = Boolean(provider && crawlerRate);
|
|
134
140
|
const bucket = (key, rate) => ({ key, ...rate, cost: input.cost });
|
|
135
|
-
const buckets = [bucket('global', this.policy.globalRate), bucket('ip:' + (0, admission_1.keyPart)(ip), this.policy.perIpRate)];
|
|
141
|
+
const buckets = [bucket('global', minimum(this.policy.globalRate, rates?.global)), bucket('ip:' + (0, admission_1.keyPart)(ip), minimum(this.policy.perIpRate, rates?.perIp))];
|
|
136
142
|
if (customer) {
|
|
137
143
|
buckets.splice(0, buckets.length, bucket('customer:' + lane, lane === 'checkout' ? this.policy.customers.checkoutRate : this.policy.customers.shopperRate), bucket('customer-principal:' + lane + ':' + (0, admission_1.keyPart)(customer.principal), this.policy.perIpRate));
|
|
138
144
|
}
|
|
139
|
-
buckets.push(bucket((customer ? lane + ':' : '') + 'route:' + input.routeGroup, this.policy.routes[input.routeGroup].rate));
|
|
145
|
+
buckets.push(bucket((customer ? lane + ':' : '') + 'route:' + input.routeGroup, minimum(this.policy.routes[input.routeGroup].rate, rates?.routes?.[input.routeGroup])));
|
|
140
146
|
if (!customer) {
|
|
141
147
|
if (privileged) {
|
|
142
|
-
buckets.push(bucket('provider:' + evidence.provider, provider.rate));
|
|
148
|
+
buckets.push(bucket('provider:' + evidence.provider, minimum(provider.rate, rates?.providers?.[evidence.provider])));
|
|
143
149
|
buckets.push(bucket('crawler:' + evidence.provider + ':' + evidence.crawlerClass, crawlerRate));
|
|
144
150
|
}
|
|
145
|
-
else
|
|
146
|
-
|
|
151
|
+
else {
|
|
152
|
+
let unknown = minimum(this.policy.unknownRate, rates?.unknown);
|
|
153
|
+
for (const rate of Object.values(rates?.providers ?? {}))
|
|
154
|
+
unknown = minimum(unknown, rate);
|
|
155
|
+
buckets.push(bucket('unknown', unknown));
|
|
156
|
+
}
|
|
147
157
|
}
|
|
148
|
-
const denied = !customer &&
|
|
158
|
+
const denied = !customer && (verified
|
|
159
|
+
? (controls ? controls.rules.find(r => r.provider === evidence.provider && r.crawlerClass === evidence.crawlerClass && r.groups.includes(input.routeGroup))?.action ?? controls.defaultAction : this.config.crawlerAccess?.(evidence, input.routeGroup)) === 'deny'
|
|
160
|
+
: (controls?.unverifiedAction ?? this.config.unverifiedAccess) === 'deny');
|
|
149
161
|
if (denied && mode === 'enforce') {
|
|
150
162
|
decision = { ...base, action: 'block', reason: 'crawler_policy_denied' };
|
|
151
163
|
this.emit(decision, evidence, { ...details, proposedAction: 'block' });
|
package/dist/index.d.ts
CHANGED
|
@@ -18,3 +18,4 @@ export * from './webbotauth';
|
|
|
18
18
|
export { CrawlerMonthlyLimitError, createCrawlerActivation, activateCrawlerProtection, CRAWLER_ACTIVATION_ENDPOINT, type CrawlerActivation } from './activation';
|
|
19
19
|
export { DeviceIdentity, MemoryIdentityStore, RedisIdentityStore, createNodeDeviceIdentityMiddleware, deviceIdentityCollectorScript, serializeCookieClear, DEVICE_IDENTITY_DEFAULT_BASE_PATH, } from './device-identity';
|
|
20
20
|
export type { DeviceIdentityOptions, DeviceIdentityMiddlewareConfig, Recognition, RecognitionState, RecognizeResult, IdentityStore, StoredProfile, RawSignals, ScreenSignals, CookieOptions, VerifiedCookie, } from './device-identity';
|
|
21
|
+
export * from './controls';
|
package/dist/index.js
CHANGED
|
@@ -48,3 +48,4 @@ Object.defineProperty(exports, "createNodeDeviceIdentityMiddleware", { enumerabl
|
|
|
48
48
|
Object.defineProperty(exports, "deviceIdentityCollectorScript", { enumerable: true, get: function () { return device_identity_1.deviceIdentityCollectorScript; } });
|
|
49
49
|
Object.defineProperty(exports, "serializeCookieClear", { enumerable: true, get: function () { return device_identity_1.serializeCookieClear; } });
|
|
50
50
|
Object.defineProperty(exports, "DEVICE_IDENTITY_DEFAULT_BASE_PATH", { enumerable: true, get: function () { return device_identity_1.DEVICE_IDENTITY_DEFAULT_BASE_PATH; } });
|
|
51
|
+
__exportStar(require("./controls"), exports);
|
package/dist/onboarding.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export declare function planCrawlerRollout(configuration: unknown, baseline?: Ca
|
|
|
19
19
|
enforceGroups: readonly string[];
|
|
20
20
|
inventory: {
|
|
21
21
|
id: string;
|
|
22
|
-
kind: "
|
|
22
|
+
kind: "protected" | "bypass";
|
|
23
23
|
methods: readonly string[];
|
|
24
24
|
path: string;
|
|
25
25
|
}[];
|
|
@@ -51,6 +51,8 @@ export declare function createEcommerceConfiguration(input: {
|
|
|
51
51
|
rollout: CrawlerConfiguration['rollout'];
|
|
52
52
|
cache?: CrawlerConfiguration['cache'];
|
|
53
53
|
crawlerAccess?: CrawlerConfiguration['crawlerAccess'];
|
|
54
|
+
crawlerAccessDefault?: CrawlerConfiguration['crawlerAccessDefault'];
|
|
55
|
+
unverifiedAccess?: CrawlerConfiguration['unverifiedAccess'];
|
|
54
56
|
}, now?: number): CrawlerConfiguration;
|
|
55
57
|
/** @deprecated Use createEcommerceConfiguration. Retained for existing integrations. */
|
|
56
58
|
export declare const createEcommercePilotConfiguration: typeof createEcommerceConfiguration;
|
package/dist/onboarding.js
CHANGED
|
@@ -49,7 +49,9 @@ function createEcommerceConfiguration(input, now = Date.now()) {
|
|
|
49
49
|
{ id: 'catalog-detail', kind: 'protected', path: input.paths.detail, methods: ['GET', 'HEAD'], group: input.groups.detail },
|
|
50
50
|
{ id: 'checkout', kind: 'protected', path: input.paths.checkout, methods: ['GET', 'HEAD', 'POST'], group: input.groups.checkout },
|
|
51
51
|
...(input.paths.bypass ?? []).map(r => ({ ...r, kind: 'bypass' })),
|
|
52
|
-
], ...(input.cache ? { cache: input.cache } : {}), ...(input.crawlerAccess ? { crawlerAccess: input.crawlerAccess } : {})
|
|
52
|
+
], ...(input.cache ? { cache: input.cache } : {}), ...(input.crawlerAccess ? { crawlerAccess: input.crawlerAccess } : {}),
|
|
53
|
+
...(input.crawlerAccessDefault ? { crawlerAccessDefault: input.crawlerAccessDefault } : {}),
|
|
54
|
+
...(input.unverifiedAccess ? { unverifiedAccess: input.unverifiedAccess } : {}) };
|
|
53
55
|
if (input.policy.routes[input.groups.checkout]?.customerLane !== 'checkout')
|
|
54
56
|
throw new Error('Checkout group needs explicit customerLane');
|
|
55
57
|
if (input.groups.listing === input.groups.checkout || input.groups.detail === input.groups.checkout)
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { createCrawlerControlClient } from './controls';
|
|
1
2
|
import type { IncomingMessage } from 'node:http';
|
|
2
3
|
import { CrawlerGuard, type RequestContext } from './guard';
|
|
3
4
|
import { ManagedRedisAdmission } from './operations';
|
|
@@ -17,6 +18,7 @@ export declare function createCrawlerRuntime(input: {
|
|
|
17
18
|
bing?: BingVerifier;
|
|
18
19
|
customer?: GuardDependencies['customer'];
|
|
19
20
|
trustedEvidence?: GuardDependencies['trustedEvidence'];
|
|
21
|
+
controlClient?: ReturnType<typeof createCrawlerControlClient>;
|
|
20
22
|
onDecision?: GuardDependencies['onDecision'];
|
|
21
23
|
now?: () => number;
|
|
22
24
|
timeoutMs?: number;
|
|
@@ -41,6 +43,33 @@ export declare function createCrawlerRuntime(input: {
|
|
|
41
43
|
expiresAt?: number;
|
|
42
44
|
}>;
|
|
43
45
|
}>;
|
|
46
|
+
controlClient: {
|
|
47
|
+
configurationId: string;
|
|
48
|
+
refresh: () => Promise<void>;
|
|
49
|
+
record: (decision: import("./admission").Decision, evidence?: import("./verification").CrawlerEvidence, details?: import("./guard").DecisionDetails) => void;
|
|
50
|
+
current(): Readonly<{
|
|
51
|
+
mode: "observe" | "enforce";
|
|
52
|
+
enforceGroups?: readonly string[];
|
|
53
|
+
defaultAction: "budget" | "deny";
|
|
54
|
+
unverifiedAction: "budget" | "deny";
|
|
55
|
+
rules: readonly import("./configuration").CrawlerAccessRule[];
|
|
56
|
+
rates: Readonly<{
|
|
57
|
+
global?: import("./controls").ControlRate;
|
|
58
|
+
unknown?: import("./controls").ControlRate;
|
|
59
|
+
perIp?: import("./controls").ControlRate;
|
|
60
|
+
routes?: Readonly<Record<string, import("./controls").ControlRate>>;
|
|
61
|
+
providers?: Readonly<Record<string, import("./controls").ControlRate>>;
|
|
62
|
+
}>;
|
|
63
|
+
logging: boolean;
|
|
64
|
+
}>;
|
|
65
|
+
status(): {
|
|
66
|
+
error?: "unavailable" | "rejected" | undefined;
|
|
67
|
+
revision: number;
|
|
68
|
+
mode: "observe" | "enforce";
|
|
69
|
+
active: boolean;
|
|
70
|
+
};
|
|
71
|
+
start(): () => void;
|
|
72
|
+
} | undefined;
|
|
44
73
|
nodeMiddleware: (request: import("./adapters").GuardedRequest, response: import("http").ServerResponse, next: (error?: unknown) => void) => void;
|
|
45
74
|
nuxtMiddleware: (event: {
|
|
46
75
|
node: {
|
package/dist/runtime.js
CHANGED
|
@@ -14,14 +14,19 @@ const activation_1 = require("./activation");
|
|
|
14
14
|
function createCrawlerRuntime(input) {
|
|
15
15
|
const compiled = (0, configuration_1.compileCrawlerConfiguration)(input.configuration, (input.now ?? Date.now)());
|
|
16
16
|
(0, activation_1.validateActivation)(input.activation, compiled.configuration.tenant);
|
|
17
|
+
if (input.controlClient && input.controlClient.configurationId !== compiled.fingerprint)
|
|
18
|
+
throw Error('Crawler control configuration mismatch');
|
|
17
19
|
const store = new operations_1.ManagedRedisAdmission(input.redis, compiled.configuration.tenant, compiled.policy, input.timeoutMs);
|
|
18
20
|
const report = new reporting_1.CrawlerReport(compiled.policy, 1024, compiled.configuration.crawlerAccess);
|
|
19
21
|
const access = compiled.configuration.crawlerAccess ?? [];
|
|
20
22
|
const guard = new guard_1.CrawlerGuard({ activation: input.activation, policy: compiled.policy, store, registry: input.registry ?? new verification_1.CrawlerRegistry(), bing: input.bing ?? new verification_1.BingVerifier(),
|
|
23
|
+
controls: input.controlClient?.current,
|
|
24
|
+
unverifiedAccess: compiled.configuration.unverifiedAccess,
|
|
21
25
|
customer: input.customer, trustedEvidence: input.trustedEvidence, now: input.now,
|
|
22
|
-
crawlerAccess: (e, group) => access.find(rule => rule.provider === e.provider && rule.crawlerClass === e.crawlerClass && rule.groups.includes(group))?.action ?? 'budget',
|
|
26
|
+
crawlerAccess: (e, group) => access.find(rule => rule.provider === e.provider && rule.crawlerClass === e.crawlerClass && rule.groups.includes(group))?.action ?? compiled.configuration.crawlerAccessDefault ?? 'budget',
|
|
23
27
|
onDecision: (decision, evidence, details) => {
|
|
24
28
|
report.decision(decision, evidence, details);
|
|
29
|
+
input.controlClient?.record(decision, evidence, details);
|
|
25
30
|
return input.onDecision?.(decision, evidence, details);
|
|
26
31
|
},
|
|
27
32
|
});
|
|
@@ -47,7 +52,7 @@ function createCrawlerRuntime(input) {
|
|
|
47
52
|
throw error;
|
|
48
53
|
}
|
|
49
54
|
}
|
|
50
|
-
return Object.freeze({ compiled, store, guard, report, activation: input.activation,
|
|
55
|
+
return Object.freeze({ compiled, store, guard, report, activation: input.activation, controlClient: input.controlClient,
|
|
51
56
|
nodeMiddleware: (0, adapters_1.createNodeCrawlerMiddleware)(adapter), nuxtMiddleware: (0, adapters_1.createNuxtCrawlerMiddleware)(adapter),
|
|
52
57
|
withDatabaseAdmission: (context, operation) => work('database', context, operation),
|
|
53
58
|
withRenderingAdmission: (context, operation) => work('render', context, operation),
|
package/dist/telemetry.js
CHANGED
|
@@ -33,8 +33,10 @@ function createCrawlerTelemetry(input) {
|
|
|
33
33
|
}
|
|
34
34
|
catch { /* Report unavailable capacity without changing admission. */ }
|
|
35
35
|
const snapshot = runtime.report.snapshot();
|
|
36
|
+
const control = runtime.controlClient?.status();
|
|
36
37
|
const body = JSON.stringify({ site: input.site, instance, sequence: ++sequence, tenant: runtime.compiled.configuration.tenant,
|
|
37
|
-
configurationId: runtime.compiled.fingerprint, mode: runtime.compiled.configuration.rollout.mode,
|
|
38
|
+
configurationId: runtime.compiled.fingerprint, mode: control?.mode ?? runtime.compiled.configuration.rollout.mode,
|
|
39
|
+
...(control ? { control: { revision: control.revision, active: control.active } } : {}),
|
|
38
40
|
overflow: snapshot.overflow + snapshot.series.slice(256).reduce((n, s) => n + s.count, 0),
|
|
39
41
|
series: snapshot.series.slice(0, 256).map(({ tags, count, durationMs }) => ({ tags, count, durationMs })), capacity });
|
|
40
42
|
if (Buffer.byteLength(body) > 262144)
|
package/dist/verification.d.ts
CHANGED
|
@@ -47,6 +47,26 @@ export declare const CRAWLER_FEEDS: Readonly<{
|
|
|
47
47
|
provider: "openai";
|
|
48
48
|
url: "https://openai.com/chatgpt-user.json";
|
|
49
49
|
}>;
|
|
50
|
+
claudebot: Readonly<{
|
|
51
|
+
provider: "anthropic";
|
|
52
|
+
url: "https://claude.com/crawling/bots.json";
|
|
53
|
+
}>;
|
|
54
|
+
'claude-searchbot': Readonly<{
|
|
55
|
+
provider: "anthropic";
|
|
56
|
+
url: "https://claude.com/crawling/bots.json";
|
|
57
|
+
}>;
|
|
58
|
+
'claude-user': Readonly<{
|
|
59
|
+
provider: "anthropic";
|
|
60
|
+
url: "https://claude.com/crawling/bots.json";
|
|
61
|
+
}>;
|
|
62
|
+
'google-agent': Readonly<{
|
|
63
|
+
provider: "google";
|
|
64
|
+
url: "https://developers.google.com/static/crawling/ipranges/user-triggered-agents.json";
|
|
65
|
+
}>;
|
|
66
|
+
'gemini-notebook': Readonly<{
|
|
67
|
+
provider: "google";
|
|
68
|
+
url: "https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers-google.json";
|
|
69
|
+
}>;
|
|
50
70
|
googlebot: Readonly<{
|
|
51
71
|
provider: "google";
|
|
52
72
|
url: "https://developers.google.com/static/crawling/ipranges/common-crawlers.json";
|
package/dist/verification.js
CHANGED
|
@@ -12,6 +12,11 @@ const claims = [
|
|
|
12
12
|
[/\bOAI-SearchBot\//i, { provider: 'openai', crawlerClass: 'oai-searchbot' }],
|
|
13
13
|
[/\bGPTBot\//i, { provider: 'openai', crawlerClass: 'gptbot' }],
|
|
14
14
|
[/\bChatGPT-User\//i, { provider: 'openai', crawlerClass: 'chatgpt-user' }],
|
|
15
|
+
[/\bClaudeBot\//i, { provider: 'anthropic', crawlerClass: 'claudebot' }],
|
|
16
|
+
[/\bClaude-SearchBot\//i, { provider: 'anthropic', crawlerClass: 'claude-searchbot' }],
|
|
17
|
+
[/\bClaude-User\//i, { provider: 'anthropic', crawlerClass: 'claude-user' }],
|
|
18
|
+
[/\bGoogle-Agent(?=[\s;)/]|$)/i, { provider: 'google', crawlerClass: 'google-agent' }],
|
|
19
|
+
[/\b(?:Google-GeminiNotebook|Google-NotebookLM)(?=[\s;)/]|$)/i, { provider: 'google', crawlerClass: 'gemini-notebook' }],
|
|
15
20
|
[/\bGooglebot\//i, { provider: 'google', crawlerClass: 'googlebot' }],
|
|
16
21
|
[/\bAdsBot-Google(?:-Mobile)?(?=[\s;)/]|$)/i, { provider: 'google', crawlerClass: 'adsbot-google' }],
|
|
17
22
|
[/\bApplebot\//i, { provider: 'apple', crawlerClass: 'applebot' }],
|
|
@@ -70,6 +75,11 @@ exports.CRAWLER_FEEDS = Object.freeze({
|
|
|
70
75
|
'oai-searchbot': Object.freeze({ provider: 'openai', url: 'https://openai.com/searchbot.json' }),
|
|
71
76
|
gptbot: Object.freeze({ provider: 'openai', url: 'https://openai.com/gptbot.json' }),
|
|
72
77
|
'chatgpt-user': Object.freeze({ provider: 'openai', url: 'https://openai.com/chatgpt-user.json' }),
|
|
78
|
+
claudebot: Object.freeze({ provider: 'anthropic', url: 'https://claude.com/crawling/bots.json' }),
|
|
79
|
+
'claude-searchbot': Object.freeze({ provider: 'anthropic', url: 'https://claude.com/crawling/bots.json' }),
|
|
80
|
+
'claude-user': Object.freeze({ provider: 'anthropic', url: 'https://claude.com/crawling/bots.json' }),
|
|
81
|
+
'google-agent': Object.freeze({ provider: 'google', url: 'https://developers.google.com/static/crawling/ipranges/user-triggered-agents.json' }),
|
|
82
|
+
'gemini-notebook': Object.freeze({ provider: 'google', url: 'https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers-google.json' }),
|
|
73
83
|
googlebot: Object.freeze({ provider: 'google', url: 'https://developers.google.com/static/crawling/ipranges/common-crawlers.json' }),
|
|
74
84
|
'adsbot-google': Object.freeze({ provider: 'google', url: 'https://developers.google.com/static/crawling/ipranges/special-crawlers.json' }),
|
|
75
85
|
applebot: Object.freeze({ provider: 'apple', url: 'https://search.developer.apple.com/applebot.json' }),
|
package/gateway/README.md
CHANGED
|
@@ -62,7 +62,7 @@ Lock down the origin: allow the gateway's network identity and check `X-Valiron-
|
|
|
62
62
|
|
|
63
63
|
Policy control remains explicit. Use the private `gateway/admin.cjs` with the same configuration to inspect, initialize, pause, activate and resume. Initialization requires a new/drained namespace, `--confirmed-drained` and an evidence file (`CRAWLER_EVIDENCE_FILE`). Initialization creates paused state; resume separately. After crashes/timeouts, pause, stop affected origin/DB work, inspect exact orphan hold IDs and reconcile only those IDs with fresh drain evidence. Services never automatically reset holds, initialize policy or resume on startup. See [decisions and recovery](https://www.valiron.co/docs/crawler-protection/operations) for recovery steps.
|
|
64
64
|
|
|
65
|
-
The
|
|
65
|
+
The fourteen OpenAI, Anthropic, Google crawler/agent/Notebook, Applebot, DuckDuckBot and Perplexity class snapshots refresh in the background with at most three simultaneous fetches; Bing uses bounded forward-confirmed reverse DNS. Missing/expired evidence remains conservative. Ordinary visitors are not classified as human from cookies or user-agent. Reserved customer lanes need a real server-validated grant through the runtime customer hook; the default standalone command does not elevate arbitrary cookies to shopper status.
|
|
66
66
|
|
|
67
67
|
## Private language-neutral work protocol
|
|
68
68
|
|
|
@@ -99,7 +99,7 @@ For asynchronous drivers, acquire explicitly and release after confirmed query c
|
|
|
99
99
|
Hosted platforms must let you route traffic through this gateway and restrict the origin to it. A platform that prevents those controls needs a platform integration; universal routing cannot be imposed by an SDK. CDN cache hits that never reach the gateway remain outside its origin counters. Existing authorization, WAF, connection pools, query timeouts and background-job safeguards remain necessary.
|
|
100
100
|
|
|
101
101
|
|
|
102
|
-
Optional hosted telemetry: set `CRAWLER_TELEMETRY_URL` to `https://valiron-edge-proxy.onrender.com/operator/crawlers/telemetry`, `CRAWLER_TELEMETRY_API_KEY` to a server-side
|
|
102
|
+
Optional hosted telemetry: set `CRAWLER_TELEMETRY_URL` to `https://valiron-edge-proxy.onrender.com/operator/crawlers/telemetry`, `CRAWLER_TELEMETRY_API_KEY` to a server-side operator API key for the account (Free, Pro or Enterprise), and `CRAWLER_SITE_ID` to a stable site label. Use the account tenant from the validated configuration export. Every gateway process gets a new random reporting instance ID. Initial samples establish a counter baseline; subsequent background uploads power rolling 24-hour dashboard analytics, shared capacity and monitoring alerts. Admission continues independently when telemetry is unavailable. Keep keys out of browser code and uploaded configuration. See the public Crawler Protection guide for retention, missing-data semantics and bounds.
|
|
103
103
|
|
|
104
104
|
## Additional crawler directory
|
|
105
105
|
|
|
@@ -108,3 +108,13 @@ The gateway refreshes the independent Verified Bots Directory at `https://verifi
|
|
|
108
108
|
Identity metadata changes invalidate approval. Unapproved, unsupported, stale or unverifiable entries retain conservative limits; even approved CIDR identities need explicit customer budgets. Remote regex, feed URLs, DNS and signature recipes are never executed. Directory evidence is labeled `directory_cidr` and is distinct from official feeds. Download failures log `crawler_directory_unavailable`. Data expires within one hour and at most 48 hours after catalog generation. See the public crawler guide for validation bounds and in-process setup.
|
|
109
109
|
|
|
110
110
|
Attribution: Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev), CC-BY-4.0.
|
|
111
|
+
|
|
112
|
+
## Selected AI services
|
|
113
|
+
|
|
114
|
+
The gateway refreshes official OpenAI, Anthropic and Google agent/fetcher feeds in the background. Configure explicit `crawlerAccess` allowances and set `crawlerAccessDefault` to `deny` to reject other verified crawlers on protected groups. Each allowance still needs matching provider/class budgets. Optional `unverifiedAccess: "deny"` also rejects anonymous humans, spoofed claims and unavailable verifications; retain `"budget"` for ordinary anonymous storefront traffic unless an independent customer-grant integration is in place. Existing configurations keep their previous behavior.
|
|
115
|
+
|
|
116
|
+
See the [complete configuration fragment and provider boundaries](https://valiron.co/docs/agents/CRAWLER-PROTECTION.md#allow-selected-ai-services). Google-agent verification does not identify every Gemini interaction. Claude-Agent browser access requires its separately reviewed directory identity; static address changes require review against Anthropic’s official publication. Regenerate directory approval hashes when upgrading to this behavior.
|
|
117
|
+
|
|
118
|
+
## Managed dashboard controls (0.7.0+)
|
|
119
|
+
|
|
120
|
+
After deploying the management backend and migration, set `CRAWLER_MANAGED_CONTROLS=true` and a stable `CRAWLER_SITE_ID` in gateway.env. Keep `VALIRON_API_KEY` server-side. The gateway registers its validated installation, polls controls every 30 seconds and acknowledges applied revisions. The dashboard can publish access rules and tighter request budgets within installed ceilings, view bounded opt-in decisions and configure optional alerts. Match the telemetry site ID. Control leases expire within five minutes; catalog traffic fails closed when no valid lease remains. This does not initialize Redis, raise work limits or replace deployment/recovery. See [Dashboard controls](https://www.valiron.co/docs/crawler-protection/controls).
|
package/gateway/service.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const { readFile } = require('node:fs/promises');
|
|
2
2
|
const Redis = require('ioredis');
|
|
3
|
-
const { createCrawlerRuntime, createCrawlerTelemetry, createCrawlerGateway, createCrawlerWorkServer, InternalAdmission, normalizeIp,
|
|
3
|
+
const { createCrawlerRuntime, createCrawlerControlClient, createCrawlerTelemetry, createCrawlerGateway, createCrawlerWorkServer, InternalAdmission, normalizeIp,
|
|
4
4
|
createCrawlerActivation, createCloudFrontClientIpResolver, createAwsWafMetaEvidence, refreshCrawlerFeeds, CrawlerRegistry, CrawlerDirectory, refreshCrawlerDirectory } = require('../dist');
|
|
5
5
|
|
|
6
6
|
function required(name) {
|
|
@@ -35,11 +35,12 @@ async function load() {
|
|
|
35
35
|
endpoint: process.env.VALIRON_CRAWLER_ACTIVATION_URL,
|
|
36
36
|
onError: () => console.error(JSON.stringify({ event: 'crawler_activation_unavailable' })),
|
|
37
37
|
});
|
|
38
|
-
const
|
|
39
|
-
|
|
38
|
+
const controlClient = process.env.CRAWLER_MANAGED_CONTROLS === 'true' ? createCrawlerControlClient({ configuration, apiKey: required('VALIRON_API_KEY'), site: required('CRAWLER_SITE_ID') }) : undefined;
|
|
39
|
+
const runtime = createCrawlerRuntime({ controlClient, activation, configuration, redis, clientIp, registry, trustedEvidence, timeoutMs: 1500 });
|
|
40
|
+
return { runtime, redis, clientIp, registry, directory, controlClient };
|
|
40
41
|
}
|
|
41
42
|
async function main() {
|
|
42
|
-
const { runtime, redis, clientIp, registry, directory } = await load();
|
|
43
|
+
const { runtime, redis, clientIp, registry, directory, controlClient } = await load();
|
|
43
44
|
const originSecret = required('CRAWLER_ORIGIN_SECRET');
|
|
44
45
|
const apiSecret = required('CRAWLER_WORK_SECRET');
|
|
45
46
|
const signingSecret = required('CRAWLER_SIGNING_SECRET');
|
|
@@ -60,6 +61,8 @@ async function main() {
|
|
|
60
61
|
const work = createCrawlerWorkServer({ runtime, channel, apiSecret });
|
|
61
62
|
if (process.argv.includes('--check')) { console.log(JSON.stringify({ valid: true, configurationId: runtime.compiled.fingerprint })); redis.disconnect(); return; }
|
|
62
63
|
await runtime.activation.start();
|
|
64
|
+
await controlClient?.refresh();
|
|
65
|
+
const stopControls = controlClient?.start();
|
|
63
66
|
await redis.connect();
|
|
64
67
|
// Never initialize/resume from a service startup: recovery remains an explicit operator action.
|
|
65
68
|
const listen = (server, port, host) => new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
|
|
@@ -87,6 +90,7 @@ async function main() {
|
|
|
87
90
|
const shutdown = () => {
|
|
88
91
|
runtime.activation.stop();
|
|
89
92
|
telemetry?.stop();
|
|
93
|
+
stopControls?.();
|
|
90
94
|
clearInterval(interval);
|
|
91
95
|
gateway.close(() => { work.close(() => redis.disconnect()); });
|
|
92
96
|
setTimeout(() => process.exit(1), 30000).unref();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@valiron/crawler-protection",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.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",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
"files": [
|
|
14
14
|
"dist",
|
|
15
15
|
"README.md",
|
|
16
|
+
"CHANGELOG.md",
|
|
16
17
|
"public/collector.js",
|
|
17
18
|
"gateway/service.cjs",
|
|
18
19
|
"gateway/admin.cjs",
|
|
@@ -58,5 +59,3 @@
|
|
|
58
59
|
"registry": "https://registry.npmjs.org/"
|
|
59
60
|
}
|
|
60
61
|
}
|
|
61
|
-
|
|
62
|
-
|