@valiron/sdk 1.2.0 → 1.3.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/README.md CHANGED
@@ -49,6 +49,57 @@ No API key is required for basic read operations. Pro trust signals and `getWall
49
49
 
50
50
  Use `x-agent-id` for ERC-8004/Solana agents. Use `x-agent-address` plus Valiron challenge-response for local, Web2, or non-ERC-8004 agents. Agents can follow the hosted identity skill at https://www.valiron.co/auth.md.
51
51
 
52
+ Provider-backed identities such as ANS use signed `x-valiron-identity-*`
53
+ headers. SDK 1.3 provides `createAgentIdentityProof()` for agents,
54
+ `verifyAgentIdentity()` for low-level verification, and dedicated Express,
55
+ Fastify, Next.js, and generic identity gates. Valiron hosts the ANS credentials
56
+ and trusted CA bundle; SDK users do not configure them. See the
57
+ [provider-backed identity guide](https://valiron.co/docs/agents/PROVIDER-IDENTITY.md)
58
+ for the signing and middleware quickstart.
59
+
60
+ ```typescript
61
+ import {
62
+ agentIdentityProofHeaders,
63
+ createAgentIdentityProof,
64
+ createValironIdentityGate,
65
+ } from "@valiron/sdk";
66
+
67
+ // Agent: sign the exact bytes it will send.
68
+ const body = JSON.stringify({ operation: "quote" });
69
+ const proof = await createAgentIdentityProof({
70
+ provider: "ans",
71
+ agentId: "ans://v1.0.0.sales-agent.acme.com",
72
+ body,
73
+ sign: (payload) => agentKey.sign(payload),
74
+ });
75
+ await fetch(apiUrl, { method: "POST", body, headers: agentIdentityProofHeaders(proof) });
76
+
77
+ // API owner: capture raw bytes, then enforce the returned identity policy.
78
+ app.use(express.json({ verify: (req: any, _res, bytes) => { req.rawBody = Buffer.from(bytes); } }));
79
+ app.post("/quote", createValironIdentityGate({
80
+ sdk: valiron,
81
+ policy: { anonymous: "challenge", claimed: "block", verified: "allow" },
82
+ }), handler);
83
+ ```
84
+
85
+ ## Error diagnostics
86
+
87
+ SDK failures are `ValironError` instances. Handle the stable `code` programmatically and log `details.action`, `details.requestId`, `details.docsUrl`, and `details.retryAfterMs` to make recovery explicit.
88
+
89
+ ```typescript
90
+ import { ValironError } from "@valiron/sdk";
91
+
92
+ try {
93
+ await valiron.getAgentProfile("AGENT_ID");
94
+ } catch (error) {
95
+ if (error instanceof ValironError) {
96
+ console.error(error.code, error.message, error.details?.action);
97
+ }
98
+ }
99
+ ```
100
+
101
+ Trust middleware returns the same fields in JSON responses. Its primary codes are `MISSING_AGENT_IDENTITY`, `TRUST_GATE_DENIED`, `AGENT_EVALUATION_PENDING`, and `TRUST_GATE_UNAVAILABLE`. See the [error guide](https://valiron.co/docs#error-handling) for retry rules and hosted-wrapper diagnostics.
102
+
52
103
  ### Additional Features
53
104
 
54
105
  - **Auto-Sandbox** — Middleware automatically evaluates new agents (on-chain and key-based) on their first gated request
@@ -76,6 +127,9 @@ Full SDK reference, API docs, trust model, and integration guides:
76
127
  - **[SDK Reference](https://valiron.co/docs/agents/SDK-REFERENCE.md)** — all methods, options, and response types
77
128
  - **[API Reference](https://valiron.co/docs/agents/API-REFERENCE.md)** — HTTP endpoints
78
129
  - **[Quickstart](https://valiron.co/docs/agents/QUICKSTART.md)** — get started in 2 minutes
130
+ - **[End-to-End Middleware Integration](https://valiron.co/docs/agents/E2E-MIDDLEWARE-INTEGRATION.md)** — identity, trust signals, downstream policy, and testing
131
+ - **[Provider-Backed Identity](https://valiron.co/docs/agents/PROVIDER-IDENTITY.md)** — resolver foundation, proof format, replay handling, policy actions, and ANS adapter status
132
+ - **[Error Guide](https://valiron.co/docs#error-handling)** — codes, recovery actions, retries, and wrapper diagnostics
79
133
  - **[llms.txt](https://valiron.co/llms.txt)** — compact reference for LLM/agent integration
80
134
  - **Install agent skill**: `npx @valiron/skill`
81
135
 
package/dist/clients.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ValironConfig, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, WalletRiskSnapshot, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, SelfAgentProfile, SelfProofPayload, SelfSessionRequest, SelfSessionResponse, SelfStatus, ProxyRequest, ProxyResponse } from "./types";
1
+ import { ValironConfig, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, WalletRiskSnapshot, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, SelfAgentProfile, SelfProofPayload, SelfSessionRequest, SelfSessionResponse, SelfStatus, AgentIdentityProof, AgentIdentityPolicy, AgentIdentityVerificationResult, ProxyRequest, ProxyResponse } from "./types";
2
2
  /**
3
3
  * HTTP client for the Valiron Operator API.
4
4
  *
@@ -187,11 +187,15 @@ export declare class ValironClient {
187
187
  * `GET /operator/self/profile/:agentId`
188
188
  */
189
189
  getSelfProfile(agentId: string, options?: CallOptions): Promise<SelfAgentProfile>;
190
+ /** Verify a provider-backed identity proof and evaluate the supplied policy. */
191
+ verifyAgentIdentity(proof?: AgentIdentityProof, policy?: AgentIdentityPolicy): Promise<AgentIdentityVerificationResult>;
190
192
  /** Flush any pending telemetry events and clean up resources. */
191
193
  dispose(): Promise<void>;
192
194
  /** Emit an SDK telemetry event from higher-level helpers. */
193
195
  emitTelemetry(event: string, payload: Record<string, unknown>): void;
194
196
  private buildHeaders;
197
+ /** Preserve safe server diagnostics instead of collapsing every non-2xx response into API_ERROR. */
198
+ private createApiError;
195
199
  private get;
196
200
  private post;
197
201
  private extractMethodName;
package/dist/clients.js CHANGED
@@ -260,6 +260,10 @@ class ValironClient {
260
260
  async getSelfProfile(agentId, options) {
261
261
  return this.get(`/operator/self/profile/${agentId}`, this.resolveChain(options));
262
262
  }
263
+ /** Verify a provider-backed identity proof and evaluate the supplied policy. */
264
+ async verifyAgentIdentity(proof = {}, policy) {
265
+ return this.post("/operator/identity/verify", policy ? { ...proof, policy } : proof);
266
+ }
263
267
  /** Flush any pending telemetry events and clean up resources. */
264
268
  async dispose() {
265
269
  await this.telemetry.dispose();
@@ -278,6 +282,25 @@ class ValironClient {
278
282
  }
279
283
  return headers;
280
284
  }
285
+ /** Preserve safe server diagnostics instead of collapsing every non-2xx response into API_ERROR. */
286
+ createApiError(response, body, path, method) {
287
+ const message = (typeof body.message === "string" && body.message) ||
288
+ (typeof body.error === "string" && body.error) ||
289
+ `Request failed: ${response.statusText}`;
290
+ const requestId = response.headers.get("x-request-id") || response.headers.get("x-vercel-id") || undefined;
291
+ const retryAfterSeconds = Number(response.headers.get("retry-after"));
292
+ const bodyRetryAfterMs = typeof body.retryAfterMs === "number" ? body.retryAfterMs : undefined;
293
+ const details = {
294
+ method,
295
+ path,
296
+ requestId,
297
+ details: body.details,
298
+ action: typeof body.action === "string" ? body.action : typeof body.hint === "string" ? body.hint : undefined,
299
+ docsUrl: typeof body.docsUrl === "string" ? body.docsUrl : typeof body.identitySkill === "string" ? body.identitySkill : undefined,
300
+ retryAfterMs: bodyRetryAfterMs ?? (Number.isFinite(retryAfterSeconds) ? retryAfterSeconds * 1000 : undefined),
301
+ };
302
+ return new types_1.ValironError(message, typeof body.code === "string" ? body.code : "API_ERROR", response.status, details);
303
+ }
281
304
  async get(path, chain) {
282
305
  const url = new URL(path, this.endpoint);
283
306
  if (chain)
@@ -314,7 +337,7 @@ class ValironClient {
314
337
  abort_count: 0,
315
338
  });
316
339
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
317
- throw new types_1.ValironError(body.error || body.message || `Request failed: ${response.statusText}`, "API_ERROR", response.status);
340
+ throw this.createApiError(response, body, path, "GET");
318
341
  }
319
342
  const data = await response.json();
320
343
  this.telemetry.emit("sdk_call", {
@@ -349,7 +372,7 @@ class ValironClient {
349
372
  timeout_ms: timeoutMs,
350
373
  });
351
374
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
352
- throw new types_1.ValironError(`Request timeout after ${timeoutMs}ms`, "TIMEOUT_ERROR");
375
+ throw new types_1.ValironError(`Valiron did not respond within ${timeoutMs}ms. Retry the request, increase timeout, or check the service status.`, "TIMEOUT_ERROR", undefined, { method: "GET", path, action: "Retry with a longer timeout or inspect the Valiron service status.", retryAfterMs: 1000 });
353
376
  }
354
377
  if (error instanceof types_1.ValironError)
355
378
  throw error;
@@ -364,7 +387,7 @@ class ValironClient {
364
387
  abort_count: 0,
365
388
  });
366
389
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
367
- throw new types_1.ValironError(error.message || "Network error", "NETWORK_ERROR");
390
+ throw new types_1.ValironError(`Could not reach Valiron: ${error.message || "network error"}`, "NETWORK_ERROR", undefined, { method: "GET", path, action: "Check your endpoint URL, network egress, and DNS configuration before retrying." });
368
391
  }
369
392
  }
370
393
  async post(path, body, chain) {
@@ -408,7 +431,7 @@ class ValironClient {
408
431
  abort_count: 0,
409
432
  });
410
433
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
411
- throw new types_1.ValironError(respBody.error || respBody.message || `Request failed: ${response.statusText}`, "API_ERROR", response.status);
434
+ throw this.createApiError(response, respBody, path, "POST");
412
435
  }
413
436
  const data = await response.json();
414
437
  this.telemetry.emit("sdk_call", {
@@ -443,7 +466,7 @@ class ValironClient {
443
466
  timeout_ms: timeoutMs,
444
467
  });
445
468
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
446
- throw new types_1.ValironError(`Request timeout after ${timeoutMs}ms`, "TIMEOUT_ERROR");
469
+ throw new types_1.ValironError(`Valiron did not respond within ${timeoutMs}ms. Retry the request, increase timeout, or check the service status.`, "TIMEOUT_ERROR", undefined, { method: "POST", path, action: "Retry with a longer timeout or inspect the Valiron service status.", retryAfterMs: 1000 });
447
470
  }
448
471
  if (error instanceof types_1.ValironError)
449
472
  throw error;
@@ -458,7 +481,7 @@ class ValironClient {
458
481
  abort_count: 0,
459
482
  });
460
483
  this.telemetry.recordLatency(methodName, chain || "server_default", durationMs);
461
- throw new types_1.ValironError(error.message || "Network error", "NETWORK_ERROR");
484
+ throw new types_1.ValironError(`Could not reach Valiron: ${error.message || "network error"}`, "NETWORK_ERROR", undefined, { method: "POST", path, action: "Check your endpoint URL, network egress, and DNS configuration before retrying." });
462
485
  }
463
486
  }
464
487
  extractMethodName(path) {
@@ -1,3 +1,4 @@
1
+ import type { AgentIdentityProof, AgentIdentityTransportProof } from "./types";
1
2
  export interface ChallengeResponse {
2
3
  /** The challenge nonce that was signed */
3
4
  challenge: string;
@@ -6,6 +7,25 @@ export interface ChallengeResponse {
6
7
  /** The agent's Ethereum address */
7
8
  agentAddress: string;
8
9
  }
10
+ export type AgentIdentityBody = string | Uint8Array | ArrayBuffer | null | undefined;
11
+ export interface CreateAgentIdentityProofInput {
12
+ provider: string;
13
+ agentId: string;
14
+ body?: AgentIdentityBody;
15
+ /** Sign the exact UTF-8 payload with the private key bound to the provider identity. */
16
+ sign: (payload: string) => string | Uint8Array | Promise<string | Uint8Array>;
17
+ timestamp?: string;
18
+ nonce?: string;
19
+ keyId?: string;
20
+ }
21
+ export declare const AGENT_IDENTITY_HEADERS: {
22
+ readonly provider: "x-valiron-identity-provider";
23
+ readonly agentId: "x-valiron-identity-agent-id";
24
+ readonly signature: "x-valiron-identity-signature";
25
+ readonly timestamp: "x-valiron-identity-timestamp";
26
+ readonly nonce: "x-valiron-identity-nonce";
27
+ readonly keyId: "x-valiron-identity-key-id";
28
+ };
9
29
  /** Validate that a string looks like an Ethereum address (0x + 40 hex chars). */
10
30
  export declare function isValidAddress(address: string): boolean;
11
31
  /**
@@ -14,3 +34,18 @@ export declare function isValidAddress(address: string): boolean;
14
34
  * @returns A 32-byte hex-encoded nonce
15
35
  */
16
36
  export declare function generateChallenge(): string;
37
+ /** Calculate the digest Valiron binds to the signed request proof. */
38
+ export declare function sha256RequestDigest(body?: AgentIdentityBody): string;
39
+ /** Build the canonical payload understood by Valiron's provider identity verifier. */
40
+ export declare function buildAgentIdentitySigningPayload(input: {
41
+ agentId: string;
42
+ timestamp: string;
43
+ nonce: string;
44
+ requestDigest: string;
45
+ }): string;
46
+ /** Create a signed proof for one exact request body. Private keys remain with the agent. */
47
+ export declare function createAgentIdentityProof(input: CreateAgentIdentityProofInput): Promise<AgentIdentityProof>;
48
+ /** Convert a proof into transport headers. requestDigest is intentionally omitted and recomputed by the API gate. */
49
+ export declare function agentIdentityProofHeaders(proof: AgentIdentityProof): Record<string, string>;
50
+ /** Read provider identity proof fields from Fetch Headers or Node-style request headers. */
51
+ export declare function agentIdentityProofFromHeaders(headers: unknown): AgentIdentityTransportProof;
package/dist/identity.js CHANGED
@@ -1,8 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AGENT_IDENTITY_HEADERS = void 0;
3
4
  exports.isValidAddress = isValidAddress;
4
5
  exports.generateChallenge = generateChallenge;
6
+ exports.sha256RequestDigest = sha256RequestDigest;
7
+ exports.buildAgentIdentitySigningPayload = buildAgentIdentitySigningPayload;
8
+ exports.createAgentIdentityProof = createAgentIdentityProof;
9
+ exports.agentIdentityProofHeaders = agentIdentityProofHeaders;
10
+ exports.agentIdentityProofFromHeaders = agentIdentityProofFromHeaders;
5
11
  const crypto_1 = require("crypto");
12
+ exports.AGENT_IDENTITY_HEADERS = {
13
+ provider: "x-valiron-identity-provider",
14
+ agentId: "x-valiron-identity-agent-id",
15
+ signature: "x-valiron-identity-signature",
16
+ timestamp: "x-valiron-identity-timestamp",
17
+ nonce: "x-valiron-identity-nonce",
18
+ keyId: "x-valiron-identity-key-id",
19
+ };
6
20
  // ─── Validation Helpers ─────────────────────────────────────────────────────
7
21
  /** Validate that a string looks like an Ethereum address (0x + 40 hex chars). */
8
22
  function isValidAddress(address) {
@@ -17,3 +31,85 @@ function isValidAddress(address) {
17
31
  function generateChallenge() {
18
32
  return (0, crypto_1.randomBytes)(32).toString("hex");
19
33
  }
34
+ /** Calculate the digest Valiron binds to the signed request proof. */
35
+ function sha256RequestDigest(body) {
36
+ const bytes = body == null
37
+ ? Buffer.alloc(0)
38
+ : typeof body === "string"
39
+ ? Buffer.from(body, "utf8")
40
+ : body instanceof ArrayBuffer
41
+ ? Buffer.from(body)
42
+ : Buffer.from(body.buffer, body.byteOffset, body.byteLength);
43
+ return `sha256:${(0, crypto_1.createHash)("sha256").update(bytes).digest("hex")}`;
44
+ }
45
+ /** Build the canonical payload understood by Valiron's provider identity verifier. */
46
+ function buildAgentIdentitySigningPayload(input) {
47
+ return [
48
+ "valiron-agent-request-v1",
49
+ `agent-id:${input.agentId}`,
50
+ `timestamp:${input.timestamp}`,
51
+ `nonce:${input.nonce}`,
52
+ `request-digest:${input.requestDigest.toLowerCase()}`,
53
+ ].join("\n");
54
+ }
55
+ /** Create a signed proof for one exact request body. Private keys remain with the agent. */
56
+ async function createAgentIdentityProof(input) {
57
+ const timestamp = input.timestamp ?? new Date().toISOString();
58
+ const nonce = input.nonce ?? (0, crypto_1.randomBytes)(24).toString("base64url");
59
+ const requestDigest = sha256RequestDigest(input.body);
60
+ const signed = await input.sign(buildAgentIdentitySigningPayload({
61
+ agentId: input.agentId,
62
+ timestamp,
63
+ nonce,
64
+ requestDigest,
65
+ }));
66
+ const signature = typeof signed === "string" ? signed : Buffer.from(signed).toString("base64url");
67
+ return {
68
+ provider: input.provider,
69
+ agentId: input.agentId,
70
+ signature,
71
+ timestamp,
72
+ nonce,
73
+ requestDigest,
74
+ ...(input.keyId ? { keyId: input.keyId } : {}),
75
+ };
76
+ }
77
+ /** Convert a proof into transport headers. requestDigest is intentionally omitted and recomputed by the API gate. */
78
+ function agentIdentityProofHeaders(proof) {
79
+ const headers = {};
80
+ if (proof.provider)
81
+ headers[exports.AGENT_IDENTITY_HEADERS.provider] = proof.provider;
82
+ if (proof.agentId)
83
+ headers[exports.AGENT_IDENTITY_HEADERS.agentId] = proof.agentId;
84
+ if (proof.signature)
85
+ headers[exports.AGENT_IDENTITY_HEADERS.signature] = proof.signature;
86
+ if (proof.timestamp)
87
+ headers[exports.AGENT_IDENTITY_HEADERS.timestamp] = proof.timestamp;
88
+ if (proof.nonce)
89
+ headers[exports.AGENT_IDENTITY_HEADERS.nonce] = proof.nonce;
90
+ if (proof.keyId)
91
+ headers[exports.AGENT_IDENTITY_HEADERS.keyId] = proof.keyId;
92
+ return headers;
93
+ }
94
+ /** Read provider identity proof fields from Fetch Headers or Node-style request headers. */
95
+ function agentIdentityProofFromHeaders(headers) {
96
+ const read = (name) => {
97
+ if (headers && typeof headers.get === "function") {
98
+ return headers.get(name) ?? undefined;
99
+ }
100
+ if (!headers || typeof headers !== "object")
101
+ return undefined;
102
+ const value = headers[name];
103
+ if (Array.isArray(value))
104
+ return typeof value[0] === "string" ? value[0] : undefined;
105
+ return typeof value === "string" ? value : undefined;
106
+ };
107
+ return {
108
+ provider: read(exports.AGENT_IDENTITY_HEADERS.provider),
109
+ agentId: read(exports.AGENT_IDENTITY_HEADERS.agentId),
110
+ signature: read(exports.AGENT_IDENTITY_HEADERS.signature),
111
+ timestamp: read(exports.AGENT_IDENTITY_HEADERS.timestamp),
112
+ nonce: read(exports.AGENT_IDENTITY_HEADERS.nonce),
113
+ keyId: read(exports.AGENT_IDENTITY_HEADERS.keyId),
114
+ };
115
+ }
@@ -0,0 +1,50 @@
1
+ import type { ValironSDK } from "./index";
2
+ import { type AgentIdentityBody } from "./identity";
3
+ import type { AgentIdentityPolicy, AgentIdentityPolicyAction, AgentIdentityTransportProof, AgentIdentityVerificationResult } from "./types";
4
+ type MaybePromise<T> = T | Promise<T>;
5
+ export interface ValironIdentityGateConfig {
6
+ sdk: ValironSDK;
7
+ /** Policy evaluated by Valiron after identity and reputation checks. */
8
+ policy?: AgentIdentityPolicy;
9
+ /** Override transport-header extraction. */
10
+ extractProof?: (request: any) => AgentIdentityTransportProof;
11
+ /**
12
+ * Return the exact raw request bytes. Required for body-bearing Express and
13
+ * Fastify requests unless `request.rawBody` has already been populated.
14
+ */
15
+ getRawBody?: (request: any) => MaybePromise<AgentIdentityBody>;
16
+ onAllow?: (request: any, result: AgentIdentityVerificationResult) => void;
17
+ onDeny?: (request: any, response: any, result: AgentIdentityVerificationResult) => void;
18
+ }
19
+ export interface ValironIdentityFastifyConfig extends ValironIdentityGateConfig {
20
+ /** URL prefix to protect. Omit to protect every route in the plugin scope. */
21
+ prefix?: string;
22
+ }
23
+ export interface ValironIdentityNextConfig {
24
+ sdk: ValironSDK;
25
+ policy?: AgentIdentityPolicy;
26
+ paths?: string[];
27
+ extractProof?: (request: Request) => AgentIdentityTransportProof;
28
+ }
29
+ export interface ValironIdentityGateCheckResult {
30
+ hasClaim: boolean;
31
+ ok: boolean;
32
+ allow: boolean;
33
+ action?: AgentIdentityPolicyAction;
34
+ identity?: AgentIdentityVerificationResult;
35
+ status: number;
36
+ body?: Record<string, unknown>;
37
+ }
38
+ /** Framework-independent provider identity policy check. */
39
+ export declare function valironIdentityGateCheck(sdk: ValironSDK, input?: {
40
+ proof?: AgentIdentityTransportProof;
41
+ body?: AgentIdentityBody;
42
+ policy?: AgentIdentityPolicy;
43
+ }): Promise<ValironIdentityGateCheckResult>;
44
+ /** Express/Connect middleware for ANS and other provider-backed identities. */
45
+ export declare function createValironIdentityGate(config: ValironIdentityGateConfig): (request: any, response: any, next: any) => void;
46
+ /** Fastify plugin for ANS and other provider-backed identities. */
47
+ export declare function valironIdentityFastifyPlugin(fastify: any, opts: ValironIdentityFastifyConfig): Promise<void>;
48
+ /** Next.js middleware for ANS and other provider-backed identities. */
49
+ export declare function createValironIdentityNextMiddleware(config: ValironIdentityNextConfig): (request: Request) => Promise<Response | undefined>;
50
+ export {};
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.valironIdentityGateCheck = valironIdentityGateCheck;
4
+ exports.createValironIdentityGate = createValironIdentityGate;
5
+ exports.valironIdentityFastifyPlugin = valironIdentityFastifyPlugin;
6
+ exports.createValironIdentityNextMiddleware = createValironIdentityNextMiddleware;
7
+ const identity_1 = require("./identity");
8
+ class RawRequestBodyUnavailableError extends Error {
9
+ constructor() {
10
+ super("The exact raw request body is required to verify this identity proof.");
11
+ }
12
+ }
13
+ function hasIdentityClaim(proof) {
14
+ return Boolean(proof.agentId || proof.provider);
15
+ }
16
+ function actionStatus(action) {
17
+ if (action === "allow")
18
+ return 200;
19
+ if (action === "limit")
20
+ return 429;
21
+ if (action === "challenge")
22
+ return 401;
23
+ return 403;
24
+ }
25
+ function actionCode(action) {
26
+ if (action === "limit")
27
+ return "IDENTITY_RATE_LIMITED";
28
+ if (action === "challenge")
29
+ return "IDENTITY_CHALLENGE_REQUIRED";
30
+ return "IDENTITY_BLOCKED";
31
+ }
32
+ function decisionBody(result) {
33
+ const action = result.policyDecision.action;
34
+ const error = action === "limit"
35
+ ? "Agent request limited by identity policy"
36
+ : action === "challenge"
37
+ ? "Agent identity challenge required"
38
+ : "Agent request blocked by identity policy";
39
+ return {
40
+ code: action === "allow" ? "IDENTITY_ALLOWED" : actionCode(action),
41
+ error,
42
+ message: error,
43
+ action: action === "limit"
44
+ ? "Wait for the Retry-After interval, then send a newly signed request with a fresh nonce."
45
+ : action === "challenge"
46
+ ? "Send a complete, newly signed provider identity proof."
47
+ : "Do not execute the protected action unless the API owner's policy changes.",
48
+ reason: result.policyDecision.reason,
49
+ docsUrl: "https://www.valiron.co/docs/agents/PROVIDER-IDENTITY.md",
50
+ identity: result,
51
+ };
52
+ }
53
+ function unavailableBody(error) {
54
+ return {
55
+ code: "IDENTITY_GATE_UNAVAILABLE",
56
+ error: "Provider identity verification unavailable — request denied (fail-closed)",
57
+ message: "Valiron could not safely complete provider identity verification.",
58
+ action: "Retry shortly. If this persists, check the Valiron service status.",
59
+ docsUrl: "https://www.valiron.co/docs/agents/ERRORS.md#provider-backed-identity-errors",
60
+ ...(error instanceof Error ? { cause: error.message } : {}),
61
+ };
62
+ }
63
+ function bodyUnavailableBody() {
64
+ return {
65
+ code: "IDENTITY_RAW_BODY_REQUIRED",
66
+ error: "The exact raw request body is unavailable",
67
+ message: "Valiron cannot bind the identity proof to a reconstructed or reserialized body.",
68
+ action: "Capture raw request bytes before JSON or form parsing and pass them to the Valiron identity gate.",
69
+ docsUrl: "https://www.valiron.co/docs/agents/PROVIDER-IDENTITY.md#api-owner-enforce-an-identity-policy",
70
+ };
71
+ }
72
+ /** Framework-independent provider identity policy check. */
73
+ async function valironIdentityGateCheck(sdk, input = {}) {
74
+ const proof = input.proof ?? {};
75
+ const hasClaim = hasIdentityClaim(proof);
76
+ try {
77
+ const identity = await sdk.verifyAgentIdentity({ ...proof, requestDigest: (0, identity_1.sha256RequestDigest)(input.body) }, input.policy);
78
+ const action = identity.policyDecision.action;
79
+ const allow = action === "allow";
80
+ return {
81
+ hasClaim,
82
+ ok: true,
83
+ allow,
84
+ action,
85
+ identity,
86
+ status: actionStatus(action),
87
+ ...(allow ? {} : { body: decisionBody(identity) }),
88
+ };
89
+ }
90
+ catch (error) {
91
+ return {
92
+ hasClaim,
93
+ ok: false,
94
+ allow: false,
95
+ status: 503,
96
+ body: unavailableBody(error),
97
+ };
98
+ }
99
+ }
100
+ function defaultProof(request) {
101
+ return (0, identity_1.agentIdentityProofFromHeaders)(request?.headers);
102
+ }
103
+ async function exactNodeBody(request, getRawBody) {
104
+ if (getRawBody) {
105
+ const body = await getRawBody(request);
106
+ if (body !== undefined)
107
+ return body;
108
+ }
109
+ if (request?.rawBody !== undefined)
110
+ return request.rawBody;
111
+ const method = String(request?.method ?? "GET").toUpperCase();
112
+ if (method === "GET" || method === "HEAD")
113
+ return undefined;
114
+ const contentLength = Number(request?.headers?.["content-length"] ?? request?.headers?.get?.("content-length"));
115
+ const transferEncoding = request?.headers?.["transfer-encoding"] ?? request?.headers?.get?.("transfer-encoding");
116
+ const bodyWasReceived = request?.body !== undefined || (Number.isFinite(contentLength) && contentLength > 0) || Boolean(transferEncoding);
117
+ if (!bodyWasReceived)
118
+ return undefined;
119
+ throw new RawRequestBodyUnavailableError();
120
+ }
121
+ function setIdentityResponseHeaders(response, action) {
122
+ if (action === "limit") {
123
+ if (typeof response?.setHeader === "function")
124
+ response.setHeader("Retry-After", "60");
125
+ else if (typeof response?.header === "function")
126
+ response.header("Retry-After", "60");
127
+ }
128
+ if (action === "challenge") {
129
+ if (typeof response?.setHeader === "function")
130
+ response.setHeader("WWW-Authenticate", "ValironIdentity");
131
+ else if (typeof response?.header === "function")
132
+ response.header("WWW-Authenticate", "ValironIdentity");
133
+ }
134
+ }
135
+ /** Express/Connect middleware for ANS and other provider-backed identities. */
136
+ function createValironIdentityGate(config) {
137
+ const frozen = { ...config, policy: config.policy ? { ...config.policy } : undefined };
138
+ async function handler(request, response, next) {
139
+ const proof = (frozen.extractProof ?? defaultProof)(request);
140
+ let body;
141
+ try {
142
+ body = hasIdentityClaim(proof)
143
+ ? await exactNodeBody(request, frozen.getRawBody)
144
+ : undefined;
145
+ }
146
+ catch (error) {
147
+ if (error instanceof RawRequestBodyUnavailableError) {
148
+ response.status(400).json(bodyUnavailableBody());
149
+ return;
150
+ }
151
+ throw error;
152
+ }
153
+ const gate = await valironIdentityGateCheck(frozen.sdk, { proof, body, policy: frozen.policy });
154
+ if (gate.allow && gate.identity) {
155
+ request.valironIdentity = gate.identity;
156
+ frozen.onAllow?.(request, gate.identity);
157
+ next();
158
+ return;
159
+ }
160
+ if (gate.identity && frozen.onDeny) {
161
+ frozen.onDeny(request, response, gate.identity);
162
+ return;
163
+ }
164
+ setIdentityResponseHeaders(response, gate.action);
165
+ response.status(gate.status).json(gate.body);
166
+ }
167
+ return function valironIdentityGate(request, response, next) {
168
+ Promise.resolve(handler(request, response, next)).catch(next);
169
+ };
170
+ }
171
+ /** Fastify plugin for ANS and other provider-backed identities. */
172
+ async function valironIdentityFastifyPlugin(fastify, opts) {
173
+ if (!fastify.hasRequestDecorator?.("valironIdentity")) {
174
+ fastify.decorateRequest("valironIdentity", null);
175
+ }
176
+ fastify.addHook("preHandler", async (request, reply) => {
177
+ if (opts.prefix) {
178
+ const pathname = String(request.url ?? "").split("?")[0];
179
+ const prefix = opts.prefix.endsWith("/") && opts.prefix !== "/"
180
+ ? opts.prefix.slice(0, -1)
181
+ : opts.prefix;
182
+ if (pathname !== prefix && !pathname.startsWith(`${prefix}/`))
183
+ return;
184
+ }
185
+ const proof = (opts.extractProof ?? defaultProof)(request);
186
+ let body;
187
+ try {
188
+ body = hasIdentityClaim(proof)
189
+ ? await exactNodeBody(request, opts.getRawBody)
190
+ : undefined;
191
+ }
192
+ catch (error) {
193
+ if (error instanceof RawRequestBodyUnavailableError) {
194
+ return reply.status(400).send(bodyUnavailableBody());
195
+ }
196
+ throw error;
197
+ }
198
+ const gate = await valironIdentityGateCheck(opts.sdk, { proof, body, policy: opts.policy });
199
+ if (gate.allow && gate.identity) {
200
+ request.valironIdentity = gate.identity;
201
+ opts.onAllow?.(request, gate.identity);
202
+ return;
203
+ }
204
+ if (gate.identity && opts.onDeny)
205
+ return opts.onDeny(request, reply, gate.identity);
206
+ setIdentityResponseHeaders(reply, gate.action);
207
+ return reply.status(gate.status).send(gate.body);
208
+ });
209
+ }
210
+ /** Next.js middleware for ANS and other provider-backed identities. */
211
+ function createValironIdentityNextMiddleware(config) {
212
+ const frozen = { ...config, policy: config.policy ? { ...config.policy } : undefined };
213
+ return async function valironIdentityNextGate(request) {
214
+ if (frozen.paths?.length) {
215
+ const pathname = new URL(request.url).pathname;
216
+ if (!frozen.paths.some((path) => pathname === path || pathname.startsWith(`${path.replace(/\/$/, "")}/`))) {
217
+ return undefined;
218
+ }
219
+ }
220
+ const proof = (frozen.extractProof ?? ((req) => (0, identity_1.agentIdentityProofFromHeaders)(req.headers)))(request);
221
+ let gate;
222
+ try {
223
+ const method = request.method.toUpperCase();
224
+ const body = method === "GET" || method === "HEAD"
225
+ ? undefined
226
+ : new Uint8Array(await request.clone().arrayBuffer());
227
+ gate = await valironIdentityGateCheck(frozen.sdk, { proof, body, policy: frozen.policy });
228
+ }
229
+ catch (error) {
230
+ gate = {
231
+ hasClaim: hasIdentityClaim(proof),
232
+ ok: false,
233
+ allow: false,
234
+ status: 503,
235
+ body: unavailableBody(error),
236
+ };
237
+ }
238
+ if (gate.allow)
239
+ return undefined;
240
+ const headers = new Headers({ "content-type": "application/json" });
241
+ if (gate.action === "limit")
242
+ headers.set("retry-after", "60");
243
+ if (gate.action === "challenge")
244
+ headers.set("www-authenticate", "ValironIdentity");
245
+ return new Response(JSON.stringify(gate.body), { status: gate.status, headers });
246
+ };
247
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ValironConfig, CallOptions, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, WalletRiskSnapshot, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, RouteDecision, KeyAgentProfile, KeyAgentChallenge, WorldIdStatus, WorldIdAgentProfile, SelfAgentProfile, SelfProofPayload, SelfSessionRequest, SelfSessionResponse, SelfStatus, ProxyRequest, ProxyResponse } from "./types";
1
+ import { ValironConfig, CallOptions, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, WalletRiskSnapshot, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, RouteDecision, KeyAgentProfile, KeyAgentChallenge, WorldIdStatus, WorldIdAgentProfile, SelfAgentProfile, SelfProofPayload, SelfSessionRequest, SelfSessionResponse, SelfStatus, AgentIdentityProof, AgentIdentityPolicy, AgentIdentityVerificationResult, ProxyRequest, ProxyResponse } from "./types";
2
2
  /**
3
3
  * Valiron SDK – Official TypeScript SDK for the Trust Layer for Agentic Economy
4
4
  *
@@ -408,6 +408,8 @@ export declare class ValironSDK {
408
408
  * @param options - Optional overrides (e.g. `{ chain: 'base' }`)
409
409
  */
410
410
  getSelfProfile(agentId: string, options?: CallOptions): Promise<SelfAgentProfile>;
411
+ /** Verify ANS or another provider-backed identity and evaluate an action policy. */
412
+ verifyAgentIdentity(proof?: AgentIdentityProof, policy?: AgentIdentityPolicy): Promise<AgentIdentityVerificationResult>;
411
413
  /**
412
414
  * Flush any pending telemetry events and release resources.
413
415
  *
@@ -434,7 +436,9 @@ export * from "./types";
434
436
  export { ValironClient } from "./clients";
435
437
  export { createValironGate, valironFastifyPlugin, createValironNextMiddleware, valironGateCheck, } from "./middleware";
436
438
  export type { ValironGateConfig, ValironFastifyConfig, ValironNextConfig, ValironGateCheckResult, } from "./middleware";
437
- export { isValidAddress, generateChallenge, } from "./identity";
438
- export type { ChallengeResponse, } from "./identity";
439
+ export { createValironIdentityGate, valironIdentityFastifyPlugin, createValironIdentityNextMiddleware, valironIdentityGateCheck, } from "./identityMiddleware";
440
+ export type { ValironIdentityGateConfig, ValironIdentityFastifyConfig, ValironIdentityNextConfig, ValironIdentityGateCheckResult, } from "./identityMiddleware";
441
+ export { isValidAddress, generateChallenge, sha256RequestDigest, buildAgentIdentitySigningPayload, createAgentIdentityProof, agentIdentityProofHeaders, agentIdentityProofFromHeaders, AGENT_IDENTITY_HEADERS, } from "./identity";
442
+ export type { ChallengeResponse, AgentIdentityBody, CreateAgentIdentityProofInput, } from "./identity";
439
443
  export { ValironOperator } from "./operatorSdk";
440
444
  export type { ValironOperatorConfig, PaywallConfig } from "./operatorSdk";