Open History to see the last commit
1/**
2 * API-key fallback registration (PLAN.md task 5.3) — for agents that don't
3 * speak the agent-auth protocol: one POST creates a Better Auth user and an
4 * API key (returned exactly once).
5 */
6import { halGet, halPost } from '#/server/hal.ts'
7import { eq } from 'drizzle-orm'
8
9import type { Db } from '#/db/index.ts'
10import { user } from '#/db/schema.ts'
11import type { Auth } from '#/lib/auth.ts'
12import { requireAgent } from '#/server/require-agent.ts'
13import { AUTHENTICATED_LIMIT, readRateUsage } from '#/server/rate-limit.ts'
14
15export interface RegisterKeyBody {
16 name: string
17 email?: string
18}
19
20export function parseRegisterKeyBody(raw: unknown): RegisterKeyBody | null {
21 if (typeof raw !== 'object' || raw === null) return null
22 const body = raw as Record<string, unknown>
23 if (typeof body.name !== 'string' || body.name.trim() === '') return null
24 if (body.email !== undefined && typeof body.email !== 'string') return null
25 return { name: body.name.trim(), email: body.email }
26}
27
28export type RegisterKeyOutcome =
29 | {
30 ok: true
31 result: {
32 key: string
33 keyId: string
34 userId: string
35 name: string
36 note: string
37 }
38 }
39 | { ok: false; status: number; code: string; message: string }
40
41export async function registerKeyAgent(
42 auth: Auth,
43 db: Db,
44 body: RegisterKeyBody,
45): Promise<RegisterKeyOutcome> {
46 const slug = body.name
47 .toLowerCase()
48 .replace(/[^a-z0-9]+/g, '-')
49 .replace(/^-+|-+$/g, '')
50 .slice(0, 40)
51 const email =
52 body.email ??
53 `${slug || 'agent'}-${crypto.randomUUID().slice(0, 8)}@agents.modelschemas.invalid`
54
55 // Pre-check the email: better-auth's sign-up throw leaves a floating
56 // rejection in its dispatch layer, so refuse duplicates before calling it.
57 const existing = await db.query.user.findFirst({
58 where: eq(user.email, email),
59 columns: { id: true },
60 })
61 if (existing) {
62 return {
63 ok: false,
64 status: 409,
65 code: 'email_taken',
66 message: `An account already exists for '${email}'.`,
67 }
68 }
69
70 // Random throwaway password: this account authenticates via API key only.
71 const password = crypto.randomUUID() + crypto.randomUUID()
72
73 let userId: string
74 try {
75 const signUp = await auth.api.signUpEmail({
76 body: { name: body.name, email, password },
77 })
78 userId = signUp.user.id
79 } catch (error) {
80 return {
81 ok: false,
82 status: 409,
83 code: 'registration_failed',
84 message:
85 error instanceof Error
86 ? `Could not create account: ${error.message}`
87 : 'Could not create account.',
88 }
89 }
90
91 const created = await auth.api.createApiKey({
92 body: { name: `${body.name} key`, userId },
93 })
94
95 return {
96 ok: true,
97 result: {
98 key: created.key,
99 keyId: created.id,
100 userId,
101 name: body.name,
102 note: 'Store this key now — it is shown exactly once. Send it as Authorization: Bearer <key>.',
103 },
104 }
105}
106
107/** GET /v1/agents/me (task 5.5): identity, grants, limits, current usage. */
108export async function agentsMe(
109 auth: Auth,
110 kv: KVNamespace,
111 request: Request,
112): Promise<Response> {
113 const result = await requireAgent(auth, request)
114 if (!result.ok) return result.response
115
116 const principal = result.principal
117 const bucket =
118 principal.kind === 'agent'
119 ? `agent:${principal.agentId}`
120 : `key:${principal.keyId}`
121 const usage = await readRateUsage(
122 kv,
123 bucket,
124 AUTHENTICATED_LIMIT.limit,
125 AUTHENTICATED_LIMIT.windowSeconds,
126 )
127
128 return Response.json({
129 agent: principal,
130 grants: principal.capabilities,
131 limits: {
132 requestsPerHour: AUTHENTICATED_LIMIT.limit,
133 anonymousRequestsPerHour: 60,
134 },
135 usage,
136 _links: {
137 self: halGet('/v1/agents/me'),
138 capabilities: halPost('/api/auth/capability/list'),
139 changes: halGet('/v1/changes'),
140 subscriptions: halGet('/v1/subscriptions'),
141 },
142 })
143}