@valiron/sdk 2.0.0 → 2.1.1

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.
Files changed (38) hide show
  1. package/README.md +12 -0
  2. package/bin/valiron-card.mjs +211 -0
  3. package/dist/card.d.ts +565 -0
  4. package/dist/card.js +722 -0
  5. package/dist/clients.js +2 -2
  6. package/dist/edge.d.ts +87 -0
  7. package/dist/edge.js +164 -0
  8. package/dist/edgeGate.d.ts +146 -0
  9. package/dist/edgeGate.js +230 -0
  10. package/dist/edgeGateVerify.d.ts +146 -0
  11. package/dist/edgeGateVerify.js +243 -0
  12. package/dist/index.d.ts +1 -0
  13. package/dist/index.js +1 -0
  14. package/dist/middleware.d.ts +2 -0
  15. package/dist/middleware.js +6 -3
  16. package/dist/operatorSdk.d.ts +8 -0
  17. package/dist/operatorSdk.js +8 -0
  18. package/docs/API-REFERENCE.md +59 -80
  19. package/docs/CLOUDFLARE-GATE-MIDDLEWARE.md +196 -0
  20. package/docs/CRAWLER-PROTECTION.md +509 -25
  21. package/docs/DASHBOARD.md +72 -214
  22. package/docs/E2E-MIDDLEWARE-INTEGRATION.md +9 -46
  23. package/docs/ERRORS.md +3 -11
  24. package/docs/PROVIDER-IDENTITY.md +1 -1
  25. package/docs/QUICKSTART.md +7 -22
  26. package/docs/README.md +10 -9
  27. package/docs/SDK-REFERENCE.md +51 -7
  28. package/docs/SECURITY-UPGRADE-2026-10-31.md +3 -3
  29. package/docs/llms.txt +19 -14
  30. package/examples/cloudflare-gate-worker/README.md +198 -0
  31. package/examples/cloudflare-gate-worker/package.json +20 -0
  32. package/examples/cloudflare-gate-worker/worker.ts +309 -0
  33. package/examples/cloudflare-gate-worker/wrangler.toml +46 -0
  34. package/examples/cloudflare-worker/package.json +8 -0
  35. package/examples/cloudflare-worker/worker.ts +495 -0
  36. package/examples/cloudflare-worker/wrangler.toml +57 -0
  37. package/package.json +34 -4
  38. package/docs/AGENT-READY-APIS.md +0 -294
@@ -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 an operator API key for a Pro account with the Crawler Protection add-on (or Enterprise) 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
 
@@ -15,8 +17,6 @@ SDK 0.2.0+ requires a Free/Pro/Enterprise operator API key and account-bound act
15
17
  3. **Copy your API key** when it is shown; returning incomplete accounts can generate a dedicated setup key
16
18
  4. Add the SDK middleware below to the backend routes agents call. Choose registered, key-based, or ANS/provider-backed identity in the wizard.
17
19
 
