@valiron/sdk 0.9.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ValironConfig, CallOptions, AgentProfile, WalletProfile, SandboxResult, GateResult, GateOptions, RouteDecision } from "./types";
1
+ import { ValironConfig, CallOptions, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, GateResult, GateOptions, RouteDecision } from "./types";
2
2
  /**
3
3
  * Valiron SDK – Official TypeScript SDK for the Trust Layer for Agentic Economy
4
4
  *
@@ -97,6 +97,54 @@ export declare class ValironSDK {
97
97
  * ```
98
98
  */
99
99
  getWalletProfile(wallet: string, options?: CallOptions): Promise<WalletProfile>;
100
+ /**
101
+ * Resolve a wallet address to an ERC-8004 agent ID.
102
+ *
103
+ * Lightweight lookup that returns just the agentId and how it was
104
+ * resolved, without fetching the full trust profile. Useful when you
105
+ * only need to know *which* agent owns a wallet (e.g. after extracting
106
+ * a wallet from an x402 payment header).
107
+ *
108
+ * Resolution chain: Redis → Agent0 subgraph → null.
109
+ *
110
+ * @param wallet - Ethereum wallet address
111
+ * @param options - Optional overrides (e.g. `{ chain: 'base' }`)
112
+ * @returns Wallet resolution with agentId and source
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * const resolution = await valiron.resolveWallet('0x52ce…');
117
+ * if (resolution.agentId) {
118
+ * const profile = await valiron.getAgentProfile(resolution.agentId);
119
+ * }
120
+ * ```
121
+ */
122
+ resolveWallet(wallet: string, options?: CallOptions): Promise<WalletResolution>;
123
+ /**
124
+ * Get the latest behavioral snapshot hash for an agent.
125
+ *
126
+ * Returns an opaque hash of the agent's most recent behavioral
127
+ * evaluation, the previous hash for chain continuity, and basic
128
+ * metadata. Contains no raw metrics or proprietary scoring data.
129
+ *
130
+ * Designed for hash-chain commitment systems (e.g. BehaviorChain)
131
+ * that need to commit behavioral state on-chain without accessing
132
+ * the underlying evaluation details.
133
+ *
134
+ * @param agentId - The ERC-8004 agent ID
135
+ * @param options - Optional overrides (e.g. `{ chain: 'base' }`)
136
+ * @returns Snapshot hash, previous hash, timestamp, and interaction count
137
+ *
138
+ * @example
139
+ * ```typescript
140
+ * const snapshot = await valiron.getAgentSnapshot('25459');
141
+ * console.log(snapshot.snapshotHash); // '0xabc…'
142
+ * console.log(snapshot.previousHash); // '0x0' (genesis) or '0xdef…'
143
+ * console.log(snapshot.encryptedDataUri); // 'ipfs://Qm…' or null
144
+ * console.log(snapshot.interactionCount); // 15
145
+ * ```
146
+ */
147
+ getAgentSnapshot(agentId: string, options?: CallOptions): Promise<AgentSnapshotSummary>;
100
148
  /**
101
149
  * Trigger real sandbox testing for an agent.
102
150
  *
@@ -170,5 +218,5 @@ export declare class ValironSDK {
170
218
  }
171
219
  export * from "./types";
172
220
  export { ValironClient } from "./clients";
173
- export { createValironGate } from "./middleware";
174
- export type { ValironGateConfig } from "./middleware";
221
+ export { createValironGate, valironFastifyPlugin, createValironNextMiddleware, valironGateCheck, } from "./middleware";
222
+ export type { ValironGateConfig, ValironFastifyConfig, ValironNextConfig, ValironGateCheckResult, } from "./middleware";
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.createValironGate = exports.ValironClient = exports.ValironSDK = void 0;
17
+ exports.valironGateCheck = exports.createValironNextMiddleware = exports.valironFastifyPlugin = exports.createValironGate = exports.ValironClient = exports.ValironSDK = void 0;
18
18
  const clients_1 = require("./clients");
19
19
  /**
20
20
  * Valiron SDK – Official TypeScript SDK for the Trust Layer for Agentic Economy
@@ -122,6 +122,58 @@ class ValironSDK {
122
122
  async getWalletProfile(wallet, options) {
123
123
  return this.client.getWalletProfile(wallet, options);
124
124
  }
125
+ /**
126
+ * Resolve a wallet address to an ERC-8004 agent ID.
127
+ *
128
+ * Lightweight lookup that returns just the agentId and how it was
129
+ * resolved, without fetching the full trust profile. Useful when you
130
+ * only need to know *which* agent owns a wallet (e.g. after extracting
131
+ * a wallet from an x402 payment header).
132
+ *
133
+ * Resolution chain: Redis → Agent0 subgraph → null.
134
+ *
135
+ * @param wallet - Ethereum wallet address
136
+ * @param options - Optional overrides (e.g. `{ chain: 'base' }`)
137
+ * @returns Wallet resolution with agentId and source
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * const resolution = await valiron.resolveWallet('0x52ce…');
142
+ * if (resolution.agentId) {
143
+ * const profile = await valiron.getAgentProfile(resolution.agentId);
144
+ * }
145
+ * ```
146
+ */
147
+ async resolveWallet(wallet, options) {
148
+ return this.client.resolveWallet(wallet, options);
149
+ }
150
+ /**
151
+ * Get the latest behavioral snapshot hash for an agent.
152
+ *
153
+ * Returns an opaque hash of the agent's most recent behavioral
154
+ * evaluation, the previous hash for chain continuity, and basic
155
+ * metadata. Contains no raw metrics or proprietary scoring data.
156
+ *
157
+ * Designed for hash-chain commitment systems (e.g. BehaviorChain)
158
+ * that need to commit behavioral state on-chain without accessing
159
+ * the underlying evaluation details.
160
+ *
161
+ * @param agentId - The ERC-8004 agent ID
162
+ * @param options - Optional overrides (e.g. `{ chain: 'base' }`)
163
+ * @returns Snapshot hash, previous hash, timestamp, and interaction count
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * const snapshot = await valiron.getAgentSnapshot('25459');
168
+ * console.log(snapshot.snapshotHash); // '0xabc…'
169
+ * console.log(snapshot.previousHash); // '0x0' (genesis) or '0xdef…'
170
+ * console.log(snapshot.encryptedDataUri); // 'ipfs://Qm…' or null
171
+ * console.log(snapshot.interactionCount); // 15
172
+ * ```
173
+ */
174
+ async getAgentSnapshot(agentId, options) {
175
+ return this.client.getAgentSnapshot(agentId, options);
176
+ }
125
177
  /**
126
178
  * Trigger real sandbox testing for an agent.
127
179
  *
@@ -206,3 +258,6 @@ var clients_2 = require("./clients");
206
258
  Object.defineProperty(exports, "ValironClient", { enumerable: true, get: function () { return clients_2.ValironClient; } });
207
259
  var middleware_1 = require("./middleware");
208
260
  Object.defineProperty(exports, "createValironGate", { enumerable: true, get: function () { return middleware_1.createValironGate; } });
261
+ Object.defineProperty(exports, "valironFastifyPlugin", { enumerable: true, get: function () { return middleware_1.valironFastifyPlugin; } });
262
+ Object.defineProperty(exports, "createValironNextMiddleware", { enumerable: true, get: function () { return middleware_1.createValironNextMiddleware; } });
263
+ Object.defineProperty(exports, "valironGateCheck", { enumerable: true, get: function () { return middleware_1.valironGateCheck; } });
@@ -8,7 +8,7 @@ export interface ValironGateConfig {
8
8
  sdk: ValironSDK;
9
9
  /**
10
10
  * Extract the agent ID from an incoming request.
11
- * Defaults to `req.headers['x-agent-id']`.
11
+ * Defaults to reading `x-agent-id` header.
12
12
  */
