@valiron/sdk 1.2.1 → 1.3.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.
@@ -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";
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.ValironOperator = exports.generateChallenge = exports.isValidAddress = exports.valironGateCheck = exports.createValironNextMiddleware = exports.valironFastifyPlugin = exports.createValironGate = exports.ValironClient = exports.ValironSDK = void 0;
17
+ exports.ValironOperator = exports.AGENT_IDENTITY_HEADERS = exports.agentIdentityProofFromHeaders = exports.agentIdentityProofHeaders = exports.createAgentIdentityProof = exports.buildAgentIdentitySigningPayload = exports.sha256RequestDigest = exports.generateChallenge = exports.isValidAddress = exports.valironIdentityGateCheck = exports.createValironIdentityNextMiddleware = exports.valironIdentityFastifyPlugin = exports.createValironIdentityGate = exports.valironGateCheck = exports.createValironNextMiddleware = exports.valironFastifyPlugin = exports.createValironGate = exports.ValironClient = exports.ValironSDK = void 0;
18
18
  const clients_1 = require("./clients");
19
19
  /**
20
20
  * Valiron SDK – Official TypeScript SDK for the Trust Layer for Agentic Economy
@@ -444,6 +444,10 @@ class ValironSDK {
444
444
  async getSelfProfile(agentId, options) {
445
445
  return this.client.getSelfProfile(agentId, options);
446
446
  }
447
+ /** Verify ANS or another provider-backed identity and evaluate an action policy. */
448
+ async verifyAgentIdentity(proof = {}, policy) {
449
+ return this.client.verifyAgentIdentity(proof, policy);
450
+ }
447
451
  /**
448
452
  * Flush any pending telemetry events and release resources.
449
453
  *
@@ -480,8 +484,19 @@ Object.defineProperty(exports, "createValironGate", { enumerable: true, get: fun
480
484
  Object.defineProperty(exports, "valironFastifyPlugin", { enumerable: true, get: function () { return middleware_1.valironFastifyPlugin; } });
481
485
  Object.defineProperty(exports, "createValironNextMiddleware", { enumerable: true, get: function () { return middleware_1.createValironNextMiddleware; } });
482
486
  Object.defineProperty(exports, "valironGateCheck", { enumerable: true, get: function () { return middleware_1.valironGateCheck; } });
487
+ var identityMiddleware_1 = require("./identityMiddleware");
488
+ Object.defineProperty(exports, "createValironIdentityGate", { enumerable: true, get: function () { return identityMiddleware_1.createValironIdentityGate; } });
489
+ Object.defineProperty(exports, "valironIdentityFastifyPlugin", { enumerable: true, get: function () { return identityMiddleware_1.valironIdentityFastifyPlugin; } });
490
+ Object.defineProperty(exports, "createValironIdentityNextMiddleware", { enumerable: true, get: function () { return identityMiddleware_1.createValironIdentityNextMiddleware; } });
491
+ Object.defineProperty(exports, "valironIdentityGateCheck", { enumerable: true, get: function () { return identityMiddleware_1.valironIdentityGateCheck; } });
483
492
  var identity_1 = require("./identity");
484
493
  Object.defineProperty(exports, "isValidAddress", { enumerable: true, get: function () { return identity_1.isValidAddress; } });
485
494
  Object.defineProperty(exports, "generateChallenge", { enumerable: true, get: function () { return identity_1.generateChallenge; } });
495
+ Object.defineProperty(exports, "sha256RequestDigest", { enumerable: true, get: function () { return identity_1.sha256RequestDigest; } });
496
+ Object.defineProperty(exports, "buildAgentIdentitySigningPayload", { enumerable: true, get: function () { return identity_1.buildAgentIdentitySigningPayload; } });
497
+ Object.defineProperty(exports, "createAgentIdentityProof", { enumerable: true, get: function () { return identity_1.createAgentIdentityProof; } });
498
+ Object.defineProperty(exports, "agentIdentityProofHeaders", { enumerable: true, get: function () { return identity_1.agentIdentityProofHeaders; } });
499
+ Object.defineProperty(exports, "agentIdentityProofFromHeaders", { enumerable: true, get: function () { return identity_1.agentIdentityProofFromHeaders; } });
500
+ Object.defineProperty(exports, "AGENT_IDENTITY_HEADERS", { enumerable: true, get: function () { return identity_1.AGENT_IDENTITY_HEADERS; } });
486
501
  var operatorSdk_1 = require("./operatorSdk");
487
502
  Object.defineProperty(exports, "ValironOperator", { enumerable: true, get: function () { return operatorSdk_1.ValironOperator; } });
@@ -67,6 +67,13 @@ class ValironOperator {
67
67
  icebreaker_included: trustSignals.includes("icebreaker"),
68
68
  self_included: trustSignals.includes("self"),
69
69
  wallet_included: trustSignals.includes("wallet"),
70
+ decision: entry.decision,
71
+ error_code: entry.errorCode || undefined,
72
+ request_id: entry.requestId || undefined,
73
+ identity_type: entry.identityType,
74
+ trust_route: entry.trustRoute || undefined,
75
+ trust_tier: entry.trustTier || undefined,
76
+ trust_score: entry.trustScore ?? undefined,
70
77
  };
71
78
  void fetch(this.buildAnalyticsUrl(), {
72
79
  method: "POST",
@@ -171,6 +178,13 @@ class ValironOperator {
171
178
  ipAddress: this.expressIp(req),
172
179
  errorMessage,
173
180
  trustSignals: config.trustSignals,
181
+ decision: allowed ? "allowed" : statusCode === 503 ? "unavailable" : "denied",
182
+ errorCode: !allowed ? (statusCode === 503 ? "TRUST_GATE_UNAVAILABLE" : "TRUST_GATE_DENIED") : undefined,
183
+ requestId: this.extractHeader(req, "x-request-id"),
184
+ identityType: gate?.agentId ? "onchain" : this.extractHeader(req, "x-agent-address") ? "key" : "missing",
185
+ trustRoute: gate?.route,
186
+ trustTier: gate?.tier,
187
+ trustScore: gate?.score,
174
188
  });
175
189
  };
176
190
  if (typeof res.once === "function") {
@@ -256,6 +270,13 @@ class ValironOperator {
256
270
  ipAddress: request.ip || this.extractHeader(request, "x-forwarded-for")?.split(",")[0]?.trim() || null,
257
271
  errorMessage,
258
272
  trustSignals: config.trustSignals,
273
+ decision: allowed ? "allowed" : statusCode === 503 ? "unavailable" : "denied",
274
+ errorCode: !allowed ? (statusCode === 503 ? "TRUST_GATE_UNAVAILABLE" : "TRUST_GATE_DENIED") : undefined,
275
+ requestId: this.extractHeader(request, "x-request-id"),
276
+ identityType: gate?.agentId ? "onchain" : this.extractHeader(request, "x-agent-address") ? "key" : "missing",
277
+ trustRoute: gate?.route,
278
+ trustTier: gate?.tier,
279
+ trustScore: gate?.score,
259
280
  });
260
281
  });
261
282
  done();
package/dist/telemetry.js CHANGED
@@ -1,7 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TelemetryClient = void 0;
4
- const SDK_VERSION = "1.1.1";
4
+ // Read the shipped package version so releases cannot drift from telemetry.
5
+ const SDK_VERSION = require("../package.json").version;
6
+ function detectEnvironment() {
7
+ const nodeEnv = globalThis.process?.env?.NODE_ENV;
8
+ if (nodeEnv === "production")
9
+ return "prod";
10
+ if (nodeEnv === "development")
11
+ return "dev";
12
+ if (nodeEnv === "test")
13
+ return "test";
14
+ return "unknown";
15
+ }
5
16
  function detectRuntime() {
6
17
  return typeof globalThis.window === "undefined" ? "node" : "browser";
7
18
  }
@@ -26,7 +37,7 @@ class TelemetryClient {
26
37
  this.endpoint = config?.endpoint || `${apiEndpoint.replace(/\/$/, "")}/telemetry/sdk`;
27
38
  this.appId = config?.appId;
28
39
  this.workspaceId = config?.workspaceId;
29
- this.env = config?.env || "prod";
40
+ this.env = config?.env ?? detectEnvironment();
30
41
  this.runtime = detectRuntime();
31
42
  this.sampleRate = Math.max(0, Math.min(1, config?.sampleRate ?? 1));
32
43
  this.batchSize = Math.max(1, config?.batchSize ?? 25);
@@ -62,9 +73,10 @@ class TelemetryClient {
62
73
  emit(event, payload) {
63
74
  if (!this.enabled)
64
75
  return;
65
- if (Math.random() > this.sampleRate)
76
+ if (this.sampleRate <= 0 || Math.random() >= this.sampleRate)
66
77
  return;
67
78
  const enriched = {
79
+ ...payload,
68
80
  event,
69
81
  ts: new Date().toISOString(),
70
82
  sdk_version: SDK_VERSION,
@@ -72,9 +84,13 @@ class TelemetryClient {
72
84
  env: this.env,
73
85
  app_id: this.appId,
74
86
  workspace_id: this.workspaceId,
75
- ...payload,
87
+ sample_rate: this.sampleRate,
76
88
  };
77
- this.onEvent?.(enriched);
89
+ // A telemetry callback must never change the outcome of the observed API call.
90
+ try {
91
+ this.onEvent?.({ ...enriched });
92
+ }
93
+ catch { /* Best-effort telemetry. */ }
78
94
  this.queue.push(enriched);
