@valiron/sdk 2.0.0 → 2.1.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/docs/DASHBOARD.md CHANGED
@@ -40,25 +40,31 @@ Sign in on the website to manage your account. Keep the operator API key in your
40
40
  The dashboard uses the same three product sections as the documentation. Choose a product from the **Product** switcher; its navigation appears underneath:
41
41
 
42
42
  - **Agent Access**: Overview & setup, Agents, Analytics, Call logs and Playground. `/dashboard` retains the identity/trust integration setup and saved endpoint onboarding.
43
- - **Crawler Protection**: Traffic & analytics and Setup & configuration (`/dashboard/crawler-protection/setup`). Traffic & analytics stays open even when no runtime has reported. Its empty state links to setup; selecting a tab, refreshing or reloading analytics never redirects to configuration. Ordinary crawlers do not need to register as agents. This product is included on Free, Pro and Enterprise.
43
+ - **Crawler Protection**: Traffic & analytics, Crawler controls, Decision logs, Alerts and Setup & configuration (`/dashboard/crawler-protection/setup`). Traffic & analytics stays open even when no runtime has reported. Its empty state links to setup; selecting a tab, refreshing or reloading analytics never redirects to configuration. Ordinary crawlers do not need to register as agents. This product is included on Free, Pro and Enterprise.
44
44
  - **API Scaffolding**: Overview (`/dashboard/api-scaffolding`) and Endpoints & testing (`/dashboard/wrappers`). Configure upstream routes, payments, optional trust checks and tests in the existing endpoint screen. `/dashboard/endpoints` remains supported and selects the same product.
45
45
 
46
46
  **API Keys**, **Settings & billing**, and role-restricted **Administration** remain shared account tools. On mobile, use the product switcher and horizontally scrollable product tabs; expand **Account tools** for shared pages. Opening a shared page retains the last selected product during navigation. Direct product URLs select their corresponding product, including after a reload. Existing Agent Access and shared-account URLs are unchanged. API analytics remains account-scoped; crawler analytics uses its separate origin telemetry.
47
47
 
48
48
  ---
49
49
 
50
+ **Account → Usage** (`/dashboard/usage`) shows both products together: admitted requests this UTC month, included and remaining allowance, additional calls, estimated request-overage charges grouped by currency, allowance reset date and enrollment/review status. Each product has its own opt-in. Counts refresh every 15 seconds while the page is visible; **Refresh** checks immediately. A failed refresh preserves the last successful counts and marks them out of date. An initial outage shows unavailable usage, never a fabricated zero. Request-overage estimates exclude the Pro subscription, taxes and billing adjustments; final invoice rounding can differ.
51
+
52
+ The middleware overview and Crawler Protection each show their own monthly usage panel. Paid Pro owners can enable additional calls separately at the displayed rate of 0.001 per request after 100,000. Checkout offers separate unchecked opt-in controls; existing customers enroll from the relevant dashboard panel. Without opt-in, requests stop at the included allowance.
53
+
50
54
  ## Valiron Crawler Protection (Free, Pro, Enterprise)
51
55
 
52
56
  **Route:** `/dashboard/crawler-protection`
53
57
 
54
- Free accounts can review the feature and follow the upgrade link. Pro and Enterprise accounts can:
58
+ Free, Pro and Enterprise accounts can:
55
59
 
56
60
  1. Open **Setup & configuration**, use **Copy prompt** to hand setup to a coding agent, copy the install command, and create a server-side operator API key. An optional install checkbox is a self-reported acknowledgment, stored per account in this browser; it does not verify installation or subscription activation.
57
61
  2. Paste schema-v1 route/limit configuration and an optional measured capacity baseline. **Load example** fills a compiler-valid observation-mode sample for `/products/**`, with illustrative limits and one-hour expiry. Replace all limits and inventory before deployment; it is not a capacity recommendation.
58
62
  3. Validate against the real configuration compiler and inspect rollout blockers.
59
63
  4. Download account-scoped configuration for their own deployment, then follow the runtime environment and optional Node telemetry examples. Setup progress shows inputs validated during this visit and a runtime connection only while fresh telemetry is reporting. Editing either input clears the validation result. Select the intended reporting site in the analytics panel. If its configuration differs from the currently validated file, setup shows a mismatch and the runtime check stays incomplete. The three checks do not certify a production deployment. Setup uses a compact checklist progress bar. The optional measured baseline, deployment guidance and detailed explanations expand on demand; primary actions and validation blockers remain visible.
60
64
 