13
13
  extractAgentId?: (req: any) => string | null;
14
14
  /** Minimum Valiron score to allow (default: 65). */
@@ -21,9 +21,8 @@ export interface ValironGateConfig {
21
21
  onAllow?: (req: any, result: GateResult) => void;
22
22
  }
23
23
  /**
24
- * Create an Express-compatible middleware that sits in front of payment
25
- * protocols (x402 etc.) and gates access based on the agent's combined
26
- * Valiron trust score (on-chain reputation + sandbox tests).
24
+ * Create an Express/Connect-compatible middleware that gates access
25
+ * based on the agent's combined Valiron trust score.
27
26
  *
28
27
  * On allow: sets `req.valiron` to the {@link GateResult} and calls `next()`.
29
28
  * On deny: returns 403 with the gate result (or delegates to `onDeny`).
@@ -47,3 +46,171 @@ export interface ValironGateConfig {
47
46
  * ```
48
47
  */
49
48
  export declare function createValironGate(config: ValironGateConfig): (req: any, res: any, next: any) => Promise<any>;
49
+ /**
50
+ * Configuration for the Fastify Valiron trust gate plugin.
51
+ */
52
+ export interface ValironFastifyConfig {
53
+ /** Configured ValironSDK instance. */
54
+ sdk: ValironSDK;
55
+ /**
56
+ * Extract the agent ID from a Fastify request.
57
+ * Defaults to reading `x-agent-id` header.
58
+ */
59
+ extractAgentId?: (req: any) => string | null;
60
+ /** Minimum Valiron score to allow (default: 65). */
61
+ minScore?: number;
62
+ /** TTL for cached sandbox results in ms (default: 86400000 = 24 h). */
63
+ ttlMs?: number;
64
+ /** Custom handler when an agent is denied. If provided, must send a response. */
65
+ onDeny?: (req: any, reply: any, result: GateResult) => void;
66
+ /** Hook called after an agent is allowed. */
67
+ onAllow?: (req: any, result: GateResult) => void;
68
+ /**
69
+ * URL prefix to scope the gate to. If omitted, gates all routes.
70
+ * @example '/api'
71
+ */
72
+ prefix?: string;
73
+ }
74
+ /**
75
+ * Fastify plugin that gates incoming requests based on the agent's
76
+ * Valiron trust score. Register it as a Fastify plugin.
77
+ *
78
+ * On allow: decorates `request.valiron` with the {@link GateResult}.
79
+ * On deny: returns 403 (or delegates to `onDeny`).
80
+ * On error: returns 503 (fail-closed).
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * import Fastify from 'fastify';
85
+ * import { ValironSDK, valironFastifyPlugin } from '@valiron/sdk';
86
+ *
87
+ * const app = Fastify();
88
+ * const valiron = new ValironSDK({ chain: 'monad' });
89
+ *
90
+ * // Gate all routes
91
+ * app.register(valironFastifyPlugin, { sdk: valiron });
92
+ *
93
+ * // Or gate a specific prefix
94
+ * app.register(valironFastifyPlugin, {
95
+ * sdk: valiron,
96
+ * prefix: '/api',
97
+ * minScore: 85,
98
+ * });
99
+ * ```
100
+ */
101
+ export declare function valironFastifyPlugin(fastify: any, opts: ValironFastifyConfig): Promise<void>;
102
+ /**
103
+ * Configuration for the Next.js Valiron gate.
104
+ */
105
+ export interface ValironNextConfig {
106
+ /** Configured ValironSDK instance. */
107
+ sdk: ValironSDK;
108
+ /**
109
+ * Extract the agent ID from a Next.js request.
110
+ * Defaults to reading `x-agent-id` header.
111
+ */
112
+ extractAgentId?: (req: Request) => string | null;
113
+ /** Minimum Valiron score to allow (default: 65). */
114
+ minScore?: number;
115
+ /** TTL for cached sandbox results in ms (default: 86400000 = 24 h). */
116
+ ttlMs?: number;
117
+ /**
118
+ * URL path patterns to gate. Uses `startsWith` matching.
119
+ * If omitted, gates all routes.
120
+ * @example ['/api/paid', '/api/premium']
121
+ */
122
+ paths?: string[];
123
+ }
124
+ /**
125
+ * Create a Next.js middleware function that gates routes based on
126
+ * agent trust scores. Use in `middleware.ts` at the project root.
127
+ *
128
+ * Returns a standard `Response` — either continues the request
129
+ * or returns 401/403/503.
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * // middleware.ts (Next.js project root)
134
+ * import { ValironSDK, createValironNextMiddleware } from '@valiron/sdk';
135
+ *
136
+ * const valiron = new ValironSDK({ chain: 'monad' });
137
+ *
138
+ * const valironMiddleware = createValironNextMiddleware({
139
+ * sdk: valiron,
140
+ * paths: ['/api/paid'],
141
+ * minScore: 65,
142
+ * });
143
+ *
144
+ * export async function middleware(request: Request) {
145
+ * return valironMiddleware(request);
146
+ * }
147
+ *
148
+ * export const config = { matcher: '/api/:path*' };
149
+ * ```
150
+ */
151
+ export declare function createValironNextMiddleware(config: ValironNextConfig): (request: Request) => Promise<Response | undefined>;
152
+ /**
153
+ * Result from the generic gate check. Use this to build middleware
154
+ * for any framework (Hono, Koa, Deno Oak, Bun, etc.).
155
+ */
156
+ export interface ValironGateCheckResult {
157
+ /** Whether an agent ID was found in the request. */
158
+ hasAgent: boolean;
159
+ /** The extracted agent ID, or null. */
160
+ agentId: string | null;
161
+ /** Whether the gate check succeeded (no unexpected internal or network error). If false, the caller should treat the request as failed/denied regardless of allow. */
162
+ ok: boolean;
163
+ /** Whether the agent is allowed. Undefined if hasAgent=false or ok=false. */
164
+ allow?: boolean;
165
+ /** Full gate result. Undefined if hasAgent=false or ok=false. */
166
+ result?: GateResult;
167
+ /** Suggested HTTP status code for the response. */
168
+ status: number;
169
+ /** Suggested JSON body if the request should be blocked. Undefined if allowed. */
170
+ body?: Record<string, unknown>;
171
+ }
172
+ /**
173
+ * Framework-agnostic gate check. Returns a structured result that you
174
+ * can map into any HTTP framework's response type.
175
+ *
176
+ * @example
177
+ * ```typescript
178
+ * // Hono
179
+ * import { Hono } from 'hono';
180
+ * import { ValironSDK, valironGateCheck } from '@valiron/sdk';
181
+ *
182
+ * const valiron = new ValironSDK({ chain: 'monad' });
183
+ * const app = new Hono();
184
+ *
185
+ * app.use('/api/*', async (c, next) => {
186
+ * const gate = await valironGateCheck(valiron, {
187
+ * agentId: c.req.header('x-agent-id') ?? null,
188
+ * });
189
+ * if (!gate.allow) return c.json(gate.body, gate.status);
190
+ * c.set('valiron', gate.result);
191
+ * await next();
192
+ * });
193
+ * ```
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * // Koa
198
+ * app.use(async (ctx, next) => {
199
+ * const gate = await valironGateCheck(valiron, {
200
+ * agentId: ctx.get('x-agent-id') || null,
201
+ * });
202
+ * if (!gate.allow) {
203
+ * ctx.status = gate.status;
204
+ * ctx.body = gate.body;
205
+ * return;
206
+ * }
207
+ * ctx.state.valiron = gate.result;
208
+ * await next();
209
+ * });
210
+ * ```
211
+ */
212
+ export declare function valironGateCheck(sdk: ValironSDK, opts: {
213
+ agentId: string | null;
214
+ minScore?: number;
215
+ ttlMs?: number;
216
+ }): Promise<ValironGateCheckResult>;
@@ -1,10 +1,46 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createValironGate = createValironGate;
4
+ exports.valironFastifyPlugin = valironFastifyPlugin;
5
+ exports.createValironNextMiddleware = createValironNextMiddleware;
6
+ exports.valironGateCheck = valironGateCheck;
7
+ // ─── Shared gate logic ──────────────────────────────────────────────────────
8
+ function defaultExtractAgentId(req) {
9
+ // Works for Express, Fastify, Koa, raw Node http (object headers)
10
+ // and Fetch-based frameworks like Hono (Headers with .get())
11
+ const headers = req?.headers ?? {};
12
+ let value = null;
13
+ if (headers && typeof headers.get === "function") {
14
+ value = headers.get("x-agent-id");
15
+ }
16
+ else {
17
+ const raw = headers["x-agent-id"];
18
+ value = Array.isArray(raw) ? raw[0] : raw;
19
+ }
20
+ return value ?? null;
21
+ }
22
+ async function runGateCheck(config, req) {
23
+ const extractAgentId = config.extractAgentId || defaultExtractAgentId;
24
+ const agentId = extractAgentId(req);
25
+ if (!agentId)
26
+ return { agentId: null };
27
+ try {
28
+ const result = await config.sdk.gate(agentId, {
29
+ minScore: config.minScore,
30
+ ttlMs: config.ttlMs,
31
+ });
32
+ return { agentId, result };
33
+ }
34
+ catch (error) {
35
+ return { agentId, error };
36
+ }
37
+ }
38
+ // ═══════════════════════════════════════════════════════════════════════════
39
+ // EXPRESS / CONNECT MIDDLEWARE
40
+ // ═══════════════════════════════════════════════════════════════════════════
4
41
  /**
5
- * Create an Express-compatible middleware that sits in front of payment
6
- * protocols (x402 etc.) and gates access based on the agent's combined
7
- * Valiron trust score (on-chain reputation + sandbox tests).
42
+ * Create an Express/Connect-compatible middleware that gates access
43
+ * based on the agent's combined Valiron trust score.
8
44
  *
9
45
  * On allow: sets `req.valiron` to the {@link GateResult} and calls `next()`.
10
46
  * On deny: returns 403 with the gate result (or delegates to `onDeny`).
@@ -28,34 +64,236 @@ exports.createValironGate = createValironGate;
28
64
  * ```
29
65
  */