79
95
  if (this.queue.length >= this.batchSize) {
80
96
  void this.flush();
@@ -100,11 +116,15 @@ class TelemetryClient {
100
116
  return;
101
117
  const batch = this.queue.splice(0, this.queue.length);
102
118
  try {
103
- await fetch(this.endpoint, {
104
- method: "POST",
105
- headers: { "Content-Type": "application/json" },
106
- body: JSON.stringify({ events: batch }),
107
- });
119
+ // Keep every request within the ingestion limit, including final disposal
120
+ // and custom batch sizes.
121
+ for (let offset = 0; offset < batch.length; offset += 100) {
122
+ await fetch(this.endpoint, {
123
+ method: "POST",
124
+ headers: { "Content-Type": "application/json" },
125
+ body: JSON.stringify({ events: batch.slice(offset, offset + 100) }),
126
+ });
127
+ }
108
128
  }
109
129
  catch {
110
130
  // Best-effort telemetry: drop on failures to avoid impacting SDK consumers.
package/dist/types.d.ts CHANGED
@@ -11,6 +11,50 @@ export type RiskLevel = "GREEN" | "YELLOW" | "RED";
11
11
  export type MoodysRating = "AAA" | "AA" | "A" | "BAA" | "BA" | "B" | "CAA" | "CA" | "C";
12
12
  export type TrustSignal = "8004" | "sandbox" | "world" | "icebreaker" | "self" | "wallet";
13
13
  export type WalletRiskLevel = "LOW" | "MEDIUM" | "HIGH" | "CRITICAL";
14
+ export type AgentIdentityStatus = "anonymous" | "claimed" | "verified";
15
+ export type AgentIdentityPolicyAction = "allow" | "limit" | "challenge" | "block";
16
+ /** Proof submitted to Valiron's provider-independent identity verifier. */
17
+ export interface AgentIdentityProof {
18
+ provider?: string;
19
+ agentId?: string;
20
+ signature?: string;
21
+ timestamp?: string;
22
+ nonce?: string;
23
+ requestDigest?: string;
24
+ keyId?: string;
25
+ }
26
+ /** Proof fields transported with an HTTP request. The receiving gate computes requestDigest itself. */
27
+ export type AgentIdentityTransportProof = Omit<AgentIdentityProof, "requestDigest">;
28
+ export interface AgentIdentityPolicy {
29
+ anonymous?: AgentIdentityPolicyAction;
30
+ claimed?: AgentIdentityPolicyAction;
31
+ verified?: AgentIdentityPolicyAction;
32
+ belowMinimumScore?: AgentIdentityPolicyAction;
33
+ minReputationScore?: number;
34
+ mediumRisk?: AgentIdentityPolicyAction;
35
+ highRisk?: AgentIdentityPolicyAction;
36
+ }
37
+ export interface AgentIdentityPolicyDecision {
38
+ action: AgentIdentityPolicyAction;
39
+ reason: string;
40
+ }
41
+ /** Normalized provider identity, Valiron reputation, and the caller-selected policy decision. */
42
+ export interface AgentIdentityVerificationResult {
43
+ agentId: string | null;
44
+ provider: string | null;
45
+ organization: string | null;
46
+ identityStatus: AgentIdentityStatus;
47
+ humanIdentified: false;
48
+ stableIdentityId: string | null;
49
+ credentialId?: string;
50
+ credentialVersion?: string;
51
+ externalTrust?: Record<string, unknown>;
52
+ verifiedAt: string | null;
53
+ failureReason?: string;
54
+ reputationScore: number | null;
55
+ riskLevel: "low" | "medium" | "high" | "unknown";
56
+ policyDecision: AgentIdentityPolicyDecision;
57
+ }
14
58
  export interface AgentIdentity {
15
59
  agentId: string;
16
60
  wallet: string;
@@ -507,7 +551,7 @@ export interface CallOptions {
507
551
  /** Customer-selected scoring signals for profile/routing calls. */
508
552
  trustSignals?: TrustSignal[];
509
553
  }
510
- export type TelemetryEnvironment = "prod" | "staging" | "dev";
554
+ export type TelemetryEnvironment = "prod" | "staging" | "dev" | "test" | "unknown";
511
555
  export interface TelemetryEventBase {
512
556
  event: string;
513
557
  ts: string;
@@ -523,6 +567,7 @@ export interface TelemetryConfig {
523
567
  endpoint?: string;
524
568
  appId?: string;
525
569
  workspaceId?: string;
570
+ /** Defaults to NODE_ENV when recognized, otherwise unknown. */
526
571
  env?: TelemetryEnvironment;
527
572
  sampleRate?: number;
528
573
  flushIntervalMs?: number;
@@ -13,6 +13,13 @@ Agent or client
13
13
  -> response returned through Valiron
14
14
  ```
15
15
 
16
+ > **Important: protect the origin.** A hosted wrapper evaluates and logs only
17
+ > requests sent to its Valiron URL. It is not a network firewall in front of a
18
+ > separately public API origin. If callers can reach your origin directly, they
19
+ > can bypass the wrapper's payment, trust, rate-limit, and analytics path.
20
+ > Publish the generated wrapper URL as the agent-facing URL and configure your
21
+ > origin to accept only authenticated requests from Valiron.
22
+
16
23
  The wrapper is intentionally narrow: Valiron forwards valid HTTP requests to an existing upstream API. It does not need direct database access, internal service access, or provider infrastructure credentials beyond the optional upstream auth secret needed to call the API.
17
24
 
18
25
  ## When To Use This
@@ -43,7 +50,7 @@ Providers configure one wrapper per public endpoint.
43
50
  | Payment protocol | Yes | `x402` or `MPP`. |
44
51
  | Payment network | Yes | x402: `eip155:8453` or `eip155:84532`; MPP: `tempo:4217` or `tempo:42431`. |
45
52
  | Payout wallet | Paid only | EVM address receiving payment. |
46
- | Upstream auth | No | Secret Valiron injects when forwarding to your upstream. |
53
+ | Upstream auth | Required to prevent origin bypass | Auth Valiron adds when forwarding to your upstream. Use `hmac` for a public origin. |
47
54
  | Rate limit | No | Max requests per minute per client. |
48
55
  | Trust check | No | Whether callers must pass Valiron agent trust evaluation before forwarding. |
49
56
 
@@ -72,9 +79,12 @@ https://api.example.com/v1/weather
72
79
  3. Click **Make API Agent-Ready**.
73
80
  4. Enter the upstream URL, public path, method, price, protocol, network, and payout wallet.
74
81
  5. Choose whether Valiron trust checks are required.
75
- 6. Configure upstream auth only if your API needs it.
82
+ 6. Configure upstream authentication. For a public origin, choose `hmac` and
83
+ store the same secret in your origin's verification middleware.
76
84
  7. Create the wrapper.
77
- 8. Distribute the generated Valiron URL to agent clients or API customers.
85
+ 8. Distribute only the generated Valiron URL to agent clients or API customers.
86
+ 9. Verify that a direct request to your origin is rejected and a request to the
87
+ wrapper is recorded in Valiron call logs.
78
88
 
79
89
  ## HTTP API Flow
80
90
 
@@ -117,7 +127,8 @@ curl -X POST https://valiron-edge-proxy.onrender.com/operator/endpoints \
117
127
  "paymentProtocol": "x402",
118
128
  "paymentNetwork": "eip155:8453",
119
129
  "trustEnabled": false,
120
- "upstreamAuthType": "none"
130
+ "upstreamAuthType": "hmac",
131
+ "upstreamAuthSecret": "replace-with-a-unique-shared-secret"
121
132
  }'
122
133
  ```
123
134
 
@@ -136,7 +147,8 @@ curl -X POST https://valiron-edge-proxy.onrender.com/operator/endpoints \
136
147
  "paymentNetwork": "eip155:8453",
137
148
  "payoutAddress": "0xYourPayoutWallet",
138
149
  "trustEnabled": false,
139
- "upstreamAuthType": "none"
150
+ "upstreamAuthType": "hmac",
151
+ "upstreamAuthSecret": "replace-with-a-unique-shared-secret"
140
152
  }'
141
153
  ```
142
154
 
@@ -155,7 +167,8 @@ curl -X POST https://valiron-edge-proxy.onrender.com/operator/endpoints \
155
167
  "paymentNetwork": "tempo:4217",
156
168
  "payoutAddress": "0xYourPayoutWallet",
157
169
  "trustEnabled": false,
158
- "upstreamAuthType": "none"
170
+ "upstreamAuthType": "hmac",
171
+ "upstreamAuthSecret": "replace-with-a-unique-shared-secret"
159
172
  }'
160
173
  ```
161
174
 
@@ -299,7 +312,15 @@ Use payment-only wrappers when:
299
312
 
300
313
  ## Upstream Auth
301
314
 
302
- If your existing API requires auth, Valiron stores the secret encrypted and injects it only when forwarding a valid request upstream.
315
+ Valiron stores the configured secret encrypted and injects or derives it only
316
+ when forwarding a request that has reached the wrapper. This is how your origin
317
+ distinguishes an authenticated wrapper request from a direct public request.
318
+
319
+ For a public API origin, configure upstream authentication before announcing or
320
+ indexing the wrapper. Otherwise, a caller can send traffic directly to the
321
+ origin and bypass Valiron entirely. `none` is appropriate only when the origin
322
+ is already inaccessible to untrusted callers or bypass is intentionally
323
+ acceptable.
303
324
 
304
325
  Supported auth modes:
305
326
 
@@ -312,6 +333,40 @@ Supported auth modes:
312
333
 
313
334
  The calling agent never sees your upstream secret.
314
335
 
336
+ ### Recommended production pattern: HMAC origin verification
337
+
338
+ Choose `hmac` for an origin that is publicly reachable. Valiron sends:
339
+
340
+ ```text
341
+ x-valiron-signature: sha256=<hex HMAC>
342
+ x-valiron-timestamp: <Unix seconds>
343
+ ```
344
+
345
+ Your origin must reject requests when the signature is missing, invalid, or too
346
+ old. Verify the signature against the request method, public wrapper path, raw
347
+ body SHA-256, and timestamp with the shared secret configured on the wrapper.
348
+ Use constant-time signature comparison and a short timestamp window to reduce
349
+ replay risk.
350
+
351
+ Do **not** treat headers such as `x-valiron-wrapper-id`,
352
+ `x-valiron-payment-protocol`, or `x-valiron-trust-enabled` as proof that a
353
+ request came through Valiron. They are request metadata, not a credential, and
354
+ can be forged by a caller that reaches your origin directly.
355
+
356
+ ### Origin-lockdown checklist
357
+
358
+ Before production:
359
+
360
+ 1. Set `upstreamAuthType` to `hmac` and configure a unique secret.
361
+ 2. Deploy origin middleware that verifies the HMAC and timestamp before the API
362
+ handler runs.
363
+ 3. Make the Valiron `/wrap/{operatorId}/{path}` URL the only public URL in
364
+ agent discovery metadata, examples, and client configuration.
365
+ 4. Send a direct request to the origin without the signature and confirm a
366
+ `401` or `403` response.
367
+ 5. Send a request through the wrapper and confirm the expected payment/trust
368
+ result and a corresponding Valiron call-log entry.
369
+
315
370
  Production requires `VALIRON_SECRET_ENCRYPTION_KEY` to store upstream auth secrets. Use a 32-byte hex key:
316
371
 
317
372
  ```bash