18
- > **Tip:** Before writing any code, try the [API Playground](./DASHBOARD.md#api-playground) to see how Valiron evaluates agents at different trust levels against your endpoints.
19
-
20
20
  ## Step 1 — Install the SDK
21
21
 
22
22
  ```bash
@@ -198,7 +198,6 @@ Once your integration is live, use the [Operator Dashboard](./DASHBOARD.md) to:
198
198
  - **Agents** — See every agent that has called your API, sorted by activity, spend, or errors
199
199
  - **Analytics** — Track revenue, call volume, and top endpoints over time
200
200
  - **Call Logs** — Paginated log of every request with status codes, latency, and cost
201
- - **Playground** — Test how agents at different trust levels are evaluated against your endpoints
202
201
 
203
202
  ## Using the HTTP API directly (no SDK)
204
203
 
@@ -231,23 +230,6 @@ curl -X POST https://valiron-edge-proxy.onrender.com/operator/webhooks/register
231
230
  -d '{"event": "evaluation_complete", "url": "https://your-endpoint.com/hooks"}'
232
231
  ```
233
232
 
234
- ## Separate product — API Scaffolding
235
-
236
- Valiron middleware is the primary backend integration. API Scaffolding is a separate product for exposing an existing HTTPS API through a Valiron-hosted, agent-facing URL.
237
-
238
- 1. Open [valiron.co/dashboard](https://www.valiron.co/dashboard).
239
- 2. Choose **API Scaffolding → Endpoints & testing**.
240
- 3. Enter your public path, upstream API base URL, price, payment protocol, and optional trust settings.
241
- 4. Distribute the generated wrapper URL to agent clients:
242
-
243
- ```text
244
- https://valiron-edge-proxy.onrender.com/wrap/{operatorId}/{path}
245
- ```
246
-
247
- API Scaffolding can collect payment, apply optional trust checks, enforce rate limits, forward upstream, and log usage. For deployments requiring full backend control, protect the API directly with Valiron middleware using `createValironGate()` or `ValironOperator.paywall()`.
248
-
249
- ---
250
-
251
233
  ## Cleanup (long-running servers)
252
234
 
253
235
  Call `dispose()` when shutting down to flush pending telemetry:
@@ -265,7 +247,6 @@ process.on("SIGTERM", async () => {
265
247
 
266
248
  - **[End-to-End Middleware Integration](./E2E-MIDDLEWARE-INTEGRATION.md)** — Choose identity, trust signals, and a downstream policy for a production integration
267
249
  - **[Proxy Gateway](./SDK-REFERENCE.md#proxy-gateway)** — Forward requests through Valiron's edge proxy (Free)
268
- - **[API Scaffolding](./AGENT-READY-APIS.md)** — Create hosted x402/MPP wrappers for existing APIs
269
250
  - **[Key-Based Agents](./SDK-REFERENCE.md#key-based-agents)** — Support Web2 agents without on-chain identity
270
251
  - **[World ID](./SDK-REFERENCE.md#world-id-methods)** — Verify agent-human linkage
271
252
  - **[Self](./SDK-REFERENCE.md#self-methods)** — Create Self Enterprise sessions and verify eligible-human linkage
@@ -344,3 +325,7 @@ curl -H "Authorization: Bearer $VALIRON_API_KEY" -X POST "https://valiron-edge-p
344
325
  # Liveness check
345
326
  curl -H "Authorization: Bearer $VALIRON_API_KEY" "https://valiron-edge-proxy.onrender.com/operator/agent/1226/liveness?chain=solana"
346
327
  ```
328
+
329
+ 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 Protection or Agent Access calls at $0.001 each. 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.
330
+
331
+ 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
@@ -1,8 +1,8 @@
1
1
  # Valiron — Documentation
2
2
 
3
- Social Graph (Icebreaker) is a Pro feature. Bot protection is included with Free. All other capabilities are included with Free: 10,000 agent requests/month and 10,000 bot protection requests/month, 3 registered endpoints, and 5 sandbox runs/day. Pro includes 100,000 requests per product/month. Enterprise: email founders@valiron.co. Operator authentication and tenant isolation apply on every plan.
3
+ Each product includes 10,000 requests a month on Free and 100,000 on Pro ($149/month), then $0.001 per additional request once enabled. Social Graph (Icebreaker) is Pro only. Crawler Protection traffic insights and the edge rules simulator are included with Pro; Crawler Protection enforcement (Cloudflare, AWS WAF, and the SDK/gateway runtime) is a $29.99/month add-on to Pro. Everything else in Agent Access is included with Free, with 5 sandbox runs/day. Enterprise: email founders@valiron.co. Operator authentication and tenant isolation apply on every plan.
4
4
 
5
- Choose a product in the [documentation home](https://www.valiron.co/docs): [Crawler Protection](https://www.valiron.co/docs/crawler-protection), [Agent Access](https://www.valiron.co/docs/agent-access), or [API Scaffolding](https://www.valiron.co/docs/api-scaffolding). Each product has its own setup guide and navigation; accounts and billing are shared. The Markdown references below retain their existing URLs.
5
+ Choose a product in the [documentation home](https://www.valiron.co/docs): [Crawler Protection](https://www.valiron.co/docs/crawler-protection) or [Agent Access](https://www.valiron.co/docs/agent-access). Each product has its own setup guide and navigation; accounts and billing are shared. The Markdown references below retain their existing URLs.
6
6
 
7
7
 
8
8
  > **Protect your API endpoints from bad or malicious AI agents.** This documentation covers how to integrate Valiron into your API to gate, score, and sandbox agents before they reach your infrastructure.
@@ -13,22 +13,19 @@ Valiron is trust infrastructure for API sellers. It evaluates AI agents using on
13
13
 
14
14
  **If you sell APIs**, Valiron's core product is middleware deployed within the API backend through the SDK. It provides direct control over trust checks, routing, sandboxing, payment gating, and analytics before requests reach application handlers.
15
15
 
16
- Valiron also provides **API Scaffolding** as a separate product for organizations that require a hosted, agent-facing wrapper URL for an existing HTTPS API. It can add x402/MPP payment challenges, optional trust checks, rate limits, upstream forwarding, and logging without requiring backend code changes. Scaffolding can serve as an evaluation path before adopting a first-party backend integration protected by Valiron middleware.
17
-
18
16
  ## Documentation Index
19
17
 
20
18
  | File | Purpose |
21
19
  |------|---------|
22
20
  | [QUICKSTART.md](./QUICKSTART.md) | Install the SDK, configure caller verification and gate an endpoint |
23
21
  | [E2E-MIDDLEWARE-INTEGRATION.md](./E2E-MIDDLEWARE-INTEGRATION.md) | End-to-end middleware integration — identity, trust signals, downstream policy, and testing |
24
- | [AGENT-READY-APIS.md](./AGENT-READY-APIS.md) | API Scaffolding — hosted x402/MPP wrappers for existing APIs |
25
- | [DASHBOARD.md](./DASHBOARD.md) | Operator Dashboard — manage endpoints, keys, analytics, and playground |
22
+ | [DASHBOARD.md](./DASHBOARD.md) | Operator Dashboard — manage keys, agents, analytics, and logs |
26
23
  | [API-REFERENCE.md](./API-REFERENCE.md) | Complete HTTP API reference with request/response schemas |
27
24
  | [SDK-REFERENCE.md](./SDK-REFERENCE.md) | TypeScript SDK methods, signatures, and usage examples |
28
25
  | [TRUST-MODEL.md](./TRUST-MODEL.md) | How agents are scored, what behaviors are penalized, tier assignments |
29
26
  | [IDENTITY.md](./IDENTITY.md) | Agent identity — ERC-8004/Solana agents and key-based Web2 agents |
30
27
  | [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 |
28
+ | [CRAWLER-PROTECTION.md](./CRAWLER-PROTECTION.md) | Valiron Crawler Protection — read-only traffic insights from request logs (Pro) (Cloudflare, AWS WAF, CloudFront, server logs or SDK request log); 0.6.0 official AI source verification, explicit allow/block defaults, shared quotas, HTTP gateway and language-neutral work admission |
32
29
  | [SANDBOX.md](./SANDBOX.md) | How the sandbox evaluates agents and determines production readiness |
33
30
  | [CHAINS.md](./CHAINS.md) | Supported blockchain networks and contract addresses |
34
31
  | [ERRORS.md](./ERRORS.md) | Error codes, troubleshooting, and retry guidance |
@@ -42,8 +39,6 @@ Valiron also provides **API Scaffolding** as a separate product for organization
42
39
  - **Trust Tier**: AAA (highest trust) → C (lowest trust). Assigned based on behavioral evaluation.
43
40
  - **Risk Level**: GREEN, YELLOW, or RED.
44
41
  - **Route Decision**: `prod`, `prod_throttled`, `sandbox`, or `sandbox_only` — determines what access level your API should give.
45
- - **API Scaffolding**: A separate hosted Valiron wrapper product at `/wrap/{operatorId}/{path}` that can collect x402/MPP payments, optionally gate by trust, and forward to an upstream API.
46
- - **Payment Protocol**: `x402` for Base/USDC HTTP payments or `mpp` for Machine Payment Protocol payments through Tempo.
47
42
  - **Sandbox**: An isolated test environment where Valiron evaluates agent behavior before granting production access.
48
43
  - **Wallet Intelligence**: A Free trust signal that converts bounded Alchemy or Helius wallet history into an explainable score, risk level, confidence, and reasons.
49
44
  - **Liveness** (Solana only): Endpoint health probe via `isItAlive()`. See [API-REFERENCE.md](./API-REFERENCE.md#solana-support).
@@ -87,3 +82,9 @@ https://valiron-edge-proxy.onrender.com
87
82
  ## Upgrading an existing integration
88
83
 
89
84
  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.
85
+
86
+ Both products include 100,000 requests on Pro, then $0.001 per additional call with separate opt-ins. See [monthly request billing](./API-REFERENCE.md#monthly-request-allowance).
87
+
88
+ 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.
89
+
90
+ 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.
@@ -4,13 +4,15 @@
4
4
 
5
5
  See the [security upgrade guide](SECURITY-UPGRADE-2026-10-31.md) before upgrading existing integrations: trust gates require request-bound identity verification, and enrollment and signed-request contracts have changed.
6
6
 
7
- Social Graph (Icebreaker) is a Pro feature. Bot protection is included with Free. All other capabilities are included with Free: 10,000 agent requests/month and 10,000 bot protection requests/month, 3 registered endpoints, and 5 sandbox runs/day. Pro includes 100,000 requests per product/month. Enterprise: email founders@valiron.co. Operator authentication and tenant isolation apply on every plan.
7
+ Each product includes 10,000 requests a month on Free and 100,000 on Pro ($149/month), then $0.001 per additional request once enabled. Social Graph (Icebreaker) is Pro only. Crawler Protection traffic insights and the edge rules simulator are included with Pro; Crawler Protection enforcement (Cloudflare, AWS WAF, and the SDK/gateway runtime) is a $29.99/month add-on to Pro. Everything else in Agent Access is included with Free, with 5 sandbox runs/day. Enterprise: email founders@valiron.co. Operator authentication and tenant isolation apply on every plan.
8
8
 
9
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 an operator API key for a Pro account with the Crawler Protection add-on (or Enterprise) 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
 
@@ -302,7 +304,7 @@ console.log(result.valironScore); // 85
302
304
 
303
305
  ### gate(agentId, options?)
304
306
 
305
- Low-level hosted gate combining on-chain reputation and sandbox tests. The HTTP endpoint requires an operator API key plus a fresh registry-owner signature bound to this request. Configure `signRequest` with the [wallet-request v2 contract](./SECURITY-UPGRADE-2026-10-31.md#hosted-wrappers-gates-and-proxy). An API key, a claimed address, or a prior agent session alone is insufficient. Local middleware instead calls your `verifyRequest` verifier before authenticated profile reads.
307
+ Low-level hosted gate combining on-chain reputation and sandbox tests. The HTTP endpoint requires an operator API key plus a fresh registry-owner signature bound to this request. Configure `signRequest` with the [wallet-request v2 contract](./SECURITY-UPGRADE-2026-10-31.md#hosted-gates-and-proxy). An API key, a claimed address, or a prior agent session alone is insufficient. Local middleware instead calls your `verifyRequest` verifier before authenticated profile reads.
306
308
 
307
309
  ```typescript
308
310
  const result = await valiron.gate(agentId: string, options?: {
@@ -678,7 +680,7 @@ Deprecated; retained for compatibility until the next major SDK release. Not sup
678
680
 
679
681
  ## Telemetry
680
682
 
681
- The SDK collects opt-out usage telemetry to improve reliability. Events include SDK version, runtime, environment, method names, chain labels, latency, HTTP status/error buckets, route decisions, and coarse score/reputation buckets. Raw agent IDs, wallet addresses, API keys, and exact scores are not sent in SDK telemetry. Operator usage reporting is separate and disabled by default. Set `analytics: true` on `new ValironOperator(...)` to opt in. It reports authenticated decision/identity labels, method, status, latency and price; raw IP addresses, user agents, URL paths/query strings and arbitrary error messages are omitted or redacted. This option does not enable or disable SDK diagnostic telemetry.
683
+ The SDK collects opt-out usage telemetry to improve reliability. Events include SDK version, runtime, environment, method names, chain labels, latency, HTTP status/error buckets, route decisions, and coarse score/reputation buckets. Raw agent IDs, wallet addresses, API keys, and exact scores are not sent in SDK telemetry.
682
684
 
683
685
  SDK reports are anonymous client reports and may be sampled. Signal counts describe reported selections, not successful verifications. Version comes from the shipped package metadata. Environment defaults to recognized `NODE_ENV` values (`production` → `prod`, `development` → `dev`, `test` → `test`), otherwise `unknown`; set it explicitly for browser applications. Telemetry observer failures do not affect API calls.
684
686
 
@@ -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
@@ -912,7 +949,6 @@ Headers attached to proxied/gated requests:
912
949
  ```typescript
913
950
  import {
914
951
  ValironSDK,
915
- ValironOperator,
916
952
  ValironClient,
917
953
  createValironGate,
918
954
  valironFastifyPlugin,
@@ -949,7 +985,15 @@ import {
949
985
  | World ID and Self | ✓ | ✓ |
950
986
  | Social Graph (Icebreaker) | — | ✓ |
951
987
  | Valiron Crawler Protection | ✓ | ✓ |
952
- | Monthly agent requests | 10,000 | 100,000 |
953
- | Monthly bot protection requests | 10,000 | 100,000 |
988
+ | Monthly Agent Access requests | 10,000 | 100,000 |
989
+ | Monthly Crawler Protection requests | 10,000 | 100,000 |
954
990
 
955
991
  Pro plan requires an operator API key (`val_op_` prefix) from the [Operator Dashboard](./DASHBOARD.md).
992
+
993
+ 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 Protection or Agent Access calls at $0.001 each. 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.
994
+
995
+ 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.
996
+
997
+ ## Crawler managed controls (0.7.0+)
998
+
999
+ `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#managed-controls) for the setup, API endpoints, leases and retention limits.
@@ -12,7 +12,7 @@ For provider-backed identities, use the built-in identity middleware described i
12
12
 
13
13
  New agents remain denied while their real sandbox evaluation is pending. Provisional simulations do not establish behavioral reputation.
14
14
 
15
- ## Hosted wrappers, gates and proxy
15
+ ## Hosted gates and proxy
16
16
 
17
17
  SDK clients can provide a `signRequest({ method, url, body, chain })` callback in `ValironConfig`. It returns the proof headers for the actual URL and serialized body; signing finishes before the network timeout starts. The signer must create a new nonce and timestamp for each call.
18
18
 
@@ -31,7 +31,7 @@ nonce:<fresh-nonce>
31
31
 
32
32
  The body hash covers `JSON.stringify` of the parsed JSON body, or the empty string for a request without a body. The server checks the current registry owner and atomically consumes the nonce. Send a newly signed request for each retry. Provider-identity middleware instead hashes exact raw body bytes; these are separate proof protocols.
33
33
 
34
- Only admitted requests consume a hosted wrapper's monthly quota. Crawler Protection applies local rate and access decisions before monthly admission; monthly exhaustion still prevents origin work.
34
+ Crawler Protection applies local rate and access decisions before monthly admission; monthly exhaustion still prevents origin work.
35
35
 
36
36
  ## Identity enrollment and endpoints
37
37
 
@@ -45,7 +45,7 @@ Operator usage analytics now require explicit `analytics: true`. Raw IP addresse
45
45
 
46
46
  ## Upgrade checklist
47
47
 
48
- 1. Configure application-owned verifiers for local gates and paywalls. An invalid or absent verifier returns `AGENT_OWNERSHIP_REQUIRED` (401); failed trust checks return 403.
48
+ 1. Configure application-owned verifiers for local gates. An invalid or absent verifier returns `AGENT_OWNERSHIP_REQUIRED` (401); failed trust checks return 403.
49
49
  2. Configure hosted request signers and migrate provider identities to proof v2. Each payment retry also needs a new identity nonce.
50
50
  3. Re-verify older World ID/Self links and re-register operator/chain-scoped webhook subscriptions. Expect cold reputation decisions to deny until a real evaluation completes.
51
51
  4. Enable operator analytics only with explicit `analytics: true`; SDK diagnostic telemetry remains separately configured.
package/docs/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # Valiron
2
2
 
3
- Valiron provides decision-time agent access control, crawler protection and a separate hosted API Scaffolding product. These documents describe the hardened source contract. Merging source, publishing npm packages and deploying production services are separate steps; confirm the installed version supports the verifier/signer and provider proof v2 contract before upgrading.
3
+ Valiron provides decision-time agent access control and crawler protection. These documents describe the hardened source contract. Merging source, publishing npm packages and deploying production services are separate steps; confirm the installed version supports the verifier/signer and provider proof v2 contract before upgrading.
4
4
 
5
5
  ## Documentation
6
6
 
@@ -14,7 +14,6 @@ Valiron provides decision-time agent access control, crawler protection and a se
14
14
  - Identity and enrollment: https://www.valiron.co/docs/agents/IDENTITY.md
15
15
  - Key enrollment: https://www.valiron.co/auth.md
16
16
  - Crawler protection: https://www.valiron.co/docs/agents/CRAWLER-PROTECTION.md
17
- - Hosted wrappers: https://www.valiron.co/docs/agents/AGENT-READY-APIS.md
18
17
  - Dashboard: https://www.valiron.co/docs/agents/DASHBOARD.md
19
18
  - Trust model: https://www.valiron.co/docs/agents/TRUST-MODEL.md
20
19
  - Errors: https://www.valiron.co/docs/agents/ERRORS.md
@@ -26,13 +25,13 @@ Create an operator account at https://www.valiron.co/dashboard. Password signup
26
25
 
27
26
  Profile/status reads and trust operations require Authorization: Bearer val_op_.... Missing, invalid or revoked credentials return 401. Health and key-registration challenge/verify are intentionally accessible without an operator key. Key enrollment establishes possession of that key, not authority for later requests. The private Icebreaker view accepts a Pro operator key or a verified agent session scoped to its own address. Legacy global evaluation histories and platform statistics are administrator-only; use account-scoped dashboard analytics.
28
27
 
29
- Profiles return allowlisted identity/trust summaries, not raw behavioral metrics, evidence-storage URLs, credential subjects or nullifiers. Social Graph (Icebreaker) is Pro; standard identity, World ID, Self, wallet signals and crawler protection are included with Free within limits.
28
+ Profiles return allowlisted identity/trust summaries, not raw behavioral metrics, evidence-storage URLs, credential subjects or nullifiers. Social Graph (Icebreaker) is Pro; standard identity, World ID, Self and wallet signals are included with Free within limits. Crawler Protection needs Pro, and enforcement is a $29.99/month add-on.
30
29
 
31
30
  ## Fresh request verification
32
31
 
33
32
  x-agent-id identifies an ERC-8004 token ID or Solana asset/indexed ID. x-agent-address identifies a persistent Ethereum-style key-based agent. Neither header proves the current caller controls that identity.
34
33
 
35
- createValironGate, valironFastifyPlugin, createValironNextMiddleware and operator paywalls require verifyRequest(request, identifier). valironGateCheck requires verifyRequest(identifier); capture the current request in that callback. The verifier is application-owned, not a header-presence test or an SDK stub. Verify cryptographic control, identity, method, full URL, body, freshness and atomic nonce replay protection. It runs before cached reputation. Missing/invalid proof returns AGENT_OWNERSHIP_REQUIRED (401). Profile lookup, prior key enrollment, human linkage and payment do not replace action authorization.
34
+ createValironGate, valironFastifyPlugin, createValironNextMiddleware require verifyRequest(request, identifier). valironGateCheck requires verifyRequest(identifier); capture the current request in that callback. The verifier is application-owned, not a header-presence test or an SDK stub. Verify cryptographic control, identity, method, full URL, body, freshness and atomic nonce replay protection. It runs before cached reputation. Missing/invalid proof returns AGENT_OWNERSHIP_REQUIRED (401). Profile lookup, prior key enrollment, human linkage and payment do not replace action authorization.
36
35
 
37
36
  Cached decisions include signal selection and score threshold. Pending or provisional sandbox results deny production access. A real completed evaluation is required. Preserve the same identity and retry with a new proof after retryAfterMs.
38
37
 
@@ -76,30 +75,36 @@ Self session creation also requires operator and owner approval. Only new owner-
76
75
 
77
76
  ## Pricing, quotas and billing
78
77
 
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.
78
+ Free: 10,000 Agent Access requests and a separate 10,000 Crawler Protection requests per UTC calendar month 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 and require separate explicit opt-in.
80
79
 
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.
80
+ Crawler local access/rate denials precede monthly admission. Database operations are not counted as additional monthly crawler requests. Storage failures fail closed.
82
81
 
83
82
  Checkout/subscriptions are bound to the authenticated operator's customer identity, not a supplied checkout email. Promotion eligibility is handled by Stripe checkout. Successful password resets revoke existing operator sessions and API keys; sign in again and replace affected integration keys.
84
83
 
85
- ## Hosted API Scaffolding
84
+ ## Crawler Protection
86
85
 
87
- Configure an existing public HTTPS upstream in Dashboard → API Scaffolding. Agents call /wrap/{operatorId}/{path}. Wrappers apply configured payment (x402 or MPP), trust, rate and forwarding policies. Protect origins against direct bypass using HMAC upstream authentication; x-valiron-* metadata is not an origin credential.
86
+ Observability (read-only, Pro and Enterprise): connect request logs to see verified crawlers, spoofed crawler claims, other declared automation and unclassified traffic by route, without installing the runtime or changing traffic. Sources: Cloudflare Logpush (HTTP destination), AWS WAF or CloudFront real-time logs through Amazon Data Firehose, file uploads (CloudFront, ALB, nginx/Apache/Caddy combined, Vercel, Cloudflare, WAF, Valiron NDJSON), any log shipper posting to POST /ingest/crawler/logs/:connectionId with a per-connection vcl_ token, or createCrawlerRequestLog() from @valiron/crawler-protection for sites without log access. Query strings, cookies and headers other than User-Agent are discarded; client IPs are stored only as keyed hashes. Unclassified traffic is never labeled human. Guide: https://www.valiron.co/docs/crawler-protection/observability. Policy simulator and edge protection: replay a policy against observed traffic (exact block matches, rate limits estimated with Cloudflare or AWS WAF counting), then, with the Crawler Protection add-on ($29.99/month on top of Pro), deploy it as Valiron-managed Cloudflare or AWS WAF rules. The dashboard shows Protecting only after provider read-back; turning off removes only Valiron rules. Guide: https://www.valiron.co/docs/crawler-protection/edge-protection
88
87
 
89
- Trust-enabled wrappers require x-agent-id, x-chain matching the signed network, and the fresh owner-proof headers above. A payment proof alone is insufficient. A signed payment retry must use a new identity nonce. Only supported on-chain identities are accepted here; use your own SDK middleware for key-based agents. Disabling wrapper trust skips identity/trust policy, not rate, monthly quota or safe-forwarding controls.
88
+ 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.
90
89
 
91
- ## Crawler Protection
90
+ 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.
92
91
 
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.
92
+ 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.
94
93
 
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.
94
+ 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
95
 
97
- 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.
96
+ Use a server-side operator key (Pro with the Crawler Protection add-on, or Enterprise) 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
97
 
99
98
  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
99
 
100
+ 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.
101
+
101
102
  ## Reporting and errors
102
103
 
103
- 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
+ SDK diagnostic telemetry remains separately configurable with telemetry.enabled (default true); disable with telemetry: {enabled:false}. 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
105
 
105
106
  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.
107
+
108
+ 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 Protection or Agent Access calls at $0.001 each. 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.
109
+
110
+ 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
+ }