30
66
  function createValironGate(config) {
31
- const { sdk, extractAgentId = (req) => req.headers?.["x-agent-id"], minScore, ttlMs, onDeny, onAllow, } = config;
67
+ // Snapshot config at creation time so mutations after middleware
68
+ // creation don't affect behavior.
69
+ const frozen = { ...config };
32
70
  return async function valironGate(req, res, next) {
33
- const agentId = extractAgentId(req);
71
+ const { agentId, result, error } = await runGateCheck(frozen, req);
34
72
  if (!agentId) {
35
73
  return res.status(401).json({ error: "Missing agent id" });
36
74
  }
75
+ if (error) {
76
+ return res.status(503).json({
77
+ error: "Trust gate unavailable \u2014 request denied (fail-closed)",
78
+ });
79
+ }
80
+ if (result.allow) {
81
+ req.valiron = result;
82
+ if (config.onAllow)
83
+ config.onAllow(req, result);
84
+ return next();
85
+ }
86
+ if (config.onDeny) {
87
+ return config.onDeny(req, res, result);
88
+ }
89
+ return res.status(403).json({
90
+ error: "Agent blocked by Valiron trust gate",
91
+ ...result,
92
+ });
93
+ };
94
+ }
95
+ /**
96
+ * Fastify plugin that gates incoming requests based on the agent's
97
+ * Valiron trust score. Register it as a Fastify plugin.
98
+ *
99
+ * On allow: decorates `request.valiron` with the {@link GateResult}.
100
+ * On deny: returns 403 (or delegates to `onDeny`).
101
+ * On error: returns 503 (fail-closed).
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import Fastify from 'fastify';
106
+ * import { ValironSDK, valironFastifyPlugin } from '@valiron/sdk';
107
+ *
108
+ * const app = Fastify();
109
+ * const valiron = new ValironSDK({ chain: 'monad' });
110
+ *
111
+ * // Gate all routes
112
+ * app.register(valironFastifyPlugin, { sdk: valiron });
113
+ *
114
+ * // Or gate a specific prefix
115
+ * app.register(valironFastifyPlugin, {
116
+ * sdk: valiron,
117
+ * prefix: '/api',
118
+ * minScore: 85,
119
+ * });
120
+ * ```
121
+ */
122
+ async function valironFastifyPlugin(fastify, opts) {
123
+ const gateConfig = {
124
+ sdk: opts.sdk,
125
+ extractAgentId: opts.extractAgentId,
126
+ minScore: opts.minScore,
127
+ ttlMs: opts.ttlMs,
128
+ onAllow: opts.onAllow,
129
+ };
130
+ // Decorate request with valiron property
131
+ if (!fastify.hasRequestDecorator?.("valiron")) {
132
+ fastify.decorateRequest("valiron", null);
133
+ }
134
+ fastify.addHook("onRequest", async (request, reply) => {
135
+ // Skip if prefix is set and URL pathname doesn't match on a segment boundary
136
+ if (opts.prefix) {
137
+ const rawUrl = request.url || "";
138
+ const pathname = rawUrl.split("?")[0];
139
+ const prefix = opts.prefix.endsWith("/") && opts.prefix !== "/"
140
+ ? opts.prefix.slice(0, -1)
141
+ : opts.prefix;
142
+ if (pathname !== prefix && !pathname.startsWith(prefix + "/"))
143
+ return;
144
+ }
145
+ const { agentId, result, error } = await runGateCheck(gateConfig, request);
146
+ if (!agentId) {
147
+ return reply.status(401).send({ error: "Missing agent id" });
148
+ }
149
+ if (error) {
150
+ return reply.status(503).send({
151
+ error: "Trust gate unavailable \u2014 request denied (fail-closed)",
152
+ });
153
+ }
154
+ if (result.allow) {
155
+ request.valiron = result;
156
+ if (opts.onAllow)
157
+ opts.onAllow(request, result);
158
+ return; // continue to handler
159
+ }
160
+ if (opts.onDeny) {
161
+ return opts.onDeny(request, reply, result);
162
+ }
163
+ return reply.status(403).send({
164
+ error: "Agent blocked by Valiron trust gate",
165
+ ...result,
166
+ });
167
+ });
168
+ }
169
+ /**
170
+ * Create a Next.js middleware function that gates routes based on
171
+ * agent trust scores. Use in `middleware.ts` at the project root.
172
+ *
173
+ * Returns a standard `Response` — either continues the request
174
+ * or returns 401/403/503.
175
+ *
176
+ * @example
177
+ * ```typescript
178
+ * // middleware.ts (Next.js project root)
179
+ * import { ValironSDK, createValironNextMiddleware } from '@valiron/sdk';
180
+ *
181
+ * const valiron = new ValironSDK({ chain: 'monad' });
182
+ *
183
+ * const valironMiddleware = createValironNextMiddleware({
184
+ * sdk: valiron,
185
+ * paths: ['/api/paid'],
186
+ * minScore: 65,
187
+ * });
188
+ *
189
+ * export async function middleware(request: Request) {
190
+ * return valironMiddleware(request);
191
+ * }
192
+ *
193
+ * export const config = { matcher: '/api/:path*' };
194
+ * ```
195
+ */
196
+ function createValironNextMiddleware(config) {
197
+ const { sdk, minScore, ttlMs, paths } = config;
198
+ const extractAgentId = config.extractAgentId ||
199
+ ((req) => req.headers.get("x-agent-id"));
200
+ return async function valironNextGate(request) {
201
+ // Skip paths not in scope
202
+ if (paths && paths.length > 0) {
203
+ const url = new URL(request.url);
204
+ if (!paths.some((p) => url.pathname.startsWith(p))) {
205
+ return undefined; // pass through
206
+ }
207
+ }
208
+ const agentId = extractAgentId(request);
209
+ if (!agentId) {
210
+ return Response.json({ error: "Missing agent id" }, { status: 401 });
211
+ }
37
212
  try {
38
213
  const result = await sdk.gate(agentId, { minScore, ttlMs });
39
214
  if (result.allow) {
40
- req.valiron = result;
41
- if (onAllow)
42
- onAllow(req, result);
43
- return next();
215
+ return undefined; // continue to route handler
44
216
  }
45
- // Denied
46
- if (onDeny) {
47
- return onDeny(req, res, result);
48
- }
49
- return res.status(403).json({
50
- error: "Agent blocked by Valiron trust gate",
51
- ...result,
52
- });
217
+ return Response.json({ error: "Agent blocked by Valiron trust gate", ...result }, { status: 403 });
53
218
  }
54
219
  catch {
55
- // Fail-closed: deny on any error
56
- return res.status(503).json({
57
- error: "Trust gate unavailable — request denied (fail-closed)",
58
- });
220
+ return Response.json({ error: "Trust gate unavailable \u2014 request denied (fail-closed)" }, { status: 503 });
59
221
  }
60
222
  };
61
223
  }
