@valiron/sdk 1.4.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +11 -148
  2. package/bin/valiron-card.mjs +211 -0
  3. package/dist/card.d.ts +565 -0
  4. package/dist/card.js +722 -0
  5. package/dist/clients.d.ts +6 -6
  6. package/dist/clients.js +33 -26
  7. package/dist/edge.d.ts +87 -0
  8. package/dist/edge.js +164 -0
  9. package/dist/edgeGate.d.ts +146 -0
  10. package/dist/edgeGate.js +230 -0
  11. package/dist/edgeGateVerify.d.ts +146 -0
  12. package/dist/edgeGateVerify.js +243 -0
  13. package/dist/identity.d.ts +6 -0
  14. package/dist/identity.js +6 -1
  15. package/dist/identityMiddleware.d.ts +8 -0
  16. package/dist/identityMiddleware.js +12 -4
  17. package/dist/index.d.ts +5 -10
  18. package/dist/index.js +4 -10
  19. package/dist/middleware.d.ts +20 -9
  20. package/dist/middleware.js +47 -19
  21. package/dist/operatorSdk.d.ts +11 -2
  22. package/dist/operatorSdk.js +13 -7
  23. package/dist/types.d.ts +14 -4
  24. package/docs/AGENT-READY-APIS.md +3 -181
  25. package/docs/API-REFERENCE.md +94 -546
  26. package/docs/CHAINS.md +3 -3
  27. package/docs/CLOUDFLARE-GATE-MIDDLEWARE.md +196 -0
  28. package/docs/CRAWLER-PROTECTION.md +545 -0
  29. package/docs/DASHBOARD.md +55 -23
  30. package/docs/E2E-MIDDLEWARE-INTEGRATION.md +19 -13
  31. package/docs/ERRORS.md +29 -19
  32. package/docs/IDENTITY.md +16 -14
  33. package/docs/PROVIDER-IDENTITY.md +15 -5
  34. package/docs/QUICKSTART.md +40 -24
  35. package/docs/README.md +21 -4
  36. package/docs/SANDBOX.md +7 -1
  37. package/docs/SDK-REFERENCE.md +115 -52
  38. package/docs/SECURITY-UPGRADE-2026-10-31.md +98 -0
  39. package/docs/TRUST-MODEL.md +14 -11
  40. package/docs/llms.txt +70 -302
  41. package/examples/cloudflare-gate-worker/README.md +198 -0
  42. package/examples/cloudflare-gate-worker/package.json +20 -0
  43. package/examples/cloudflare-gate-worker/worker.ts +309 -0
  44. package/examples/cloudflare-gate-worker/wrangler.toml +46 -0
  45. package/examples/cloudflare-worker/package.json +8 -0
  46. package/examples/cloudflare-worker/worker.ts +495 -0
  47. package/examples/cloudflare-worker/wrangler.toml +57 -0
  48. package/package.json +35 -5
  49. package/docs/MCP.md +0 -50
@@ -3,6 +3,9 @@ import { type AgentIdentityBody } from "./identity";
3
3
  import type { AgentIdentityPolicy, AgentIdentityPolicyAction, AgentIdentityTransportProof, AgentIdentityVerificationResult } from "./types";
4
4
  type MaybePromise<T> = T | Promise<T>;
5
5
  export interface ValironIdentityGateConfig {
6
+ /** Trusted API origin and audience, configured by the API owner. */
7
+ audience?: string;
8
+ origin?: string;
6
9
  sdk: ValironSDK;
7
10
  /** Policy evaluated by Valiron after identity and reputation checks. */
8
11
  policy?: AgentIdentityPolicy;
@@ -21,6 +24,8 @@ export interface ValironIdentityFastifyConfig extends ValironIdentityGateConfig
21
24
  prefix?: string;
22
25
  }
