@valiron/crawler-protection 0.6.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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
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
+
3
12
  All notable changes to `@valiron/crawler-protection` are documented here. The project uses semantic versioning.
4
13
 
5
14
  ## 0.6.0 (2026-11-12)
package/README.md CHANGED
@@ -84,7 +84,7 @@ pnpm test:crawlers:service
84
84
 
85
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`.
86
86
 
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 policies. See the public integration guide for telemetry setup, retention and measurement limits.
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.
88
88
 
89
89
  ## Release CI coverage
90
90
 
@@ -334,3 +334,91 @@ Trust boundaries, deliberately stricter than the draft minimum:
334
334
  ## Upgrade to 0.6.0
335
335
 
336
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.
@@ -52,5 +52,6 @@ export type CompiledCrawlerConfiguration = Readonly<{
52
52
  fingerprint: string;
53
53
  resolve: (request: Pick<IncomingMessage, 'method' | 'url'>) => ResolvedRoute;
54
54
  }>;
55
+ export declare function assertCrawlerJsonData(input: unknown): void;
55
56
  /** Strict JSON-compatible schema v1. Unknown fields, overlapping routes and missing groups reject. */
56
57
  export declare function compileCrawlerConfiguration(input: unknown, now?: number): CompiledCrawlerConfiguration;
@@ -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 jsonData(input) {
17
+ function assertCrawlerJsonData(input) {
17
18
  let count = 0;
18
19
  const visiting = new Set();
19
20
  function visit(value, depth) {
@@ -92,7 +93,7 @@ function matches(pattern, path) {
92
93
  /** Strict JSON-compatible schema v1. Unknown fields, overlapping routes and missing groups reject. */
93
94
  function compileCrawlerConfiguration(input, now = Date.now()) {
94
95
  // Reject non-JSON fields rather than silently dropping callbacks/undefined during serialization.
95
- jsonData(input);
96
+ assertCrawlerJsonData(input);
96
97
  const encoded = JSON.stringify(input);
97
98
  if (!encoded || Buffer.byteLength(encoded) > 262144)
98
99
  throw new Error('Configuration too large');
@@ -0,0 +1,90 @@
1
+ import type { Decision } from "./admission";
2
+ import type { CrawlerEvidence } from "./verification";
3
+ import type { DecisionDetails } from "./guard";
4
+ import type { GuardPolicy } from "./guard";
5
+ import type { CrawlerAccessRule } from "./configuration";
6
+ export type ControlRate = Readonly<{
7
+ capacity: number;
8
+ refillPerSecond: number;
9
+ }>;
10
+ export type CrawlerControls = Readonly<{
11
+ mode: "observe" | "enforce";
12
+ enforceGroups?: readonly string[];
13
+ defaultAction: "budget" | "deny";
14
+ unverifiedAction: "budget" | "deny";
15
+ rules: readonly CrawlerAccessRule[];
16
+ rates: Readonly<{
17
+ global?: ControlRate;
18
+ unknown?: ControlRate;
19
+ perIp?: ControlRate;
20
+ routes?: Readonly<Record<string, ControlRate>>;
21
+ providers?: Readonly<Record<string, ControlRate>>;
22
+ }>;
23
+ logging: boolean;
24
+ }>;
25
+ /** Dashboard controls cannot increase locally installed request ceilings or alter work pools. */
26
+ export declare function validateCrawlerControls(raw: unknown, policy: GuardPolicy): CrawlerControls;
27
+ export declare function defaultCrawlerControls(configuration: {
28
+ policy: GuardPolicy;
29
+ rollout?: {
30
+ mode: "observe" | "enforce";
31
+ enforceGroups?: readonly string[];
32
+ };
33
+ crawlerAccess?: readonly CrawlerAccessRule[];
34
+ crawlerAccessDefault?: "budget" | "deny";
35
+ unverifiedAccess?: "budget" | "deny";
36
+ }): CrawlerControls;
37
+ export type CrawlerDecisionLog = {
38
+ id: string;
39
+ at: number;
40
+ group: string;
41
+ provider: string;
42
+ crawlerClass: string;
43
+ action: Decision["action"];
44
+ reason: string;
45
+ verification: string;
46
+ mode: string;
47
+ };
48
+ /** Separate opt-in bounded log buffer; never retains IP, URL, user agent or caller request IDs. */
49
+ export declare function createCrawlerDecisionBuffer(policy: GuardPolicy, enabled: () => boolean, now?: () => number): {
50
+ record(decision: Decision, evidence?: CrawlerEvidence, details?: DecisionDetails): void;
51
+ batch(): CrawlerDecisionLog[];
52
+ ack(ids: readonly string[]): void;
53
+ clear(): void;
54
+ dropped(): number;
55
+ };
56
+ /** Memory-only short lease. Dashboard sessions alone publish; requests use cached controls. */
57
+ export declare function createCrawlerControlClient(input: {
58
+ apiKey: string;
59
+ site: string;
60
+ configuration: unknown;
61
+ endpoint?: string;
62
+ fetch?: typeof fetch;
63
+ now?: () => number;
64
+ }): {
65
+ configurationId: string;
66
+ refresh: () => Promise<void>;
67
+ record: (decision: Decision, evidence?: CrawlerEvidence, details?: DecisionDetails) => void;
68
+ current(): Readonly<{
69
+ mode: "observe" | "enforce";
70
+ enforceGroups?: readonly string[];
71
+ defaultAction: "budget" | "deny";
72
+ unverifiedAction: "budget" | "deny";
73
+ rules: readonly CrawlerAccessRule[];
74
+ rates: Readonly<{
75
+ global?: ControlRate;
76
+ unknown?: ControlRate;
77
+ perIp?: ControlRate;
78
+ routes?: Readonly<Record<string, ControlRate>>;
79
+ providers?: Readonly<Record<string, ControlRate>>;
80
+ }>;
81
+ logging: boolean;
82
+ }>;
83
+ status(): {
84
+ error?: "unavailable" | "rejected" | undefined;
85
+ revision: number;
86
+ mode: "observe" | "enforce";
87
+ active: boolean;
88
+ };
89
+ start(): () => void;
90
+ };
@@ -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/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,7 @@ 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;
94
96
  unverifiedAccess?: 'budget' | 'deny';
95
97
  crawlerAccess?: (evidence: CrawlerEvidence, routeGroup: string) => 'budget' | 'deny';
96
98
  onDecision?: (decision: Readonly<Decision>, evidence?: CrawlerEvidence, details?: DecisionDetails) => void;
package/dist/guard.js CHANGED
@@ -118,10 +118,14 @@ class CrawlerGuard {
118
118
  throw new Error('Invalid customer grant');
119
119
  if (customer?.lane === 'checkout' && this.policy.routes[input.routeGroup].customerLane !== 'checkout')
120
120
  customer = { ...customer, lane: 'shopper' };
121
+ const controls = customer ? undefined : this.config.controls?.();
121
122
  const lane = customer?.lane ?? 'catalog';
122
123
  const rollout = this.policy.rollout;
123
- const mode = customer || !rollout || (rollout.mode === 'enforce' && rollout.enforceGroups.includes(input.routeGroup)) ? 'enforce' : 'observe';
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;
124
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) });
125
129
  const classified = this.config.registry.classify(ip, input.userAgent);
126
130
  evidence = this.config.trustedEvidence?.(input.request, ip, input.userAgent) ?? (classified.claimedCrawler === 'bingbot' && (0, verification_1.crawlerClaim)(input.userAgent)?.provider === 'bing'
127
131
  ? this.config.bing.classify(ip) : classified);
@@ -134,22 +138,26 @@ class CrawlerGuard {
134
138
  // Known source without an explicit allowance gets the conservative policy.
135
139
  const privileged = Boolean(provider && crawlerRate);
136
140
  const bucket = (key, rate) => ({ key, ...rate, cost: input.cost });
137
- 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))];
138
142
  if (customer) {
139
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));
140
144
  }
141
- 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])));
142
146
  if (!customer) {
143
147
  if (privileged) {
144
- buckets.push(bucket('provider:' + evidence.provider, provider.rate));
148
+ buckets.push(bucket('provider:' + evidence.provider, minimum(provider.rate, rates?.providers?.[evidence.provider])));
145
149
  buckets.push(bucket('crawler:' + evidence.provider + ':' + evidence.crawlerClass, crawlerRate));
146
150
  }
147
- else
148
- buckets.push(bucket('unknown', this.policy.unknownRate));
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
+ }
149
157
  }
150
158
  const denied = !customer && (verified
151
- ? this.config.crawlerAccess?.(evidence, input.routeGroup) === 'deny'
152
- : this.config.unverifiedAccess === 'deny');
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');
153
161
  if (denied && mode === 'enforce') {
154
162
  decision = { ...base, action: 'block', reason: 'crawler_policy_denied' };
155
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);
@@ -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: "bypass" | "protected";
22
+ kind: "protected" | "bypass";
23
23
  methods: readonly string[];
24
24
  path: string;
25
25
  }[];
package/dist/runtime.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { createCrawlerControlClient } from './controls';
1
2
  import type { IncomingMessage } from 'node:http';
2
3
  import { CrawlerGuard, type RequestContext } from './guard';
3
4
  import { ManagedRedisAdmission } from './operations';
@@ -17,6 +18,7 @@ export declare function createCrawlerRuntime(input: {
17
18
  bing?: BingVerifier;
18
19
  customer?: GuardDependencies['customer'];
19
20
  trustedEvidence?: GuardDependencies['trustedEvidence'];
21
+ controlClient?: ReturnType<typeof createCrawlerControlClient>;
20
22
  onDecision?: GuardDependencies['onDecision'];
21
23
  now?: () => number;
22
24
  timeoutMs?: number;
@@ -41,6 +43,33 @@ export declare function createCrawlerRuntime(input: {
41
43
  expiresAt?: number;
42
44
  }>;
43
45
  }>;
46
+ controlClient: {
47
+ configurationId: string;
48
+ refresh: () => Promise<void>;
49
+ record: (decision: import("./admission").Decision, evidence?: import("./verification").CrawlerEvidence, details?: import("./guard").DecisionDetails) => void;
50
+ current(): Readonly<{
51
+ mode: "observe" | "enforce";
52
+ enforceGroups?: readonly string[];
53
+ defaultAction: "budget" | "deny";
54
+ unverifiedAction: "budget" | "deny";
55
+ rules: readonly import("./configuration").CrawlerAccessRule[];
56
+ rates: Readonly<{
57
+ global?: import("./controls").ControlRate;
58
+ unknown?: import("./controls").ControlRate;
59
+ perIp?: import("./controls").ControlRate;
60
+ routes?: Readonly<Record<string, import("./controls").ControlRate>>;
61
+ providers?: Readonly<Record<string, import("./controls").ControlRate>>;
62
+ }>;
63
+ logging: boolean;
64
+ }>;
65
+ status(): {
66
+ error?: "unavailable" | "rejected" | undefined;
67
+ revision: number;
68
+ mode: "observe" | "enforce";
69
+ active: boolean;
70
+ };
71
+ start(): () => void;
72
+ } | undefined;
44
73
  nodeMiddleware: (request: import("./adapters").GuardedRequest, response: import("http").ServerResponse, next: (error?: unknown) => void) => void;
45
74
  nuxtMiddleware: (event: {
46
75
  node: {
package/dist/runtime.js CHANGED
@@ -14,15 +14,19 @@ const activation_1 = require("./activation");
14
14
  function createCrawlerRuntime(input) {
15
15
  const compiled = (0, configuration_1.compileCrawlerConfiguration)(input.configuration, (input.now ?? Date.now)());
16
16
  (0, activation_1.validateActivation)(input.activation, compiled.configuration.tenant);
17
+ if (input.controlClient && input.controlClient.configurationId !== compiled.fingerprint)
18
+ throw Error('Crawler control configuration mismatch');
17
19
  const store = new operations_1.ManagedRedisAdmission(input.redis, compiled.configuration.tenant, compiled.policy, input.timeoutMs);
18
20
  const report = new reporting_1.CrawlerReport(compiled.policy, 1024, compiled.configuration.crawlerAccess);
19
21
  const access = compiled.configuration.crawlerAccess ?? [];
20
22
  const guard = new guard_1.CrawlerGuard({ activation: input.activation, policy: compiled.policy, store, registry: input.registry ?? new verification_1.CrawlerRegistry(), bing: input.bing ?? new verification_1.BingVerifier(),
23
+ controls: input.controlClient?.current,
21
24
  unverifiedAccess: compiled.configuration.unverifiedAccess,
22
25
  customer: input.customer, trustedEvidence: input.trustedEvidence, now: input.now,
23
26
  crawlerAccess: (e, group) => access.find(rule => rule.provider === e.provider && rule.crawlerClass === e.crawlerClass && rule.groups.includes(group))?.action ?? compiled.configuration.crawlerAccessDefault ?? 'budget',
24
27
  onDecision: (decision, evidence, details) => {
25
28
  report.decision(decision, evidence, details);
29
+ input.controlClient?.record(decision, evidence, details);
26
30
  return input.onDecision?.(decision, evidence, details);
27
31
  },
28
32
  });
@@ -48,7 +52,7 @@ function createCrawlerRuntime(input) {
48
52
  throw error;
49
53
  }
50
54
  }
51
- return Object.freeze({ compiled, store, guard, report, activation: input.activation,
55
+ return Object.freeze({ compiled, store, guard, report, activation: input.activation, controlClient: input.controlClient,
52
56
  nodeMiddleware: (0, adapters_1.createNodeCrawlerMiddleware)(adapter), nuxtMiddleware: (0, adapters_1.createNuxtCrawlerMiddleware)(adapter),
53
57
  withDatabaseAdmission: (context, operation) => work('database', context, operation),
54
58
  withRenderingAdmission: (context, operation) => work('render', context, operation),
package/dist/telemetry.js CHANGED
@@ -33,8 +33,10 @@ function createCrawlerTelemetry(input) {
33
33
  }
34
34
  catch { /* Report unavailable capacity without changing admission. */ }
35
35
  const snapshot = runtime.report.snapshot();
36
+ const control = runtime.controlClient?.status();
36
37
  const body = JSON.stringify({ site: input.site, instance, sequence: ++sequence, tenant: runtime.compiled.configuration.tenant,
37
- configurationId: runtime.compiled.fingerprint, mode: runtime.compiled.configuration.rollout.mode,
38
+ configurationId: runtime.compiled.fingerprint, mode: control?.mode ?? runtime.compiled.configuration.rollout.mode,
39
+ ...(control ? { control: { revision: control.revision, active: control.active } } : {}),
38
40
  overflow: snapshot.overflow + snapshot.series.slice(256).reduce((n, s) => n + s.count, 0),
39
41
  series: snapshot.series.slice(0, 256).map(({ tags, count, durationMs }) => ({ tags, count, durationMs })), capacity });
40
42
  if (Buffer.byteLength(body) > 262144)
package/gateway/README.md CHANGED
@@ -114,3 +114,7 @@ Attribution: Verified Bots Directory by Mayank Gupta (https://verifiedbots.dev),
114
114
  The gateway refreshes official OpenAI, Anthropic and Google agent/fetcher feeds in the background. Configure explicit `crawlerAccess` allowances and set `crawlerAccessDefault` to `deny` to reject other verified crawlers on protected groups. Each allowance still needs matching provider/class budgets. Optional `unverifiedAccess: "deny"` also rejects anonymous humans, spoofed claims and unavailable verifications; retain `"budget"` for ordinary anonymous storefront traffic unless an independent customer-grant integration is in place. Existing configurations keep their previous behavior.
115
115
 
116
116
  See the [complete configuration fragment and provider boundaries](https://valiron.co/docs/agents/CRAWLER-PROTECTION.md#allow-selected-ai-services). Google-agent verification does not identify every Gemini interaction. Claude-Agent browser access requires its separately reviewed directory identity; static address changes require review against Anthropic’s official publication. Regenerate directory approval hashes when upgrading to this behavior.
117
+
118
+ ## Managed dashboard controls (0.7.0+)
119
+
120
+ After deploying the management backend and migration, set `CRAWLER_MANAGED_CONTROLS=true` and a stable `CRAWLER_SITE_ID` in gateway.env. Keep `VALIRON_API_KEY` server-side. The gateway registers its validated installation, polls controls every 30 seconds and acknowledges applied revisions. The dashboard can publish access rules and tighter request budgets within installed ceilings, view bounded opt-in decisions and configure optional alerts. Match the telemetry site ID. Control leases expire within five minutes; catalog traffic fails closed when no valid lease remains. This does not initialize Redis, raise work limits or replace deployment/recovery. See [Dashboard controls](https://www.valiron.co/docs/crawler-protection/controls).
@@ -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 runtime = createCrawlerRuntime({ activation, configuration, redis, clientIp, registry, trustedEvidence, timeoutMs: 1500 });
39
- return { runtime, redis, clientIp, registry, directory };
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.6.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",