
Better Auth Agent Auth 插件如何为 AI 代理提供服务发现、注册与能力授权【免费下载链接】better-authThe most comprehensive authentication framework项目地址: https://gitcode.com/GitHub_Trending/be/better-auth如果你已经有一个基于 Better Auth 的服务端想让它直接对 AI 代理开放代理能发现你的服务能力、注册自己、经用户批准后在授权范围内调用接口better-auth/agent-auth插件就是做这件事的。它让你的 Better Auth 服务端充当 Agent Auth provider服务端实现了 Agent Auth Protocol代理通过服务发现文档拿到端点信息注册后请求能力授权grants再使用短期签名的 JWT 执行有范围的 capability。注意官方文档的提醒该插件是对一个仍在重度开发中的标准的实现尚未稳定未来可能有变动。安装插件先在项目中安装服务端插件包npm install better-auth/agent-auth文档还列出两个可选包客户端与 CLInpm install auth/agent auth/agent-cli在 auth 配置中声明 capabilities 与 onExecute插件的核心配置是两部分你的服务对外暴露哪些 capability以及执行这些 capability 的onExecute处理函数。一个 capability 由name、description和可选的 JSON Schemainput组成。import { betterAuth } from better-auth; import { agentAuth } from better-auth/agent-auth; export const auth betterAuth({ plugins: [ agentAuth({ providerName: Acme, providerDescription: Acme project and deployment APIs for AI agents., modes: [delegated, autonomous], capabilities: [ { name: deploy_project, description: Deploy a project to production., input: { type: object, properties: { projectId: { type: string }, }, required: [projectId], }, }, { name: list_projects, description: List projects the current user can access., }, ], async onExecute({ capability, arguments: args, agentSession }) { switch (capability) { case list_projects: return [{ id: proj_123, name: marketing-site }]; case deploy_project: return { ok: true, projectId: args?.projectId, requestedBy: agentSession.user.id, }; default: throw new Error(Unsupported capability: ${capability}); } }, }), ], });关于onExecute的适用边界要记清楚它只处理走默认执行 URL发现文档里的default_location的调用如果某个 capability 设置了自定义location代理会直接调用那个 URLonExecute不会被执行。文档建议用 capability 暴露窄范围、可审查的动作而不是宽泛的 API 访问。暴露服务发现文档插件提供auth.api.getAgentConfiguration()你需要把它挂到应用根目录的/.well-known/agent-configurationNext.js 的写法如下import { auth } from /lib/auth; import { NextResponse } from next/server; export async function GET() { const configuration await auth.api.getAgentConfiguration(); return NextResponse.json(configuration); }即使你的 Better Auth base path 是/api/auth这个发现路由也要放在/.well-known/agent-configuration。发现文档里对执行最关键的三个字段issuer— provider 的基础 URL即 Better Auth 的baseURLendpoints— 各路由的绝对 URL例如execute指向该 base 下的POST /capability/executedefault_location— 默认执行端点的完整 URL始终与endpoints.execute一致。capability 没有自定义 URL 时代理用它作为 JWT 的aud也用它作为请求 URL。验证方式直接向/.well-known/agent-configuration发 GET 请求返回的 JSON 就是代理用来交互的全部端点信息。迁移数据库插件需要 agent、host、grant 和 approval 表。迁移方式二选一npx auth migrate或者生成 schema 后自行应用npx auth generate代理注册与能力授权流程文档描述的标准流程是代理从/.well-known/agent-configuration发现你的 provider代理列出 capabilities决定需要哪些代理在你的服务端注册并请求 capability grants用户通过 device authorization 或 CIBA 批准请求代理用短期签名 JWTaud匹配所调用的 URL在default_location或 capability 自己的location上调用每个已授权能力。批准方法默认device_authorization和ciba都启用可用approvalMethods和resolveApprovalMethod限制或定制agentAuth({ approvalMethods: [ciba, device_authorization], resolveApprovalMethod: ({ preferredMethod, supportedMethods }) { if (preferredMethod supportedMethods.includes(preferredMethod)) { return preferredMethod; } return device_authorization; }, deviceAuthorizationPage: /device/capabilities, });两个容易踩的点插件不会替你渲染设备授权审批页面deviceAuthorizationPage指向的页面必须由你的应用自己提供如果想控制哪些能力自动授予新注册的 host可以用defaultHostCapabilities传true表示全部、单个 HTTP 方法字符串、方法数组或接收完整运行时上下文的回调allowDynamicHostRegistration控制是否允许未知 host 动态注册。执行能力grant 校验与自定义 location默认路径无location代理向default_locationPOST{ capability, arguments }。插件依次验证 JWT包括aud、附加agentSession、检查 grant然后调用你的onExecute。JWT 的aud规则capability 没有自定义location时aud用default_location/endpoints.execute或插件已允许的 issuer / base URL设置了location时aud应是该绝对 URLGET /capability/list在有location时也会返回它配置中非法的location会在启动时报错capabilities恰好只列一个 id 时aud也可以等于该 capability 的location列了多个 capability 时不接受各 capability 的location作为aud应使用 issuer、base path 或默认执行端点反代后面如需让Host/X-Forwarded-Proto与aud校验对齐设置trustProxy默认false。自定义location路径代理仍然带Authorization: Bearer头发送 agent JWT你在自己的路由里解析会话。两个等价入口任选其一auth.api.getAgentSession({ headers })在进程内完成校验签名、aud、jti防重放、过期、请求绑定声明返回AgentSession或nullverifyAgentRequest(request, auth)则把Request的 headers 转发到GET /agent/session。import { auth } from /lib/auth; export async function POST(request: Request) { const agentSession await auth.api.getAgentSession({ headers: request.headers, }); if (!agentSession) { return new Response(Unauthorized, { status: 401 }); } // Check grants, enforce constraints, run your handler… }拿到agentSession后检查 grant——agentSession.agent.capabilityGrants是数据库中有效的 grants 与 JWTcapabilities声明的交集const CAP create_issue; const allowed agentSession.agent.capabilityGrants.some( (g) g.capability CAP g.status active, ); if (!allowed) { return new Response(Forbidden, { status: 403 }); }注意如果该 grant 带有constraints要在自定义路由里按POST /capability/execute相同的方式校验请求体或 query——插件不会在任意路由上重跑 execute 的约束校验这段逻辑留在你的 handler 里或抽成与onExecute共享的代码。agentSession上可用的字段agentSession.userdelegated host 用户或resolveAutonomousUser解析出的用户、agentSession.agentid、name、mode、capabilityGrants、host id、metadata、agentSession.host代理链接到 host 时的 host 记录。类型从better-auth/agent-auth导出如AgentSession。可选路径用 OpenAPI 规范自动生成如果你的服务已有 OpenAPI 3.x 规范createFromOpenAPI可以直接生成插件需要的全部内容capabilities每个带operationId的 operation 变成一个同名 capability、输入/输出 JSON Schemapath/query/header 参数加 JSON 请求体合并为input200/201 响应体作为output、代理onExecute并可选地从info取providerName/providerDescriptionimport { betterAuth } from better-auth; import { agentAuth } from better-auth/agent-auth; import { createFromOpenAPI } from better-auth/agent-auth/openapi; const spec await fetch(https://api.example.com/openapi.json).then((r) r.json(), ); export const auth betterAuth({ plugins: [ agentAuth({ ...createFromOpenAPI(spec, { baseUrl: https://api.example.com, }), }), ], });其中api.example.com替换为你自己的 API 地址与规范地址。常用选项resolveHeaders— 代理 handler 代表代理调用你的上游 API用它注入每次请求需要的凭据例如从agentSession查出用户级 access token 后放入Authorization头defaultHostCapabilities— 控制自动授予新 host 的能力如[GET, HEAD]approvalStrength— 按 HTTP 方法映射批准强度例如GET: session、POST/PUT/DELETE: webauthn让写操作要求更强的用户验证location— 所有派生 capability 都带上该 URL代理直接带着 agent JWT 打真实 API URL由你自己的中间件处理会话而不是走onExecute代理。如果只需要管线的一部分还有两个低层 helperfromOpenAPI(spec)只返回Capability[]createOpenAPIHandler(spec, opts)只返回onExecute代理 handler方便搭配手写 capabilities 使用。import { fromOpenAPI, createOpenAPIHandler, } from better-auth/agent-auth/openapi; const capabilities fromOpenAPI(spec); const onExecute createOpenAPIHandler(spec, { baseUrl: https://api.example.com, }); agentAuth({ capabilities, onExecute });客户端插件与事件审计可选需要类型安全地访问插件端点时在 Better Auth 客户端里加上客户端插件import { createAuthClient } from better-auth/client; import { agentAuthClient } from better-auth/agent-auth/client; export const authClient createAuthClient({ plugins: [ agentAuthClient(), ], });审计方面onEvent回调会捕获生命周期事件agent 创建与吊销、host 创建与登记、capability 请求与批准、capability 执行。文档指出这是写审计日志或接入分析管线的合适位置。完成后的验证方式与限制按上面的顺序做完后可以按以下方式核对GET/.well-known/agent-configuration确认返回的发现文档包含issuer、endpoints、default_location走一遍代理流程后自定义路由中auth.api.getAgentSession({ headers })返回非null的AgentSession即代表 JWT 校验通过返回null则按文档示例响应 401未获批的能力调用时capabilityGrants中没有status active的匹配项按文档示例响应 403。限制方面插件明确标注为不稳定实现设备审批页面需要你的应用自行提供capability 设置了location后onExecute不生效约束校验也转移到你的 handler。更多配置项requireAuthForCapabilities、resolveCapabilities过滤可见能力等见仓库中的 Agent Auth 插件文档。【免费下载链接】better-authThe most comprehensive authentication framework项目地址: https://gitcode.com/GitHub_Trending/be/better-auth创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考