Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

require-agent.ts

193 lines5.6 KB

1/**
2 * Agent JWT verification for our native /v1 routes (PLAN.md task 5.2) — as
3 * opposed to the /capability/execute proxy. Wraps the plugin's
4 * verifyAgentRequest + a grant check. Task 5.3 extends the accepted
5 * credentials with API keys.
6 */
7import { verifyAgentRequest } from '@better-auth/agent-auth'
8​
9import { publicCapabilityNames } from '#/lib/auth.ts'
10import type { Auth } from '#/lib/auth.ts'
11import { jsonError } from '#/server/admin.ts'
12​
13export interface AgentPrincipal {
14 kind: 'agent'
15 agentId: string
16 name: string
17 mode: 'autonomous' | 'delegated'
18 userId: string | null
19 capabilities: Array<string>
21​
22/** Authenticated via the api-key fallback (task 5.3) — public capabilities only. */
23export interface ApiKeyPrincipal {
24 kind: 'api-key'
25 keyId: string
26 name: string | null
27 userId: string
28 capabilities: Array<string>
30​
31export type Principal = AgentPrincipal | ApiKeyPrincipal
32​
33interface AgentSessionResponse {
34 type: 'autonomous' | 'delegated'
35 agent: {
36 id: string
37 name: string
38 mode: 'autonomous' | 'delegated'
39 capabilityGrants: Array<{ capability: string; status: string }>
40 }
41 host: { id: string; userId: string | null } | null
42 user: { id: string } | null
44​
45async function fetchAgentSession(
46 auth: Auth,
47 request: Request,
48): Promise<AgentSessionResponse | null> {
49 const viaHelper = (await verifyAgentRequest(
50 request,
51 auth,
52 )) as AgentSessionResponse | null
53 if (viaHelper) return viaHelper
54​
55 // verifyAgentRequest builds `${options.baseURL}/agent/session`, which
56 // misses the basePath when baseURL is a bare origin — retry with it.
57 const base = (auth.options.baseURL ?? '').replace(/\/$/, '')
58 const basePath = (
59 (auth.options as { basePath?: string }).basePath ?? '/api/auth'
60 ).replace(/\/$/, '')
61 if (!base || !request.headers.get('authorization')) return null
62 const response = await auth.handler(
63 new Request(`${base}${basePath}/agent/session`, {
64 method: 'GET',
65 headers: request.headers,
66 }),
67 )
68 if (!response.ok) return null
69 try {
70 return (await response.json()) as AgentSessionResponse
71 } catch {
72 return null
73 }
75​
76export type RequireAgentResult =
77 | { ok: true; principal: Principal }
78 | { ok: false; response: Response }
79​
80/** Bearer credentials that are not three-part JWTs are treated as API keys. */
81function bearerApiKey(request: Request): string | null {
82 const header = request.headers.get('authorization')
83 const bearer = header?.startsWith('Bearer ')
84 ? header.slice('Bearer '.length)
85 : null
86 const candidate = request.headers.get('x-api-key') ?? bearer
87 if (!candidate || candidate.split('.').length === 3) return null
88 return candidate
90​
91async function verifyApiKeyPrincipal(
92 auth: Auth,
93 key: string,
94): Promise<ApiKeyPrincipal | null> {
95 const verified = await auth.api.verifyApiKey({ body: { key } })
96 if (!verified.valid || !verified.key) return null
97 // The plugin stores the owning user under `referenceId`.
98 const owner = verified.key as { id: string; name?: string | null } & {
99 referenceId?: string
100 userId?: string
101 }
102 const userId = owner.referenceId ?? owner.userId
103 if (!userId) return null
104 return {
105 kind: 'api-key',
106 keyId: owner.id,
107 name: owner.name ?? null,
108 userId,
109 capabilities: publicCapabilityNames(),
110 }
112​
113/**
114 * Authenticate a request with an agent JWT or an API key (Bearer or
115 * X-Api-Key); optionally require an active grant for a specific capability
116 * (API keys pass capability checks — they are the full-access fallback).
117 * Returns a ready-made 401/403 Response on failure.
118 */
119export async function requireAgent(
120 auth: Auth,
121 request: Request,
122 options?: { capability?: string },
123): Promise<RequireAgentResult> {
124 const apiKey = bearerApiKey(request)
125 if (apiKey) {
126 const principal = await verifyApiKeyPrincipal(auth, apiKey)
127 if (!principal) {
128 return {
129 ok: false,
130 response: jsonError(
131 401,
132 'invalid_api_key',
133 'API key is invalid or disabled. Register a new one at POST /v1/agents/register-key.',
134 ),
135 }
136 }
137 // API keys satisfy only public (approval-free) capabilities — privileged
138 // capabilities require the agent-auth grant flow.
139 if (
140 options?.capability &&
141 !principal.capabilities.includes(options.capability)
142 ) {
143 return {
144 ok: false,
145 response: jsonError(
146 403,
147 'capability_not_granted',
148 `API keys cannot satisfy the '${options.capability}' capability. Use the agent-auth protocol (see /.well-known/agent-configuration).`,
149 ),
150 }
151 }
152 return { ok: true, principal }
153 }
154​
155 const session = await fetchAgentSession(auth, request)
156 if (!session?.agent) {
157 return {
158 ok: false,
159 response: jsonError(
160 401,
161 'unauthorized',
162 'Provide an agent JWT or API key (Authorization: Bearer). Register at /.well-known/agent-configuration or POST /v1/agents/register-key.',
163 ),
164 }
165 }
166​
167 const capabilities = session.agent.capabilityGrants
168 .filter((grant) => grant.status === 'active')
169 .map((grant) => grant.capability)
170​
171 if (options?.capability && !capabilities.includes(options.capability)) {
172 return {
173 ok: false,
174 response: jsonError(
175 403,
176 'capability_not_granted',
177 `This operation requires the '${options.capability}' capability. Request it via /api/auth/agent/request-capability.`,
178 ),
179 }
180 }
181​
182 return {
183 ok: true,
184 principal: {
185 kind: 'agent',
186 agentId: session.agent.id,
187 name: session.agent.name,
188 mode: session.agent.mode,
189 userId: session.user?.id ?? session.host?.userId ?? null,
190 capabilities,
191 },
192 }