@valiron/sdk 1.4.0 → 2.0.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/README.md CHANGED
@@ -1,5 +1,10 @@
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.
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.
6
+
7
+
3
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.
4
9
 
5
10
  ## What is Valiron?
@@ -14,7 +19,7 @@ Valiron also provides **API Scaffolding** as a separate product for organization
14
19
 
15
20
  | File | Purpose |
16
21
  |------|---------|
17
- | [QUICKSTART.md](./QUICKSTART.md) | Get started in under 2 minutes — install the SDK, gate your first endpoint |
22
+ | [QUICKSTART.md](./QUICKSTART.md) | Install the SDK, configure caller verification and gate an endpoint |
18
23
  | [E2E-MIDDLEWARE-INTEGRATION.md](./E2E-MIDDLEWARE-INTEGRATION.md) | End-to-end middleware integration — identity, trust signals, downstream policy, and testing |
19
24
  | [AGENT-READY-APIS.md](./AGENT-READY-APIS.md) | API Scaffolding — hosted x402/MPP wrappers for existing APIs |
20
25
  | [DASHBOARD.md](./DASHBOARD.md) | Operator Dashboard — manage endpoints, keys, analytics, and playground |
@@ -23,6 +28,7 @@ Valiron also provides **API Scaffolding** as a separate product for organization
23
28
  | [TRUST-MODEL.md](./TRUST-MODEL.md) | How agents are scored, what behaviors are penalized, tier assignments |
24
29
  | [IDENTITY.md](./IDENTITY.md) | Agent identity — ERC-8004/Solana agents and key-based Web2 agents |
25
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 |
26
32
  | [SANDBOX.md](./SANDBOX.md) | How the sandbox evaluates agents and determines production readiness |
27
33
  | [CHAINS.md](./CHAINS.md) | Supported blockchain networks and contract addresses |
28
34
  | [ERRORS.md](./ERRORS.md) | Error codes, troubleshooting, and retry guidance |
@@ -31,7 +37,7 @@ Valiron also provides **API Scaffolding** as a separate product for organization
31
37
 
32
38
  - **Agent ID**: An agent's ERC-8004 token ID (EVM) or Metaplex Core asset pubkey (Solana) — their on-chain identity. Use this with `x-agent-id` and `/operator/agent/:agentId`.
33
39
  - **Key-Based Agent Address**: A persistent Ethereum-style address for a local, Web2, or non-ERC-8004 agent. Use this with `x-agent-address` and `/operator/key/:agentAddress`.
34
- - **Provider-Backed Identity**: An ANS or future provider identity verified through `ValironSDK.verifyAgentIdentity()`. SDK 1.3 includes signing helpers and dedicated Express, Fastify, Next.js, and generic identity gates. Valiron hosts the ANS credentials and CA configuration.
40
+ - **Provider-Backed Identity**: An ANS or future provider identity verified through `ValironSDK.verifyAgentIdentity()`. The SDK includes signing helpers and dedicated Express, Fastify, Next.js, and generic identity gates. Valiron hosts the ANS credentials and CA configuration.
35
41
  - **Sequential ID** (Solana only): A convenience integer (1, 2, 42…) assigned by the QuantuLabs indexer. Maps to an asset pubkey.
36
42
  - **Trust Tier**: AAA (highest trust) → C (lowest trust). Assigned based on behavioral evaluation.
37
43
  - **Risk Level**: GREEN, YELLOW, or RED.
@@ -39,11 +45,13 @@ Valiron also provides **API Scaffolding** as a separate product for organization
39
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.
40
46
  - **Payment Protocol**: `x402` for Base/USDC HTTP payments or `mpp` for Machine Payment Protocol payments through Tempo.
41
47
  - **Sandbox**: An isolated test environment where Valiron evaluates agent behavior before granting production access.
