@valiron/crawler-protection 0.4.0 → 0.6.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 ADDED
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@valiron/crawler-protection` are documented here. The project uses semantic versioning.
4
+
5
+ ## 0.6.0 (2026-11-12)
6
+
7
+ - Added official feed verification for Anthropic’s `ClaudeBot`, `Claude-SearchBot`, `Claude-User`, Google-Agent and Gemini Notebook, keeping training/search/user-fetch policies separate.
8
+ - 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.
9
+ - 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.
10
+ - Added regression coverage for provider spoofing, feed expiry, address rotation, access defaults, observation reporting and real Redis enforcement.
11
+
12
+ ## 0.5.0 (2026-11-10)
13
+
14
+ - 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.
15
+ - Browser middleware maps quota exhaustion to 429 and unavailable activation/admission to 503.
16
+ - 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.
17
+
18
+ ## 0.4.0 (2026-11-09)
19
+
20
+ ### Added
21
+
22
+ - **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.
23
+ - **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.
24
+
25
+ ### Fixed
26
+
27
+ - `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`.
28
+
29
+ ### Notes
30
+
31
+ - 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
+
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.
@@ -30,12 +31,14 @@ The package also includes returning-browser recognition, folded in from the form
30
31
 
31
32
  Recognition is **evidence, not a verdict**: no risk score, no block decision, no enforcement hook. `similar` means "this browser resembles one we have seen" - shared devices, corporate fleets and fresh installs all produce false links, so a `similar` link is never sufficient grounds to deny or limit service.
32
33
 
33
- Mount the middleware to expose the endpoints, then call the browser collector to begin recognition:
34
+ With SDK 0.5.0 or later, mount the middleware to expose the endpoints, then call the browser collector to begin recognition:
34
35
 
35
36
  ```ts
36
- import { DeviceIdentity, RedisIdentityStore, createNodeDeviceIdentityMiddleware } from '@valiron/crawler-protection';
37
+ import { activateCrawlerProtection, DeviceIdentity, RedisIdentityStore, createNodeDeviceIdentityMiddleware } from '@valiron/crawler-protection';
37
38
 
