@valiron/sdk 1.0.0 → 1.0.2
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 +8 -1
- package/dist/clients.d.ts +16 -1
- package/dist/clients.js +51 -6
- package/dist/index.d.ts +21 -1
- package/dist/index.js +24 -0
- package/dist/middleware.d.ts +50 -12
- package/dist/middleware.js +485 -20
- package/dist/operatorSdk.d.ts +24 -3
- package/dist/operatorSdk.js +153 -5
- package/dist/telemetry.js +1 -1
- package/dist/types.d.ts +23 -2
- package/docs/API-REFERENCE.md +5 -1
- package/docs/ERRORS.md +1 -1
- package/docs/QUICKSTART.md +31 -6
- package/docs/SANDBOX.md +51 -1
- package/docs/SDK-REFERENCE.md +101 -14
- package/docs/TRUST-MODEL.md +36 -4
- package/docs/llms.txt +10 -1
- package/package.json +1 -1
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,130 @@ 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
|
+
function normalizeTrustSignals(trustSignals) {
|
|
142
|
+
return trustSignals?.length ? [...trustSignals].sort() : undefined;
|
|
143
|
+
}
|
|
144
|
+
function cacheKeyFor(agentId, trustSignals) {
|
|
145
|
+
const normalized = normalizeTrustSignals(trustSignals);
|
|
146
|
+
return normalized ? `${agentId}:${normalized.join(",")}` : agentId;
|
|
147
|
+
}
|
|
148
|
+
function bucketScore(score) {
|
|
149
|
+
if (score === undefined || !Number.isFinite(score))
|
|
150
|
+
return "unknown";
|
|
151
|
+
if (score <= 40)
|
|
152
|
+
return "0-40";
|
|
153
|
+
if (score <= 70)
|
|
154
|
+
return "41-70";
|
|
155
|
+
if (score <= 90)
|
|
156
|
+
return "71-90";
|
|
157
|
+
return "91+";
|
|
158
|
+
}
|
|
159
|
+
function emitGateTelemetry(sdk, payload) {
|
|
160
|
+
if (typeof sdk.emitTelemetry !== "function")
|
|
161
|
+
return;
|
|
162
|
+
const signals = normalizeTrustSignals(payload.trustSignals);
|
|
163
|
+
sdk.emitTelemetry("gate_decision", {
|
|
164
|
+
framework: payload.framework,
|
|
165
|
+
agent_type: payload.agentType,
|
|
166
|
+
chain: payload.chain || "unknown",
|
|
167
|
+
allow: payload.allow,
|
|
168
|
+
route: payload.route,
|
|
169
|
+
tier: payload.tier,
|
|
170
|
+
risk_level: payload.riskLevel,
|
|
171
|
+
score_bucket: bucketScore(payload.score),
|
|
172
|
+
min_score_bucket: bucketScore(payload.minScore),
|
|
173
|
+
cached: payload.cached,
|
|
174
|
+
pending_evaluation: payload.pendingEvaluation || false,
|
|
175
|
+
trust_signals: signals?.join(","),
|
|
176
|
+
trust_signal_count: signals?.length,
|
|
177
|
+
world_included: signals?.includes("world"),
|
|
178
|
+
icebreaker_included: signals?.includes("icebreaker"),
|
|
179
|
+
status: payload.status || "ok",
|
|
180
|
+
latency_ms: payload.latencyMs,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
async function runGateCheck(config, req, cache) {
|
|
184
|
+
const minScore = config.minScore ?? 65;
|
|
185
|
+
const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
55
186
|
// 1. Try on-chain agent ID (ERC-8004 / Solana)
|
|
56
187
|
const extractAgentId = config.extractAgentId || defaultExtractAgentId;
|
|
57
188
|
const agentId = extractAgentId(req);
|
|
58
189
|
if (agentId) {
|
|
190
|
+
const agentCacheKey = cacheKeyFor(agentId, config.trustSignals);
|
|
191
|
+
// Check client-side cache first
|
|
192
|
+
if (cacheTtl > 0) {
|
|
193
|
+
const cached = cache.getCached(agentCacheKey, cacheTtl);
|
|
194
|
+
if (cached)
|
|
195
|
+
return { agentId, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
|
|
196
|
+
}
|
|
59
197
|
try {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
198
|
+
// Use getAgentProfile() which hits the PUBLIC /operator/agent/ endpoint.
|
|
199
|
+
// The old gate() call used POST /operator/gate/ which is protected by
|
|
200
|
+
// agent challenge-response auth and fails from server contexts.
|
|
201
|
+
const profile = await config.sdk.getAgentProfile(agentId, {
|
|
202
|
+
trustSignals: normalizeTrustSignals(config.trustSignals),
|
|
63
203
|
});
|
|
64
|
-
|
|
204
|
+
const result = profileToGateResult(profile, minScore);
|
|
205
|
+
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
206
|
+
// Trigger a sandbox evaluation so the agent can build a score.
|
|
207
|
+
// The result is cached normally — when the cache expires the next
|
|
208
|
+
// request will re-fetch the profile, which should now have a score.
|
|
209
|
+
const isNewAgent = !result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0;
|
|
210
|
+
if (isNewAgent) {
|
|
211
|
+
// Fire-and-forget — don't block the response on sandbox completion
|
|
212
|
+
config.sdk.triggerSandboxTest(agentId).catch(() => { });
|
|
213
|
+
}
|
|
214
|
+
if (cacheTtl > 0)
|
|
215
|
+
cache.setCache(agentCacheKey, result, isNewAgent || undefined);
|
|
216
|
+
return { agentId, result, pendingEvaluation: isNewAgent || undefined };
|
|
65
217
|
}
|
|
66
218
|
catch (error) {
|
|
67
219
|
return { agentId, error };
|
|
@@ -71,10 +223,25 @@ async function runGateCheck(config, req) {
|
|
|
71
223
|
const extractAddress = config.extractAgentAddress || defaultExtractAgentAddress;
|
|
72
224
|
const agentAddr = extractAddress(req);
|
|
73
225
|
if (agentAddr) {
|
|
226
|
+
const agentCacheKey = cacheKeyFor(agentAddr, config.trustSignals);
|
|
227
|
+
// Check client-side cache first
|
|
228
|
+
if (cacheTtl > 0) {
|
|
229
|
+
const cached = cache.getCached(agentCacheKey, cacheTtl);
|
|
230
|
+
if (cached)
|
|
231
|
+
return { agentId: agentAddr, result: cached.result, pendingEvaluation: cached.pendingEvaluation };
|
|
232
|
+
}
|
|
74
233
|
try {
|
|
75
234
|
const profile = await config.sdk.getKeyAgentProfile(agentAddr);
|
|
76
|
-
const result = keyProfileToGateResult(profile,
|
|
77
|
-
|
|
235
|
+
const result = keyProfileToGateResult(profile, minScore);
|
|
236
|
+
// Detect brand-new key agent: verified but never scored.
|
|
237
|
+
// Trigger a sandbox evaluation so the agent can build a score.
|
|
238
|
+
const isNewKeyAgent = !result.allow && profile.verified && profile.score == null;
|
|
239
|
+
if (isNewKeyAgent && typeof config.sdk.triggerKeyAgentSandbox === "function") {
|
|
240
|
+
config.sdk.triggerKeyAgentSandbox(agentAddr).catch(() => { });
|
|
241
|
+
}
|
|
242
|
+
if (cacheTtl > 0)
|
|
243
|
+
cache.setCache(agentCacheKey, result, isNewKeyAgent || undefined);
|
|
244
|
+
return { agentId: agentAddr, result, pendingEvaluation: isNewKeyAgent || undefined };
|
|
78
245
|
}
|
|
79
246
|
catch (error) {
|
|
80
247
|
return { agentId: agentAddr, error };
|
|
@@ -94,6 +261,11 @@ async function runGateCheck(config, req) {
|
|
|
94
261
|
* On deny: returns 403 with the gate result (or delegates to `onDeny`).
|
|
95
262
|
* On error: returns 503 (fail-closed).
|
|
96
263
|
*
|
|
264
|
+
* **Express 4 compatibility**: The returned middleware wraps the async
|
|
265
|
+
* gate check with `Promise.resolve().catch(next)` so that unhandled
|
|
266
|
+
* rejections are forwarded to Express's error handler instead of causing
|
|
267
|
+
* silent failures. Express 4 does not natively `await` async middleware.
|
|
268
|
+
*
|
|
97
269
|
* @example
|
|
98
270
|
* ```typescript
|
|
99
271
|
* import { ValironSDK, createValironGate } from '@valiron/sdk';
|
|
@@ -101,14 +273,14 @@ async function runGateCheck(config, req) {
|
|
|
101
273
|
* const valiron = new ValironSDK({ chain: 'monad' });
|
|
102
274
|
*
|
|
103
275
|
* // Apply before your x402 / payment handler
|
|
104
|
-
* Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
|
|
276
|
+
* // Works with both on-chain (x-agent-id) and key-based (x-agent-address) agents
|
|
105
277
|
* app.use('/api/paid', createValironGate({ sdk: valiron }));
|
|
106
278
|
*
|
|
107
|
-
* // Custom threshold
|
|
279
|
+
* // Custom threshold + cache TTL
|
|
108
280
|
* app.use('/api/premium', createValironGate({
|
|
109
281
|
* sdk: valiron,
|
|
110
282
|
* minScore: 85,
|
|
111
|
-
*
|
|
283
|
+
* cacheTtlMs: 60_000, // 60s client-side cache
|
|
112
284
|
* }));
|
|
113
285
|
* ```
|
|
114
286
|
*/
|
|
@@ -116,9 +288,24 @@ function createValironGate(config) {
|
|
|
116
288
|
// Snapshot config at creation time so mutations after middleware
|
|
117
289
|
// creation don't affect behavior.
|
|
118
290
|
const frozen = { ...config };
|
|
119
|
-
|
|
120
|
-
|
|
291
|
+
const cache = createProfileCache();
|
|
292
|
+
async function valironGateHandler(req, res, next) {
|
|
293
|
+
const startedAt = Date.now();
|
|
294
|
+
const { agentId, result, error, pendingEvaluation } = await runGateCheck(frozen, req, cache);
|
|
295
|
+
const latencyMs = Date.now() - startedAt;
|
|
296
|
+
const minScore = frozen.minScore ?? 65;
|
|
297
|
+
const agentType = agentId
|
|
298
|
+
? (defaultExtractAgentAddress(req) === agentId ? "key" : "onchain")
|
|
299
|
+
: "missing";
|
|
121
300
|
if (!agentId) {
|
|
301
|
+
emitGateTelemetry(frozen.sdk, {
|
|
302
|
+
framework: "express",
|
|
303
|
+
agentType: "missing",
|
|
304
|
+
minScore,
|
|
305
|
+
trustSignals: frozen.trustSignals,
|
|
306
|
+
status: "missing_identity",
|
|
307
|
+
latencyMs,
|
|
308
|
+
});
|
|
122
309
|
return res.status(401).json({
|
|
123
310
|
error: "Missing agent identity",
|
|
124
311
|
message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
|
|
@@ -126,16 +313,48 @@ function createValironGate(config) {
|
|
|
126
313
|
});
|
|
127
314
|
}
|
|
128
315
|
if (error) {
|
|
316
|
+
emitGateTelemetry(frozen.sdk, {
|
|
317
|
+
framework: "express",
|
|
318
|
+
agentType,
|
|
319
|
+
minScore,
|
|
320
|
+
trustSignals: frozen.trustSignals,
|
|
321
|
+
status: "error",
|
|
322
|
+
latencyMs,
|
|
323
|
+
});
|
|
129
324
|
return res.status(503).json({
|
|
130
325
|
error: "Trust gate unavailable \u2014 request denied (fail-closed)",
|
|
131
326
|
});
|
|
132
327
|
}
|
|
328
|
+
emitGateTelemetry(frozen.sdk, {
|
|
329
|
+
framework: "express",
|
|
330
|
+
agentType,
|
|
331
|
+
chain: result.chain?.network,
|
|
332
|
+
allow: result.allow,
|
|
333
|
+
route: result.route,
|
|
334
|
+
tier: result.tier,
|
|
335
|
+
riskLevel: result.riskLevel,
|
|
336
|
+
score: result.score,
|
|
337
|
+
minScore,
|
|
338
|
+
cached: result.cached,
|
|
339
|
+
pendingEvaluation,
|
|
340
|
+
trustSignals: frozen.trustSignals,
|
|
341
|
+
latencyMs,
|
|
342
|
+
});
|
|
133
343
|
if (result.allow) {
|
|
134
344
|
req.valiron = result;
|
|
135
345
|
if (config.onAllow)
|
|
136
346
|
config.onAllow(req, result);
|
|
137
347
|
return next();
|
|
138
348
|
}
|
|
349
|
+
// New agent with no reputation — sandbox test triggered in background
|
|
350
|
+
if (pendingEvaluation) {
|
|
351
|
+
return res.status(403).json({
|
|
352
|
+
error: "Agent pending evaluation",
|
|
353
|
+
message: "This agent was recently registered and is being evaluated. Retry shortly.",
|
|
354
|
+
retryAfterMs: 30000,
|
|
355
|
+
...result,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
139
358
|
if (config.onDeny) {
|
|
140
359
|
return config.onDeny(req, res, result);
|
|
141
360
|
}
|
|
@@ -143,6 +362,14 @@ function createValironGate(config) {
|
|
|
143
362
|
error: "Agent blocked by Valiron trust gate",
|
|
144
363
|
...result,
|
|
145
364
|
});
|
|
365
|
+
}
|
|
366
|
+
// Wrap with Promise.catch(next) for Express 4 async safety.
|
|
367
|
+
// Express 4 does NOT await async middleware, so without this wrapper
|
|
368
|
+
// an unhandled rejection would silently hang the request. This also
|
|
369
|
+
// prevents race conditions when chained with other async middleware
|
|
370
|
+
// (e.g. x402's paymentMiddleware running before the gate resolves).
|
|
371
|
+
return function valironGate(req, res, next) {
|
|
372
|
+
Promise.resolve(valironGateHandler(req, res, next)).catch(next);
|
|
146
373
|
};
|
|
147
374
|
}
|
|
148
375
|
/**
|
|
@@ -178,9 +405,10 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
178
405
|
extractAgentId: opts.extractAgentId,
|
|
179
406
|
extractAgentAddress: opts.extractAgentAddress,
|
|
180
407
|
minScore: opts.minScore,
|
|
181
|
-
|
|
408
|
+
cacheTtlMs: opts.cacheTtlMs,
|
|
182
409
|
onAllow: opts.onAllow,
|
|
183
410
|
};
|
|
411
|
+
const cache = createProfileCache();
|
|
184
412
|
// Decorate request with valiron property
|
|
185
413
|
if (!fastify.hasRequestDecorator?.("valiron")) {
|
|
186
414
|
fastify.decorateRequest("valiron", null);
|
|
@@ -196,8 +424,22 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
196
424
|
if (pathname !== prefix && !pathname.startsWith(prefix + "/"))
|
|
197
425
|
return;
|
|
198
426
|
}
|
|
199
|
-
const
|
|
427
|
+
const startedAt = Date.now();
|
|
428
|
+
const { agentId, result, error, pendingEvaluation } = await runGateCheck(gateConfig, request, cache);
|
|
429
|
+
const latencyMs = Date.now() - startedAt;
|
|
430
|
+
const minScore = opts.minScore ?? 65;
|
|
431
|
+
const agentType = agentId
|
|
432
|
+
? (defaultExtractAgentAddress(request) === agentId ? "key" : "onchain")
|
|
433
|
+
: "missing";
|
|
200
434
|
if (!agentId) {
|
|
435
|
+
emitGateTelemetry(opts.sdk, {
|
|
436
|
+
framework: "fastify",
|
|
437
|
+
agentType: "missing",
|
|
438
|
+
minScore,
|
|
439
|
+
trustSignals: opts.trustSignals,
|
|
440
|
+
status: "missing_identity",
|
|
441
|
+
latencyMs,
|
|
442
|
+
});
|
|
201
443
|
return reply.status(401).send({
|
|
202
444
|
error: "Missing agent identity",
|
|
203
445
|
message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
|
|
@@ -205,16 +447,48 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
205
447
|
});
|
|
206
448
|
}
|
|
207
449
|
if (error) {
|
|
450
|
+
emitGateTelemetry(opts.sdk, {
|
|
451
|
+
framework: "fastify",
|
|
452
|
+
agentType,
|
|
453
|
+
minScore,
|
|
454
|
+
trustSignals: opts.trustSignals,
|
|
455
|
+
status: "error",
|
|
456
|
+
latencyMs,
|
|
457
|
+
});
|
|
208
458
|
return reply.status(503).send({
|
|
209
459
|
error: "Trust gate unavailable \u2014 request denied (fail-closed)",
|
|
210
460
|
});
|
|
211
461
|
}
|
|
462
|
+
emitGateTelemetry(opts.sdk, {
|
|
463
|
+
framework: "fastify",
|
|
464
|
+
agentType,
|
|
465
|
+
chain: result.chain?.network,
|
|
466
|
+
allow: result.allow,
|
|
467
|
+
route: result.route,
|
|
468
|
+
tier: result.tier,
|
|
469
|
+
riskLevel: result.riskLevel,
|
|
470
|
+
score: result.score,
|
|
471
|
+
minScore,
|
|
472
|
+
cached: result.cached,
|
|
473
|
+
pendingEvaluation,
|
|
474
|
+
trustSignals: opts.trustSignals,
|
|
475
|
+
latencyMs,
|
|
476
|
+
});
|
|
212
477
|
if (result.allow) {
|
|
213
478
|
request.valiron = result;
|
|
214
479
|
if (opts.onAllow)
|
|
215
480
|
opts.onAllow(request, result);
|
|
216
481
|
return; // continue to handler
|
|
217
482
|
}
|
|
483
|
+
// New agent with no reputation — sandbox test triggered in background
|
|
484
|
+
if (pendingEvaluation) {
|
|
485
|
+
return reply.status(403).send({
|
|
486
|
+
error: "Agent pending evaluation",
|
|
487
|
+
message: "This agent was recently registered and is being evaluated. Retry shortly.",
|
|
488
|
+
retryAfterMs: 30000,
|
|
489
|
+
...result,
|
|
490
|
+
});
|
|
491
|
+
}
|
|
218
492
|
if (opts.onDeny) {
|
|
219
493
|
return opts.onDeny(request, reply, result);
|
|
220
494
|
}
|
|
@@ -252,12 +526,14 @@ async function valironFastifyPlugin(fastify, opts) {
|
|
|
252
526
|
* ```
|
|
253
527
|
*/
|
|
254
528
|
function createValironNextMiddleware(config) {
|
|
255
|
-
const { sdk, minScore,
|
|
529
|
+
const { sdk, minScore, paths, trustSignals } = config;
|
|
530
|
+
const cache = createProfileCache();
|
|
256
531
|
const extractAgentId = config.extractAgentId ||
|
|
257
532
|
((req) => req.headers.get("x-agent-id"));
|
|
258
533
|
const extractAddress = config.extractAgentAddress ||
|
|
259
534
|
((req) => req.headers.get("x-agent-address") || req.headers.get("x-agent-key-hash"));
|
|
260
535
|
return async function valironNextGate(request) {
|
|
536
|
+
const startedAt = Date.now();
|
|
261
537
|
// Skip paths not in scope
|
|
262
538
|
if (paths && paths.length > 0) {
|
|
263
539
|
const url = new URL(request.url);
|
|
@@ -269,27 +545,111 @@ function createValironNextMiddleware(config) {
|
|
|
269
545
|
const agentId = extractAgentId(request);
|
|
270
546
|
const agentAddr = agentId ? null : extractAddress(request);
|
|
271
547
|
if (!agentId && !agentAddr) {
|
|
548
|
+
emitGateTelemetry(sdk, {
|
|
549
|
+
framework: "next",
|
|
550
|
+
agentType: "missing",
|
|
551
|
+
minScore: minScore ?? 65,
|
|
552
|
+
trustSignals,
|
|
553
|
+
status: "missing_identity",
|
|
554
|
+
latencyMs: Date.now() - startedAt,
|
|
555
|
+
});
|
|
272
556
|
return Response.json({
|
|
273
557
|
error: "Missing agent identity",
|
|
274
558
|
message: "Provide an x-agent-id or x-agent-address header. If you don't have an identity yet, see the Valiron Identity Skill.",
|
|
275
559
|
identitySkill: "https://valiron.co/auth.md",
|
|
276
560
|
}, { status: 401 });
|
|
277
561
|
}
|
|
562
|
+
const cacheTtl = config.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
563
|
+
const effectiveMinScore = minScore ?? 65;
|
|
278
564
|
try {
|
|
279
565
|
let result;
|
|
566
|
+
let pendingEvaluation = false;
|
|
567
|
+
const identifier = agentId || agentAddr;
|
|
568
|
+
// Check client-side cache first
|
|
569
|
+
if (cacheTtl > 0) {
|
|
570
|
+
const cached = cache.getCached(identifier, cacheTtl);
|
|
571
|
+
if (cached) {
|
|
572
|
+
emitGateTelemetry(sdk, {
|
|
573
|
+
framework: "next",
|
|
574
|
+
agentType: agentId ? "onchain" : "key",
|
|
575
|
+
chain: cached.result.chain?.network,
|
|
576
|
+
allow: cached.result.allow,
|
|
577
|
+
route: cached.result.route,
|
|
578
|
+
tier: cached.result.tier,
|
|
579
|
+
riskLevel: cached.result.riskLevel,
|
|
580
|
+
score: cached.result.score,
|
|
581
|
+
minScore: effectiveMinScore,
|
|
582
|
+
cached: true,
|
|
583
|
+
pendingEvaluation: cached.pendingEvaluation,
|
|
584
|
+
trustSignals,
|
|
585
|
+
latencyMs: Date.now() - startedAt,
|
|
586
|
+
});
|
|
587
|
+
if (cached.result.allow)
|
|
588
|
+
return undefined;
|
|
589
|
+
return Response.json({ error: "Agent blocked by Valiron trust gate", ...cached.result }, { status: 403 });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
280
592
|
if (agentId) {
|
|
281
|
-
|
|
593
|
+
const profile = await sdk.getAgentProfile(agentId, {
|
|
594
|
+
trustSignals: normalizeTrustSignals(trustSignals),
|
|
595
|
+
});
|
|
596
|
+
result = profileToGateResult(profile, effectiveMinScore);
|
|
597
|
+
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
598
|
+
if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
|
|
599
|
+
sdk.triggerSandboxTest(agentId).catch(() => { });
|
|
600
|
+
pendingEvaluation = true;
|
|
601
|
+
}
|
|
282
602
|
}
|
|
283
603
|
else {
|
|
284
604
|
const profile = await sdk.getKeyAgentProfile(agentAddr);
|
|
285
|
-
result = keyProfileToGateResult(profile,
|
|
605
|
+
result = keyProfileToGateResult(profile, effectiveMinScore);
|
|
606
|
+
// Detect brand-new key agent: verified but never scored.
|
|
607
|
+
if (!result.allow && profile.verified && profile.score == null) {
|
|
608
|
+
if (typeof sdk.triggerKeyAgentSandbox === "function") {
|
|
609
|
+
sdk.triggerKeyAgentSandbox(agentAddr).catch(() => { });
|
|
610
|
+
}
|
|
611
|
+
pendingEvaluation = true;
|
|
612
|
+
}
|
|
286
613
|
}
|
|
614
|
+
if (cacheTtl > 0)
|
|
615
|
+
cache.setCache(identifier, result, pendingEvaluation || undefined);
|
|
616
|
+
emitGateTelemetry(sdk, {
|
|
617
|
+
framework: "next",
|
|
618
|
+
agentType: agentId ? "onchain" : "key",
|
|
619
|
+
chain: result.chain?.network,
|
|
620
|
+
allow: result.allow,
|
|
621
|
+
route: result.route,
|
|
622
|
+
tier: result.tier,
|
|
623
|
+
riskLevel: result.riskLevel,
|
|
624
|
+
score: result.score,
|
|
625
|
+
minScore: effectiveMinScore,
|
|
626
|
+
cached: result.cached,
|
|
627
|
+
pendingEvaluation,
|
|
628
|
+
trustSignals,
|
|
629
|
+
latencyMs: Date.now() - startedAt,
|
|
630
|
+
});
|
|
287
631
|
if (result.allow) {
|
|
288
632
|
return undefined; // continue to route handler
|
|
289
633
|
}
|
|
634
|
+
if (pendingEvaluation) {
|
|
635
|
+
return Response.json({
|
|
636
|
+
error: "Agent pending evaluation",
|
|
637
|
+
message: "This agent was recently registered and is being evaluated. Retry shortly.",
|
|
638
|
+
retryAfterMs: 30000,
|
|
639
|
+
...result,
|
|
640
|
+
}, { status: 403 });
|
|
641
|
+
}
|
|
290
642
|
return Response.json({ error: "Agent blocked by Valiron trust gate", ...result }, { status: 403 });
|
|
291
643
|
}
|
|
292
644
|
catch {
|
|
645
|
+
emitGateTelemetry(sdk, {
|
|
646
|
+
framework: "next",
|
|
647
|
+
agentType: agentId ? "onchain" : "key",
|
|
648
|
+
minScore: effectiveMinScore,
|
|
649
|
+
trustSignals,
|
|
650
|
+
status: "error",
|
|
651
|
+
latencyMs: Date.now() - startedAt,
|
|
652
|
+
});
|
|
293
653
|
return Response.json({ error: "Trust gate unavailable \u2014 request denied (fail-closed)" }, { status: 503 });
|
|
294
654
|
}
|
|
295
655
|
};
|
|
@@ -337,9 +697,18 @@ function createValironNextMiddleware(config) {
|
|
|
337
697
|
* ```
|
|
338
698
|
*/
|
|
339
699
|
async function valironGateCheck(sdk, opts) {
|
|
340
|
-
const { agentId, agentAddress, minScore,
|
|
700
|
+
const { agentId, agentAddress, minScore, trustSignals } = opts;
|
|
701
|
+
const startedAt = Date.now();
|
|
341
702
|
const identifier = agentId || agentAddress || null;
|
|
342
703
|
if (!identifier) {
|
|
704
|
+
emitGateTelemetry(sdk, {
|
|
705
|
+
framework: "generic",
|
|
706
|
+
agentType: "missing",
|
|
707
|
+
minScore: minScore ?? 65,
|
|
708
|
+
trustSignals,
|
|
709
|
+
status: "missing_identity",
|
|
710
|
+
latencyMs: Date.now() - startedAt,
|
|
711
|
+
});
|
|
343
712
|
return {
|
|
344
713
|
hasAgent: false,
|
|
345
714
|
agentId: null,
|
|
@@ -352,18 +721,106 @@ async function valironGateCheck(sdk, opts) {
|
|
|
352
721
|
},
|
|
353
722
|
};
|
|
354
723
|
}
|
|
724
|
+
const effectiveMinScore = minScore ?? 65;
|
|
725
|
+
const cacheTtl = opts.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
|
|
726
|
+
// Get or create a per-SDK cache instance
|
|
727
|
+
const cache = getGateCheckCache(sdk);
|
|
728
|
+
// Check client-side cache first
|
|
729
|
+
if (cacheTtl > 0) {
|
|
730
|
+
const cached = cache.getCached(identifier, cacheTtl);
|
|
731
|
+
if (cached) {
|
|
732
|
+
emitGateTelemetry(sdk, {
|
|
733
|
+
framework: "generic",
|
|
734
|
+
agentType: agentId ? "onchain" : "key",
|
|
735
|
+
chain: cached.result.chain?.network,
|
|
736
|
+
allow: cached.result.allow,
|
|
737
|
+
route: cached.result.route,
|
|
738
|
+
tier: cached.result.tier,
|
|
739
|
+
riskLevel: cached.result.riskLevel,
|
|
740
|
+
score: cached.result.score,
|
|
741
|
+
minScore: effectiveMinScore,
|
|
742
|
+
cached: true,
|
|
743
|
+
pendingEvaluation: cached.pendingEvaluation,
|
|
744
|
+
trustSignals,
|
|
745
|
+
latencyMs: Date.now() - startedAt,
|
|
746
|
+
});
|
|
747
|
+
if (cached.result.allow) {
|
|
748
|
+
return { hasAgent: true, agentId: identifier, ok: true, allow: true, result: cached.result, status: 200 };
|
|
749
|
+
}
|
|
750
|
+
return {
|
|
751
|
+
hasAgent: true,
|
|
752
|
+
agentId: identifier,
|
|
753
|
+
ok: true,
|
|
754
|
+
allow: false,
|
|
755
|
+
result: cached.result,
|
|
756
|
+
status: 403,
|
|
757
|
+
body: { error: "Agent blocked by Valiron trust gate", ...cached.result,
|
|
758
|
+
...(cached.pendingEvaluation ? { pendingEvaluation: true, retryAfterMs: 30000 } : {}) },
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
}
|
|
355
762
|
try {
|
|
356
763
|
let result;
|
|
764
|
+
let pendingEvaluation = false;
|
|
357
765
|
if (agentId) {
|
|
358
|
-
|
|
766
|
+
const profile = await sdk.getAgentProfile(agentId, {
|
|
767
|
+
trustSignals: normalizeTrustSignals(trustSignals),
|
|
768
|
+
});
|
|
769
|
+
result = profileToGateResult(profile, effectiveMinScore);
|
|
770
|
+
// Detect brand-new agent: on-chain identity exists but zero reputation.
|
|
771
|
+
if (!result.allow && (profile.onchainReputation?.totalFeedback ?? 0) === 0) {
|
|
772
|
+
sdk.triggerSandboxTest(agentId).catch(() => { });
|
|
773
|
+
pendingEvaluation = true;
|
|
774
|
+
}
|
|
359
775
|
}
|
|
360
776
|
else {
|
|
361
777
|
const profile = await sdk.getKeyAgentProfile(agentAddress);
|
|
362
|
-
result = keyProfileToGateResult(profile,
|
|
778
|
+
result = keyProfileToGateResult(profile, effectiveMinScore);
|
|
779
|
+
// Detect brand-new key agent: verified but never scored.
|
|
780
|
+
if (!result.allow && profile.verified && profile.score == null) {
|
|
781
|
+
if (typeof sdk.triggerKeyAgentSandbox === "function") {
|
|
782
|
+
sdk.triggerKeyAgentSandbox(agentAddress).catch(() => { });
|
|
783
|
+
}
|
|
784
|
+
pendingEvaluation = true;
|
|
785
|
+
}
|
|
363
786
|
}
|
|
787
|
+
if (cacheTtl > 0)
|
|
788
|
+
cache.setCache(identifier, result, pendingEvaluation || undefined);
|
|
789
|
+
emitGateTelemetry(sdk, {
|
|
790
|
+
framework: "generic",
|
|
791
|
+
agentType: agentId ? "onchain" : "key",
|
|
792
|
+
chain: result.chain?.network,
|
|
793
|
+
allow: result.allow,
|
|
794
|
+
route: result.route,
|
|
795
|
+
tier: result.tier,
|
|
796
|
+
riskLevel: result.riskLevel,
|
|
797
|
+
score: result.score,
|
|
798
|
+
minScore: effectiveMinScore,
|
|
799
|
+
cached: result.cached,
|
|
800
|
+
pendingEvaluation,
|
|
801
|
+
trustSignals,
|
|
802
|
+
latencyMs: Date.now() - startedAt,
|
|
803
|
+
});
|
|
364
804
|
if (result.allow) {
|
|
365
805
|
return { hasAgent: true, agentId: identifier, ok: true, allow: true, result, status: 200 };
|
|
366
806
|
}
|
|
807
|
+
if (pendingEvaluation) {
|
|
808
|
+
return {
|
|
809
|
+
hasAgent: true,
|
|
810
|
+
agentId: identifier,
|
|
811
|
+
ok: true,
|
|
812
|
+
allow: false,
|
|
813
|
+
result,
|
|
814
|
+
status: 403,
|
|
815
|
+
pendingEvaluation: true,
|
|
816
|
+
body: {
|
|
817
|
+
error: "Agent pending evaluation",
|
|
818
|
+
message: "This agent was recently registered and is being evaluated. Retry shortly.",
|
|
819
|
+
retryAfterMs: 30000,
|
|
820
|
+
...result,
|
|
821
|
+
},
|
|
822
|
+
};
|
|
823
|
+
}
|
|
367
824
|
return {
|
|
368
825
|
hasAgent: true,
|
|
369
826
|
agentId: identifier,
|
|
@@ -375,6 +832,14 @@ async function valironGateCheck(sdk, opts) {
|
|
|
375
832
|
};
|
|
376
833
|
}
|
|
377
834
|
catch {
|
|
835
|
+
emitGateTelemetry(sdk, {
|
|
836
|
+
framework: "generic",
|
|
837
|
+
agentType: agentId ? "onchain" : "key",
|
|
838
|
+
minScore: effectiveMinScore,
|
|
839
|
+
trustSignals,
|
|
840
|
+
status: "error",
|
|
841
|
+
latencyMs: Date.now() - startedAt,
|
|
842
|
+
});
|
|
378
843
|
return {
|
|
379
844
|
hasAgent: true,
|
|
380
845
|
agentId: identifier,
|