Skip to content

Express

An Express app embeds aidy in the same Node process. aidy calls your API over HTTP like any client, with the user’s credential and an Aidy-Assertion; you add x-aidy to the OpenAPI document you already generate.

Terminal window
npm install @aidy-dev/core @aidy-dev/server @aidy-dev/spec @aidy-dev/sql

@aidy-dev/core exports createAidy and the stores; @aidy-dev/server exports nodeHandler.

Keep the generator you have (zod-openapi, tsoa, swagger-jsdoc, a hand-written file). Each operation that joins the catalog gets an x-aidy object; operations without one stay invisible to aidy.

paths:
/api/vm/{vm_id}/stop:
post:
operationId: stopVm
summary: Stop server
x-aidy:
name: stop_vm
effect: update
description: Stop a running cloud server (VM).
open: /console/instance/{vm_id}
confirmation:
title: Stop server {resource_name}?
lookup: { path: /api/vm/{vm_id}, labelPath: name }
/api/me:
get:
x-aidy: { name: whoami, role: identity }
/api/vms/search:
get:
x-aidy: { name: search_vms, role: search }

Serve the document as OpenAPI 3.1, for example at GET /openapi.json, behind the same authentication as your API. Run aidy check --openapi http://localhost:3000/openapi.json to catch catalog errors. Field-by-field rules are in the x-aidy reference.

nodeHandler(aidy) adapts aidy’s Web-standard fetch to Node’s (req, res), for Express, Connect or node:http. It reads req.originalUrl when there is one, so aidy sees the full path whether you mount it with app.all or app.use. Register it before any body parser, because aidy reads the raw request body itself.

import express from 'express';
import { createAidy, SqlStore } from '@aidy-dev/core';
import { nodeHandler } from '@aidy-dev/server';
import { importSigningKey } from '@aidy-dev/spec/delegation';
import { postgresDriver } from '@aidy-dev/sql/postgres';
const app = express();
const signingKey = await importSigningKey(JSON.parse(process.env.AIDY_SIGNING_KEY!)); // from `aidy keys generate`
const aidy = createAidy({
url: 'https://console.example.com',
host: {
origin: 'https://console.example.com',
baseUrl: 'http://127.0.0.1:3000', // aidy reaches the API on loopback
openapi: '/openapi.json',
},
signingKey,
secret: process.env.AIDY_SECRET!,
store: new SqlStore(postgresDriver(process.env.DATABASE_URL!)),
models: { chain: [{ id: 'main', provider: 'openai', model: 'gpt-5', apiKey: process.env.OPENAI_API_KEY }] },
});
const handler = nodeHandler(aidy);
app.all(['/aidy/v0/*splat', '/mcp', '/skill.md', '/llms.txt', '/.well-known/aidy-keys.json'], handler);
app.use(express.json({ verify(req, _res, buf) { (req as { rawBody?: Buffer }).rawBody = buf; } }));
// ... your routes
app.listen(3000);

The route patterns use Express 5 syntax. Call await aidy.close() on shutdown to let runs in progress finish. express.json({ verify }) keeps the exact body bytes for the assertion check below.

verifyAssertion and checkCall from @aidy-dev/spec/delegation implement the host checks of Delegation. Run them in a middleware after your authentication, so the user is known.

import {
ASSERTION_HEADER,
AssertionError,
checkCall,
importPublicKeys,
verifyAssertion,
} from '@aidy-dev/spec/delegation';
const keys = await importPublicKeys([JSON.parse(process.env.AIDY_PUBLIC_JWK!)]);
// Method + route pattern -> operation; build it from your OpenAPI document.
const catalog: { method: string; pattern: RegExp; op: string; approval: 'never' | 'always' }[] = [
{ method: 'POST', pattern: /^\/api\/vm\/[^/]+\/stop$/, op: 'stop_vm', approval: 'always' },
{ method: 'GET', pattern: /^\/api\/vm\/[^/]+$/, op: 'get_vm', approval: 'never' },
];
app.use('/api', async (req, res, next) => {
const token = req.get(ASSERTION_HEADER);
if (!token) return next(); // an ordinary user request
try {
const claims = await verifyAssertion(token, {
keys,
audience: 'https://console.example.com',
request: {
method: req.method,
url: `https://console.example.com${req.originalUrl}`, // public origin + path, even over loopback
body: (req as { rawBody?: Buffer }).rawBody ?? new Uint8Array(),
},
remember: (jti, until) => redis.set(`aidy:jti:${jti}`, '1', { NX: true, EXAT: until }).then(Boolean),
});
const served = catalog.find((o) => o.method === req.method && o.pattern.test(req.baseUrl + req.path));
checkCall(claims, {
subject: req.user.id,
tenant: req.user.tenantId,
op: served?.op ?? '',
approval: served?.approval ?? 'always',
});
res.locals.aidy = claims; // rid, cid, apr for your audit log
next();
} catch (error) {
if (!(error instanceof AssertionError)) return next(error);
res.status(401).json({ error: 'aidy_assertion_invalid', code: error.code });
}
});

Points to get right:

  • url is the host’s public origin followed by the path and query aidy called (req.originalUrl), even when aidy reaches the API through host.baseUrl on loopback.
  • body is the exact bytes received. An empty body hashes as the empty string.
  • remember must answer false for a jti seen before its expiry. Share it across processes (Redis here, node-redis v4 set options).
  • An operation with approval: always needs apr; checkCall enforces it when you pass the operation’s effective approval (never for reads, always otherwise, unless x-aidy.approval says so).

aidy ships no Express middleware package; this middleware is the whole check.

If you prefer to keep aidy out of the app process, run aidy-server and reverse-proxy the aidy paths to it. The x-aidy annotations and the assertion middleware stay the same; set AIDY_HOST_BASE_URL to where aidy-server reaches your API.