39
+ const activation = await activateCrawlerProtection({ apiKey: process.env.VALIRON_API_KEY!, tenant: process.env.VALIRON_TENANT! });
38
40
  const identity = new DeviceIdentity({
41
+ activation,
39
42
  salt: process.env.DEVICE_IDENTITY_SALT!, // per-deployment, 16+ chars, from a secret manager
40
43
  cookie: {
41
44
  name: '__Host-vid',
@@ -63,7 +66,7 @@ Privacy properties enforced in code:
63
66
  - The cookie carries only a random id and an HMAC - no device data.
64
67
  - `identity.forget(visitorId)` deletes a profile and its index entries (data-subject deletion hook).
65
68
 
66
- Every default here - 30-day retention, the 8/11.5 similarity threshold, the 180-day example cookie lifetime, optional privacy-signal handling - is a placeholder so the module runs, **not an approved production policy**. Before production rollout, the deployment must explicitly decide: consent flow per jurisdiction (a first-party identification cookie is not strictly necessary for most sites), DNT/GPC behavior, retention, similarity-threshold tuning against real traffic, what may consume `similar` links (recommend observe-only analytics first; the link graph is attacker-influenceable, though links and matched ids never leave the server), and cookie lifetime/rotation. Account metering/gating for this module is likewise a follow-up decision; activation is not currently required to use it.
69
+ Every default here - 30-day retention, the 8/11.5 similarity threshold, the 180-day example cookie lifetime, optional privacy-signal handling - is a placeholder so the module runs, **not an approved production policy**. Before production rollout, the deployment must explicitly decide: consent flow per jurisdiction (a first-party identification cookie is not strictly necessary for most sites), DNT/GPC behavior, retention, similarity-threshold tuning against real traffic, what may consume `similar` links (recommend observe-only analytics first; the link graph is attacker-influenceable, though links and matched ids never leave the server), and cookie lifetime/rotation. SDK 0.5.0 requires account-bound activation for this module. Each `recognize()` call consumes one bot-quota admission before identity storage. Missing/revoked/expired activation and unavailable quota checks stop recognition; its middleware returns 429 for quota exhaustion and 503 for unavailable admission. Exclude the recognition endpoint from outer request admission if it would otherwise admit that same HTTP request twice. Previous public releases cannot be retroactively restricted.
67
70
 
68
71
  ## Account activation and monthly usage
69
72
 
@@ -286,11 +289,11 @@ Run unit/Redis tests, then the [isolated stack fixture](fixtures/README.md). It
286
289
 
287
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.
288
291
 
289
- 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.
290
293
 
291
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.
292
295
 
293
- Free includes 10,000 protected HTTP requests per UTC calendar month; Pro ($149/month) includes 100,000. The bot allowance is independent from agent access and shared across an account's API keys, sites and replicas. Local access/rate denials run before hosted quota admission and do not consume the allowance. Once hosted admission succeeds, the request is counted even if a later work-capacity check fails. Quota exhaustion returns HTTP 429; an unavailable usage check fails closed with 503. This adds a hosted round trip before protected origin work. Enterprise: email founders@valiron.co.
296
+ Free includes 10,000 protected HTTP requests per UTC calendar month; Pro ($149/month) includes 100,000. The bot allowance is independent from agent access and shared across an account's API keys, sites and replicas. Local access/rate denials run before hosted quota admission and do not consume the allowance. Once hosted admission succeeds, the request is counted even if a later work-capacity check fails. Quota exhaustion returns HTTP 429; an unavailable usage check fails closed with 503. This adds a hosted round trip before protected origin work. Pro can enable additional crawler calls at 0.001 each in the subscription billing currency after explicit price acceptance; Free remains capped at 10,000. Unconfigured or inactive usage billing retains the 100,000 Pro cap. Enterprise: email founders@valiron.co.
294
297
 
295
298
  ## Security compatibility and admission recovery
296
299
 
@@ -323,3 +326,11 @@ Trust boundaries, deliberately stricter than the draft minimum:
323
326
  - 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.
324
327
  - 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.
325
328
 
329
+
330
+ ## Request usage
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.
@@ -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 = {
@@ -97,7 +97,7 @@ function compileCrawlerConfiguration(input, now = Date.now()) {
97
97
  if (!encoded || Buffer.byteLength(encoded) > 262144)
98
98
  throw new Error('Configuration too large');
99
99
  const c = JSON.parse(encoded);
100
- object(c, ['schemaVersion', 'tenant', 'policy', 'inventory', 'rollout', 'crawlerAccess', 'cache'], 'configuration');
100
+ object(c, ['schemaVersion', 'tenant', 'policy', 'inventory', 'rollout', 'crawlerAccess', 'crawlerAccessDefault', 'unverifiedAccess', 'cache'], 'configuration');
101
101
  if (c.schemaVersion !== 1 || typeof c.tenant !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(c.tenant))
102
102
  throw new Error('Invalid configuration version or tenant');
103
103
  object(c.policy, ['version', 'expiresAt', 'globalRate', 'unknownRate', 'perIpRate', 'providers', 'globalWorkLimit', 'unknownWorkLimit', 'providerWorkLimit', 'localWorkLimit', 'customers', 'maxOperationsPerRequest', 'maxContextAgeMs', 'routes'], 'policy');
@@ -171,6 +171,10 @@ function compileCrawlerConfiguration(input, now = Date.now()) {
171
171
  }
172
172
  if (Object.keys(policy.routes).some(group => !groups.has(group)))
173
173
  throw new Error('Policy group missing from route inventory');
174
+ for (const key of ['crawlerAccessDefault', 'unverifiedAccess']) {
175
+ if (c[key] !== undefined && !['budget', 'deny'].includes(c[key]))
176
+ throw new Error('Invalid ' + key);
177
+ }
174
178
  if (c.crawlerAccess !== undefined) {
175
179
  if (!Array.isArray(c.crawlerAccess) || c.crawlerAccess.length > 128)
176
180
  throw new Error('Invalid crawler access rules');
@@ -1,18 +1,4 @@
1
- /**
2
- * Valiron Device Identity.
3
- *
4
- * Recognizes a returning browser from two independent signal classes:
5
- * 1. deterministic - the server-signed first-party visitor cookie
6
- * 2. probabilistic - coarsened device signals, compared per component
7
- *
8
- * The output is identification evidence, nothing more. This package has no
9
- * notion of fraud, risk, or enforcement. A 'similar' result means "this
10
- * browser resembles a browser we have seen"; it does not establish the
11
- * same person (shared devices, managed fleets, fresh installs all break
12
- * that inference), and it is never sufficient grounds to deny service.
13
- * Abuse decisions belong to the policy layer (crawler protection, the
14
- * identity gate), which may consume this evidence alongside its own.
15
- */
1
+ import { type CrawlerActivation } from "../activation";
16
2
  import { type CookieOptions } from './cookie';
17
3
  import { type RawSignals } from './signals';
18
4
  import { type IdentityStore } from './store';
@@ -44,6 +30,8 @@ export type RecognizeResult = Readonly<{
44
30
  setCookie: string;
45
31
  }>;
46
32
  export type DeviceIdentityOptions = Readonly<{
33
+ /** Account-bound activation from the server-side operator API key. */
34
+ activation: CrawlerActivation;
47
35
  /** Per-deployment salt for component hashes. Required; never shared across deployments. */
48
36
  salt: string;
49
37
  /** Bump when rotating the salt. Old profiles stop matching similarity lookups after rotation. */
@@ -1,4 +1,7 @@
1
1
  "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DeviceIdentity = exports.COMPONENT_WEIGHTS = void 0;
4
+ const activation_1 = require("../activation");
2
5
  /**
3
6
  * Valiron Device Identity.
4
7
  *
@@ -14,8 +17,6 @@
14
17
  * Abuse decisions belong to the policy layer (crawler protection, the
15
18
  * identity gate), which may consume this evidence alongside its own.
16
19
  */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.DeviceIdentity = exports.COMPONENT_WEIGHTS = void 0;
19
20
  const node_crypto_1 = require("node:crypto");
20
21
  const cookie_1 = require("./cookie");
21
22
  const signals_1 = require("./signals");
@@ -45,6 +46,8 @@ class DeviceIdentity {
45
46
  hardMismatch;
46
47
  constructor(options) {
47
48
  this.options = options;
49
+ (0, activation_1.validateActivation)(options.activation);
50
+ (0, activation_1.assertActivation)(options.activation);
48
51
  if (typeof options.salt !== 'string' || options.salt.length < 16 || options.salt.length > 256) {
49
52
  throw new Error('Invalid identity salt');
50
53
  }
@@ -118,6 +121,8 @@ class DeviceIdentity {
118
121
  * continuity belongs only to the browser that actually holds the cookie.
119
122
  */
120
123
  async recognize(input) {
124
+ (0, activation_1.assertActivation)(this.options.activation);
125
+ await this.options.activation.consume();
121
126
  const now = this.now();
122
127
  const signals = (0, signals_1.normalizeSignals)(input.signals ?? {});
123
128
  const verified = (0, cookie_1.verifyVisitorCookie)(this.options.cookie, input.cookieHeader, now);
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = void 0;
4
4
  exports.deviceIdentityCollectorScript = deviceIdentityCollectorScript;
5
5
  exports.createNodeDeviceIdentityMiddleware = createNodeDeviceIdentityMiddleware;
6
+ const activation_1 = require("../activation");
6
7
  const collector_script_1 = require("./collector-script");
7
8
  exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = '/api/valiron/device-identity';
8
9
  let collectorCache;
@@ -102,7 +103,9 @@ function createNodeDeviceIdentityMiddleware(config) {
102
103
  // evidence would let a caller mimicking another browser's signals
103
104
  // harvest that browser's identity.
104
105
  sendJson(response, 200, { state: recognition.state }, { 'Set-Cookie': setCookie });
105
- })().catch(next);
106
+ })().catch((error) => {
107
+ sendJson(response, error instanceof activation_1.CrawlerMonthlyLimitError ? 429 : 503, { error: error instanceof activation_1.CrawlerMonthlyLimitError ? "monthly_request_limit_exceeded" : "recognition_unavailable" });
108
+ });
106
109
  return;
107
110
  }
108
111
  next();
@@ -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.some(t => (0, verification_1.crawlerClaim)(t + '/1.0') || /^(facebook|meta-)/.test(t)))
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
- const cidrs = bot.resolved_cidrs;
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, resolved_cidrs: [...cidrs].sort() })).digest('hex');
85
- const entry = { id: bot.id, name: bot.name, operatorUrl, docs, category: bot.category, tokens, approval, cidrs, hasCidrEvidence };
86
- entries.push(entry);
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
- // Reject broad network claims, including IPv4-mapped IPv6. The strict matcher validates syntax too.
89
- for (const range of cidrs) {
90
- const [ip, bits] = range.split('/');
91
- const normalized = (0, ip_1.normalizeIp)(ip);
92
- if ((normalized.includes(':') && Number(bits) < 32) || (!normalized.includes(':') && (ip.includes(':') || Number(bits) < 8)))
93
- throw Error('Overbroad directory CIDR');
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
@@ -91,6 +91,7 @@ export declare class CrawlerGuard {
91
91
  wires in here so signed crawlers outside the approved lists get a verification
92
92
  path without taking precedence over established source verification. */
93
93
  fallbackEvidence?: (request: unknown, ip: string, userAgent: string) => CrawlerEvidence | undefined;
94
+ unverifiedAccess?: 'budget' | 'deny';
94
95
  crawlerAccess?: (evidence: CrawlerEvidence, routeGroup: string) => 'budget' | 'deny';
95
96
  onDecision?: (decision: Readonly<Decision>, evidence?: CrawlerEvidence, details?: DecisionDetails) => void;
96
97
  });
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);
@@ -145,7 +147,9 @@ class CrawlerGuard {
145
147
  else
146
148
  buckets.push(bucket('unknown', this.policy.unknownRate));
147
149
  }
148
- const denied = !customer && evidence.state === 'verified' && this.config.crawlerAccess?.(evidence, input.routeGroup) === 'deny';
150
+ const denied = !customer && (verified
151
+ ? this.config.crawlerAccess?.(evidence, input.routeGroup) === 'deny'
152
+ : this.config.unverifiedAccess === 'deny');
149
153
  if (denied && mode === 'enforce') {
150
154
  decision = { ...base, action: 'block', reason: 'crawler_policy_denied' };
151
155
  this.emit(decision, evidence, { ...details, proposedAction: 'block' });
package/dist/index.d.ts CHANGED
@@ -15,6 +15,6 @@ export * from './gateway';
15
15
  export * from './telemetry';
16
16
  export * from './directory';
17
17
  export * from './webbotauth';
18
- export { createCrawlerActivation, activateCrawlerProtection, CRAWLER_ACTIVATION_ENDPOINT, type CrawlerActivation } from './activation';
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';
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = exports.serializeCookieClear = exports.deviceIdentityCollectorScript = exports.createNodeDeviceIdentityMiddleware = exports.RedisIdentityStore = exports.MemoryIdentityStore = exports.DeviceIdentity = exports.CRAWLER_ACTIVATION_ENDPOINT = exports.activateCrawlerProtection = exports.createCrawlerActivation = void 0;
17
+ exports.DEVICE_IDENTITY_DEFAULT_BASE_PATH = exports.serializeCookieClear = exports.deviceIdentityCollectorScript = exports.createNodeDeviceIdentityMiddleware = exports.RedisIdentityStore = exports.MemoryIdentityStore = exports.DeviceIdentity = exports.CRAWLER_ACTIVATION_ENDPOINT = exports.activateCrawlerProtection = exports.createCrawlerActivation = exports.CrawlerMonthlyLimitError = void 0;
18
18
  __exportStar(require("./ip"), exports);
19
19
  __exportStar(require("./verification"), exports);
20
20
  __exportStar(require("./admission"), exports);
@@ -33,6 +33,7 @@ __exportStar(require("./telemetry"), exports);
33
33
  __exportStar(require("./directory"), exports);
34
34
  __exportStar(require("./webbotauth"), exports);
35
35
  var activation_1 = require("./activation");
36
+ Object.defineProperty(exports, "CrawlerMonthlyLimitError", { enumerable: true, get: function () { return activation_1.CrawlerMonthlyLimitError; } });
36
37
  Object.defineProperty(exports, "createCrawlerActivation", { enumerable: true, get: function () { return activation_1.createCrawlerActivation; } });
37
38
  Object.defineProperty(exports, "activateCrawlerProtection", { enumerable: true, get: function () { return activation_1.activateCrawlerProtection; } });
38
39
  Object.defineProperty(exports, "CRAWLER_ACTIVATION_ENDPOINT", { enumerable: true, get: function () { return activation_1.CRAWLER_ACTIVATION_ENDPOINT; } });
@@ -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;
@@ -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.js CHANGED
@@ -18,8 +18,9 @@ function createCrawlerRuntime(input) {
18
18
  const report = new reporting_1.CrawlerReport(compiled.policy, 1024, compiled.configuration.crawlerAccess);
19
19
  const access = compiled.configuration.crawlerAccess ?? [];
20
20
  const guard = new guard_1.CrawlerGuard({ activation: input.activation, policy: compiled.policy, store, registry: input.registry ?? new verification_1.CrawlerRegistry(), bing: input.bing ?? new verification_1.BingVerifier(),
21
+ unverifiedAccess: compiled.configuration.unverifiedAccess,
21
22
  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',
23
+ crawlerAccess: (e, group) => access.find(rule => rule.provider === e.provider && rule.crawlerClass === e.crawlerClass && rule.groups.includes(group))?.action ?? compiled.configuration.crawlerAccessDefault ?? 'budget',
23
24
  onDecision: (decision, evidence, details) => {
24
25
  report.decision(decision, evidence, details);
25
26
  return input.onDecision?.(decision, evidence, details);
@@ -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";
@@ -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 nine OpenAI, Googlebot/AdsBot, Applebot, DuckDuckBot and Perplexity feed 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.
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 Pro operator API key, 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.
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,9 @@ 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@valiron/crawler-protection",
3
- "version": "0.4.0",
3
+ "version": "0.6.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
-