42
- - **Wallet Intelligence**: A Pro trust signal that converts bounded Alchemy or Helius wallet history into an explainable score, risk level, confidence, and reasons.
48
+ - **Wallet Intelligence**: A Free trust signal that converts bounded Alchemy or Helius wallet history into an explainable score, risk level, confidence, and reasons.
43
49
  - **Liveness** (Solana only): Endpoint health probe via `isItAlive()`. See [API-REFERENCE.md](./API-REFERENCE.md#solana-support).
44
50
 
45
51
  ## Which Identity Path Should I Use?
46
52
 
53
+ Ordinary website crawlers need not enroll as key-based or on-chain agents. Their supported source-check path is the separate [Valiron Crawler Protection](./CRAWLER-PROTECTION.md). Network provenance is not signed agent identity, human identity or unlimited permission to crawl.
54
+
47
55
  | Agent type | Use this identifier | Request header | Lookup path |
48
56
  |------------|---------------------|----------------|-------------|
49
57
  | ERC-8004 / on-chain EVM agent | ERC-8004 token ID | `x-agent-id` | `/operator/agent/:agentId` |
@@ -74,5 +82,8 @@ https://valiron-edge-proxy.onrender.com
74
82
  ## Developer interfaces
75
83
 
76
84
  - [Valiron OpenAPI](https://www.valiron.co/openapi.json)
77
- - [Valiron MCP server setup](./MCP.md)
78
85
  - [Valiron developer portal](https://www.valiron.co/developers)
86
+
87
+ ## Upgrading an existing integration
88
+
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.
package/docs/SANDBOX.md CHANGED
@@ -33,7 +33,7 @@ You can proactively evaluate agents before they hit your production endpoints, o
33
33
  ```typescript
34
34
  import { ValironSDK } from "@valiron/sdk";
35
35
 
36
- const valiron = new ValironSDK();
36
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
37
37
 
38
38
  // On-chain agent
39
39
  const result = await valiron.triggerSandboxTest("YOUR_AGENT_ID");
@@ -138,3 +138,9 @@ Solana reputation includes ATOM engine metrics that EVM agents don't have:
138
138
  | `uniqueCallers` | Number of distinct feedback submitters |
139
139
 
140
140
  These appear in the sandbox/gate response under `onchainReputation.solana` and are factored into the final Valiron risk score alongside the standard behavioral penalties.
141
+
142
+ ## Authorization and pending evaluations
143
+
144
+ Trigger evaluations through the authenticated Valiron operator API. Sandbox work resources require a short-lived capability scoped to the evaluated agent; a resource ID alone is not authorization. Agents never receive observer-control credentials. Provisional or synthetic gate results do not authorize production traffic. New agents remain denied while their real evaluation is pending; retry with the same identity and a fresh request proof after the indicated delay.
145
+
146
+ Agent metadata and probe targets must resolve to permitted public HTTPS destinations. Private/link-local addresses, redirects and overlarge or timed-out responses are rejected; response bodies do not expose internal transport errors.
@@ -1,7 +1,17 @@
1
1
  # SDK Reference
2
2
 
3
+ > **Request verification:** Examples using `verifyAgentRequest` assume an application-owned verifier imported from your own module, not an SDK export. It must verify a fresh signature against the claimed identity, bind method, full URL and body, and atomically reject replayed nonces. See the [request-proof upgrade guide](https://www.valiron.co/docs/agents/SECURITY-UPGRADE-2026-10-31.md). Missing or invalid proofs return 401 before profile-cache lookup.
4
+
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
+
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.
8
+
3
9
  Package: `@valiron/sdk`
4
10
 
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
+
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.
14
+
5
15
  ## Installation
6
16
 
7
17
  ```bash
@@ -22,12 +32,13 @@ const valiron = new ValironSDK(config?: ValironConfig);
22
32
 
23
33
  | Field | Type | Default | Description |
24
34
  |-------|------|---------|-------------|
25
- | `apiKey` | string | — | Operator API key. Optional for basic reads; required for sandbox runs; Pro is required for paid signals, enriched profiles, proxy calls, and webhooks |
35
+ | `apiKey` | string | — | Operator API key. Required for profile/status reads, trust gates, and sandbox runs; Pro is required only for Social Graph (Icebreaker); other capabilities are Free within usage limits |
26
36
  | `endpoint` | string | `https://valiron-edge-proxy.onrender.com` | API base URL |
27
37
  | `chain` | SupportedChain | `"ethereum"` | Default blockchain network |
28
38
  | `timeout` | number | method-aware | Request timeout in milliseconds. Defaults are 10s generally, 15s for `gate()`/`proxy()`, and 30s for sandbox triggers. If set, this value overrides all method-aware defaults. |
29
39
  | `debug` | boolean | `false` | Enable debug logging |
30
- | `telemetry` | TelemetryConfig | — | Optional telemetry configuration |
40
+ | `telemetry` | TelemetryConfig | — | Optional SDK diagnostic telemetry configuration |
41
+ | `signRequest` | `(request: { method: "POST"; url: string; body: string; chain?: SupportedChain }) => Promise<Record<string, string>>` | — | Fresh owner-proof headers for each POST; required by hosted gate/proxy and human enrollment flows. Keys remain in your signer. |
31
42
 
32
43
  ### SupportedChain
33
44
 
@@ -77,7 +88,7 @@ if (route === "prod") {
77
88
 
78
89
  **Solana example**:
79
90
  ```typescript
80
- const valiron = new ValironSDK({ chain: "solana" });
91
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: "solana" });
81
92
 
82
93
  // By asset pubkey
83
94
  const route = await valiron.checkAgent("DFkntsJ9aTCHkK88m6WZVQEvLdLNi4X1LVUgRMqetFPM");
@@ -107,7 +118,6 @@ interface AgentProfile {
107
118
  onchainReputation: OnchainReputation;
108
119
  routing: {
109
120
  finalRoute: RouteDecision;
110
- meetsThreshold: boolean;
111
121
  };
112
122
  chain: ChainContext;
113
123
  timestamp: string;
@@ -118,13 +128,12 @@ interface AgentProfile {
118
128
  ```typescript
119
129
  const profile = await valiron.getAgentProfile("25459");
120
130
  console.log(profile.routing.finalRoute); // "prod"
121
- console.log(profile.routing.meetsThreshold); // true
122
131
  console.log(profile.onchainReputation.averageScore); // 92.5
123
132
  ```
124
133
 
125
134
  **Solana example**:
126
135
  ```typescript
127
- const valiron = new ValironSDK({ chain: "solana" });
136
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: "solana" });
128
137
  const profile = await valiron.getAgentProfile("1226"); // sequential ID works
129
138
 
130
139
  console.log(profile.identity.name); // "NoahScout_Bot.noah"
@@ -152,7 +161,7 @@ console.log(profile.routing.finalRoute);
152
161
 
153
162
  **Solana example**:
154
163
  ```typescript
155
- const valiron = new ValironSDK({ chain: "solana" });
164
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: "solana" });
156
165
  const profile = await valiron.getWalletProfile("VSAnVX4MQjEXreHc92iHxWuXPQZ1tjwiKccpFLCgLM9");
157
166
  ```
158
167
 
@@ -160,7 +169,7 @@ const profile = await valiron.getWalletProfile("VSAnVX4MQjEXreHc92iHxWuXPQZ1tjwi
160
169
 
161
170
  ### getWalletRisk(wallet, options?)
162
171
 
163
- Return an explainable wallet-history assessment. This is a Pro feature and requires an operator API key.
172
+ Return an explainable wallet-history assessment. This is included with Free and requires an operator API key.
164
173
 
165
174
  ```typescript
166
175
  const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
@@ -185,7 +194,7 @@ Supported history networks are Ethereum, Base, Arbitrum, Optimism, Polygon, and
185
194
 
186
195
  Lightweight wallet → agentId resolution without the full trust profile. Useful when you only need to know which agent owns a wallet (e.g. after extracting a wallet from an x402 payment header).
187
196
 
188
- Resolution chain: Redis → in-memory cache → Agent0 subgraph → null.
197
+ Wallet resolution returns the associated agent ID when available.
189
198
 
190
199
  Signature: `resolveWallet(wallet: string, options?: { chain?: SupportedChain }): Promise<WalletResolution>`
191
200
 
@@ -212,9 +221,10 @@ if (resolution.agentId) {
212
221
 
213
222
  **Solana example**:
214
223
  ```typescript
215
- const valiron = new ValironSDK({ chain: "solana" });
224
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: "solana" });
216
225
  const resolution = await valiron.resolveWallet("VSAnVX4MQjEXreHc92iHxWuXPQZ1tjwiKccpFLCgLM9");
217
- // resolution.source will be "solana" instead of "redis" | "subgraph"
226
+ // Solana matches return source "solana_registry"; no match returns "none".
227
+ // The SDK 1.4 ResolutionSource type does not yet include "solana_registry".
218
228
  ```
219
229
 
220
230
  ---
@@ -292,7 +302,7 @@ console.log(result.valironScore); // 85
292
302
 
293
303
  ### gate(agentId, options?)
294
304
 
295
- Trust gate — single call for allow/deny decisions. Combines on-chain reputation and sandbox tests. Designed for payment protocol protection (x402, etc.).
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.
296
306
 
297
307
  ```typescript
298
308
  const result = await valiron.gate(agentId: string, options?: {
@@ -351,9 +361,7 @@ interface AgentSnapshotSummary {
351
361
  agentId: string;
352
362
  snapshotHash: string; // deterministic SHA-256 hash of behavioral evaluation (opaque)
353
363
  previousHash: string; // hash from prior evaluation, or "0x0" for first
354
- encryptedDataUri: string | null; // IPFS CID of encrypted snapshot data, if available
355
364
  timestamp: string | null; // ISO 8601 timestamp of evaluation
356
- interactionCount: number; // total interactions in the evaluation window
357
365
  }
358
366
  ```
359
367
 
@@ -362,7 +370,6 @@ interface AgentSnapshotSummary {
362
370
  const snapshot = await valiron.getAgentSnapshot("25459");
363
371
  console.log(snapshot.snapshotHash); // "0x3a7f..."
364
372
  console.log(snapshot.previousHash); // "0x0" (genesis) or "0x8b2c..."
365
- console.log(snapshot.interactionCount); // 15
366
373
  ```
367
374
 
368
375
  **Notes**:
@@ -374,7 +381,7 @@ console.log(snapshot.interactionCount); // 15
374
381
 
375
382
  ### verifyAgentIdentity(proof, policy?)
376
383
 
377
- Verifies an ANS or other provider-backed identity, loads Valiron reputation,
384
+ Verifies a provider proof v2 bound to audience, method, full URL and the exact raw-body digest, loads Valiron reputation,
378
385
  and returns the requested policy decision.
379
386
 
380
387
  ```typescript
@@ -401,7 +408,7 @@ types, signing helpers, identity statuses, and policy semantics.
401
408
 
402
409
  Express-compatible middleware factory. Automatically gates requests based on agent trust.
403
410
 
404
- Uses the public `getAgentProfile()` endpoint under the hood (not the protected `gate()` endpoint), so it works from any server context — no agent challenge-response auth required.
411
+ Uses `getAgentProfile()` with your server-side operator API key. The middleware requires your `verifyRequest(request, identifier)` callback to prove control of this exact request before any profile or cache lookup. Missing or invalid proofs return `AGENT_OWNERSHIP_REQUIRED` (401).
405
412
 
406
413
  **Express 4 safe**: The returned middleware wraps the async handler with `Promise.resolve(handler(...)).catch(next)` so async rejections are properly forwarded to Express's error handler. This prevents race conditions when chained with other async middleware (e.g. x402's `paymentMiddleware`).
407
414
 
@@ -410,6 +417,7 @@ import { ValironSDK, createValironGate } from "@valiron/sdk";
410
417
 
411
418
  const gate = createValironGate(config: {
412
419
  sdk: ValironSDK;
420
+ verifyRequest: (request: Request, identifier: string) => Promise<boolean>; // required for authorization
413
421
  minScore?: number; // default: 65
414
422
  trustSignals?: Array<"8004" | "sandbox" | "world" | "self" | "icebreaker" | "wallet">;
415
423
  cacheTtlMs?: number; // default: 30000 (30s client-side cache)
@@ -422,20 +430,21 @@ const gate = createValironGate(config: {
422
430
 
423
431
  **Default behavior**:
424
432
  - Extracts agent ID from `x-agent-id` header (on-chain) or `x-agent-address` header (key-based)
425
- - Returns 401 if no agent identity is found (with link to identity skill)
433
+ - Returns 401 if no identity is found, or `AGENT_OWNERSHIP_REQUIRED` if the request verifier is missing or rejects the proof
426
434
  - Returns 403 if agent is denied
427
435
  - Returns 503 if the trust gate is unreachable (fail-closed)
428
- - Caches profiles in memory for 30s to survive x402 retry flows
436
+ - Caches reputation decisions by identity, chain, signal selection and threshold for 30s; verifies each fresh request before cache use
429
437
 
430
438
  **Example**:
431
439
  ```typescript
432
- const valiron = new ValironSDK({ chain: "monad" });
440
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: "monad" });
433
441
 
434
442
  // Basic gate
435
- app.use("/api/paid", createValironGate({ sdk: valiron }));
443
+ app.use("/api/paid", createValironGate({ verifyRequest: verifyAgentRequest, sdk: valiron }));
436
444
 
437
445
  // Custom threshold + longer cache
438
446
  app.use("/api/premium", createValironGate({
447
+ verifyRequest: verifyAgentRequest,
439
448
  sdk: valiron,
440
449
  minScore: 85,
441
450
  trustSignals: ["8004", "sandbox"],
@@ -444,6 +453,7 @@ app.use("/api/premium", createValironGate({
444
453
 
445
454
  // Custom agent ID extraction
446
455
  app.use("/api/custom", createValironGate({
456
+ verifyRequest: verifyAgentRequest,
447
457
  sdk: valiron,
448
458
  extractAgentId: (req) => req.query.agent_id as string,
449
459
  onDeny: (req, res, result) => {
@@ -470,7 +480,7 @@ Call this when shutting down long-running processes.
470
480
 
471
481
  ---
472
482
 
473
- ## Proxy Gateway (Pro)
483
+ ## Proxy Gateway
474
484
 
475
485
  Forward requests through Valiron's edge proxy with automatic trust gating, logging, and SSRF protection.
476
486
 
@@ -527,7 +537,7 @@ For Web2 agents that don't have on-chain identities, Valiron supports key-based
527
537
  3. Agent signs the nonce with their private key
528
538
  4. Valiron verifies the signature and creates a `KeyAgentProfile`
529
539
 
530
- The SDK auto-detects key-based agents from the `x-agent-address` header. No configuration needed.
540
+ The SDK detects key-based claims from `x-agent-address`; a valid `verifyRequest` callback is still required. Prior enrollment proves the key existed, not that the current request is authorized.
531
541
 
532
542
  ### Sandbox Evaluation for Key Agents
533
543
 
@@ -560,8 +570,8 @@ curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox-ke
560
570
  | `tier` | string \| null | Moody's-style trust tier once scored |
561
571
  | `riskLevel` | string \| null | GREEN / YELLOW / RED once scored |
562
572
  | `route` | string \| null | Route decision once scored |
563
- | `icebreaker` | object \| null | Redacted from the public profile; use `getKeyAgentIcebreaker()` with a Pro key |
564
- | `reasons` | string[] | Redacted from the public profile |
573
+ | `icebreaker` | object \| null | Redacted from the summary profile; use `getKeyAgentIcebreaker()` with a Pro key |
574
+ | `reasons` | string[] | Redacted from the summary profile |
565
575
  | `timestamp` | string | ISO timestamp for the profile response |
566
576
 
567
577
  ```typescript
@@ -582,12 +592,12 @@ Verify agent-human linkage via Worldcoin's zero-knowledge proof system.
582
592
 
583
593
  ### verifyWorldId(agentId, proof, options?)
584
594
 
585
- Submit a World ID proof for verification.
595
+ Submit a complete production IDKit result with `idkit_result`, using operator authentication and a fresh owner proof from `signRequest`. Only a verified proof-of-human credential currently creates a trusted link; legacy links must be re-verified.
586
596
 
587
597
  ```typescript
588
598
  const result = await valiron.verifyWorldId(agentId: string, proof: WorldIdProof, options?: {
589
599
  chain?: SupportedChain;
590
- }): Promise<WorldIdVerificationResult>;
600
+ }): Promise<{ ok: boolean; agentId: string; worldId: WorldIdStatus; timestamp: string }>;
591
601
  ```
592
602
 
593
603
  **Example**:
@@ -596,7 +606,8 @@ const result = await valiron.verifyWorldId("25459", {
596
606
  merkle_root: "0x...",
597
607
  nullifier_hash: "0x...",
598
608
  proof: "0x...",
599
- signal: "0x...",
609
+ verification_level: "orb",
610
+ idkit_result: idkitResult, // complete, unmodified production IDKit result
600
611
  });
601
612
  ```
602
613
 
@@ -607,13 +618,13 @@ Check if an agent has a verified World ID.
607
618
  ```typescript
608
619
  const status = await valiron.getWorldIdStatus(agentId: string, options?: {
609
620
  chain?: SupportedChain;
610
- }): Promise<WorldIdStatus>;
611
- // { verified: true, verifiedAt: "2025-01-15T...", level: "orb" }
621
+ }): Promise<{ agentId: string; worldId: WorldIdStatus; timestamp: string }>;
622
+ // status.worldId: { verified: true, verificationLevel: "orb" }
612
623
  ```
613
624
 
614
625
  ### getWorldIdProfile(agentId, options?)
615
626
 
616
- Get full World ID profile including verification details.
627
+ Get the World ID profile with an allowlisted verification summary using a Free or paid operator key. Icebreaker enrichment is included only for Pro/Enterprise.
617
628
 
618
629
  ```typescript
619
630
  const profile = await valiron.getWorldIdProfile(agentId: string, options?: {
@@ -629,7 +640,7 @@ Self provides eligible-human verification from government ID credentials and can
629
640
 
630
641
  ### createSelfSession(agentId, request, options?)
631
642
 
632
- Create a Self Enterprise verification session for an agent. Redirect the user to the returned `verificationUrl`; Self will call Valiron's signed webhook after completion.
643
+ Create an owner-authorized Self Enterprise verification session. Configure `signRequest`; operator authentication alone cannot link a human to an agent. Omit return URLs or use the allowed `https://valiron.co` origin. Redirect the user to the returned `verificationUrl`; Self will call Valiron's signed webhook after completion.
633
644
 
634
645
  ```typescript
635
646
  const session = await valiron.createSelfSession("25459", {
@@ -651,7 +662,7 @@ console.log(self.verified, self.selfAgentLinked);
651
662
 
652
663
  ### getSelfProfile(agentId, options?)
653
664
 
654
- Get the full Self eligible-human / Agent ID profile.
665
+ Get the Self profile with eligibility and agent-binding predicates using a Free or paid operator key; provider identifiers are omitted.
655
666
 
656
667
  ```typescript
657
668
  const profile = await valiron.getSelfProfile("25459");
@@ -661,15 +672,15 @@ console.log(profile.humanTrust.hasAgentBinding);
661
672
 
662
673
  ### verifySelf(agentId, proof, options?)
663
674
 
664
- Trusted-payload ingestion for local/internal tests only. Production integrations should use `createSelfSession()` plus Self's signed webhook.
675
+ Deprecated; retained for compatibility until the next major SDK release. Not supported for hosted customer integrations. Use `createSelfSession()`, send the user to the returned verification URL, and check `getSelfStatus()` after verification. Valiron receives the signed result from Self.
665
676
 
666
677
  ---
667
678
 
668
679
  ## Telemetry
669
680
 
670
- 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 paywall usage logs are separate customer analytics and are authenticated with the operator API key.
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.
671
682
 
672
- 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. Server statistics identify persisted counters versus counters limited to one process, and latency percentiles cover the latest 1,000 reported calls per method, chain, and version.
683
+ 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.
673
684
 
674
685
  ### TelemetryConfig
675
686
 
@@ -683,6 +694,7 @@ SDK reports are anonymous client reports and may be sampled. Signal counts descr
683
694
  **Example**:
684
695
  ```typescript
685
696
  const valiron = new ValironSDK({
697
+ apiKey: process.env.VALIRON_API_KEY,
686
698
  telemetry: {
687
699
  enabled: false, // Disable entirely
688
700
  },
@@ -690,6 +702,7 @@ const valiron = new ValironSDK({
690
702
 
691
703
  // Or with custom sampling and handler
692
704
  const valiron = new ValironSDK({
705
+ apiKey: process.env.VALIRON_API_KEY,
693
706
  telemetry: {
694
707
  sampleRate: 0.1, // Sample 10% of events
695
708
  onEvent: (event) => { // Custom handler
@@ -703,10 +716,7 @@ const valiron = new ValironSDK({
703
716
 
704
717
  ## Middleware
705
718
 
706
- All middleware adapters use `getAgentProfile()` (public endpoint) rather than
707
- `gate()` (protected endpoint), so they work from any server context without
708
- agent challenge-response auth. Results are cached client-side (default 30s)
709
- to survive x402's two-request payment flow and avoid cold-start failures.
719
+ Trust middleware adapters use authenticated profile reads to evaluate route policy locally. Configure the SDK with your server-side operator API key and bind the agent identifier to your authenticated caller. The callback must cryptographically verify the caller and reject replays; a profile lookup or header-presence check is insufficient. Provider identity middleware verifies its separate v2 signed proof protocol. Profile decisions are cached for 30 seconds by default, scoped by threshold and signals. Request proofs are always checked before cache hits.
710
720
 
711
721
  ### createValironGate(config) — Express
712
722
 
@@ -722,9 +732,10 @@ You do NOT need to wrap it yourself — it's safe to use directly with
722
732
  ```typescript
723
733
  import { ValironSDK, valironFastifyPlugin } from "@valiron/sdk";
724
734
 
725
- const valiron = new ValironSDK({ chain: "monad" });
735
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: "monad" });
726
736
 
727
737
  fastify.register(valironFastifyPlugin, {
738
+ verifyRequest: verifyAgentRequest,
728
739
  sdk: valiron,
729
740
  prefix: "/api/paid",
730
741
  });
@@ -735,8 +746,9 @@ fastify.register(valironFastifyPlugin, {
735
746
  ```typescript
736
747
  import { ValironSDK, createValironNextMiddleware } from "@valiron/sdk";
737
748
 
738
- const valiron = new ValironSDK();
749
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
739
750
  export default createValironNextMiddleware({
751
+ verifyRequest: verifyAgentRequest,
740
752
  sdk: valiron,
741
753
  paths: ["/api/paid"],
742
754
  });
@@ -747,10 +759,11 @@ export default createValironNextMiddleware({
747
759
  ```typescript
748
760
  import { ValironSDK, valironGateCheck } from "@valiron/sdk";
749
761
 
750
- const valiron = new ValironSDK();
762
+ const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
751
763
 
752
764
  app.use(async (c, next) => {
753
765
  const gate = await valironGateCheck(valiron, {
766
+ verifyRequest: (identifier) => verifyAgentRequest(c.req.raw, identifier),
754
767
  agentId: c.req.header("x-agent-id") ?? null,
755
768
  agentAddress: c.req.header("x-agent-address") ?? null,
756
769
  });
@@ -774,7 +787,7 @@ import {
774
787
  } from "@valiron/sdk";
775
788
  ```
776
789
 
777
- `createValironIdentityGate({ sdk, policy, getRawBody? })` protects Express and
790
+ `createValironIdentityGate({ audience: "https://api.example.com", origin: "https://api.example.com", sdk, policy, getRawBody? })` protects Express and
778
791
  Connect routes. `valironIdentityFastifyPlugin` provides the equivalent Fastify
779
792
  `preHandler`; `createValironIdentityNextMiddleware` hashes a cloned Fetch
780
793
  request; and `valironIdentityGateCheck` accepts explicit proof fields and exact
@@ -803,7 +816,7 @@ without preserving its exact bytes.
803
816
 
804
817
  ### Client-Side Caching
805
818
 
806
- All middleware adapters include a built-in in-memory cache (default TTL: 30 seconds).
819
+ Trust middleware adapters include a built-in in-memory cache (default TTL: 30 seconds). Provider identity gates do not cache request proofs.
807
820
  This is important for payment protocols like x402 that make two requests per payment
808
821
  (discover 402 → retry with payment). Without caching, the second trust check can fail
809
822
  due to cold-start latency on the edge proxy.
@@ -878,8 +891,8 @@ Returned by `getAgentProfile()`.
878
891
  | `agentId` | string | ERC-8004 token ID |
879
892
  | `identity` | object | On-chain identity (name, wallet, endpoints, trustModels) |
880
893
  | `onchainReputation` | object | Feedback count, average score, Solana ATOM metrics |
881
- | `routing` | object | `{ finalRoute, meetsThreshold }` |
882
- | `chain` | object | `{ name, chainId }` |
894
+ | `routing` | object | Allowlisted route summary, including `finalRoute`; enforce a gate policy rather than inferring caller authorization from a profile |
895
+ | `chain` | object | `{ network, identityRegistry, reputationRegistry, cluster? }`; infrastructure RPC URLs are omitted |
883
896
  | `timestamp` | string | ISO timestamp |
884
897
 
885
898
  ### Request Headers
@@ -928,10 +941,15 @@ import {
928
941
  |---------|------|-----|
929
942
  | Gated endpoints | 3 | Unlimited |
930
943
  | Sandbox tests / day | 5 | Unlimited |
931
- | Webhooks | — | ✓ |
932
- | Proxy gateway | — | ✓ |
933
- | Analytics & logs | — | ✓ |
934
- | Custom tier thresholds | — | ✓ |
935
- | Wallet intelligence | — | ✓ |
944
+ | Webhooks | ✓ | ✓ |
945
+ | Proxy gateway | ✓ | ✓ |
946
+ | Analytics & logs | ✓ | ✓ |
947
+ | Custom tier thresholds | ✓ | ✓ |
948
+ | Wallet intelligence | ✓ | ✓ |
949
+ | World ID and Self | ✓ | ✓ |
950
+ | Social Graph (Icebreaker) | — | ✓ |
951
+ | Valiron Crawler Protection | ✓ | ✓ |
952
+ | Monthly agent requests | 10,000 | 100,000 |
953
+ | Monthly bot protection requests | 10,000 | 100,000 |
936
954
 
937
955
  Pro plan requires an operator API key (`val_op_` prefix) from the [Operator Dashboard](./DASHBOARD.md).
@@ -0,0 +1,98 @@
1
+ # Security upgrade: request-bound identity
2
+
3
+ This guide describes the hardened source contract. Check the installed package supports these APIs and coordinate its release with your backend; a source merge does not publish packages or upgrade external clients.
4
+
5
+ Reputation belongs to an agent; an `x-agent-id` or `x-agent-address` header alone does not prove that the caller controls it.
6
+
7
+ ## Trust gate integrations
8
+
9
+ `createValironGate`, `valironFastifyPlugin` and `createValironNextMiddleware` require `verifyRequest(request, identifier)`. `valironGateCheck` requires `verifyRequest(identifier)`. The callback must cryptographically verify the current caller against the registry owner or provider-bound key, bind the proof to the API audience, HTTP method, full URL and body, enforce a short timestamp window, and atomically reject replayed nonces in shared storage. It runs before every decision, including reputation-cache hits. An absent or invalid verifier denies the request. Never implement it as a header-presence check.
10
+
11
+ For provider-backed identities, use the built-in identity middleware described in [Provider identity](PROVIDER-IDENTITY.md). Configure its `audience` and trusted `origin`; the middleware computes request context and the raw-body digest locally. New signatures use `valiron-agent-request-v2`. Existing v1 proofs cannot authorize a request.
12
+
13
+ New agents remain denied while their real sandbox evaluation is pending. Provisional simulations do not establish behavioral reputation.
14
+
15
+ ## Hosted wrappers, gates and proxy
16
+
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
+
19
+ Signed wallet requests use these headers: `x-agent-timestamp` (milliseconds), `x-agent-nonce` (24–128 URL-safe characters), and `x-agent-request-signature`. EVM owners sign the UTF-8 payload using EIP-191. Solana owners sign the same payload using Ed25519 and encode signatures as base64url.
20
+
21
+ ```text
22
+ valiron-wallet-request-v2
23
+ agent:<exact-request-agent-id>
24
+ chain:<normalized-chain>
25
+ method:<UPPERCASE-method>
26
+ url:<absolute-public-request-URL>
27
+ body-sha256:<lowercase-SHA256-hex>
28
+ timestamp:<milliseconds>
29
+ nonce:<fresh-nonce>
30
+ ```
31
+
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
+
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.
35
+
36
+ ## Identity enrollment and endpoints
37
+
38
+ World ID enrollment requires an authenticated Valiron operator, an owner-signed request and the complete, unmodified production IDKit result. Browser assertions and partial proofs are rejected. The server verifies the proof before persisting a link, derives credential strength from the verified credential, and ignores older records without server-verification provenance. Current enrollment accepts the proof-of-human credential. Existing device-only links must not be treated as biometric proof.
39
+
40
+ Self enrollment also requires operator authentication and owner approval. Newly created sessions carry ownership provenance; old sessions cannot create new trusted links. Sandbox probes use short-lived, agent-scoped capabilities rather than exposing observer-control secrets.
41
+
42
+ SDK API endpoints remain configurable. Crawler activation can use an explicitly configured HTTPS endpoint at `/operator/crawlers/activation`. Configure only a service you control and trust: it receives the operator credential. Redirects are rejected.
43
+
44
+ Operator usage analytics now require explicit `analytics: true`. Raw IP addresses, user agents, query strings and paths are not transmitted.
45
+
46
+ ## Upgrade checklist
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.
49
+ 2. Configure hosted request signers and migrate provider identities to proof v2. Each payment retry also needs a new identity nonce.
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
+ 4. Enable operator analytics only with explicit `analytics: true`; SDK diagnostic telemetry remains separately configured.
52
+ 5. Validate stale, replayed, wrong-subject, wrong-method, wrong-URL and altered-body proofs as well as valid requests. Missing verification, quota storage or required identity infrastructure must fail closed.
53
+
54
+ ## Example: sign one hosted EVM gate request
55
+
56
+ This Node.js example signs for one configured registry agent and chain. The private key must belong to that agent's current registry owner. Use a wallet/key manager in production; never send the owner key to the API seller. A Solana signer must instead produce the Ed25519/base64url signature described above.
57
+
58
+ ```typescript
59
+ import { createHash, randomBytes } from "node:crypto";
60
+ import { privateKeyToAccount } from "viem/accounts";
61
+ import { ValironSDK } from "@valiron/sdk";
62
+
63
+ const agentId = "25459";
64
+ const chain = "ethereum";
65
+ const endpoint = "https://valiron-edge-proxy.onrender.com";
66
+ const key = process.env.AGENT_OWNER_PRIVATE_KEY;
67
+ if (!key) throw new Error("Configure your agent owner's signer");
68
+ const owner = privateKeyToAccount(key as `0x${string}`);
69
+ const sdk = new ValironSDK({
70
+ apiKey: process.env.VALIRON_API_KEY,
71
+ chain,
72
+ endpoint,
73
+ async signRequest(request) {
74
+ const target = new URL(request.url);
75
+ if (target.origin !== endpoint || target.pathname !== `/operator/gate/${agentId}` ||
76
+ request.chain !== chain || request.method !== "POST") {
77
+ throw new Error("This signer is scoped to one agent gate");
78
+ }
79
+ const timestamp = String(Date.now());
80
+ const nonce = randomBytes(24).toString("base64url");
81
+ const digest = createHash("sha256").update(request.body).digest("hex");
82
+ const message = [
83
+ "valiron-wallet-request-v2", `agent:${agentId}`, `chain:${chain}`,
84
+ `method:${request.method}`, `url:${request.url}`, `body-sha256:${digest}`,
85
+ `timestamp:${timestamp}`, `nonce:${nonce}`,
86
+ ].join("\n");
87
+ return {
88
+ "x-agent-timestamp": timestamp,
89
+ "x-agent-nonce": nonce,
90
+ "x-agent-request-signature": await owner.signMessage({ message }),
91
+ };
92
+ },
93
+ });
94
+ const result = await sdk.gate(agentId);
95
+ if (!result.allow) throw new Error("Agent not admitted");
96
+ ```
97
+
98
+ Use a separately scoped signer for proxy or enrollment operations rather than removing the destination check. This wallet-request protocol is distinct from provider proof v2, which hashes raw bytes and binds an explicit API audience.