224
+ /**
225
+ * Framework-agnostic gate check. Returns a structured result that you
226
+ * can map into any HTTP framework's response type.
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * // Hono
231
+ * import { Hono } from 'hono';
232
+ * import { ValironSDK, valironGateCheck } from '@valiron/sdk';
233
+ *
234
+ * const valiron = new ValironSDK({ chain: 'monad' });
235
+ * const app = new Hono();
236
+ *
237
+ * app.use('/api/*', async (c, next) => {
238
+ * const gate = await valironGateCheck(valiron, {
239
+ * agentId: c.req.header('x-agent-id') ?? null,
240
+ * });
241
+ * if (!gate.allow) return c.json(gate.body, gate.status);
242
+ * c.set('valiron', gate.result);
243
+ * await next();
244
+ * });
245
+ * ```
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * // Koa
250
+ * app.use(async (ctx, next) => {
251
+ * const gate = await valironGateCheck(valiron, {
252
+ * agentId: ctx.get('x-agent-id') || null,
253
+ * });
254
+ * if (!gate.allow) {
255
+ * ctx.status = gate.status;
256
+ * ctx.body = gate.body;
257
+ * return;
258
+ * }
259
+ * ctx.state.valiron = gate.result;
260
+ * await next();
261
+ * });
262
+ * ```
263
+ */
264
+ async function valironGateCheck(sdk, opts) {
265
+ const { agentId, minScore, ttlMs } = opts;
266
+ if (!agentId) {
267
+ return {
268
+ hasAgent: false,
269
+ agentId: null,
270
+ ok: false,
271
+ status: 401,
272
+ body: { error: "Missing agent id" },
273
+ };
274
+ }
275
+ try {
276
+ const result = await sdk.gate(agentId, { minScore, ttlMs });
277
+ if (result.allow) {
278
+ return { hasAgent: true, agentId, ok: true, allow: true, result, status: 200 };
279
+ }
280
+ return {
281
+ hasAgent: true,
282
+ agentId,
283
+ ok: true,
284
+ allow: false,
285
+ result,
286
+ status: 403,
287
+ body: { error: "Agent blocked by Valiron trust gate", ...result },
288
+ };
289
+ }
290
+ catch {
291
+ return {
292
+ hasAgent: true,
293
+ agentId,
294
+ ok: false,
295
+ status: 503,
296
+ body: { error: "Trust gate unavailable \u2014 request denied (fail-closed)" },
297
+ };
298
+ }
299
+ }