Set up your framework
Before you upgrade. These examples describe the hardened source contract. Import
verifyAgentRequest from your application-owned signature verifier; it is not an SDK export. It must bind identity, method, full URL and body and atomically reject replayed nonces. Missing or invalid verification returns AGENT_OWNERSHIP_REQUIRED (401). Confirm your installed package supports this contract before upgrading. Read the request-proof upgrade guide.Drop-in middleware for every major Node.js framework. All middleware variants auto-detect on-chain (x-agent-id) and key-based (x-agent-address) agents automatically.
Express / Connect
import { ValironSDK, createValironGate } from '@valiron/sdk';
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
// Basic — checks x-agent-id first, then x-agent-address, minScore 65
// Includes a 30s client-side cache for payment retries and cold starts
// Safe with Express 4 (async errors handled via Promise.catch(next))
app.use('/api/paid', createValironGate({ verifyRequest: verifyAgentRequest, sdk: valiron }));
// Custom threshold + longer cache
app.use('/api/premium', createValironGate({
verifyRequest: verifyAgentRequest,
sdk: valiron,
minScore: 85,
cacheTtlMs: 60_000, // 60s
}));
// Custom agent ID extraction + hooks
app.use('/api/custom', createValironGate({
verifyRequest: verifyAgentRequest,
sdk: valiron,
extractAgentId: (req) => req.query.agent_id as string,
onAllow: (req, result) => {
console.log(`Allowed agent ${result.agentId} (score: ${result.score})`);
},
onDeny: (req, res, result) => {
res.status(403).json({
error: 'Insufficient trust score',
requiredTier: 'A',
currentTier: result.tier,
});
},
}));Fastify
import Fastify from 'fastify';
import { ValironSDK, valironFastifyPlugin } from '@valiron/sdk';
const app = Fastify();
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
// Gate all routes
app.register(valironFastifyPlugin, { verifyRequest: verifyAgentRequest, sdk: valiron });
// Or gate a specific prefix
app.register(valironFastifyPlugin, {
verifyRequest: verifyAgentRequest,
sdk: valiron,
prefix: '/api',
minScore: 85,
});
app.get('/api/data', async (req) => {
// req.valiron is populated with GateResult
return { data: 'protected', tier: req.valiron.tier };
});Next.js
Use createValironNextMiddleware() in your project's middleware.ts to gate API routes.
// middleware.ts (Next.js project root)
import { ValironSDK, createValironNextMiddleware } from '@valiron/sdk';
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY, chain: 'monad' });
const valironMiddleware = createValironNextMiddleware({
verifyRequest: verifyAgentRequest,
sdk: valiron,
paths: ['/api/paid', '/api/premium'], // only gate these paths
minScore: 65,
});
export async function middleware(request: Request) {
return valironMiddleware(request);
}
export const config = { matcher: '/api/:path*' };Returns undefined (pass through) when the agent is allowed, or a JSON Response (401/403/503) when blocked. Paths not in the paths array are passed through without checking.
Generic (Hono, Koa, Bun…)
Use valironGateCheck() for any framework. Returns a structured result you can map to any HTTP response type.
import { ValironSDK, valironGateCheck } from '@valiron/sdk';
const valiron = new ValironSDK({ apiKey: process.env.VALIRON_API_KEY });
// Hono
app.use('/api/*', async (c, next) => {
const gate = await valironGateCheck(valiron, {
verifyRequest: (identifier) => verifyAgentRequest(c.req.raw, identifier),
agentId: c.req.header('x-agent-id') ?? null,
agentAddress: c.req.header('x-agent-address') ?? null,
minScore: 65,
});
if (!gate.allow) return c.json(gate.body, gate.status);
c.set('valiron', gate.result);
await next();
});
// Koa
app.use(async (ctx, next) => {
const gate = await valironGateCheck(valiron, {
verifyRequest: (identifier) => verifyAgentRequest(ctx.req, identifier),
agentId: ctx.get('x-agent-id') || null,
agentAddress: ctx.get('x-agent-address') || null,
});
if (!gate.allow) {
ctx.status = gate.status;
ctx.body = gate.body;
return;
}
ctx.state.valiron = gate.result;
await next();
});Middleware Error Responses
All middleware variants use identical, actionable error responses. Use code for program logic; message, action, and docsUrl explain recovery.
| Status | Code | When | Next step |
|---|---|---|---|
| 401 | MISSING_AGENT_IDENTITY | No supported identity header | Send x-agent-id or x-agent-address |
| 401 | AGENT_OWNERSHIP_REQUIRED | Missing verifier, invalid proof or replay | Configure verification and sign the actual request with a fresh nonce |
| 403 | TRUST_GATE_DENIED | Agent did not meet policy | Inspect score, tier, route, and reasons |
| 403 | AGENT_EVALUATION_PENDING | New agent evaluation is running | Keep the same identity and retry after retryAfterMs |
| 503 | TRUST_GATE_UNAVAILABLE | Gate could not evaluate | Fail closed, retry shortly, and inspect the logged cause |
Fail-closed: If the Valiron API is unreachable, all middleware returns
503 and denies the request. Valiron never fails open — an unknown agent is never allowed through.