23
26
  export interface ValironIdentityNextConfig {
27
+ audience?: string;
28
+ origin?: string;
24
29
  sdk: ValironSDK;
25
30
  policy?: AgentIdentityPolicy;
26
31
  paths?: string[];
@@ -40,6 +45,9 @@ export declare function valironIdentityGateCheck(sdk: ValironSDK, input?: {
40
45
  proof?: AgentIdentityTransportProof;
41
46
  body?: AgentIdentityBody;
42
47
  policy?: AgentIdentityPolicy;
48
+ audience?: string;
49
+ method?: string;
50
+ url?: string;
43
51
  }): Promise<ValironIdentityGateCheckResult>;
44
52
  /** Express/Connect middleware for ANS and other provider-backed identities. */
45
53
  export declare function createValironIdentityGate(config: ValironIdentityGateConfig): (request: any, response: any, next: any) => void;
@@ -74,7 +74,9 @@ async function valironIdentityGateCheck(sdk, input = {}) {
74
74
  const proof = input.proof ?? {};
75
75
  const hasClaim = hasIdentityClaim(proof);
76
76
  try {
77
- const identity = await sdk.verifyAgentIdentity({ ...proof, requestDigest: (0, identity_1.sha256RequestDigest)(input.body) }, input.policy);
77
+ if (!input.audience || !input.method || !input.url)
78
+ throw new Error("Trusted request context required");
79
+ const identity = await sdk.verifyAgentIdentity({ ...proof, requestDigest: (0, identity_1.sha256RequestDigest)(input.body), audience: input.audience, method: input.method.toUpperCase(), url: input.url }, input.policy);
78
80
  const action = identity.policyDecision.action;
79
81
  const allow = action === "allow";
80
82
  return {
@@ -150,7 +152,7 @@ function createValironIdentityGate(config) {
150
152
  }
151
153
  throw error;
152
154
  }
153
- const gate = await valironIdentityGateCheck(frozen.sdk, { proof, body, policy: frozen.policy });
155
+ const gate = await valironIdentityGateCheck(frozen.sdk, { proof, body, policy: frozen.policy, audience: frozen.audience, method: request.method, url: boundUrl(request, frozen.origin) });
154
156
  if (gate.allow && gate.identity) {
155
157
  request.valironIdentity = gate.identity;
156
158
  frozen.onAllow?.(request, gate.identity);
@@ -195,7 +197,7 @@ async function valironIdentityFastifyPlugin(fastify, opts) {
195
197
  }
196
198
  throw error;
197
199
  }
198
- const gate = await valironIdentityGateCheck(opts.sdk, { proof, body, policy: opts.policy });
200
+ const gate = await valironIdentityGateCheck(opts.sdk, { proof, body, policy: opts.policy, audience: opts.audience, method: request.method, url: boundUrl(request, opts.origin) });
199
201
  if (gate.allow && gate.identity) {
200
202
  request.valironIdentity = gate.identity;
201
203
  opts.onAllow?.(request, gate.identity);
@@ -224,7 +226,7 @@ function createValironIdentityNextMiddleware(config) {
224
226
  const body = method === "GET" || method === "HEAD"
225
227
  ? undefined
226
228
  : new Uint8Array(await request.clone().arrayBuffer());
227
- gate = await valironIdentityGateCheck(frozen.sdk, { proof, body, policy: frozen.policy });
229
+ gate = await valironIdentityGateCheck(frozen.sdk, { proof, body, policy: frozen.policy, audience: frozen.audience, method: request.method, url: boundUrl(request, frozen.origin) });
228
230
  }
229
231
  catch (error) {
230
232
  gate = {
@@ -245,3 +247,9 @@ function createValironIdentityNextMiddleware(config) {
245
247
  return new Response(JSON.stringify(gate.body), { status: gate.status, headers });
246
248
  };
247
249
  }
250
+ function boundUrl(request, origin) {
251
+ if (!origin)
252
+ return undefined;
253
+ const url = new URL(request.originalUrl || request.url, origin);
254
+ return url.origin === new URL(origin).origin ? url.toString() : undefined;
255
+ }
package/dist/index.d.ts CHANGED
@@ -281,7 +281,7 @@ export declare class ValironSDK {
281
281
  /**
282
282
  * Get trust profile for a key-based agent by its Ethereum address.
283
283
  *
284
- * Returns behavioral score. Icebreaker ownership is redacted from this public profile.
284
+ * Returns behavioral score. Icebreaker ownership is redacted from this authenticated summary.
285
285
  * Use getKeyAgentIcebreaker() with a Pro operator key for the owner context.
286
286
  * The agent must have been verified via challenge-response at least once.
287
287
  *
@@ -319,6 +319,7 @@ export declare class ValironSDK {
319
319
  merkle_root: string;
320
320
  nullifier_hash: string;
321
321
  verification_level: "orb" | "device" | "phone";
322
+ idkit_result?: unknown;
322
323
  }, options?: CallOptions): Promise<{
323
324
  ok: boolean;
324
325
  agentId: string;
@@ -377,15 +378,9 @@ export declare class ValironSDK {
377
378
  */
378
379
  createSelfSession(agentId: string, request?: SelfSessionRequest, options?: CallOptions): Promise<SelfSessionResponse>;
379
380
  /**
380
- * Store a Self verified eligible-human proof and optional Self Agent ID link.
381
- *
382
- * Production integrations should use `createSelfSession()` and the signed
383
- * Self webhook. This method is only useful when the server explicitly allows
384
- * trusted payload ingestion for local or internal tests.
385
- *
386
- * @param agentId - The ERC-8004 agent ID
387
- * @param proof - Verified Self proof predicates and optional Agent ID link
388
- * @param options - Optional overrides (e.g. `{ chain: 'base' }`)
381
+ * @deprecated Not supported for hosted customer integrations. Use
382
+ * `createSelfSession()` and `getSelfStatus()`. Retained for compatibility;
383
+ * scheduled for removal in the next major SDK release.
389
384
  */
390
385
  verifySelf(agentId: string, proof: SelfProofPayload, options?: CallOptions): Promise<{
391
386
  ok: boolean;
package/dist/index.js CHANGED
@@ -322,7 +322,7 @@ class ValironSDK {
322
322
  /**
323
323
  * Get trust profile for a key-based agent by its Ethereum address.
324
324
  *
325
- * Returns behavioral score. Icebreaker ownership is redacted from this public profile.
325
+ * Returns behavioral score. Icebreaker ownership is redacted from this authenticated summary.
326
326
  * Use getKeyAgentIcebreaker() with a Pro operator key for the owner context.
327
327
  * The agent must have been verified via challenge-response at least once.
328
328
  *
@@ -418,15 +418,9 @@ class ValironSDK {
418
418
  return this.client.createSelfSession(agentId, request, options);
419
419
  }
420
420
  /**
421
- * Store a Self verified eligible-human proof and optional Self Agent ID link.
422
- *
423
- * Production integrations should use `createSelfSession()` and the signed
424
- * Self webhook. This method is only useful when the server explicitly allows
425
- * trusted payload ingestion for local or internal tests.
426
- *
427
- * @param agentId - The ERC-8004 agent ID
428
- * @param proof - Verified Self proof predicates and optional Agent ID link
429
- * @param options - Optional overrides (e.g. `{ chain: 'base' }`)
421
+ * @deprecated Not supported for hosted customer integrations. Use
422
+ * `createSelfSession()` and `getSelfStatus()`. Retained for compatibility;
423
+ * scheduled for removal in the next major SDK release.
430
424
  */
431
425
  async verifySelf(agentId, proof, options) {
432
426
  return this.client.verifySelf(agentId, proof, options);
@@ -21,9 +21,11 @@ export interface ValironGateConfig {
21
21
  * Defaults to reading `x-agent-address` header (falls back to `x-agent-key-hash`).
22
22
  */
23
23
  extractAgentAddress?: (req: any) => string | null;
24
+ /** Required: verify a fresh cryptographic proof bound to this identity, method, URL and raw body; enforce replay protection. */
25
+ verifyRequest?: (request: any, identifier: string) => Promise<boolean>;
24
26
  /** Minimum Valiron score to allow (default: 65). */
25
27
  minScore?: number;
26
- /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+self+icebreaker+wallet. */
28
+ /** Customer-selected scoring signals. Free includes 8004, sandbox, world, self, and wallet; Pro adds icebreaker (Social Graph). */
27
29
  trustSignals?: TrustSignal[];
28
30
  /**
29
31
  * Client-side profile cache TTL in ms.
@@ -58,15 +60,16 @@ export interface ValironGateConfig {
58
60
  * ```typescript
59
61
  * import { ValironSDK, createValironGate } from '@valiron/sdk';
60
62
  *
61
- * const valiron = new ValironSDK({ chain: 'monad' });
63
+ * const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
62
64
  *
63
65
  * // Apply before your x402 / payment handler
64
66
  * // Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
65
- * app.use('/api/paid', createValironGate({ sdk: valiron }));
67
+ * app.use('/api/paid', createValironGate({ sdk: valiron, verifyRequest: verifyAgentRequest }));
66
68
  *
67
69
  * // Custom threshold + cache TTL
68
70
  * app.use('/api/premium', createValironGate({
69
71
  * sdk: valiron,
72
+ * verifyRequest: verifyAgentRequest, // application-owned request signature verifier
70
73
  * minScore: 85,
71
74
  * cacheTtlMs: 60_000, // 60s client-side cache
72
75
  * }));
@@ -77,6 +80,7 @@ export declare function createValironGate(config: ValironGateConfig): (req: any,
77
80
  * Configuration for the Fastify Valiron trust gate plugin.
78
81
  */
79
82
  export interface ValironFastifyConfig {
83
+ verifyRequest?: ValironGateConfig["verifyRequest"];
80
84
  /** Configured ValironSDK instance. */
81
85
  sdk: ValironSDK;
82
86
  /**
@@ -91,7 +95,7 @@ export interface ValironFastifyConfig {
91
95
  extractAgentAddress?: (req: any) => string | null;
92
96
  /** Minimum Valiron score to allow (default: 65). */
93
97
  minScore?: number;
94
- /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+self+icebreaker+wallet. */
98
+ /** Customer-selected scoring signals. Free includes 8004, sandbox, world, self, and wallet; Pro adds icebreaker (Social Graph). */
95
99
  trustSignals?: TrustSignal[];
96
100
  /**
97
101
  * Client-side profile cache TTL in ms (default: 30000).
@@ -122,7 +126,7 @@ export interface ValironFastifyConfig {
122
126
  * import { ValironSDK, valironFastifyPlugin } from '@valiron/sdk';
123
127
  *
124
128
  * const app = Fastify();
125
- * const valiron = new ValironSDK({ chain: 'monad' });
129
+ * const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
126
130
  *
127
131
  * // Gate all routes
128
132
  * app.register(valironFastifyPlugin, { sdk: valiron });
@@ -130,6 +134,7 @@ export interface ValironFastifyConfig {
130
134
  * // Or gate a specific prefix
131
135
  * app.register(valironFastifyPlugin, {
132
136
  * sdk: valiron,
137
+ * verifyRequest: verifyAgentRequest, // application-owned request signature verifier
133
138
  * prefix: '/api',
134
139
  * minScore: 85,
135
140
  * });
@@ -140,6 +145,7 @@ export declare function valironFastifyPlugin(fastify: any, opts: ValironFastifyC
140
145
  * Configuration for the Next.js Valiron gate.
141
146
  */
142
147
  export interface ValironNextConfig {
148
+ verifyRequest?: (request: Request, identifier: string) => Promise<boolean>;
143
149
  /** Configured ValironSDK instance. */
144
150
  sdk: ValironSDK;
145
151
  /**
@@ -154,7 +160,7 @@ export interface ValironNextConfig {
154
160
  extractAgentAddress?: (req: Request) => string | null;
155
161
  /** Minimum Valiron score to allow (default: 65). */
156
162
  minScore?: number;
157
- /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+self+icebreaker+wallet. */
163
+ /** Customer-selected scoring signals. Free includes 8004, sandbox, world, self, and wallet; Pro adds icebreaker (Social Graph). */
158
164
  trustSignals?: TrustSignal[];
159
165
  /**
160
166
  * Client-side profile cache TTL in ms (default: 30000).
@@ -180,10 +186,11 @@ export interface ValironNextConfig {
180
186
  * // middleware.ts (Next.js project root)
181
187
  * import { ValironSDK, createValironNextMiddleware } from '@valiron/sdk';
182
188
  *
183
- * const valiron = new ValironSDK({ chain: 'monad' });
189
+ * const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
184
190
  *
185
191
  * const valironMiddleware = createValironNextMiddleware({
186
192
  * sdk: valiron,
193
+ * verifyRequest: verifyAgentRequest, // application-owned request signature verifier
187
194
  * paths: ['/api/paid'],
188
195
  * minScore: 65,
189
196
  * });
@@ -232,7 +239,7 @@ export interface ValironGateCheckResult {
232
239
  * import { Hono } from 'hono';
233
240
  * import { ValironSDK, valironGateCheck } from '@valiron/sdk';
234
241
  *
235
- * const valiron = new ValironSDK({ chain: 'monad' });
242
+ * const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
236
243
  * const app = new Hono();
237
244
  *
238
245
  * app.use('/api/*', async (c, next) => {
@@ -265,12 +272,16 @@ export interface ValironGateCheckResult {
265
272
  * ```
266
273
  */
267
274
  export declare function valironGateCheck(sdk: ValironSDK, opts: {
275
+ /** Retain automatic evaluation work after an edge response. */
276
+ waitUntil?: (pending: Promise<unknown>) => void;
268
277
  /** On-chain agent ID (ERC-8004 / Solana). */
269
278
  agentId?: string | null;
270
279
  /** Key-based agent hash (web2). Checked if agentId is not provided. */
271
280
  agentAddress?: string | null;
281
+ /** Verify ownership and request binding before every decision, including cache hits. */
282
+ verifyRequest?: (identifier: string) => Promise<boolean>;
272
283
  minScore?: number;
273
- /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+self+icebreaker+wallet. */
284
+ /** Customer-selected scoring signals. Free includes 8004, sandbox, world, self, and wallet; Pro adds icebreaker (Social Graph). */
274
285
  trustSignals?: TrustSignal[];
275
286
  /**
276
287
  * Client-side profile cache TTL in ms (default: 30000).
@@ -71,7 +71,8 @@ function keyProfileToGateResult(profile, minScore) {
71
71
  const tier = (profile.tier ?? "C");
72
72
  const riskLevel = (profile.riskLevel ?? "RED");
73
73
  const route = (profile.route ?? "sandbox_only");
74
- const allow = profile.verified && score >= minScore;
74
+ const isProductionRoute = route === "prod" || route === "prod_throttled";
75
+ const allow = profile.verified && isProductionRoute && score >= minScore;
75
76
  return {
76
77
  allow,
77
78
  score,
@@ -236,11 +237,21 @@ function emitGateTelemetry(sdk, payload) {
236
237
  async function runGateCheck(config, req, cache) {
237
238
  const minScore = config.minScore ?? 65;
238
239
  const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
240
+ const claimed = (config.extractAgentId || defaultExtractAgentId)(req) || (config.extractAgentAddress || defaultExtractAgentAddress)(req);
241
+ if (claimed) {
242
+ try {
243
+ if (!config.verifyRequest || !await config.verifyRequest(req, claimed))
244
+ return { agentId: claimed, ownershipRequired: true };
245
+ }
246
+ catch (error) {
247
+ return { agentId: claimed, error };
248
+ }
249
+ }
239
250
  // 1. Try on-chain agent ID (ERC-8004 / Solana)
240
251
  const extractAgentId = config.extractAgentId || defaultExtractAgentId;
241
252
  const agentId = extractAgentId(req);
242
253
  if (agentId) {
243
- const agentCacheKey = cacheKeyFor(agentId, config.trustSignals);
254
+ const agentCacheKey = cacheKeyFor(agentId, config.trustSignals) + ":" + minScore;
244
255
  // Check client-side cache first
245
256
  if (cacheTtl > 0) {
246
257
  const cached = cache.getCached(agentCacheKey, cacheTtl);
@@ -248,9 +259,8 @@ async function runGateCheck(config, req, cache) {
248
259
  return { agentId, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
249
260
  }
250
261
  try {
251
- // Use getAgentProfile() which hits the PUBLIC /operator/agent/ endpoint.
252
- // The old gate() call used POST /operator/gate/ which is protected by
253
- // agent challenge-response auth and fails from server contexts.
262
+ // Read the authenticated profile after the local caller verifier passes.
263
+ // Hosted gate() calls instead require a registry-owner request signature.
254
264
  const profile = await config.sdk.getAgentProfile(agentId, {
255
265
  trustSignals: normalizeTrustSignals(config.trustSignals),
256
266
  });
@@ -276,7 +286,7 @@ async function runGateCheck(config, req, cache) {
276
286
  const extractAddress = config.extractAgentAddress || defaultExtractAgentAddress;
277
287
  const agentAddr = extractAddress(req);
278
288
  if (agentAddr) {
279
- const agentCacheKey = cacheKeyFor(agentAddr, config.trustSignals);
289
+ const agentCacheKey = cacheKeyFor(agentAddr, config.trustSignals) + ":" + minScore;
280
290
  // Check client-side cache first
281
291
  if (cacheTtl > 0) {
282
292
  const cached = cache.getCached(agentCacheKey, cacheTtl);
@@ -323,15 +333,16 @@ async function runGateCheck(config, req, cache) {
323
333
  * ```typescript
324
334
  * import { ValironSDK, createValironGate } from '@valiron/sdk';
325
335
  *
326
- * const valiron = new ValironSDK({ chain: 'monad' });
336
+ * const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
327
337
  *
328
338
  * // Apply before your x402 / payment handler
329
339
  * // Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
330
- * app.use('/api/paid', createValironGate({ sdk: valiron }));
340
+ * app.use('/api/paid', createValironGate({ sdk: valiron, verifyRequest: verifyAgentRequest }));
331
341
  *
332
342
  * // Custom threshold + cache TTL
333
343
  * app.use('/api/premium', createValironGate({
334
344
  * sdk: valiron,
345
+ * verifyRequest: verifyAgentRequest, // application-owned request signature verifier
335
346
  * minScore: 85,
336
347
  * cacheTtlMs: 60_000, // 60s client-side cache
337
348
  * }));
@@ -344,7 +355,7 @@ function createValironGate(config) {
344
355
  const cache = createProfileCache();
345
356
  async function valironGateHandler(req, res, next) {
346
357
  const startedAt = Date.now();
347
- const { agentId, result, error, pendingEvaluation } = await runGateCheck(frozen, req, cache);
358
+ const { agentId, result, error, pendingEvaluation, ownershipRequired } = await runGateCheck(frozen, req, cache);
348
359
  const latencyMs = Date.now() - startedAt;
349
360
  const minScore = frozen.minScore ?? 65;
350
361
  const agentType = agentId
@@ -361,6 +372,8 @@ function createValironGate(config) {
361
372
  });
362
373
  return res.status(401).json(missingIdentityBody());
363
374
  }
375
+ if (ownershipRequired)
376
+ return res.status(401).json({ code: "AGENT_OWNERSHIP_REQUIRED", error: "Fresh request-bound identity proof required" });
364
377
  if (error) {
365
378
  emitGateTelemetry(frozen.sdk, {
366
379
  framework: "express",
@@ -426,7 +439,7 @@ function createValironGate(config) {
426
439
  * import { ValironSDK, valironFastifyPlugin } from '@valiron/sdk';
427
440
  *
428
441
  * const app = Fastify();
429
- * const valiron = new ValironSDK({ chain: 'monad' });
442
+ * const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
430
443
  *
431
444
  * // Gate all routes
432
445
  * app.register(valironFastifyPlugin, { sdk: valiron });
@@ -434,6 +447,7 @@ function createValironGate(config) {
434
447
  * // Or gate a specific prefix
435
448
  * app.register(valironFastifyPlugin, {
436
449
  * sdk: valiron,
450
+ * verifyRequest: verifyAgentRequest, // application-owned request signature verifier
437
451
  * prefix: '/api',
438
452
  * minScore: 85,
439
453
  * });
@@ -442,9 +456,11 @@ function createValironGate(config) {
442
456
  async function valironFastifyPlugin(fastify, opts) {
443
457
  const gateConfig = {
444
458
  sdk: opts.sdk,
459
+ verifyRequest: opts.verifyRequest,
445
460
  extractAgentId: opts.extractAgentId,
446
461
  extractAgentAddress: opts.extractAgentAddress,
447
462
  minScore: opts.minScore,
463
+ trustSignals: opts.trustSignals,
448
464
  cacheTtlMs: opts.cacheTtlMs,
449
465
  onAllow: opts.onAllow,
450
466
  };
@@ -465,7 +481,7 @@ async function valironFastifyPlugin(fastify, opts) {
465
481
  return;
466
482
  }
467
483
  const startedAt = Date.now();
468
- const { agentId, result, error, pendingEvaluation } = await runGateCheck(gateConfig, request, cache);
484
+ const { agentId, result, error, pendingEvaluation, ownershipRequired } = await runGateCheck(gateConfig, request, cache);
469
485
  const latencyMs = Date.now() - startedAt;
470
486
  const minScore = opts.minScore ?? 65;
471
487
  const agentType = agentId
@@ -482,6 +498,8 @@ async function valironFastifyPlugin(fastify, opts) {
482
498
  });
483
499
  return reply.status(401).send(missingIdentityBody());
484
500
  }
501
+ if (ownershipRequired)
502
+ return reply.status(401).send({ code: "AGENT_OWNERSHIP_REQUIRED", error: "Fresh request-bound identity proof required" });
485
503
  if (error) {
486
504
  emitGateTelemetry(opts.sdk, {
487
505
  framework: "fastify",
@@ -537,10 +555,11 @@ async function valironFastifyPlugin(fastify, opts) {
537
555
  * // middleware.ts (Next.js project root)
538
556
  * import { ValironSDK, createValironNextMiddleware } from '@valiron/sdk';
539
557
  *
540
- * const valiron = new ValironSDK({ chain: 'monad' });
558
+ * const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
541
559
  *
542
560
  * const valironMiddleware = createValironNextMiddleware({
543
561
  * sdk: valiron,
562
+ * verifyRequest: verifyAgentRequest, // application-owned request signature verifier
544
563
  * paths: ['/api/paid'],
545
564
  * minScore: 65,
546
565
  * });
@@ -583,6 +602,8 @@ function createValironNextMiddleware(config) {
583
602
  return Response.json(missingIdentityBody(), { status: 401 });
584
603
  }
585
604
  const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
605
+ if (!config.verifyRequest || !await config.verifyRequest(request, agentId || agentAddr))
606
+ return Response.json({ code: "AGENT_OWNERSHIP_REQUIRED" }, { status: 401 });
586
607
  const effectiveMinScore = minScore ?? 65;
587
608
  try {
588
609
  let result;
@@ -590,7 +611,7 @@ function createValironNextMiddleware(config) {
590
611
  const identifier = agentId || agentAddr;
591
612
  // Check client-side cache first
592
613
  if (cacheTtl > 0) {
593
- const cached = cache.getCached(identifier, cacheTtl);
614
+ const cached = cache.getCached(cacheKeyFor(identifier, trustSignals) + ":" + effectiveMinScore, cacheTtl);
594
615
  if (cached) {
595
616
  emitGateTelemetry(sdk, {
596
617
  framework: "next",
@@ -637,7 +658,7 @@ function createValironNextMiddleware(config) {
637
658
  }
638
659
  }
639
660
  if (cacheTtl > 0)
640
- cache.setCache(identifier, result, pendingEvaluation || undefined);
661
+ cache.setCache(cacheKeyFor(identifier, trustSignals) + ":" + effectiveMinScore, result, pendingEvaluation || undefined);
641
662
  emitGateTelemetry(sdk, {
642
663
  framework: "next",
643
664
  agentType: agentId ? "onchain" : "key",
@@ -685,7 +706,7 @@ function createValironNextMiddleware(config) {
685
706
  * import { Hono } from 'hono';
686
707
  * import { ValironSDK, valironGateCheck } from '@valiron/sdk';
687
708
  *
688
- * const valiron = new ValironSDK({ chain: 'monad' });
709
+ * const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
689
710
  * const app = new Hono();
690
711
  *
691
712
  * app.use('/api/*', async (c, next) => {
@@ -738,13 +759,18 @@ async function valironGateCheck(sdk, opts) {
738
759
  body: missingIdentityBody(),
739
760
  };
740
761
  }
762
+ if (!opts.verifyRequest || !await opts.verifyRequest(identifier))
763
+ return {
764
+ hasAgent: true, agentId: identifier, ok: false, allow: false, status: 401,
765
+ body: { code: "AGENT_OWNERSHIP_REQUIRED", error: "Fresh request-bound identity proof required" },
766
+ };
741
767
  const effectiveMinScore = minScore ?? 65;
742
768
  const cacheTtl = opts.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
743
769
  // Get or create a per-SDK cache instance
744
770
  const cache = getGateCheckCache(sdk);
745
771
  // Check client-side cache first
746
772
  if (cacheTtl > 0) {
747
- const cached = cache.getCached(identifier, cacheTtl);
773
+ const cached = cache.getCached(cacheKeyFor(identifier, trustSignals) + ":" + effectiveMinScore, cacheTtl);
748
774
  if (cached) {
749
775
  emitGateTelemetry(sdk, {
750
776
  framework: "generic",
@@ -788,7 +814,8 @@ async function valironGateCheck(sdk, opts) {
788
814
  result = profileToGateResult(profile, effectiveMinScore);
789
815
  // Detect brand-new agent: on-chain identity exists but zero reputation.
790
816
  if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
791
- sdk.triggerSandboxTest(agentId).catch(() => { });
817
+ const pending = sdk.triggerSandboxTest(agentId).catch(() => { });
818
+ opts.waitUntil?.(pending);
792
819
  pendingEvaluation = true;
793
820
  }
794
821
  }
@@ -798,13 +825,14 @@ async function valironGateCheck(sdk, opts) {
798
825
  // Detect brand-new key agent: verified but never scored.
799
826
  if (!result.allow && profile.verified && profile.score == null) {
800
827
  if (typeof sdk.triggerKeyAgentSandbox === "function") {
801
- sdk.triggerKeyAgentSandbox(agentAddress).catch(() => { });
828
+ const pending = sdk.triggerKeyAgentSandbox(agentAddress).catch(() => { });
829
+ opts.waitUntil?.(pending);
802
830
  }
803
831
  pendingEvaluation = true;
804
832
  }
805
833
  }
806
834
  if (cacheTtl > 0)
807
- cache.setCache(identifier, result, pendingEvaluation || undefined);
835
+ cache.setCache(cacheKeyFor(identifier, trustSignals) + ":" + effectiveMinScore, result, pendingEvaluation || undefined);
808
836
  emitGateTelemetry(sdk, {
809
837
  framework: "generic",
810
838
  agentType: agentId ? "onchain" : "key",
@@ -1,9 +1,12 @@
1
1
  import { ValironSDK } from "./index.js";
2
+ import type { ValironGateConfig } from "./middleware.js";
2
3
  import type { SupportedChain, TrustSignal } from "./types.js";
3
4
  /**
4
5
  * Configuration for the Valiron Operator SDK.
5
6
  */
6
7
  export interface ValironOperatorConfig {
8
+ /** Explicit opt-in to aggregate API usage telemetry; raw IP/UA/path are never sent. */
9
+ analytics?: boolean;
7
10
  /** Operator API key (val_op_xxxx) — obtained from valiron.co/dashboard. */
8
11
  apiKey: string;
9
12
  /** Default blockchain (default: 'ethereum'). */
@@ -19,11 +22,13 @@ export interface ValironOperatorConfig {
19
22
  * Configuration for the paywall middleware.
20
23
  */
21
24
  export interface PaywallConfig {
25
+ /** Required for admission: verify a fresh request-bound proof and reject replay before cache access. */
26
+ verifyRequest?: ValironGateConfig["verifyRequest"];
22
27
  /** Price per API call in USDC. */
23
28
  pricePerCall: number;
24
29
  /** Minimum trust score to allow (default: 45). */
25
30
  minTrustScore?: number;
26
- /** Customer-selected scoring signals. Free plans support 8004+sandbox; Pro adds world+self+icebreaker+wallet. */
31
+ /** Customer-selected scoring signals. Free includes 8004, sandbox, world, self, and wallet; Pro adds icebreaker (Social Graph). */
27
32
  trustSignals?: TrustSignal[];
28
33
  /**
29
34
  * Server-side gate result TTL in ms (default: 86400000 = 24h).
@@ -55,11 +60,12 @@ export interface PaywallConfig {
55
60
  * });
56
61
  *
57
62
  * // Express: one line to monetize an endpoint
58
- * app.use('/api/inference', operator.paywall({ pricePerCall: 0.05 }));
63
+ * app.use('/api/inference', operator.paywall({ pricePerCall: 0.05, verifyRequest: verifyAgentRequest }));
59
64
  *
60
65
  * // Fastify: register as plugin
61
66
  * app.register(operator.fastifyPaywall({
62
67
  * pricePerCall: 0.10,
68
+ * verifyRequest: verifyAgentRequest, // application-owned verifier
63
69
  * prefix: '/api',
64
70
  * }));
65
71
  * ```
@@ -68,6 +74,7 @@ export declare class ValironOperator {
68
74
  private sdk;
69
75
  private apiKey;
70
76
  private debug;
77
+ private analytics;
71
78
  private endpoint;
72
79
  constructor(config: ValironOperatorConfig);
73
80
  private buildAnalyticsUrl;
@@ -87,6 +94,7 @@ export declare class ValironOperator {
87
94
  * ```typescript
88
95
  * app.use('/api/inference', operator.paywall({
89
96
  * pricePerCall: 0.05,
97
+ * verifyRequest: verifyAgentRequest, // application-owned verifier
90
98
  * minTrustScore: 45,
91
99
  * }));
92
100
  *
@@ -105,6 +113,7 @@ export declare class ValironOperator {
105
113
  * ```typescript
106
114
  * app.register(operator.fastifyPaywall({
107
115
  * pricePerCall: 0.10,
116
+ * verifyRequest: verifyAgentRequest, // application-owned verifier
108
117
  * prefix: '/api',
109
118
  * minTrustScore: 65,
110
119
  * }));
@@ -15,11 +15,12 @@ const middleware_js_1 = require("./middleware.js");
15
15
  * });
16
16
  *
17
17
  * // Express: one line to monetize an endpoint
18
- * app.use('/api/inference', operator.paywall({ pricePerCall: 0.05 }));
18
+ * app.use('/api/inference', operator.paywall({ pricePerCall: 0.05, verifyRequest: verifyAgentRequest }));
19
19
  *
20
20
  * // Fastify: register as plugin
21
21
  * app.register(operator.fastifyPaywall({
22
22
  * pricePerCall: 0.10,
23
+ * verifyRequest: verifyAgentRequest, // application-owned verifier
23
24
  * prefix: '/api',
24
25
  * }));
25
26
  * ```
@@ -30,6 +31,7 @@ class ValironOperator {
30
31
  throw new Error("Invalid operator API key — must start with 'val_op_'");
31
32
  }
32
33
  this.apiKey = config.apiKey;
34
+ this.analytics = config.analytics === true;
33
35
  this.debug = config.debug || false;
34
36
  this.endpoint = config.endpoint || "https://valiron-edge-proxy.onrender.com";
35
37
  this.sdk = new index_js_1.ValironSDK({
@@ -44,20 +46,19 @@ class ValironOperator {
44
46
  return new URL("/operator/analytics/ingest", this.endpoint).toString();
45
47
  }
46
48
  recordUsage(entry) {
49
+ if (!this.analytics)
50
+ return;
47
51
  const trustSignals = this.normalizeTrustSignals(entry.trustSignals);
48
52
  const body = {
49
53
  agent_id: entry.agentId || undefined,
50
54
  agent_label: entry.agentLabel || undefined,
51
55
  session_id: entry.sessionId || undefined,
52
56
  chain: entry.chain || undefined,
53
- path: entry.path,
57
+ path: "/redacted",
54
58
  method: entry.method,
55
59
  status_code: entry.statusCode,
56
60
  price_charged: entry.priceCharged,
57
61
  response_ms: entry.responseMs,
58
- user_agent: entry.userAgent || undefined,
59
- ip_address: entry.ipAddress || undefined,
60
- error_message: entry.errorMessage || undefined,
61
62
  trust_signals: trustSignals,
62
63
  trust_signal_count: trustSignals.length,
63
64
  scoring_mode: trustSignals.length ? trustSignals.join("+") : undefined,
@@ -77,6 +78,8 @@ class ValironOperator {
77
78
  };
78
79
  void fetch(this.buildAnalyticsUrl(), {
79
80
  method: "POST",
81
+ redirect: "error",
82
+ signal: AbortSignal.timeout(5000),
80
83
  headers: {
81
84
  "Content-Type": "application/json",
82
85
  Authorization: `Bearer ${this.apiKey}`,
@@ -99,8 +102,7 @@ class ValironOperator {
99
102
  return req.originalUrl || req.url || req.path || "/";
100
103
  }
101
104
  expressIp(req) {
102
- const forwarded = this.extractHeader(req, "x-forwarded-for")?.split(",")[0]?.trim();
103
- return forwarded || this.extractHeader(req, "x-real-ip") || req.ip || req.socket?.remoteAddress || null;
105
+ return req.ip || req.socket?.remoteAddress || null;
104
106
  }
105
107
  fastifyPath(req) {
106
108
  return req.url || req.routerPath || "/";
@@ -118,6 +120,7 @@ class ValironOperator {
118
120
  * ```typescript
119
121
  * app.use('/api/inference', operator.paywall({
120
122
  * pricePerCall: 0.05,
123
+ * verifyRequest: verifyAgentRequest, // application-owned verifier
121
124
  * minTrustScore: 45,
122
125
  * }));
123
126
  *
@@ -133,6 +136,7 @@ class ValironOperator {
133
136
  sdk: this.sdk,
134
137
  minScore: config.minTrustScore ?? 45,
135
138
  trustSignals: config.trustSignals,
139
+ verifyRequest: config.verifyRequest,
136
140
  cacheTtlMs: config.cacheTtlMs ?? config.ttlMs,
137
141
  onDeny: config.onDeny,
138
142
  onAllow: (req, result) => {
@@ -208,6 +212,7 @@ class ValironOperator {
208
212
  * ```typescript
209
213
  * app.register(operator.fastifyPaywall({
210
214
  * pricePerCall: 0.10,
215
+ * verifyRequest: verifyAgentRequest, // application-owned verifier
211
216
  * prefix: '/api',
212
217
  * minTrustScore: 65,
213
218
  * }));
@@ -218,6 +223,7 @@ class ValironOperator {
218
223
  sdk: this.sdk,
219
224
  minScore: config.minTrustScore ?? 45,
220
225
  trustSignals: config.trustSignals,
226
+ verifyRequest: config.verifyRequest,
221
227
  cacheTtlMs: config.cacheTtlMs ?? config.ttlMs,
222
228
  prefix: config.prefix,
223
229
  onDeny: config.onDeny,