61
- The server rechecks the authenticated plan on every validation. Invalid configuration, expired sessions or unavailable account lookup never grant access. Configuration is not persisted or activated by this screen. No runtime credentials are entered and no direct Redis/DB connection is made. The default **Traffic & analytics** view uses optional server-side telemetry: site/provider/route/actual-decision filters, provider totals with verification counts, plain-language allowed/limited/blocked/unavailable reasons, actual versus proposed decisions, rolling 24-hour traffic, shared work capacity, instance/configuration status, monitoring alerts and JSON export. Provider rows can be clicked to filter; Clear filters resets the view. The hourly chart remains site-wide, and JSON export includes all sites and filters. Raw metric series and reporting instances are under Advanced diagnostics. Capacity meters show reserved slots per work pool, not database utilization. Metric definitions are available under **How to read these metrics**; stale/unavailable state and observation proposals remain visible. Telemetry refreshes every 30 seconds; empty, stale and unavailable states are explicit. Analytics export is disabled until a site has reported. Setup includes the same analytics panel below the steps; a connected account can open the separate analytics view. Monitoring alerts are displayed in the dashboard; outbound notifications and remote policy activation are not included. The website behind the gateway can use another backend language or frontend framework. For database-level limits, integrate the private work API around each operation; the gateway alone bounds origin HTTP work. The package includes a Python client. SQLite and MariaDB are tested; other drivers require settlement/cancellation validation. Deploy and test the customer-side gateway/runtime before enabling useful crawlers. See [Valiron Crawler Protection](./CRAWLER-PROTECTION.md).
65
+ SDK 0.6.0 configurations can include `crawlerAccessDefault` and `unverifiedAccess` plus route-specific crawler class allowances. The validator accepts these options; the developer must deploy and activate the base configuration in the customer runtime. Analytics filters change the view only: they do not create allow/block rules. With managed controls enabled in 0.7.0+, Crawler controls can publish access changes and tighter request budgets within installed ceilings. See [selected AI services](./CRAWLER-PROTECTION.md#allow-selected-ai-services) before applying strict defaults to public pages; unidentified traffic includes anonymous shoppers.
66
+
67
+ The server rechecks the authenticated plan on every validation. Invalid configuration, expired sessions or unavailable account lookup never grant access. Configuration is not persisted or activated by this screen. No runtime credentials are entered and no direct Redis/DB connection is made. The default **Traffic & analytics** view uses optional server-side telemetry: site/provider/route/actual-decision filters, provider totals with verification counts, plain-language allowed/limited/blocked/unavailable reasons, actual versus proposed decisions, rolling 24-hour traffic, shared work capacity, instance/configuration status, monitoring alerts and JSON export. Provider rows can be clicked to filter; Clear filters resets the view. The hourly chart remains site-wide, and JSON export includes all sites and filters. Raw metric series and reporting instances are under Advanced diagnostics. Capacity meters show reserved slots per work pool, not database utilization. Metric definitions are available under **How to read these metrics**; stale/unavailable state and observation proposals remain visible. Telemetry refreshes every 30 seconds; empty, stale and unavailable states are explicit. Analytics export is disabled until a site has reported. Setup includes the same analytics panel below the steps; a connected account can open the separate analytics view. Monitoring alerts remain visible here. SDK/gateway 0.7.0+ managed integrations add separate Crawler controls, bounded Decision logs and opt-in email/webhook Alerts; see [Dashboard controls](./CRAWLER-PROTECTION.md#dashboard-controls). Static integrations retain developer-deployed configuration until managed controls are explicitly connected. The website behind the gateway can use another backend language or frontend framework. For database-level limits, integrate the private work API around each operation; the gateway alone bounds origin HTTP work. The package includes a Python client. SQLite and MariaDB are tested; other drivers require settlement/cancellation validation. Deploy and test the customer-side gateway/runtime before enabling useful crawlers. See [Valiron Crawler Protection](./CRAWLER-PROTECTION.md).
62
68
 
63
69
  ## Agents
64
70
 
@@ -364,10 +370,20 @@ For deployments requiring full backend control, protect the API directly with Va
364
370
 
365
371
  For full hosted wrapper docs, see [AGENT-READY-APIS.md](./AGENT-READY-APIS.md).
366
372
 
367
- SDK 0.2.0+ setup requires signup and an operator API key from Dashboard → API Keys. Store `VALIRON_API_KEY` server-side and use the tenant from your exported configuration. The SDK checks its account lease at startup and refreshes in the background; the dashboard does not deploy the runtime or activate Redis policy.
373
+ Crawler SDK 0.3.0+ setup requires signup and an operator API key from Dashboard → API Keys. Store `VALIRON_API_KEY` server-side and use the tenant from your exported configuration. The SDK checks its account lease at startup and refreshes in the background; the dashboard does not deploy the runtime or activate Redis policy.
368
374
 
369
375
  ## Security behavior for account owners
370
376
 
371
377
  Password reset links are rate-limited and single use. A successful reset revokes existing API keys and operator sessions; sign in again and replace affected integration keys. Billing checkout and portal access are bound to the authenticated operator account; checkout email and caller-supplied promo strings cannot select another account or grant a discount. Promotion eligibility is handled by Stripe checkout.
372
378
 
373
379
  Operator SDK usage reporting is disabled by default. Enable `analytics: true` deliberately if dashboard call reports are needed; raw IP addresses, user agents and endpoint paths are not transmitted. SDK diagnostic telemetry has its own `telemetry` configuration. Assessment PDF exports use saved server-side report results rather than client-submitted grades; older assessments without a stored report must be rerun.
380
+
381
+ Usage billing: website signup and a server-side operator API key are required. Free includes 10,000 requests per product per UTC month; Pro includes 100,000 per product. An active paid Pro subscriber can separately enable additional crawler or middleware calls at 0.001 each in the subscription billing currency, displayed before acceptance. Each product has its own allowance, meter and opt-in. Without opt-in, that product stops at 100,000; Free must upgrade after 10,000. Billing uses durable hosted admission counters, not optional telemetry or every local SDK function call. SDK 0.5.0 also requires account activation for returning-browser recognition.
382
+
383
+ ## Admin customer Crawler Protection workspace
384
+
385
+ Authorized platform admins can open **Administration → customer account → Manage customer Crawler Protection**. This customer-scoped workspace reuses the customer analytics, controls, decision logs, alerts and usage views. It also exposes the runtime-reported installed configuration and a paginated admin change history with export of loaded activity. Audit pages contain at most five complete records so installation snapshots stay within response limits. The customer name, plan and admin context remain visible. Switching customers clears local drafts and filters; requests use the admin's own session, without customer impersonation or customer API keys.
386
+
387
+ Admins can publish access/rate changes, restore revisions, adopt a validated replacement installation, toggle recent decision logging and update notification settings within the same installed safety ceilings as customers. Each write requires a 10–500 character reason. The server rechecks the current admin role, and the transaction checks it again before recording actor, customer, site, action, reason and before/after state. Audit failure rolls back the change. Customer revision history labels admin changes **Valiron support** without exposing the admin identity or reason. Admin audit history retains 90 days, with webhook paths/query credentials omitted; account deletion removes that account's audit records. Installation replacement records the before/after installed configuration.
388
+
389
+ Admin reads/writes use the authenticated `/operator/admin/crawlers/:operatorId` routes, with separate analytics, control, configuration, usage and audit resources. Normal customers and operator API keys cannot use these routes. Stored installed configuration is visible; unsaved browser drafts, browser-only baseline measurements, raw API-key secrets and passwords are not recoverable from this view. Usage is inspectable for both products, but enabling paid overages still requires the customer's billing opt-in. These screens do not deploy customer infrastructure, initialize Redis or override workload safety ceilings.
package/docs/ERRORS.md CHANGED
@@ -4,6 +4,8 @@ Common error scenarios, status codes, and guidance on how to handle them.
4
4
 
5
5
  The separate Crawler Protection product uses `AdmissionError` and adapter codes `CRAWLER_LIMIT` (429), `CRAWLER_UNAVAILABLE` (503), and `CRAWLER_BLOCK` (403 for an enforced crawler deny rule or application-defined block). These are not `ValironError` failures from `@valiron/sdk`. See [crawler decisions and recovery](./CRAWLER-PROTECTION.md#decisions-and-recovery); rate/capacity rejections must not execute protected work. The standalone gateway adds proxy errors such as 413 for oversized requests, 503 for exhausted origin capacity and 504 for an origin timeout. The private work API uses 401/403 for service/capability failures and 503 for unavailable work. Do not automatically retry an ambiguous acquisition or release capacity because an HTTP timeout elapsed; query settlement must be confirmed.
6
6
 
7
+ With Crawler Protection 0.6.0, `crawlerAccessDefault: "deny"` rejects verified classes without an explicit route allowance. `unverifiedAccess: "deny"` rejects unverified, mismatched and unavailable identities too, including anonymous humans. Enforced access denials use reason `crawler_policy_denied` and map to 403 / `CRAWLER_BLOCK`; retries do not turn a claim into verification. In observation mode, policy denials remain proposed blocks and admitted requests can pass within safety/work limits. Expired source evidence never retains verified privilege; it is not itself proof of a storage outage.
8
+
7
9
  ## Read an error before retrying
8
10
 
9
11
  Every SDK failure is a `ValironError`. Its stable `code` is for program logic; its `message` is safe to show in developer logs; and `details` provides the recovery information that was available from the API.
@@ -6,7 +6,9 @@ Configure identity verification before opening a protected endpoint. Existing in
6
6
 
7
7
  This quickstart documents the hardened agent identity/trust SDK contract in this source tree. Verify your installed npm version supports `verifyRequest`, `signRequest` and provider request proofs v2 before upgrading a live integration; source changes do not publish a package. For ordinary website crawlers, see [controlled crawler access](./CRAWLER-PROTECTION.md): a separate integration package with a standalone HTTP gateway for other website stacks, in-process Node/Nuxt adapters, shared budgets and a private language-neutral work API. Node.js is required for the gateway service, not for the website behind it. Query-level limits require operation integration; Python/SQLite and Node/Nuxt/MariaDB are tested. It is not installed by `npm install @valiron/sdk` and does not require crawler agent registration.
8
8
 
9
- SDK 0.2.0+ requires a Free/Pro/Enterprise operator API key and account-bound activation via `activateCrawlerProtection()` before constructing its runtime. Activation uses a short-lived local lease, refreshed in the background. Each protected HTTP request requires hosted monthly quota admission; database operations are not counted again. See the crawler guide for revocation, outage and recovery behavior.
9
+ Crawler SDK 0.3.0+ requires a Free/Pro/Enterprise operator API key and account-bound activation via `activateCrawlerProtection()` before constructing its runtime. Activation uses a short-lived local lease, refreshed in the background. Each protected HTTP request requires hosted monthly quota admission; database operations are not counted again. See the crawler guide for revocation, outage and recovery behavior.
10
+
11
+ For the current crawler integration, install `@valiron/crawler-protection@^0.6.0`. It adds official Anthropic and Google agent/Notebook feeds alongside OpenAI support, and `crawlerAccessDefault` / `unverifiedAccess` configuration. These are customer-runtime controls, not hosted policy-deployment APIs. See [selected AI services and upgrade steps](./CRAWLER-PROTECTION.md#allow-selected-ai-services); source verification does not grant unlimited access or authorize account actions.
10
12
 
11
13
  ## Prerequisites
12
14
 
@@ -344,3 +346,7 @@ curl -H "Authorization: Bearer $VALIRON_API_KEY" -X POST "https://valiron-edge-p
344
346
  # Liveness check
345
347
  curl -H "Authorization: Bearer $VALIRON_API_KEY" "https://valiron-edge-proxy.onrender.com/operator/agent/1226/liveness?chain=solana"
346
348
  ```
349
+
350
+ Usage billing: website signup and a server-side operator API key are required. Free includes 10,000 requests per product per UTC month; Pro includes 100,000 per product. An active paid Pro subscriber can separately enable additional crawler or middleware calls at 0.001 each in the subscription billing currency, displayed before acceptance. Each product has its own allowance, meter and opt-in. Without opt-in, that product stops at 100,000; Free must upgrade after 10,000. Billing uses durable hosted admission counters, not optional telemetry or every local SDK function call. SDK 0.5.0 also requires account activation for returning-browser recognition.
351
+
352
+ Track both products in [Dashboard → Usage](https://www.valiron.co/dashboard/usage): monthly admitted requests, remaining allowance, additional calls and estimated request-overage charges. Counts refresh every 15 seconds while visible; usage billing and traffic analytics use separate data sources.
package/docs/README.md CHANGED
@@ -28,7 +28,7 @@ Valiron also provides **API Scaffolding** as a separate product for organization
28
28
  | [TRUST-MODEL.md](./TRUST-MODEL.md) | How agents are scored, what behaviors are penalized, tier assignments |
29
29
  | [IDENTITY.md](./IDENTITY.md) | Agent identity — ERC-8004/Solana agents and key-based Web2 agents |
30
30
  | [PROVIDER-IDENTITY.md](./PROVIDER-IDENTITY.md) | Provider-backed identity — SDK signing helpers and gates, normalized proofs, replay protection, policies, and ANS |
31
- | [CRAWLER-PROTECTION.md](./CRAWLER-PROTECTION.md) | Valiron Crawler Protection — source verification, shared quotas, HTTP gateway, language-neutral work API and Node/Nuxt adapters; integration package |
31
+ | [CRAWLER-PROTECTION.md](./CRAWLER-PROTECTION.md) | Valiron Crawler Protection 0.6.0 — official AI source verification, explicit allow/block defaults, shared quotas, HTTP gateway and language-neutral work admission |
32
32
  | [SANDBOX.md](./SANDBOX.md) | How the sandbox evaluates agents and determines production readiness |
33
33
  | [CHAINS.md](./CHAINS.md) | Supported blockchain networks and contract addresses |
34
34
  | [ERRORS.md](./ERRORS.md) | Error codes, troubleshooting, and retry guidance |
@@ -87,3 +87,9 @@ https://valiron-edge-proxy.onrender.com
87
87
  ## Upgrading an existing integration
88
88
 
89
89
  Follow [Request-bound identity upgrade](./SECURITY-UPGRADE-2026-10-31.md) before deploying the hardened source contract. Configure local verifiers and hosted signers, migrate provider proofs to v2, re-verify legacy World ID/Self links and re-register tenant-scoped webhooks. Check package availability separately from source changes.
90
+
91
+ Both products include 100,000 requests on Pro, then 0.001 per additional call in the accepted subscription currency with separate opt-ins. See [monthly request billing](./API-REFERENCE.md#monthly-request-allowance).
92
+
93
+ Track both products in [Dashboard → Usage](https://www.valiron.co/dashboard/usage): monthly admitted requests, remaining allowance, additional calls and estimated request-overage charges. Counts refresh every 15 seconds while visible; usage billing and traffic analytics use separate data sources.
94
+
95
+ For selected ChatGPT, Claude and Google agent access, use [SDK 0.6.0 configuration and upgrade instructions](./CRAWLER-PROTECTION.md#allow-selected-ai-services). Search/user-fetch and training classes are separate; supporting a named provider does not identify every browser agent or authorize account actions.
@@ -10,7 +10,9 @@ Package: `@valiron/sdk`
10
10
 
11
11
  Crawler source checks and shared work admission belong to the separate `@valiron/crawler-protection` integration package. `createCrawlerGateway()`, `createCrawlerWorkServer()`, `createCrawlerRuntime()`, `CrawlerGuard`, `RedisAdmission`, `createNodeCrawlerMiddleware()` and `createNuxtCrawlerMiddleware()` are exports of that package, not `@valiron/sdk`. The gateway fronts HTTP origins independently of their application language. The private work API is database-independent but requires operation integration and confirmed settlement. A Python client is included; SQLite and MariaDB are tested, while other drivers/stacks require validation. Install it with `npm install @valiron/crawler-protection`. See [controlled crawler access](./CRAWLER-PROTECTION.md) for its integration and recovery contracts.
12
12
 
13
- SDK 0.2.0+ requires a Free/Pro/Enterprise operator API key and account-bound activation via `activateCrawlerProtection()` before constructing its runtime. Activation uses a short-lived local lease, refreshed in the background. Each protected HTTP request requires hosted monthly quota admission; database operations are not counted again. See the crawler guide for revocation, outage and recovery behavior.
13
+ Crawler SDK 0.3.0+ requires a Free/Pro/Enterprise operator API key and account-bound activation via `activateCrawlerProtection()` before constructing its runtime. Activation uses a short-lived local lease, refreshed in the background. Each protected HTTP request requires hosted monthly quota admission; database operations are not counted again. See the crawler guide for revocation, outage and recovery behavior.
14
+
15
+ For the current crawler integration, install `@valiron/crawler-protection@^0.6.0`. It adds official Anthropic and Google agent/Notebook feeds alongside OpenAI support, and `crawlerAccessDefault` / `unverifiedAccess` configuration. These are customer-runtime controls, not hosted policy-deployment APIs. See [selected AI services and upgrade steps](./CRAWLER-PROTECTION.md#allow-selected-ai-services); source verification does not grant unlimited access or authorize account actions.
14
16
 
15
17
  ## Installation
16
18
 
@@ -773,6 +775,41 @@ app.use(async (c, next) => {
773
775
  });
774
776
  ```
775
777
 
778
+ ### runValironEdgeGate - Cloudflare Workers (edge)
779
+
780
+ `@valiron/sdk/edge-gate` is a node-free entry point for Cloudflare Workers and other fetch-based edge runtimes. It enforces the same route contract as the Node gates (fresh request-bound proof checked before every decision including cache hits, a 30-second profile cache per isolate, fail-closed 503s) without importing Node built-ins.
781
+
782
+ ```typescript
783
+ import {
784
+ ValironClient,
785
+ createEdgeWalletProofVerifier,
786
+ runValironEdgeGate,
787
+ stripEdgeGateHeaders,
788
+ } from "@valiron/sdk/edge-gate";
789
+
790
+ const sdk = new ValironClient({ endpoint: env.VALIRON_ENDPOINT, apiKey: env.VALIRON_API_KEY });
791
+ const verifyRequest = createEdgeWalletProofVerifier({
792
+ sdk,
793
+ nonceStore: env.VALIRON_NONCE_STORE, // Durable Object binding - required, gate fails closed without it
794
+ evmVerifier: { verify: viemVerifyMessage }, // e.g. viem's verifyMessage
795
+ solanaVerifier: webCryptoSolanaVerifier, // exported; WebCrypto Ed25519
796
+ });
797
+
798
+ export default {
799
+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
800
+ const outcome = await runValironEdgeGate(request, { sdk, verifyRequest, originSecret: env.VALIRON_ORIGIN_SECRET, waitUntil: p => ctx.waitUntil(p) });
801
+ if (!outcome.allowed) return outcome.response;
802
+ const outbound = stripEdgeGateHeaders(request);
803
+ for (const [name, value] of Object.entries(outcome.headers)) outbound.headers.set(name, value);
804
+ return fetch(outbound);
805
+ },
806
+ };
807
+ ```
808
+
809
+ Pass `waitUntil: p => ctx.waitUntil(p)` so Workers retains automatic sandbox evaluation after a pending 403 response. Keep the SDK instance stable per isolate for the 30-second profile cache. Pending profiles are deliberately not cached.
810
+
811
+ `verifyRequest` is mandatory and application-owned, exactly as in the Node middleware. `createEdgeWalletProofVerifier` verifies the `valiron-wallet-request-v2` signed-request scheme locally at the edge: the registry owner's EIP-191 (EVM) or Ed25519 (Solana) signature over the canonical payload (agent id, chain, method, exact public URL, canonical JSON body digest, millisecond timestamp within 60 seconds, fresh nonce), checked against the agent's current registry owner wallet from the live profile, with the nonce consumed atomically in a Durable Object (121-second TTL; replay rejected). The SDK core stays dependency-free: callers inject an EVM verifier (viem works) and a Solana verifier (`webCryptoSolanaVerifier` is exported for the WebCrypto path); key-based web2 agents send `x-agent-address` with chain `key`. `createEdgeIdentityVerifier` remains available for hosted ANS verification (`POST /operator/identity/verify`) when the backend has ANS configured. On allow, the worker forwards the request to the origin with the returned trusted `x-valiron-gate-*` headers plus `x-valiron-gate-secret` when `originSecret` is set (the origin must reject requests without it, or be unreachable except through Cloudflare); run `stripEdgeGateHeaders` on every inbound request so clients cannot inject a decision. `MemoryNonceStore` is exported for local tests only - the verifier refuses to run without a nonce store (503, fail-closed). Statuses match the Node gate: 401 `MISSING_AGENT_IDENTITY`, 401 `AGENT_OWNERSHIP_REQUIRED`, 403 `TRUST_GATE_DENIED` / `AGENT_EVALUATION_PENDING`, 503 `TRUST_GATE_UNAVAILABLE`. Because the proof is checked before evaluation, an unreachable Valiron API fails closed as 401 `AGENT_OWNERSHIP_REQUIRED` when the hosted verifier cannot be reached, and as 503 `TRUST_GATE_UNAVAILABLE` when evaluation fails after a successful local wallet proof; the origin is never touched on failure. A deployable template is in `examples/cloudflare-gate-worker`; the full guide is [Cloudflare gate middleware](./CLOUDFLARE-GATE-MIDDLEWARE.md).
812
+
776
813
  ### Provider identity middleware — ANS and future adapters
777
814
 
778
815
  Provider identity uses dedicated, non-caching gates because every request has
@@ -953,3 +990,11 @@ import {
953
990
  | Monthly bot protection requests | 10,000 | 100,000 |
954
991
 
955
992
  Pro plan requires an operator API key (`val_op_` prefix) from the [Operator Dashboard](./DASHBOARD.md).
993
+
994
+ Usage billing: website signup and a server-side operator API key are required. Free includes 10,000 requests per product per UTC month; Pro includes 100,000 per product. An active paid Pro subscriber can separately enable additional crawler or middleware calls at 0.001 each in the subscription billing currency, displayed before acceptance. Each product has its own allowance, meter and opt-in. Without opt-in, that product stops at 100,000; Free must upgrade after 10,000. Billing uses durable hosted admission counters, not optional telemetry or every local SDK function call. SDK 0.5.0 also requires account activation for returning-browser recognition.
995
+
996
+ Track both products in [Dashboard → Usage](https://www.valiron.co/dashboard/usage): monthly admitted requests, remaining allowance, additional calls and estimated request-overage charges. Counts refresh every 15 seconds while visible; usage billing and traffic analytics use separate data sources.
997
+
998
+ ## Crawler managed controls (0.7.0+)
999
+
1000
+ `createCrawlerControlClient({ configuration, apiKey, site })` adds background policy polling; pass it as `controlClient` to `createCrawlerRuntime`. The dashboard manages crawler access and tighter request budgets within installed ceilings, with publish/rollback, runtime revision acknowledgments, optional bounded recent decision logs and opt-in alerts. It does not deploy customer infrastructure or change work concurrency. Static runtimes are unchanged. See [Dashboard controls](./CRAWLER-PROTECTION.md#dashboard-controls) for the setup, API endpoints, leases and retention limits.
package/docs/llms.txt CHANGED
@@ -76,7 +76,7 @@ Self session creation also requires operator and owner approval. Only new owner-
76
76
 
77
77
  ## Pricing, quotas and billing
78
78
 
79
- Free: 10,000 agent requests and a separate 10,000 bot-protection requests per UTC calendar month, three endpoints and five sandbox runs/day. Pro: $149/month, 100,000 requests per product and Social Graph. Enterprise: founders@valiron.co. Limits do not auto-upgrade or charge accounts.
79
+ Free: 10,000 agent requests and a separate 10,000 bot-protection requests per UTC calendar month, three endpoints and five sandbox runs/day. Pro: $149/month, 100,000 requests per product and Social Graph. Enterprise: founders@valiron.co. Limits never auto-upgrade accounts. Additional calls for either product cost 0.001 each in the subscription currency and require separate explicit opt-in.
80
80
 
81
81
  Hosted wrappers apply payment validation, local rate limits and trust admission before charging the owner's monthly allowance. Rejected calls do not consume that allowance; admitted calls can count even if the upstream later fails. Crawler local access/rate denials also precede monthly admission. Database operations are not counted as additional monthly crawler requests. Storage failures fail closed.
82
82
 
@@ -90,16 +90,26 @@ Trust-enabled wrappers require x-agent-id, x-chain matching the signed network,
90
90
 
91
91
  ## Crawler Protection
92
92
 
93
- Install @valiron/crawler-protection separately. The standalone Node.js 22+ HTTP gateway fronts origins regardless of backend language; in-process Node/Nuxt adapters and a private authenticated work API/Python client are available. Python/SQLite and Node/Nuxt/MariaDB are tested. Wrap every expensive operation and release capacity only after confirmed settlement/cancellation. Gateway-only limits do not instrument database drivers or protect a bypassed origin.
93
+ Install @valiron/crawler-protection@^0.6.0 separately. The standalone Node.js 22+ HTTP gateway fronts origins regardless of backend language; in-process Node/Nuxt adapters and a private authenticated work API/Python client are available. Python/SQLite and Node/Nuxt/MariaDB are tested. Wrap every expensive operation and release capacity only after confirmed settlement/cancellation. Gateway-only limits do not instrument database drivers or protect a bypassed origin.
94
94
 
95
- Supported source evidence uses reviewed official CIDRs, Bing DNS or authenticated verified WAF evidence. User-agent alone grants no verification; generic browser tokens cannot override failed official crawler evidence. Directory approvals include resolved CIDRs and must be reviewed when that evidence changes. Provenance is separate from human identity, reputation or intent.
95
+ Supported source evidence uses reviewed official CIDRs, Bing DNS or authenticated verified WAF evidence. Crawler SDK 0.4.0 adds opt-in WebBotAuthVerifier fallback for operator-pinned signing keys; only explicitly promoted valid signers receive verified budgets, and existing trusted/IP/DNS verification takes precedence. Signature validity proves key control, not good intent or authorization. User-agent alone grants no verification; generic browser tokens cannot override failed official crawler evidence. In 0.6.0, feed-backed directory approvals pin identity metadata and recipes while allowing validated CIDRs to refresh. Static recipes pin their resolved ranges too. Regenerate old approval hashes when upgrading, and review changed identity metadata or static ranges. Invalid/broad range sets disable only the affected entry; structurally invalid catalogs still reject atomically. Bare addresses normalize to host ranges. Provenance is separate from human identity, reputation or intent.
96
+
97
+ SDK 0.6.0 verifies OpenAI oai-searchbot/chatgpt-user/gptbot; Anthropic claude-searchbot/claude-user/claudebot; Google google-agent and gemini-notebook in addition to existing crawlers. Search/user fetches and training are separate class policies. Google-Agent establishes Google-hosted origin, not a particular model or user; Google-Extended is a robots.txt preference, not an HTTP identity. Claude-Agent hosted browsers require the separately reviewed directory-claude-agent / claude-agent identity; static address changes need review, and automatic SAIL refresh is not implemented. No promise covers every Claude, Gemini or Codex browsing mode.
98
+
99
+ Set crawlerAccessDefault to deny and configure explicit budget rules by provider/class/group to deny other verified crawlers. Omitted defaults retain budget behavior. unverifiedAccess budget keeps unknown traffic under conservative limits; deny blocks unknown/failed/expired identity checks, including anonymous humans. Verified customer grants retain independent shopper/checkout lanes. Access rules remain subject to configured rates and workload ceilings. Observation reports proposed blocks rather than enforcing access denials. Changes require customer-side deployment; dashboard filters are not policy controls. See https://www.valiron.co/docs/crawler-protection/policies#allow-selected-ai-services.
96
100
 
97
101
  Use a server-side Free/Pro/Enterprise operator key and account-scoped tenant with activateCrawlerProtection(). Leases refresh in the background; protected requests require hosted monthly admission. Expiry/revocation stops new work while confirmed release/recovery remains available. Activation can target an explicitly configured trusted HTTPS service and rejects redirects. Existing public older versions are not retroactively gated.
98
102
 
99
103
  Uncertain acquisitions use deadlines/cancellation to avoid unstarted holds. Started operations retain conservative holds until confirmed stopped. Recovery pauses admission and reconciles exact IDs with drain evidence; timeout alone does not prove a query stopped. The dashboard validates/exports configuration and shows optional origin-reported telemetry; it does not deploy protection or certify rollout.
100
104
 
105
+ Crawler SDK 0.4.0 also includes optional returning-browser recognition: a server-signed cookie supports exact browser continuity, while coarsened browser signals provide similarity only. Mount its Node middleware and explicitly call the browser collector to enable collection. It is observe-only, not human identification or automatic blocking, and is not automatically included in hosted crawler analytics. SDK 0.5.0 requires a server-side account activation handle for recognition and meters each recognition call against the bot allowance.
106
+
101
107
  ## Reporting and errors
102
108
 
103
109
  SDK diagnostic telemetry remains separately configurable with telemetry.enabled (default true); disable with telemetry: {enabled:false}. Operator usage reporting is disabled by default: new ValironOperator({apiKey,analytics:true}) explicitly opts in. It sends authenticated decision/identity labels, method, status, price and latency while omitting/redacting raw IP addresses, user agents, paths/query strings and arbitrary error messages.
104
110
 
105
111
  Handle codes: MISSING_AGENT_IDENTITY (401), AGENT_OWNERSHIP_REQUIRED (401), TRUST_GATE_DENIED (403), AGENT_EVALUATION_PENDING (403; honor retryAfterMs), TRUST_GATE_UNAVAILABLE (503). Ownership failures may contain only code/error; recovery fields are optional. Never fail open or bypass a proof check because a profile was cached.
112
+
113
+ Usage billing: website signup and a server-side operator API key are required. Free includes 10,000 requests per product per UTC month; Pro includes 100,000 per product. An active paid Pro subscriber can separately enable additional crawler or middleware calls at 0.001 each in the subscription billing currency, displayed before acceptance. Each product has its own allowance, meter and opt-in. Without opt-in, that product stops at 100,000; Free must upgrade after 10,000. Billing uses durable hosted admission counters, not optional telemetry or every local SDK function call. SDK 0.5.0 also requires account activation for returning-browser recognition.
114
+
115
+ Dashboard Usage: https://www.valiron.co/dashboard/usage — per-product monthly admitted requests, remaining allowance and accrued request-overage estimates; refreshes every 15 seconds while visible. Billing counters are separate from optional crawler traffic telemetry.
@@ -0,0 +1,198 @@
1
+ # Valiron trust gate on Cloudflare Workers
2
+
3
+ This template runs the general Valiron trust gate - the same middleware
4
+ semantics as `createValironGate` (Express), `valironFastifyPlugin`,
5
+ `createValironNextMiddleware` and `valironGateCheck` in `@valiron/sdk` - as a
6
+ Cloudflare Worker in front of your API. It is the general trust-score
7
+ middleware at the edge.
8
+
9
+ On every gated request the Worker:
10
+
11
+ 1. Reads the agent identity (`x-agent-id` for on-chain agents, or
12
+ `x-agent-address` for key-based web2 agents).
13
+ 2. Verifies a fresh, request-bound ownership proof BEFORE any decision,
14
+ including cache hits. The default verifier is application-owned
15
+ (`createEdgeWalletProofVerifier`): the agent signs each request in the
16
+ `valiron-wallet-request-v2` scheme (`x-agent-timestamp`,
17
+ `x-agent-nonce`, `x-agent-request-signature`; EVM owners sign with
18
+ EIP-191, Solana owners with Ed25519 - see
19
+ `docs/SECURITY-UPGRADE-2026-10-31.md`), and the Worker verifies the
20
+ signature against the agent's current registry owner wallet from the live
21
+ Valiron profile, enforces a 60-second timestamp window, and consumes the
22
+ nonce in a Durable Object so replays are rejected across all isolates. No
23
+ third-party identity provider is required for ordinary agents.
24
+ `VALIRON_VERIFIER=hosted` switches to Valiron's hosted ANS
25
+ provider-identity verification (`x-valiron-identity-*` headers via
26
+ `POST /operator/identity/verify`); that variant needs Valiron backend ANS
27
+ configuration and was not exercised in this template's isolated test
28
+ deployment.
29
+ 3. Evaluates the agent's live trust profile through the Valiron operator API
30
+ (operator-authenticated - `VALIRON_API_KEY` is required) and allows only
31
+ when routing is `prod` / `prod_throttled` AND the combined score meets
32
+ `VALIRON_MIN_SCORE` (default 65).
33
+ 4. On allow, strips client-supplied `x-valiron-gate-*` headers, sets its own
34
+ decision headers plus the shared `x-valiron-gate-secret`, and forwards to
35
+ the origin. On deny: 401 (missing identity / missing or invalid proof),
36
+ 403 (`TRUST_GATE_DENIED` or `AGENT_EVALUATION_PENDING`), or 503
37
+ fail-closed when evaluation fails or the durable nonce store is not
38
+ configured. Because the proof is checked first, an unreachable Valiron
39
+ API with the hosted verifier fails closed as 401
40
+ `AGENT_OWNERSHIP_REQUIRED`; with the default wallet verifier an owner-lookup failure also returns
41
+ 401. A failure during subsequent trust evaluation returns 503. The origin is
42
+ never touched on failure.
43
+
44
+ ## Who this is for, and whether it is required
45
+
46
+ This is an optional integration for a business that sells or exposes an API and
47
+ wants agent ownership and trust checks before requests reach its backend. The
48
+ business runs the Worker in its Cloudflare account, chooses the routes, score
49
+ threshold and trust signals, and protects its origin from direct access. The
50
+ backend can use any language. Valiron still serves profile reads and sandbox
51
+ evaluation; the default verifier also reads the current owner from Valiron.
52
+
53
+ Cloudflare is not required to use Valiron. Businesses can keep Node middleware,
54
+ call the API from their own enforcement code, or use this Worker. Use one
55
+ trust-gate layer per protected route. Agents calling those routes must identify
56
+ themselves and sign fresh requests. The gate verifies agent ownership and
57
+ applies the business's trust policy. Customer permissions, benefits and payment
58
+ authorization remain application responsibilities.
59
+
60
+
61
+ ## What has to be true before this is safe
62
+
63
+ 1. **The origin must reject anything that did not pass the gate.** The
64
+ Worker strips client-supplied `x-valiron-gate-*` headers and sets its
65
+ own, and forwards `x-valiron-gate-secret` when `VALIRON_ORIGIN_SECRET` is
66
+ set. The origin must reject requests missing that secret (or be
67
+ unreachable except through Cloudflare: Authenticated Origin Pull, Tunnel,
68
+ or a firewall rule). Otherwise the gate is bypassable by skipping the
69
+ Worker.
70
+ 2. **Replay protection is durable.** The default verifier refuses to run
71
+ without the `VALIRON_NONCE_STORE` Durable Object binding (503,
72
+ fail-closed). Nonces are claimed atomically in one named Durable Object
73
+ with a 121-second TTL matching the proof validity window, so a proof
74
+ replayed against any isolate - or after a restart - is rejected. The
75
+ in-memory `MemoryNonceStore` exported by the SDK is for local tests only;
76
+ it is not safe across isolates.
77
+ 3. **Enforce the gate at one layer per route.** If the origin also runs
78
+ `createValironGate` on the same routes, agents are evaluated twice (and
79
+ pay twice the latency). Attach the Worker to the gated routes and do not
80
+ run the origin gate there, or keep the origin gate and no Worker.
81
+ 4. **Every identified request needs a valid proof.** A request that names an
82
+ agent without a verifiable request-bound proof is denied
83
+ `401 AGENT_OWNERSHIP_REQUIRED` before trust evaluation. The default verifier needs a live owner lookup
84
+ to determine which key must sign. Do not weaken this to header claims alone.
85
+ 5. **The profile cache is per isolate.** `VALIRON_CACHE_TTL_MS` (default
86
+ 30000) matches the Node middleware's per-process cache: it bounds profile
87
+ re-reads inside one isolate and is not shared across isolates or colos.
88
+ The ownership proof is verified on every request regardless of cache.
89
+ Set it to `0` to disable.
90
+
91
+ ## Deploy
92
+
93
+ Copy this directory, install dependencies, configure `wrangler.toml`, set the
94
+ secrets, and deploy:
95
+
96
+ ```bash
97
+ cd examples/cloudflare-gate-worker
98
+ pnpm install # or npm install
99
+ wrangler secret put VALIRON_API_KEY # operator key (val_op_...)
100
+ wrangler secret put VALIRON_ORIGIN_SECRET # shared with your origin
101
+ wrangler deploy
102
+ ```
103
+
104
+ | Variable | Required | Purpose |
105
+ | --- | --- | --- |
106
+ | `VALIRON_ENDPOINT` | yes | Valiron operator API base |
107
+ | `VALIRON_API_KEY` | yes (secret) | Operator API key for profile reads (profile routes are operator-authenticated) |
108
+ | `VALIRON_NONCE_STORE` | yes (binding) | Durable Object namespace for replay protection (default verifier fails closed without it) |
109
+ | `VALIRON_ORIGIN_SECRET` | recommended (secret) | Shared secret forwarded to the origin as `x-valiron-gate-secret` |
110
+ | `VALIRON_MIN_SCORE` | no | Minimum combined score (default 65) |
111
+ | `VALIRON_GATE_PATHS` | no | Comma-separated gated path prefixes (default `/`) |
112
+ | `VALIRON_TRUST_SIGNALS` | no | Comma-separated signals; unset uses the server default set |
113
+ | `VALIRON_CACHE_TTL_MS` | no | Per-isolate profile cache TTL in ms (default 30000, 0 disables) |
114
+ | `VALIRON_VERIFIER` | no | `hosted` selects hosted ANS provider-identity verification (needs backend ANS configuration; untested in this template's isolated deployment) |
115
+ | `VALIRON_PUBLIC_ORIGIN` | hosted only | Audience for the hosted verifier variant |
116
+
117
+ Attach the Worker to the routes you want gated. Telemetry is best-effort at
118
+ the edge (the SDK's batched telemetry flush is timer-driven); use Workers
119
+ Logs / Logpush for operational visibility.
120
+
121
+ ## Agent side
122
+
123
+ Agents sign every request with the registry owner's private key in the
124
+ `valiron-wallet-request-v2` scheme. The SDK's hosted clients do this for you
125
+ via `signRequest`; from any stack the recipe is:
126
+
127
+ ```typescript
128
+ import { createHash, randomBytes } from "node:crypto";
129
+ import { privateKeyToAccount } from "viem/accounts";
130
+
131
+ const owner = privateKeyToAccount(process.env.AGENT_OWNER_PRIVATE_KEY as `0x${string}`);
132
+ const agentId = "25459"; // same value sent as x-agent-id
133
+ const chain = "ethereum"; // the agent's registry network string
134
+ const url = "https://api.example.com/api/paid"; // exact public URL
135
+ const body = JSON.stringify({ hello: "world" }); // or "" for no body
136
+
137
+ const timestamp = String(Date.now());
138
+ const nonce = randomBytes(24).toString("base64url");
139
+ const digest = createHash("sha256")
140
+ .update(body === "" ? "" : JSON.stringify(JSON.parse(body)))
141
+ .digest("hex");
142
+ const payload = [
143
+ "valiron-wallet-request-v2",
144
+ `agent:${agentId}`, `chain:${chain}`, `method:POST`, `url:${url}`,
145
+ `body-sha256:${digest}`, `timestamp:${timestamp}`, `nonce:${nonce}`,
146
+ ].join("\n");
147
+ const signature = await owner.signMessage({ message: payload }); // EIP-191
148
+
149
+ await fetch(url, {
150
+ method: "POST",
151
+ headers: {
152
+ "x-agent-id": agentId,
153
+ "x-agent-timestamp": timestamp,
154
+ "x-agent-nonce": nonce,
155
+ "x-agent-request-signature": signature,
156
+ "content-type": "application/json",
157
+ },
158
+ body,
159
+ });
160
+ ```
161
+
162
+ Solana owners sign the same UTF-8 payload with Ed25519 and send the signature
163
+ base64url-encoded; key-based web2 agents send `x-agent-address` and sign with
164
+ that address's key using chain `key`. Sign a fresh nonce and timestamp for
165
+ every request and every retry: consumed nonces are rejected for 121 seconds.
166
+ The URL signed must be the exact public URL as Cloudflare normalizes it; a
167
+ mismatch fails verification closed.
168
+
169
+ ## Workers-runtime regression harness
170
+
171
+ `test/edge-gate-worker/` runs this template under miniflare (real workerd, no
172
+ deploy): allow/deny decisions, both signing chains, proof enforcement,
173
+ replay rejection, fail-closed behavior, header stripping, path scoping and
174
+ the profile cache. See its README.
175
+
176
+ ## Origin targeting and nonce expiry
177
+
178
+ For a standalone `workers.dev` deployment, set `VALIRON_ORIGIN` to the fixed
179
+ HTTPS origin, for example `https://origin.example.com`. It must have no
180
+ credentials, path, query, or fragment and must differ from the incoming
181
+ origin. Leave it unset only when Cloudflare zone-route origin resolution is
182
+ configured. The Worker verifies the original incoming URL and body before
183
+ rewriting the destination. Path and query are preserved; caller-provided
184
+ URLs and host-like paths cannot select another host. Redirects from an
185
+ explicit origin are returned without following them, so trusted headers and
186
+ the origin secret are never sent to a redirect destination. Out-of-scope
187
+ paths are forwarded without the gate secret and cannot access protected
188
+ origin routes.
189
+
190
+ Durable Object nonce claims use a storage transaction and an explicit expiry
191
+ timestamp, not KV-only `expirationTtl`. A scheduled alarm removes expired
192
+ entries. Concurrent claims have exactly one winner; a claimed nonce stays
193
+ blocked until its 121-second expiry, including across isolates. Expiry makes
194
+ the nonce reusable but does not make an old signature fresh.
195
+
196
+ The template registers sandbox-trigger promises with `ExecutionContext.waitUntil` so pending evaluations can continue after the denial response. All inbound `x-valiron-gate-*` headers, including a forged origin secret, are stripped before forwarding.
197
+
198
+ Wallet proof freshness can be tightened with `maxAgeMs`; values above 60,000 ms are rejected. Durable nonce retention is 121 seconds to cover the entire 60-second past/future validity horizon, including its boundary.
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "valiron-cloudflare-gate-worker",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Valiron trust gate as a Cloudflare Worker (general middleware at the edge)",
6
+ "type": "module",
7
+ "scripts": {
8
+ "deploy": "wrangler deploy",
9
+ "dev": "wrangler dev",
10
+ "tail": "wrangler tail"
11
+ },
12
+ "dependencies": {
13
+ "@valiron/sdk": "^2.1.0",
14
+ "viem": "^2.21.0"
15
+ },
16
+ "devDependencies": {
17
+ "@cloudflare/workers-types": "^4.20241106.0",
18
+ "wrangler": "^3.87.0"
19
+ }
20
+ }