@valiron/sdk 1.0.0 → 1.0.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.
- package/README.md +2 -1
- package/dist/clients.d.ts +12 -1
- package/dist/clients.js +18 -0
- package/dist/index.d.ts +19 -1
- package/dist/index.js +20 -0
- package/dist/middleware.d.ts +41 -11
- package/dist/middleware.js +268 -21
- package/dist/operatorSdk.d.ts +13 -2
- package/dist/operatorSdk.js +2 -2
- package/dist/types.d.ts +14 -0
- package/docs/QUICKSTART.md +18 -5
- package/docs/SANDBOX.md +51 -1
- package/docs/SDK-REFERENCE.md +95 -10
- package/docs/llms.txt +10 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,8 +36,9 @@ No API key required for read operations.
|
|
|
36
36
|
|
|
37
37
|
### Additional Features
|
|
38
38
|
|
|
39
|
+
- **Auto-Sandbox** — Middleware automatically evaluates new agents (on-chain and key-based) on their first gated request
|
|
39
40
|
- **Proxy Gateway** (Pro) — Forward requests through Valiron's edge proxy with SSRF protection
|
|
40
|
-
- **Key-Based Agents** — Support Web2 agents via EIP-191 challenge-response (auto-detected)
|
|
41
|
+
- **Key-Based Agents** — Support Web2 agents via EIP-191 challenge-response (auto-detected, auto-sandboxed)
|
|
41
42
|
- **World ID** — Verify agent-human linkage via Worldcoin proof-of-personhood
|
|
42
43
|
- **Telemetry** — Optional anonymous usage metrics (disable with `telemetry: { enabled: false }`)
|
|
43
44
|
|
package/dist/clients.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ValironConfig, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
|
|
1
|
+
import { ValironConfig, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
|
|
2
2
|
/**
|
|
3
3
|
* HTTP client for the Valiron Operator API.
|
|
4
4
|
*
|
|
@@ -63,6 +63,17 @@ export declare class ValironClient {
|
|
|
63
63
|
* `POST /operator/trigger-sandbox/:agentId`
|
|
64
64
|
*/
|
|
65
65
|
triggerSandboxTest(agentId: string, options?: CallOptions): Promise<SandboxResult>;
|
|
66
|
+
/**
|
|
67
|
+
* Trigger sandbox testing for a key-based (web2) agent.
|
|
68
|
+
*
|
|
69
|
+
* Key agents have no on-chain endpoints, so this uses sandbox_relay mode:
|
|
70
|
+
* the agent interacts with the sandbox-api mock server, and its behavior
|
|
71
|
+
* is observed and scored. The result is written to Redis so subsequent
|
|
72
|
+
* `getKeyAgentProfile()` calls return a real score.
|
|
73
|
+
*
|
|
74
|
+
* `POST /operator/trigger-sandbox-key/:agentAddress`
|
|
75
|
+
*/
|
|
76
|
+
triggerKeyAgentSandbox(agentAddress: string): Promise<KeyAgentSandboxResult>;
|
|
66
77
|
/**
|
|
67
78
|
* Trust gate — single call combining on-chain reputation + sandbox tests.
|
|
68
79
|
*
|
package/dist/clients.js
CHANGED
|
@@ -112,6 +112,24 @@ class ValironClient {
|
|
|
112
112
|
delete result.mode;
|
|
113
113
|
return result;
|
|
114
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* Trigger sandbox testing for a key-based (web2) agent.
|
|
117
|
+
*
|
|
118
|
+
* Key agents have no on-chain endpoints, so this uses sandbox_relay mode:
|
|
119
|
+
* the agent interacts with the sandbox-api mock server, and its behavior
|
|
120
|
+
* is observed and scored. The result is written to Redis so subsequent
|
|
121
|
+
* `getKeyAgentProfile()` calls return a real score.
|
|
122
|
+
*
|
|
123
|
+
* `POST /operator/trigger-sandbox-key/:agentAddress`
|
|
124
|
+
*/
|
|
125
|
+
async triggerKeyAgentSandbox(agentAddress) {
|
|
126
|
+
const result = await this.post(`/operator/trigger-sandbox-key/${agentAddress}`);
|
|
127
|
+
// Strip internal behavioral metrics and execution details
|
|
128
|
+
delete result.metrics;
|
|
129
|
+
delete result.testSummary;
|
|
130
|
+
delete result.mode;
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
115
133
|
/**
|
|
116
134
|
* Trust gate — single call combining on-chain reputation + sandbox tests.
|
|
117
135
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ValironConfig, CallOptions, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, GateResult, GateOptions, RouteDecision, KeyAgentProfile, KeyAgentChallenge, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
|
|
1
|
+
import { ValironConfig, CallOptions, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, RouteDecision, KeyAgentProfile, KeyAgentChallenge, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
|
|
2
2
|
/**
|
|
3
3
|
* Valiron SDK – Official TypeScript SDK for the Trust Layer for Agentic Economy
|
|
4
4
|
*
|
|
@@ -166,6 +166,24 @@ export declare class ValironSDK {
|
|
|
166
166
|
* ```
|
|
167
167
|
*/
|
|
168
168
|
triggerSandboxTest(agentId: string, options?: CallOptions): Promise<SandboxResult>;
|
|
169
|
+
/**
|
|
170
|
+
* Trigger sandbox testing for a key-based (web2) agent.
|
|
171
|
+
*
|
|
172
|
+
* Key agents have no on-chain endpoints, so this uses sandbox_relay mode.
|
|
173
|
+
* The result is written to Redis so subsequent `getKeyAgentProfile()` calls
|
|
174
|
+
* return a real score.
|
|
175
|
+
*
|
|
176
|
+
* @param agentAddress - The key agent's Ethereum address
|
|
177
|
+
* @returns Sandbox test results including score and tier
|
|
178
|
+
*
|
|
179
|
+
* @example
|
|
180
|
+
* ```typescript
|
|
181
|
+
* const result = await valiron.triggerKeyAgentSandbox('0xabc...');
|
|
182
|
+
* console.log(result.valironScore); // 82
|
|
183
|
+
* console.log(result.tier); // 'A'
|
|
184
|
+
* ```
|
|
185
|
+
*/
|
|
186
|
+
triggerKeyAgentSandbox(agentAddress: string): Promise<KeyAgentSandboxResult>;
|
|
169
187
|
/**
|
|
170
188
|
* Trust gate — checks an agent by combining on-chain reputation with
|
|
171
189
|
* sandbox behavioral tests and returns a single allow/deny decision.
|
package/dist/index.js
CHANGED
|
@@ -197,6 +197,26 @@ class ValironSDK {
|
|
|
197
197
|
async triggerSandboxTest(agentId, options) {
|
|
198
198
|
return this.client.triggerSandboxTest(agentId, options);
|
|
199
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* Trigger sandbox testing for a key-based (web2) agent.
|
|
202
|
+
*
|
|
203
|
+
* Key agents have no on-chain endpoints, so this uses sandbox_relay mode.
|
|
204
|
+
* The result is written to Redis so subsequent `getKeyAgentProfile()` calls
|
|
205
|
+
* return a real score.
|
|
206
|
+
*
|
|
207
|
+
* @param agentAddress - The key agent's Ethereum address
|
|
208
|
+
* @returns Sandbox test results including score and tier
|
|
209
|
+
*
|
|
210
|
+
* @example
|
|
211
|
+
* ```typescript
|
|
212
|
+
* const result = await valiron.triggerKeyAgentSandbox('0xabc...');
|
|
213
|
+
* console.log(result.valironScore); // 82
|
|
214
|
+
* console.log(result.tier); // 'A'
|
|
215
|
+
* ```
|
|
216
|
+
*/
|
|
217
|
+
async triggerKeyAgentSandbox(agentAddress) {
|
|
218
|
+
return this.client.triggerKeyAgentSandbox(agentAddress);
|
|
219
|
+
}
|
|
200
220
|
/**
|
|
201
221
|
* Trust gate — checks an agent by combining on-chain reputation with
|
|
202
222
|
* sandbox behavioral tests and returns a single allow/deny decision.
|
package/dist/middleware.d.ts
CHANGED
|
@@ -23,8 +23,17 @@ export interface ValironGateConfig {
|
|
|
23
23
|
extractAgentAddress?: (req: any) => string | null;
|
|
24
24
|
/** Minimum Valiron score to allow (default: 65). */
|
|
25
25
|
minScore?: number;
|
|
26
|
-
/**
|
|
27
|
-
|
|
26
|
+
/**
|
|
27
|
+
* Client-side profile cache TTL in ms.
|
|
28
|
+
*
|
|
29
|
+
* When set, caches `getAgentProfile()` results in memory for this duration.
|
|
30
|
+
* This is important for protocols like x402 that make multiple requests
|
|
31
|
+
* per payment (discover → retry with payment) — without caching, the
|
|
32
|
+
* second request can fail due to cold-start latency on the edge proxy.
|
|
33
|
+
*
|
|
34
|
+
* Set to `0` to disable. Default: `30_000` (30 seconds).
|
|
35
|
+
*/
|
|
36
|
+
cacheTtlMs?: number;
|
|
28
37
|
/** Custom handler when an agent is denied. If provided, must send a response. */
|
|
29
38
|
onDeny?: (req: any, res: any, result: GateResult) => void;
|
|
30
39
|
/** Hook called after an agent is allowed — runs before next(). */
|
|
@@ -38,6 +47,11 @@ export interface ValironGateConfig {
|
|
|
38
47
|
* On deny: returns 403 with the gate result (or delegates to `onDeny`).
|
|
39
48
|
* On error: returns 503 (fail-closed).
|
|
40
49
|
*
|
|
50
|
+
* **Express 4 compatibility**: The returned middleware wraps the async
|
|
51
|
+
* gate check with `Promise.resolve().catch(next)` so that unhandled
|
|
52
|
+
* rejections are forwarded to Express's error handler instead of causing
|
|
53
|
+
* silent failures. Express 4 does not natively `await` async middleware.
|
|
54
|
+
*
|
|
41
55
|
* @example
|
|
42
56
|
* ```typescript
|
|
43
57
|
* import { ValironSDK, createValironGate } from '@valiron/sdk';
|
|
@@ -45,18 +59,18 @@ export interface ValironGateConfig {
|
|
|
45
59
|
* const valiron = new ValironSDK({ chain: 'monad' });
|
|
46
60
|
*
|
|
47
61
|
* // Apply before your x402 / payment handler
|
|
48
|
-
* Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
|
|
62
|
+
* // Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
|
|
49
63
|
* app.use('/api/paid', createValironGate({ sdk: valiron }));
|
|
50
64
|
*
|
|
51
|
-
* // Custom threshold
|
|
65
|
+
* // Custom threshold + cache TTL
|
|
52
66
|
* app.use('/api/premium', createValironGate({
|
|
53
67
|
* sdk: valiron,
|
|
54
68
|
* minScore: 85,
|
|
55
|
-
*
|
|
69
|
+
* cacheTtlMs: 60_000, // 60s client-side cache
|
|
56
70
|
* }));
|
|
57
71
|
* ```
|
|
58
72
|
*/
|
|
59
|
-
export declare function createValironGate(config: ValironGateConfig): (req: any, res: any, next: any) =>
|
|
73
|
+
export declare function createValironGate(config: ValironGateConfig): (req: any, res: any, next: any) => void;
|
|
60
74
|
/**
|
|
61
75
|
* Configuration for the Fastify Valiron trust gate plugin.
|
|
62
76
|
*/
|
|
@@ -75,8 +89,11 @@ export interface ValironFastifyConfig {
|
|
|
75
89
|
extractAgentAddress?: (req: any) => string | null;
|
|
76
90
|
/** Minimum Valiron score to allow (default: 65). */
|
|
77
91
|
minScore?: number;
|
|
78
|
-
/**
|
|
79
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Client-side profile cache TTL in ms (default: 30000).
|
|
94
|
+
* Set to `0` to disable.
|
|
95
|
+
*/
|
|
96
|
+
cacheTtlMs?: number;
|
|
80
97
|
/** Custom handler when an agent is denied. If provided, must send a response. */
|
|
81
98
|
onDeny?: (req: any, reply: any, result: GateResult) => void;
|
|
82
99
|
/** Hook called after an agent is allowed. */
|
|
@@ -133,8 +150,11 @@ export interface ValironNextConfig {
|
|
|
133
150
|
extractAgentAddress?: (req: Request) => string | null;
|
|
134
151
|
/** Minimum Valiron score to allow (default: 65). */
|
|
135
152
|
minScore?: number;
|
|
136
|
-
/**
|
|
137
|
-
|
|
153
|
+
/**
|
|
154
|
+
* Client-side profile cache TTL in ms (default: 30000).
|
|
155
|
+
* Set to `0` to disable.
|
|
156
|
+
*/
|
|
157
|
+
cacheTtlMs?: number;
|
|
138
158
|
/**
|
|
139
159
|
* URL path patterns to gate. Uses `startsWith` matching.
|
|
140
160
|
* If omitted, gates all routes.
|
|
@@ -189,6 +209,12 @@ export interface ValironGateCheckResult {
|
|
|
189
209
|
status: number;
|
|
190
210
|
/** Suggested JSON body if the request should be blocked. Undefined if allowed. */
|
|
191
211
|
body?: Record<string, unknown>;
|
|
212
|
+
/**
|
|
213
|
+
* True when the agent is brand-new (on-chain identity, zero reputation).
|
|
214
|
+
* A sandbox evaluation has been triggered in the background.
|
|
215
|
+
* The caller should tell the agent to retry after `retryAfterMs`.
|
|
216
|
+
*/
|
|
217
|
+
pendingEvaluation?: boolean;
|
|
192
218
|
}
|
|
193
219
|
/**
|
|
194
220
|
* Framework-agnostic gate check. Returns a structured result that you
|
|
@@ -238,5 +264,9 @@ export declare function valironGateCheck(sdk: ValironSDK, opts: {
|
|
|
238
264
|
/** Key-based agent hash (web2). Checked if agentId is not provided. */
|
|
239
265
|
agentAddress?: string | null;
|
|
240
266
|
minScore?: number;
|
|
241
|
-
|
|
267
|
+
/**
|
|
268
|
+
* Client-side profile cache TTL in ms (default: 30000).
|
|
269
|
+
* Set to `0` to disable.
|
|
270
|
+
*/
|
|
271
|
+
cacheTtlMs?: number;
|
|
242
272
|
}): Promise<ValironGateCheckResult>;
|
package/dist/middleware.js
CHANGED
|
@@ -23,6 +23,45 @@ function defaultExtractAgentId(req) {
|
|
|
23
23
|
function defaultExtractAgentAddress(req) {
|
|
24
24
|
return extractHeader(req, "x-agent-address") || extractHeader(req, "x-agent-key-hash");
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* Convert an AgentProfile (from the public `/operator/agent/` endpoint)
|
|
28
|
+
* into a GateResult, computing the allow/deny decision client-side.
|
|
29
|
+
*
|
|
30
|
+
* **Allow logic**: The primary signal is `routing.finalRoute` — if the
|
|
31
|
+
* operator API routes the agent to `prod` or `prod_throttled`, the agent
|
|
32
|
+
* is allowed. The `minScore` acts as an *additional* override: even if
|
|
33
|
+
* the route is production-eligible, an operator can block agents below
|
|
34
|
+
* their score threshold. This prevents incorrectly denying agents that
|
|
35
|
+
* the API has already routed to production via World ID, behavioral
|
|
36
|
+
* reputation upgrades, or other trust signals beyond raw on-chain score.
|
|
37
|
+
*
|
|
38
|
+
* The `score` field uses `localReputation.score` when available (the
|
|
39
|
+
* combined trust score factoring in sandbox, World ID, Icebreaker),
|
|
40
|
+
* falling back to `onchainReputation.averageScore` for backward compat.
|
|
41
|
+
*/
|
|
42
|
+
function profileToGateResult(profile, minScore) {
|
|
43
|
+
// Prefer the combined trust score (localReputation.score) over raw on-chain avg
|
|
44
|
+
const score = profile.localReputation?.score ??
|
|
45
|
+
profile.onchainReputation?.averageScore ??
|
|
46
|
+
0;
|
|
47
|
+
const route = profile.routing?.finalRoute ?? "sandbox_only";
|
|
48
|
+
const tier = (profile.localReputation?.tier ?? "C");
|
|
49
|
+
const riskLevel = (profile.localReputation?.riskLevel ?? "RED");
|
|
50
|
+
const isProductionRoute = route === "prod" || route === "prod_throttled";
|
|
51
|
+
const allow = isProductionRoute && score >= minScore;
|
|
52
|
+
return {
|
|
53
|
+
allow,
|
|
54
|
+
score,
|
|
55
|
+
tier,
|
|
56
|
+
riskLevel,
|
|
57
|
+
route,
|
|
58
|
+
agentId: profile.agentId,
|
|
59
|
+
wallet: profile.identity?.wallet ?? "",
|
|
60
|
+
chain: profile.chain,
|
|
61
|
+
sandboxRan: false,
|
|
62
|
+
cached: false,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
26
65
|
/**
|
|
27
66
|
* Normalize a KeyAgentProfile into a GateResult so all middleware
|
|
28
67
|
* consumers get one consistent type regardless of agent kind.
|
|
@@ -51,17 +90,85 @@ function keyProfileToGateResult(profile, minScore) {
|
|
|
51
90
|
cached: true,
|
|
52
91
|
};
|
|
53
92
|
}
|
|
54
|
-
|
|
93
|
+
const DEFAULT_CACHE_TTL_MS = 30000;
|
|
94
|
+
const MAX_CACHE_SIZE = 1000;
|
|
95
|
+
/**
|
|
96
|
+
* Per-instance profile cache. Each `createValironGate()` /
|
|
97
|
+
* `createValironNextMiddleware()` call gets its own Map so that
|
|
98
|
+
* different SDK instances (potentially on different chains) don't
|
|
99
|
+
* share cached results.
|
|
100
|
+
*/
|
|
101
|
+
function createProfileCache() {
|
|
102
|
+
const cache = new Map();
|
|
103
|
+
function getCached(agentId, ttl) {
|
|
104
|
+
const entry = cache.get(agentId);
|
|
105
|
+
if (!entry)
|
|
106
|
+
return null;
|
|
107
|
+
if (Date.now() - entry.ts > ttl) {
|
|
108
|
+
cache.delete(agentId);
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
return { result: { ...entry.result, cached: true }, pendingEvaluation: entry.pendingEvaluation };
|
|
112
|
+
}
|
|
113
|
+
function setCache(agentId, result, pendingEvaluation) {
|
|
114
|
+
// Don't cache pending evaluation results — the next request should
|
|
115
|
+
// re-fetch the profile to see if evaluation has completed.
|
|
116
|
+
if (pendingEvaluation)
|
|
117
|
+
return;
|
|
118
|
+
// Evict oldest entries when cache exceeds max size
|
|
119
|
+
if (cache.size >= MAX_CACHE_SIZE) {
|
|
120
|
+
const firstKey = cache.keys().next().value;
|
|
121
|
+
if (firstKey !== undefined)
|
|
122
|
+
cache.delete(firstKey);
|
|
123
|
+
}
|
|
124
|
+
cache.set(agentId, { result, ts: Date.now() });
|
|
125
|
+
}
|
|
126
|
+
return { getCached, setCache };
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Per-SDK cache for `valironGateCheck()`. Uses a WeakMap so caches
|
|
130
|
+
* are garbage-collected when the SDK instance is no longer referenced.
|
|
131
|
+
*/
|
|
132
|
+
const gateCheckCaches = new WeakMap();
|
|
133
|
+
function getGateCheckCache(sdk) {
|
|
134
|
+
let cache = gateCheckCaches.get(sdk);
|
|
135
|
+
if (!cache) {
|
|
136
|
+
cache = createProfileCache();
|
|
137
|
+
gateCheckCaches.set(sdk, cache);
|
|
138
|
+
}
|
|
139
|
+
return cache;
|
|
140
|
+
}
|
|
141
|
+
async function runGateCheck(config, req, cache) {
|
|
142
|
+
const minScore = config.minScore ?? 65;
|
|
143
|
+
const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
55
144
|
// 1. Try on-chain agent ID (ERC-8004 / Solana)
|
|
56
145
|
const extractAgentId = config.extractAgentId || defaultExtractAgentId;
|
|
57
146
|
const agentId = extractAgentId(req);
|
|
58
147
|
if (agentId) {
|
|
148
|
+
// Check client-side cache first
|
|
149
|
+
if (cacheTtl > 0) {
|
|
150
|
+
const cached = cache.getCached(agentId, cacheTtl);
|
|
151
|
+
if (cached)
|
|
152
|
+
return { agentId, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
|
|
153
|
+
}
|
|
59
154
|
try {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
155
|
+
// Use getAgentProfile() which hits the PUBLIC /operator/agent/ endpoint.
|
|
156
|
+
// The old gate() call used POST /operator/gate/ which is protected by
|
|
157
|
+
// agent challenge-response auth and fails from server contexts.
|
|
158
|
+
const profile = await config.sdk.getAgentProfile(agentId);
|
|
159
|
+
const result = profileToGateResult(profile, minScore);
|
|
160
|
+
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
161
|
+
// Trigger a sandbox evaluation so the agent can build a score.
|
|
162
|
+
// The result is cached normally — when the cache expires the next
|
|
163
|
+
// request will re-fetch the profile, which should now have a score.
|
|
164
|
+
const isNewAgent = !result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0;
|
|
165
|
+
if (isNewAgent) {
|
|
166
|
+
// Fire-and-forget — don't block the response on sandbox completion
|
|
167
|
+
config.sdk.triggerSandboxTest(agentId).catch(() => { });
|
|
168
|
+
}
|
|
169
|
+
if (cacheTtl > 0)
|
|
170
|
+
cache.setCache(agentId, result, isNewAgent || undefined);
|
|
171
|
+
return { agentId, result, pendingEvaluation: isNewAgent || undefined };
|
|
65
172
|
}
|
|
66
173
|
catch (error) {
|
|
67
174
|
return { agentId, error };
|
|
@@ -71,10 +178,24 @@ async function runGateCheck(config, req) {
|
|
|
71
178
|
const extractAddress = config.extractAgentAddress || defaultExtractAgentAddress;
|
|
72
179
|
const agentAddr = extractAddress(req);
|
|
73
180
|
if (agentAddr) {
|
|
181
|
+
// Check client-side cache first
|
|
182
|
+
if (cacheTtl > 0) {
|
|
183
|
+
const cached = cache.getCached(agentAddr, cacheTtl);
|
|
184
|
+
if (cached)
|
|
185
|
+
return { agentId: agentAddr, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
|
|
186
|
+
}
|
|
74
187
|
try {
|
|
75
188
|
const profile = await config.sdk.getKeyAgentProfile(agentAddr);
|
|
76
|
-
const result = keyProfileToGateResult(profile,
|
|
77
|
-
|
|
189
|
+
const result = keyProfileToGateResult(profile, minScore);
|
|
190
|
+
// Detect brand-new key agent: verified but never scored.
|
|
191
|
+
// Trigger a sandbox evaluation so the agent can build a score.
|
|
192
|
+
const isNewKeyAgent = !result.allow && profile.verified && profile.score == null;
|
|
193
|
+
if (isNewKeyAgent && typeof config.sdk.triggerKeyAgentSandbox === "function") {
|
|
194
|
+
config.sdk.triggerKeyAgentSandbox(agentAddr).catch(() => { });
|
|
195
|
+
}
|
|
196
|
+
if (cacheTtl > 0)
|
|
197
|
+
cache.setCache(agentAddr, result, isNewKeyAgent || undefined);
|
|
198
|
+
return { agentId: agentAddr, result, pendingEvaluation: isNewKeyAgent || undefined };
|
|
78
199
|
}
|
|
79
200
|
catch (error) {
|
|
80
201
|
return { agentId: agentAddr, error };
|
|
@@ -94,6 +215,11 @@ async function runGateCheck(config, req) {
|
|
|
94
215
|
* On deny: returns 403 with the gate result (or delegates to `onDeny`).
|
|
95
216
|
* On error: returns 503 (fail-closed).
|
|
96
217
|
*
|
|
218
|
+
* **Express 4 compatibility**: The returned middleware wraps the async
|
|
219
|
+
* gate check with `Promise.resolve().catch(next)` so that unhandled
|
|
220
|
+
* rejections are forwarded to Express's error handler instead of causing
|
|
221
|
+
* silent failures. Express 4 does not natively `await` async middleware.
|
|
222
|
+
*
|
|
97
223
|
* @example
|
|
98
224
|
* ```typescript
|
|
99
225
|
* import { ValironSDK, createValironGate } from '@valiron/sdk';
|
|
@@ -101,14 +227,14 @@ async function runGateCheck(config, req) {
|
|
|
101
227
|
* const valiron = new ValironSDK({ chain: 'monad' });
|
|
102
228
|
*
|
|
103
229
|
* // Apply before your x402 / payment handler
|
|
104
|
-
* Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
|
|
230
|
+
* // Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
|
|
105
231
|
* app.use('/api/paid', createValironGate({ sdk: valiron }));
|
|
106
232
|
*
|
|
107
|
-
* // Custom threshold
|
|
233
|
+
* // Custom threshold + cache TTL
|
|
108
234
|
* app.use('/api/premium', createValironGate({
|
|
109
235
|
* sdk: valiron,
|
|
110
236
|
* minScore: 85,
|
|
111
|
-
*
|
|
237
|
+
* cacheTtlMs: 60_000, // 60s client-side cache
|
|
112
238
|
* }));
|
|
113
239
|
* ```
|
|
114
240
|
*/
|
|
@@ -116,8 +242,9 @@ function createValironGate(config) {
|
|
|
116
242
|
// Snapshot config at creation time so mutations after middleware
|
|
117
243
|
// creation don't affect behavior.
|
|
118
244
|
const frozen = { ...config };
|
|
119
|
-
|
|
120
|
-
|
|
245
|
+
const cache = createProfileCache();
|
|
246
|
+
async function valironGateHandler(req, res, next) {
|
|
247
|
+
const { agentId, result, error, pendingEvaluation } = await runGateCheck(frozen, req, cache);
|
|
121
248
|
if (!agentId) {
|
|
122
249
|
return res.status(401).json({
|
|
123
250
|
error: "Missing agent identity",
|
|
@@ -136,6 +263,15 @@ function createValironGate(config) {
|
|
|
136
263
|
config.onAllow(req, result);
|
|
137
264
|
return next();
|
|
138
265
|
}
|
|
266
|
+
// New agent with no reputation — sandbox test triggered in background
|
|
267
|
+
if (pendingEvaluation) {
|
|
268
|
+
return res.status(403).json({
|
|
269
|
+
error: "Agent pending evaluation",
|
|
270
|
+
message: "This agent was recently registered and is being evaluated. Retry shortly.",
|
|
271
|
+
retryAfterMs: 30000,
|
|
272
|
+
...result,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
139
275
|
if (config.onDeny) {
|
|
140
276
|
return config.onDeny(req, res, result);
|
|
141
277
|
}
|
|
@@ -143,6 +279,14 @@ function createValironGate(config) {
|
|
|
143
279
|
error: "Agent blocked by Valiron trust gate",
|
|
144
280
|
...result,
|
|
145
281
|
});
|
|
282
|
+
}
|
|
283
|
+
// Wrap with Promise.catch(next) for Express 4 async safety.
|
|
284
|
+
// Express 4 does NOT await async middleware, so without this wrapper
|
|
285
|
+
// an unhandled rejection would silently hang the request. This also
|
|
286
|
+
// prevents race conditions when chained with other async middleware
|
|
287
|
+
// (e.g. x402's paymentMiddleware running before the gate resolves).
|
|
288
|
+
return function valironGate(req, res, next) {
|
|
289
|
+
Promise.resolve(valironGateHandler(req, res, next)).catch(next);
|
|
146
290
|
};
|
|
147
291
|
}
|
|
148
292
|
/**
|
|
@@ -178,9 +322,10 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
178
322
|
extractAgentId: opts.extractAgentId,
|
|
179
323
|
extractAgentAddress: opts.extractAgentAddress,
|
|
180
324
|
minScore: opts.minScore,
|
|
181
|
-
|
|
325
|
+
cacheTtlMs: opts.cacheTtlMs,
|
|
182
326
|
onAllow: opts.onAllow,
|
|
183
327
|
};
|
|
328
|
+
const cache = createProfileCache();
|
|
184
329
|
// Decorate request with valiron property
|
|
185
330
|
if (!fastify.hasRequestDecorator?.("valiron")) {
|
|
186
331
|
fastify.decorateRequest("valiron", null);
|
|
@@ -196,7 +341,7 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
196
341
|
if (pathname !== prefix && !pathname.startsWith(prefix + "/"))
|
|
197
342
|
return;
|
|
198
343
|
}
|
|
199
|
-
const { agentId, result, error } = await runGateCheck(gateConfig, request);
|
|
344
|
+
const { agentId, result, error, pendingEvaluation } = await runGateCheck(gateConfig, request, cache);
|
|
200
345
|
if (!agentId) {
|
|
201
346
|
return reply.status(401).send({
|
|
202
347
|
error: "Missing agent identity",
|
|
@@ -215,6 +360,15 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
215
360
|
opts.onAllow(request, result);
|
|
216
361
|
return; // continue to handler
|
|
217
362
|
}
|
|
363
|
+
// New agent with no reputation — sandbox test triggered in background
|
|
364
|
+
if (pendingEvaluation) {
|
|
365
|
+
return reply.status(403).send({
|
|
366
|
+
error: "Agent pending evaluation",
|
|
367
|
+
message: "This agent was recently registered and is being evaluated. Retry shortly.",
|
|
368
|
+
retryAfterMs: 30000,
|
|
369
|
+
...result,
|
|
370
|
+
});
|
|
371
|
+
}
|
|
218
372
|
if (opts.onDeny) {
|
|
219
373
|
return opts.onDeny(request, reply, result);
|
|
220
374
|
}
|
|
@@ -252,7 +406,8 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
252
406
|
* ```
|
|
253
407
|
*/
|
|
254
408
|
function createValironNextMiddleware(config) {
|
|
255
|
-
const { sdk, minScore,
|
|
409
|
+
const { sdk, minScore, paths } = config;
|
|
410
|
+
const cache = createProfileCache();
|
|
256
411
|
const extractAgentId = config.extractAgentId ||
|
|
257
412
|
((req) => req.headers.get("x-agent-id"));
|
|
258
413
|
const extractAddress = config.extractAgentAddress ||
|
|
@@ -275,18 +430,54 @@ function createValironNextMiddleware(config) {
|
|
|
275
430
|
identitySkill: "https://valiron.co/auth.md",
|
|
276
431
|
}, { status: 401 });
|
|
277
432
|
}
|
|
433
|
+
const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
434
|
+
const effectiveMinScore = minScore ?? 65;
|
|
278
435
|
try {
|
|
279
436
|
let result;
|
|
437
|
+
let pendingEvaluation = false;
|
|
438
|
+
const identifier = agentId || agentAddr;
|
|
439
|
+
// Check client-side cache first
|
|
440
|
+
if (cacheTtl > 0) {
|
|
441
|
+
const cached = cache.getCached(identifier, cacheTtl);
|
|
442
|
+
if (cached) {
|
|
443
|
+
if (cached.result.allow)
|
|
444
|
+
return undefined;
|
|
445
|
+
return Response.json({ error: "Agent blocked by Valiron trust gate", ...cached.result }, { status: 403 });
|
|
446
|
+
}
|
|
447
|
+
}
|
|
280
448
|
if (agentId) {
|
|
281
|
-
|
|
449
|
+
const profile = await sdk.getAgentProfile(agentId);
|
|
450
|
+
result = profileToGateResult(profile, effectiveMinScore);
|
|
451
|
+
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
452
|
+
if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
|
|
453
|
+
sdk.triggerSandboxTest(agentId).catch(() => { });
|
|
454
|
+
pendingEvaluation = true;
|
|
455
|
+
}
|
|
282
456
|
}
|
|
283
457
|
else {
|
|
284
458
|
const profile = await sdk.getKeyAgentProfile(agentAddr);
|
|
285
|
-
result = keyProfileToGateResult(profile,
|
|
459
|
+
result = keyProfileToGateResult(profile, effectiveMinScore);
|
|
460
|
+
// Detect brand-new key agent: verified but never scored.
|
|
461
|
+
if (!result.allow && profile.verified && profile.score == null) {
|
|
462
|
+
if (typeof sdk.triggerKeyAgentSandbox === "function") {
|
|
463
|
+
sdk.triggerKeyAgentSandbox(agentAddr).catch(() => { });
|
|
464
|
+
}
|
|
465
|
+
pendingEvaluation = true;
|
|
466
|
+
}
|
|
286
467
|
}
|
|
468
|
+
if (cacheTtl > 0)
|
|
469
|
+
cache.setCache(identifier, result, pendingEvaluation || undefined);
|
|
287
470
|
if (result.allow) {
|
|
288
471
|
return undefined; // continue to route handler
|
|
289
472
|
}
|
|
473
|
+
if (pendingEvaluation) {
|
|
474
|
+
return Response.json({
|
|
475
|
+
error: "Agent pending evaluation",
|
|
476
|
+
message: "This agent was recently registered and is being evaluated. Retry shortly.",
|
|
477
|
+
retryAfterMs: 30000,
|
|
478
|
+
...result,
|
|
479
|
+
}, { status: 403 });
|
|
480
|
+
}
|
|
290
481
|
return Response.json({ error: "Agent blocked by Valiron trust gate", ...result }, { status: 403 });
|
|
291
482
|
}
|
|
292
483
|
catch {
|
|
@@ -337,7 +528,7 @@ function createValironNextMiddleware(config) {
|
|
|
337
528
|
* ```
|
|
338
529
|
*/
|
|
339
530
|
async function valironGateCheck(sdk, opts) {
|
|
340
|
-
const { agentId, agentAddress, minScore
|
|
531
|
+
const { agentId, agentAddress, minScore } = opts;
|
|
341
532
|
const identifier = agentId || agentAddress || null;
|
|
342
533
|
if (!identifier) {
|
|
343
534
|
return {
|
|
@@ -352,18 +543,74 @@ async function valironGateCheck(sdk, opts) {
|
|
|
352
543
|
},
|
|
353
544
|
};
|
|
354
545
|
}
|
|
546
|
+
const effectiveMinScore = minScore ?? 65;
|
|
547
|
+
const cacheTtl = opts.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
548
|
+
// Get or create a per-SDK cache instance
|
|
549
|
+
const cache = getGateCheckCache(sdk);
|
|
550
|
+
// Check client-side cache first
|
|
551
|
+
if (cacheTtl > 0) {
|
|
552
|
+
const cached = cache.getCached(identifier, cacheTtl);
|
|
553
|
+
if (cached) {
|
|
554
|
+
if (cached.result.allow) {
|
|
555
|
+
return { hasAgent: true, agentId: identifier, ok: true, allow: true, result: cached.result, status: 200 };
|
|
556
|
+
}
|
|
557
|
+
return {
|
|
558
|
+
hasAgent: true,
|
|
559
|
+
agentId: identifier,
|
|
560
|
+
ok: true,
|
|
561
|
+
allow: false,
|
|
562
|
+
result: cached.result,
|
|
563
|
+
status: 403,
|
|
564
|
+
body: { error: "Agent blocked by Valiron trust gate", ...cached.result,
|
|
565
|
+
...(cached.pendingEvaluation ? { pendingEvaluation: true, retryAfterMs: 30000 } : {}) },
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
}
|
|
355
569
|
try {
|
|
356
570
|
let result;
|
|
571
|
+
let pendingEvaluation = false;
|
|
357
572
|
if (agentId) {
|
|
358
|
-
|
|
573
|
+
const profile = await sdk.getAgentProfile(agentId);
|
|
574
|
+
result = profileToGateResult(profile, effectiveMinScore);
|
|
575
|
+
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
576
|
+
if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
|
|
577
|
+
sdk.triggerSandboxTest(agentId).catch(() => { });
|
|
578
|
+
pendingEvaluation = true;
|
|
579
|
+
}
|
|
359
580
|
}
|
|
360
581
|
else {
|
|
361
582
|
const profile = await sdk.getKeyAgentProfile(agentAddress);
|
|
362
|
-
result = keyProfileToGateResult(profile,
|
|
583
|
+
result = keyProfileToGateResult(profile, effectiveMinScore);
|
|
584
|
+
// Detect brand-new key agent: verified but never scored.
|
|
585
|
+
if (!result.allow && profile.verified && profile.score == null) {
|
|
586
|
+
if (typeof sdk.triggerKeyAgentSandbox === "function") {
|
|
587
|
+
sdk.triggerKeyAgentSandbox(agentAddress).catch(() => { });
|
|
588
|
+
}
|
|
589
|
+
pendingEvaluation = true;
|
|
590
|
+
}
|
|
363
591
|
}
|
|
592
|
+
if (cacheTtl > 0)
|
|
593
|
+
cache.setCache(identifier, result, pendingEvaluation || undefined);
|
|
364
594
|
if (result.allow) {
|
|
365
595
|
return { hasAgent: true, agentId: identifier, ok: true, allow: true, result, status: 200 };
|
|
366
596
|
}
|
|
597
|
+
if (pendingEvaluation) {
|
|
598
|
+
return {
|
|
599
|
+
hasAgent: true,
|
|
600
|
+
agentId: identifier,
|
|
601
|
+
ok: true,
|
|
602
|
+
allow: false,
|
|
603
|
+
result,
|
|
604
|
+
status: 403,
|
|
605
|
+
pendingEvaluation: true,
|
|
606
|
+
body: {
|
|
607
|
+
error: "Agent pending evaluation",
|
|
608
|
+
message: "This agent was recently registered and is being evaluated. Retry shortly.",
|
|
609
|
+
retryAfterMs: 30000,
|
|
610
|
+
...result,
|
|
611
|
+
},
|
|
612
|
+
};
|
|
613
|
+
}
|
|
367
614
|
return {
|
|
368
615
|
hasAgent: true,
|
|
369
616
|
agentId: identifier,
|
package/dist/operatorSdk.d.ts
CHANGED
|
@@ -23,8 +23,19 @@ export interface PaywallConfig {
|
|
|
23
23
|
pricePerCall: number;
|
|
24
24
|
/** Minimum trust score to allow (default: 45). */
|
|
25
25
|
minTrustScore?: number;
|
|
26
|
-
/**
|
|
26
|
+
/**
|
|
27
|
+
* Server-side gate result TTL in ms (default: 86400000 = 24h).
|
|
28
|
+
* @deprecated Use `cacheTtlMs` for client-side cache control.
|
|
29
|
+
* This field is kept for backward compatibility and
|
|
30
|
+
* maps to `cacheTtlMs` if `cacheTtlMs` is not set.
|
|
31
|
+
*/
|
|
27
32
|
ttlMs?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Client-side profile cache TTL in ms (default: 30000 = 30s).
|
|
35
|
+
* Controls how long gate results are cached in memory to absorb
|
|
36
|
+
* x402 retry flows. Set to `0` to disable caching.
|
|
37
|
+
*/
|
|
38
|
+
cacheTtlMs?: number;
|
|
28
39
|
/** Custom handler when an agent is denied. */
|
|
29
40
|
onDeny?: (req: any, res: any, result: any) => void;
|
|
30
41
|
/** Hook called after an agent is allowed. */
|
|
@@ -76,7 +87,7 @@ export declare class ValironOperator {
|
|
|
76
87
|
* });
|
|
77
88
|
* ```
|
|
78
89
|
*/
|
|
79
|
-
paywall(config: PaywallConfig): (req: any, res: any, next: any) =>
|
|
90
|
+
paywall(config: PaywallConfig): (req: any, res: any, next: any) => void;
|
|
80
91
|
/**
|
|
81
92
|
* Create a Fastify plugin that gates access + tracks usage.
|
|
82
93
|
*
|
package/dist/operatorSdk.js
CHANGED
|
@@ -63,7 +63,7 @@ class ValironOperator {
|
|
|
63
63
|
const gateConfig = {
|
|
64
64
|
sdk: this.sdk,
|
|
65
65
|
minScore: config.minTrustScore ?? 45,
|
|
66
|
-
|
|
66
|
+
cacheTtlMs: config.cacheTtlMs ?? config.ttlMs,
|
|
67
67
|
onDeny: config.onDeny,
|
|
68
68
|
onAllow: (req, result) => {
|
|
69
69
|
// Enrich the gate result with pricing
|
|
@@ -98,7 +98,7 @@ class ValironOperator {
|
|
|
98
98
|
const pluginConfig = {
|
|
99
99
|
sdk: this.sdk,
|
|
100
100
|
minScore: config.minTrustScore ?? 45,
|
|
101
|
-
|
|
101
|
+
cacheTtlMs: config.cacheTtlMs ?? config.ttlMs,
|
|
102
102
|
prefix: config.prefix,
|
|
103
103
|
onDeny: config.onDeny,
|
|
104
104
|
onAllow: (req, result) => {
|
package/dist/types.d.ts
CHANGED
|
@@ -152,6 +152,20 @@ export interface SandboxResult {
|
|
|
152
152
|
chain: ChainContext;
|
|
153
153
|
message: string;
|
|
154
154
|
}
|
|
155
|
+
/**
|
|
156
|
+
* Response from `POST /operator/trigger-sandbox-key/:agentAddress`
|
|
157
|
+
*
|
|
158
|
+
* Same scoring as on-chain agents, but keyed by agent address instead of
|
|
159
|
+
* on-chain agent ID.
|
|
160
|
+
*/
|
|
161
|
+
export interface KeyAgentSandboxResult {
|
|
162
|
+
ok: boolean;
|
|
163
|
+
agentAddress: string;
|
|
164
|
+
valironScore: number;
|
|
165
|
+
tier: MoodysRating;
|
|
166
|
+
riskLevel: RiskLevel;
|
|
167
|
+
message: string;
|
|
168
|
+
}
|
|
155
169
|
/**
|
|
156
170
|
* Response from `GET /operator/agent/:agentId/snapshot`
|
|
157
171
|
*
|
package/docs/QUICKSTART.md
CHANGED
|
@@ -66,19 +66,22 @@ import { createValironGate } from "@valiron/sdk";
|
|
|
66
66
|
app.use("/api/paid", createValironGate({ sdk: valiron }));
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
-
This reads `x-agent-id` from the request header and returns 403 for untrusted agents.
|
|
69
|
+
This reads `x-agent-id` from the request header, checks trust via the public agent profile endpoint, and returns 403 for untrusted agents. It's safe with Express 4 (async errors are handled) and includes a 30-second client-side cache for x402 compatibility.
|
|
70
70
|
|
|
71
|
-
Or use `
|
|
71
|
+
Or use `getAgentProfile()` directly for custom logic:
|
|
72
72
|
|
|
73
73
|
```typescript
|
|
74
|
-
const
|
|
75
|
-
|
|
74
|
+
const profile = await valiron.getAgentProfile("INCOMING_AGENT_ID");
|
|
75
|
+
const { finalRoute, decision } = profile.routing;
|
|
76
|
+
if (finalRoute === "prod" || finalRoute === "prod_throttled") {
|
|
76
77
|
// Serve the request — agent is trusted
|
|
77
78
|
} else {
|
|
78
|
-
// Block — agent is untrusted (tier:
|
|
79
|
+
// Block — agent is untrusted (tier: profile.localReputation?.tier)
|
|
79
80
|
}
|
|
80
81
|
```
|
|
81
82
|
|
|
83
|
+
> **Note**: The `gate()` method calls a protected endpoint that requires agent challenge-response auth. Use the middleware (`createValironGate`) or `getAgentProfile()` for server-side trust checks.
|
|
84
|
+
|
|
82
85
|
## What happens next?
|
|
83
86
|
|
|
84
87
|
Based on the route decision, your API should:
|
|
@@ -93,13 +96,20 @@ Based on the route decision, your API should:
|
|
|
93
96
|
Proactively evaluate an agent before they hit your endpoints:
|
|
94
97
|
|
|
95
98
|
```typescript
|
|
99
|
+
// On-chain agents
|
|
96
100
|
const result = await valiron.triggerSandboxTest("AGENT_ID");
|
|
97
101
|
|
|
98
102
|
console.log(result.tier); // "AAA"
|
|
99
103
|
console.log(result.riskLevel); // "GREEN"
|
|
100
104
|
console.log(result.meetsThreshold); // true
|
|
105
|
+
|
|
106
|
+
// Key-based (Web2) agents
|
|
107
|
+
const keyResult = await valiron.triggerKeyAgentSandbox("0x1234...abcd");
|
|
108
|
+
console.log(keyResult.tier); // "A"
|
|
101
109
|
```
|
|
102
110
|
|
|
111
|
+
> **Auto-sandbox:** You usually don't need to call these manually. When a new agent (on-chain with `totalFeedback === 0`, or key-based with no score yet) hits a gated endpoint, the middleware automatically triggers sandbox evaluation in the background. The agent receives a `403` with `{ error: "Agent pending evaluation", retryAfterMs: 30000 }` — they should retry after 30 seconds.
|
|
112
|
+
|
|
103
113
|
## Step 7 — Register a webhook (optional)
|
|
104
114
|
|
|
105
115
|
Get notified whenever Valiron evaluates an agent calling your API:
|
|
@@ -128,6 +138,9 @@ curl https://valiron-edge-proxy.onrender.com/operator/agent/AGENT_ID
|
|
|
128
138
|
# Trigger sandbox evaluation
|
|
129
139
|
curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox/AGENT_ID
|
|
130
140
|
|
|
141
|
+
# Trigger sandbox for key-based agent
|
|
142
|
+
curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox-key/0x1234...abcd
|
|
143
|
+
|
|
131
144
|
# Gate decision (allow/deny)
|
|
132
145
|
curl -X POST https://valiron-edge-proxy.onrender.com/operator/gate/AGENT_ID
|
|
133
146
|
|
package/docs/SANDBOX.md
CHANGED
|
@@ -26,7 +26,7 @@ Once graduated, the trust evaluation is cached. The route decision persists unti
|
|
|
26
26
|
|
|
27
27
|
## Triggering a Sandbox Test
|
|
28
28
|
|
|
29
|
-
You can proactively evaluate agents before they hit your production endpoints.
|
|
29
|
+
You can proactively evaluate agents before they hit your production endpoints, or let the middleware handle it automatically (see Auto-Sandbox below).
|
|
30
30
|
|
|
31
31
|
### Via SDK
|
|
32
32
|
|
|
@@ -34,17 +34,67 @@ You can proactively evaluate agents before they hit your production endpoints.
|
|
|
34
34
|
import { ValironSDK } from "@valiron/sdk";
|
|
35
35
|
|
|
36
36
|
const valiron = new ValironSDK();
|
|
37
|
+
|
|
38
|
+
// On-chain agent
|
|
37
39
|
const result = await valiron.triggerSandboxTest("YOUR_AGENT_ID");
|
|
38
40
|
|
|
39
41
|
console.log(result.tier); // "AAA"
|
|
40
42
|
console.log(result.riskLevel); // "GREEN"
|
|
41
43
|
console.log(result.meetsThreshold); // true
|
|
44
|
+
|
|
45
|
+
// Key-based agent
|
|
46
|
+
const keyResult = await valiron.triggerKeyAgentSandbox("0x1234...abcd");
|
|
47
|
+
console.log(keyResult.tier); // "A"
|
|
42
48
|
```
|
|
43
49
|
|
|
44
50
|
### Via HTTP
|
|
45
51
|
|
|
46
52
|
```bash
|
|
53
|
+
# On-chain agent
|
|
47
54
|
curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox/YOUR_AGENT_ID
|
|
55
|
+
|
|
56
|
+
# Key-based agent
|
|
57
|
+
curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox-key/0x1234...abcd
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Auto-Sandbox
|
|
61
|
+
|
|
62
|
+
When a new agent hits a gated endpoint for the first time, the middleware automatically triggers sandbox evaluation in the background. No manual trigger is needed.
|
|
63
|
+
|
|
64
|
+
### On-Chain Agents (ERC-8004)
|
|
65
|
+
|
|
66
|
+
New on-chain agents are detected by `totalFeedback === 0` in their reputation profile. The middleware calls `triggerSandboxTest()` as a fire-and-forget background task and returns:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
{ "error": "Agent pending evaluation", "retryAfterMs": 30000 }
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The agent should retry after 30 seconds. Once evaluation completes, subsequent requests are gated normally.
|
|
73
|
+
|
|
74
|
+
### Key-Based Agents (Web2)
|
|
75
|
+
|
|
76
|
+
New key agents are detected by `verified === true` but `score === null`. The middleware calls `triggerKeyAgentSandbox()` in the background and returns the same 403 pending response.
|
|
77
|
+
|
|
78
|
+
Key agents don't have on-chain endpoints, so sandbox evaluation uses `sandbox_relay` mode — a conservative set of behavioral metrics are computed without probing endpoints.
|
|
79
|
+
|
|
80
|
+
#### Via SDK
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
// On-chain agent
|
|
84
|
+
const result = await valiron.triggerSandboxTest("YOUR_AGENT_ID");
|
|
85
|
+
|
|
86
|
+
// Key-based agent
|
|
87
|
+
const result = await valiron.triggerKeyAgentSandbox("0x1234...abcd");
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
#### Via HTTP
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
# On-chain agent
|
|
94
|
+
curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox/YOUR_AGENT_ID
|
|
95
|
+
|
|
96
|
+
# Key-based agent
|
|
97
|
+
curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox-key/0x1234...abcd
|
|
48
98
|
```
|
|
49
99
|
|
|
50
100
|
## Tips for Passing Sandbox Tests
|
package/docs/SDK-REFERENCE.md
CHANGED
|
@@ -230,6 +230,41 @@ console.log(result.riskLevel); // "GREEN"
|
|
|
230
230
|
console.log(result.meetsThreshold); // true
|
|
231
231
|
```
|
|
232
232
|
|
|
233
|
+
> **Auto-sandbox:** The middleware (`createValironGate`, `valironFastifyPlugin`, `createValironNextMiddleware`, `valironGateCheck`) automatically triggers `triggerSandboxTest()` in the background for new on-chain agents (those with `totalFeedback === 0`). The agent receives a 403 with `{ error: "Agent pending evaluation", retryAfterMs: 30000 }` while evaluation runs. No manual trigger is needed.
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
### triggerKeyAgentSandbox(agentAddress)
|
|
238
|
+
|
|
239
|
+
Run sandbox tests against a key-based (Web2) agent and compute a trust evaluation. Key agents don't have on-chain endpoints, so this uses the `sandbox_relay` mode internally.
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
const result = await valiron.triggerKeyAgentSandbox(agentAddress: string): Promise<KeyAgentSandboxResult>;
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
**Returns**: `KeyAgentSandboxResult`
|
|
246
|
+
|
|
247
|
+
```typescript
|
|
248
|
+
interface KeyAgentSandboxResult {
|
|
249
|
+
ok: boolean;
|
|
250
|
+
agentAddress: string;
|
|
251
|
+
valironScore: number;
|
|
252
|
+
tier: MoodysRating;
|
|
253
|
+
riskLevel: "GREEN" | "YELLOW" | "RED";
|
|
254
|
+
message: string;
|
|
255
|
+
}
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
**Example**:
|
|
259
|
+
```typescript
|
|
260
|
+
const result = await valiron.triggerKeyAgentSandbox("0x1234...abcd");
|
|
261
|
+
console.log(result.tier); // "A"
|
|
262
|
+
console.log(result.riskLevel); // "GREEN"
|
|
263
|
+
console.log(result.valironScore); // 85
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
> **Auto-sandbox:** The middleware automatically triggers `triggerKeyAgentSandbox()` in the background for new key agents (those with `verified === true` but `score === null`). The agent receives a 403 with `{ error: "Agent pending evaluation", retryAfterMs: 30000 }` while evaluation runs.
|
|
267
|
+
|
|
233
268
|
---
|
|
234
269
|
|
|
235
270
|
### gate(agentId, options?)
|
|
@@ -315,22 +350,30 @@ console.log(snapshot.interactionCount); // 15
|
|
|
315
350
|
|
|
316
351
|
Express-compatible middleware factory. Automatically gates requests based on agent trust.
|
|
317
352
|
|
|
353
|
+
Uses the public `getAgentProfile()` endpoint under the hood (not the protected `gate()` endpoint), so it works from any server context — no agent challenge-response auth required.
|
|
354
|
+
|
|
355
|
+
**Express 4 safe**: The returned middleware wraps the async handler with `Promise.resolve(handler(...)).catch(next)` so async rejections are properly forwarded to Express's error handler. This prevents race conditions when chained with other async middleware (e.g. x402's `paymentMiddleware`).
|
|
356
|
+
|
|
318
357
|
```typescript
|
|
319
358
|
import { ValironSDK, createValironGate } from "@valiron/sdk";
|
|
320
359
|
|
|
321
360
|
const gate = createValironGate(config: {
|
|
322
361
|
sdk: ValironSDK;
|
|
323
|
-
|
|
324
|
-
|
|
362
|
+
minScore?: number; // default: 65
|
|
363
|
+
cacheTtlMs?: number; // default: 30000 (30s client-side cache)
|
|
364
|
+
extractAgentId?: (req: Request) => string | null;
|
|
365
|
+
extractAgentAddress?: (req: Request) => string | null;
|
|
325
366
|
onAllow?: (req: Request, result: GateResult) => void;
|
|
326
367
|
onDeny?: (req: Request, res: Response, result: GateResult) => void;
|
|
327
368
|
});
|
|
328
369
|
```
|
|
329
370
|
|
|
330
371
|
**Default behavior**:
|
|
331
|
-
- Extracts agent ID from `x-agent-id`
|
|
372
|
+
- Extracts agent ID from `x-agent-id` header (on-chain) or `x-agent-address` header (key-based)
|
|
373
|
+
- Returns 401 if no agent identity is found (with link to identity skill)
|
|
332
374
|
- Returns 403 if agent is denied
|
|
333
|
-
- Returns
|
|
375
|
+
- Returns 503 if the trust gate is unreachable (fail-closed)
|
|
376
|
+
- Caches profiles in memory for 30s to survive x402 retry flows
|
|
334
377
|
|
|
335
378
|
**Example**:
|
|
336
379
|
```typescript
|
|
@@ -339,10 +382,11 @@ const valiron = new ValironSDK({ chain: "monad" });
|
|
|
339
382
|
// Basic gate
|
|
340
383
|
app.use("/api/paid", createValironGate({ sdk: valiron }));
|
|
341
384
|
|
|
342
|
-
// Custom
|
|
385
|
+
// Custom threshold + longer cache
|
|
343
386
|
app.use("/api/premium", createValironGate({
|
|
344
387
|
sdk: valiron,
|
|
345
|
-
|
|
388
|
+
minScore: 85,
|
|
389
|
+
cacheTtlMs: 60_000, // 60s
|
|
346
390
|
}));
|
|
347
391
|
|
|
348
392
|
// Custom agent ID extraction
|
|
@@ -432,6 +476,22 @@ For Web2 agents that don't have on-chain identities, Valiron supports key-based
|
|
|
432
476
|
|
|
433
477
|
The SDK auto-detects key-based agents from the `x-agent-address` header. No configuration needed.
|
|
434
478
|
|
|
479
|
+
### Sandbox Evaluation for Key Agents
|
|
480
|
+
|
|
481
|
+
New key agents (verified but not yet scored) are automatically evaluated when they first hit a gated endpoint. The middleware triggers `triggerKeyAgentSandbox()` in the background and returns 403 with `retryAfterMs: 30000`. After evaluation completes, the agent receives a trust score and can access endpoints normally.
|
|
482
|
+
|
|
483
|
+
You can also trigger evaluation manually:
|
|
484
|
+
|
|
485
|
+
```typescript
|
|
486
|
+
const result = await valiron.triggerKeyAgentSandbox("0x1234...abcd");
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
Or via HTTP:
|
|
490
|
+
|
|
491
|
+
```bash
|
|
492
|
+
curl -X POST https://valiron-edge-proxy.onrender.com/operator/trigger-sandbox-key/0x1234...abcd
|
|
493
|
+
```
|
|
494
|
+
|
|
435
495
|
### KeyAgentProfile
|
|
436
496
|
|
|
437
497
|
| Field | Type | Description |
|
|
@@ -528,10 +588,20 @@ const valiron = new ValironSDK({
|
|
|
528
588
|
|
|
529
589
|
## Middleware
|
|
530
590
|
|
|
591
|
+
All middleware adapters use `getAgentProfile()` (public endpoint) rather than
|
|
592
|
+
`gate()` (protected endpoint), so they work from any server context without
|
|
593
|
+
agent challenge-response auth. Results are cached client-side (default 30s)
|
|
594
|
+
to survive x402's two-request payment flow and avoid cold-start failures.
|
|
595
|
+
|
|
531
596
|
### createValironGate(config) — Express
|
|
532
597
|
|
|
533
598
|
See above for full documentation.
|
|
534
599
|
|
|
600
|
+
**Express 4 note**: The returned middleware uses a synchronous wrapper
|
|
601
|
+
(`Promise.resolve().catch(next)`) to ensure async errors are properly caught.
|
|
602
|
+
You do NOT need to wrap it yourself — it's safe to use directly with
|
|
603
|
+
`app.use()` even on Express 4.
|
|
604
|
+
|
|
535
605
|
### valironFastifyPlugin — Fastify
|
|
536
606
|
|
|
537
607
|
```typescript
|
|
@@ -553,7 +623,7 @@ import { ValironSDK, createValironNextMiddleware } from "@valiron/sdk";
|
|
|
553
623
|
const valiron = new ValironSDK();
|
|
554
624
|
export default createValironNextMiddleware({
|
|
555
625
|
sdk: valiron,
|
|
556
|
-
|
|
626
|
+
paths: ["/api/paid"],
|
|
557
627
|
});
|
|
558
628
|
```
|
|
559
629
|
|
|
@@ -565,13 +635,27 @@ import { ValironSDK, valironGateCheck } from "@valiron/sdk";
|
|
|
565
635
|
const valiron = new ValironSDK();
|
|
566
636
|
|
|
567
637
|
app.use(async (c, next) => {
|
|
568
|
-
const
|
|
569
|
-
|
|
570
|
-
|
|
638
|
+
const gate = await valironGateCheck(valiron, {
|
|
639
|
+
agentId: c.req.header("x-agent-id") ?? null,
|
|
640
|
+
agentAddress: c.req.header("x-agent-address") ?? null,
|
|
641
|
+
});
|
|
642
|
+
if (!gate.allow) return c.json(gate.body, gate.status);
|
|
643
|
+
c.set("valiron", gate.result);
|
|
571
644
|
await next();
|
|
572
645
|
});
|
|
573
646
|
```
|
|
574
647
|
|
|
648
|
+
### Client-Side Caching
|
|
649
|
+
|
|
650
|
+
All middleware adapters include a built-in in-memory cache (default TTL: 30 seconds).
|
|
651
|
+
This is important for payment protocols like x402 that make two requests per payment
|
|
652
|
+
(discover 402 → retry with payment). Without caching, the second trust check can fail
|
|
653
|
+
due to cold-start latency on the edge proxy.
|
|
654
|
+
|
|
655
|
+
The Express gate exposes `cacheTtlMs` to override this TTL; set it to `0` to disable
|
|
656
|
+
caching for that middleware instance. `createValironNextMiddleware` and
|
|
657
|
+
`valironGateCheck` also accept `cacheTtlMs`.
|
|
658
|
+
|
|
575
659
|
### Middleware Error Responses
|
|
576
660
|
|
|
577
661
|
All middleware variants return consistent error responses:
|
|
@@ -580,6 +664,7 @@ All middleware variants return consistent error responses:
|
|
|
580
664
|
|--------|------|------|
|
|
581
665
|
| 401 | No agent ID found in request | `{ error: "No agent identity provided" }` |
|
|
582
666
|
| 403 | Agent denied by trust gate | `{ error: "Access denied", tier, riskLevel, route }` |
|
|
667
|
+
| 403 | New agent pending evaluation | `{ error: "Agent pending evaluation", retryAfterMs: 30000 }` |
|
|
583
668
|
| 503 | Valiron service unavailable | `{ error: "Trust evaluation unavailable" }` |
|
|
584
669
|
|
|
585
670
|
> **Fail-closed:** When the Valiron service is unreachable, middleware returns 503 — it never fails open and never allows unverified agents through.
|
package/docs/llms.txt
CHANGED
|
@@ -17,9 +17,12 @@ GET /operator/wallet/{wallet}?chain={chain}
|
|
|
17
17
|
### Resolve wallet to agent
|
|
18
18
|
GET /operator/resolve-wallet/{wallet}?chain={chain}
|
|
19
19
|
|
|
20
|
-
### Run sandbox test
|
|
20
|
+
### Run sandbox test (on-chain agent)
|
|
21
21
|
POST /operator/trigger-sandbox/{agentId}
|
|
22
22
|
|
|
23
|
+
### Run sandbox test (key-based agent)
|
|
24
|
+
POST /operator/trigger-sandbox-key/{agentAddress}
|
|
25
|
+
|
|
23
26
|
### Trust gate (allow/deny)
|
|
24
27
|
POST /operator/gate/{agentId}
|
|
25
28
|
Body: { "ttlMs": 86400000 }
|
|
@@ -60,8 +63,14 @@ if (gate.allow) { /* proceed */ }
|
|
|
60
63
|
const snapshot = await valiron.getAgentSnapshot("AGENT_ID");
|
|
61
64
|
console.log(snapshot.snapshotHash); // "0xabc..."
|
|
62
65
|
console.log(snapshot.previousHash); // "0x0" (genesis)
|
|
66
|
+
|
|
67
|
+
// Sandbox evaluation for key-based agent
|
|
68
|
+
const keyResult = await valiron.triggerKeyAgentSandbox("0x1234...abcd");
|
|
69
|
+
console.log(keyResult.tier); // "A"
|
|
63
70
|
```
|
|
64
71
|
|
|
72
|
+
Auto-sandbox: Middleware automatically triggers sandbox evaluation for new agents (on-chain with totalFeedback=0, or key-based with no score). Returns 403 with { error: "Agent pending evaluation", retryAfterMs: 30000 }.
|
|
73
|
+
|
|
65
74
|
## Trust Tiers
|
|
66
75
|
|
|
67
76
|
Valiron assigns Moody's-style credit tiers: AAA (highest trust) through C (lowest trust). Higher tiers route to production, lower tiers are sandboxed or blocked. Exact score ranges are not disclosed.
|