跳转到内容

Express

Express 应用可以把 aidy 内嵌在同一个 Node 进程中。aidy 像普通客户端一样通过 HTTP 调用你的 API,带上用户凭证和 Aidy-Assertion;你只需在已有的 OpenAPI 文档里加上 x-aidy。

终端窗口
npm install @aidy-dev/core @aidy-dev/server @aidy-dev/spec @aidy-dev/sql

@aidy-dev/core 导出 createAidy 和存储实现;@aidy-dev/server 导出 nodeHandler。

继续使用现有的生成方式(zod-openapi、tsoa、swagger-jsdoc 或手写文件)。要加入目录的操作加上一个 x-aidy 对象,没有它的操作对 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 }

以 OpenAPI 3.1 格式提供文档,例如 GET /openapi.json,认证方式与 API 相同。运行 aidy check --openapi http://localhost:3000/openapi.json 检查目录错误。各字段规则见 x-aidy 参考。

nodeHandler(aidy) 把 aidy 的 Web 标准 fetch 适配为 Node 的 (req, res),可用于 Express、Connect 或 node:http。存在 req.originalUrl 时它会读取这个值,所以无论用 app.all 还是 app.use 挂载,aidy 看到的都是完整路径。它要注册在所有 body 解析中间件之前,因为 aidy 自己读取原始请求体。

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);

路由模式使用 Express 5 语法。关闭进程时调用 await aidy.close(),等待进行中的运行结束。express.json({ verify }) 保留原始请求体字节,供下面的断言校验使用。

@aidy-dev/spec/delegation 中的 verifyAssertion 和 checkCall 实现了委托中宿主需要做的检查。把它们放在认证之后的中间件里,此时用户已经确定。

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 });
}
});

需要注意的几点:

  • url 是宿主的公开源加上 aidy 调用的路径和查询串(req.originalUrl),即使 aidy 通过回环地址上的 host.baseUrl 访问 API 也是如此。
  • body 是收到的原始字节。没有请求体时按空字符串计算哈希。
  • 对于在过期前已出现过的 jti,remember 必须返回 false。多进程之间要共享这份记录(这里用 Redis,参数为 node-redis v4 的 set 选项)。
  • approval: always 的操作必须带 apr。传入操作的实际审批策略后,checkCall 会强制检查(读操作默认 never,其他默认 always,x-aidy.approval 可覆盖)。

aidy 不提供 Express 中间件包,上面这个中间件就是完整的校验。

如果不想让 aidy 运行在应用进程里,可以运行 aidy-server,并把 aidy 的路径反向代理过去。x-aidy 标注和断言中间件保持不变;把 AIDY_HOST_BASE_URL 设为 aidy-server 访问你的 API 的地址。