Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3
4import { getDb } from '../db/index.ts'
5import { requireAgent } from '../server/require-agent.ts'
6import { createAuth } from './auth.ts'
7
8const BASE = 'http://account.test'
9
10async function signedInSession() {
11 const captured: Array<{ email: string; otp: string }> = []
12 const auth = createAuth(getDb(env), {
13 secret: 'vitest-only-better-auth-secret-0123456789',
14 baseUrl: BASE,
15 sendOtp: (data) => {
16 captured.push(data)
17 return Promise.resolve()
18 },
19 })
20 const email = `keys-${crypto.randomUUID().slice(0, 8)}@example.com`
21 await auth.api.sendVerificationOTP({ body: { email, type: 'sign-in' } })
22 const signedIn = await auth.api.signInEmailOTP({
23 body: { email, otp: captured[0]?.otp ?? '' },
24 })
25 return {
26 auth,
27 email,
28 headers: new Headers({ authorization: `Bearer ${signedIn.token}` }),
29 }
30}
31
32describe('human API-key lifecycle (task 9.3)', () => {
33 it('creates, lists, uses, and revokes a key within the session', async () => {
34 const { auth, headers } = await signedInSession()
35
36 // Create (session-authed — no explicit userId).
37 const created = await auth.api.createApiKey({
38 body: { name: 'laptop key', expiresIn: 30 * 86_400 },
39 headers,
40 })
41 expect(created.key).toBeTruthy()
42 expect(created.name).toBe('laptop key')
43 expect(created.expiresAt).not.toBeNull()
44
45 // List shows it without the secret value.
46 const listed = await auth.api.listApiKeys({ headers })
47 expect(listed.apiKeys.map((k) => k.id)).toContain(created.id)
48 expect(JSON.stringify(listed)).not.toContain(created.key)
49
50 // The key authenticates like any agent credential.
51 const authed = await requireAgent(
52 auth,
53 new Request(`${BASE}/v1/agents/me`, {
54 headers: { authorization: `Bearer ${created.key}` },
55 }),
56 )
57 expect(authed.ok).toBe(true)
58 if (authed.ok) expect(authed.principal.kind).toBe('api-key')
59
60 // Revoke → the key stops working.
61 await auth.api.deleteApiKey({ body: { keyId: created.id }, headers })
62 const afterRevoke = await requireAgent(
63 auth,
64 new Request(`${BASE}/v1/agents/me`, {
65 headers: { authorization: `Bearer ${created.key}` },
66 }),
67 )
68 expect(afterRevoke.ok).toBe(false)
69 if (!afterRevoke.ok) expect(afterRevoke.response.status).toBe(401)
70 expect(
71 (await auth.api.listApiKeys({ headers })).apiKeys.map((k) => k.id),
72 ).not.toContain(created.id)
73 })
74
75 it('scopes keys to their owner session', async () => {
76 const alice = await signedInSession()
77 const bob = await signedInSession()
78
79 const aliceKey = await alice.auth.api.createApiKey({
80 body: { name: 'alice key' },
81 headers: alice.headers,
82 })
83
84 // Bob cannot see or revoke Alice's key.
85 const bobList = await bob.auth.api.listApiKeys({ headers: bob.headers })
86 expect(bobList.apiKeys.map((k) => k.id)).not.toContain(aliceKey.id)
87 await expect(
88 bob.auth.api.deleteApiKey({
89 body: { keyId: aliceKey.id },
90 headers: bob.headers,
91 }),
92 ).rejects.toThrow()
93
94 // Alice's key still works.
95 const stillWorks = await requireAgent(
96 alice.auth,
97 new Request(`${BASE}/v1/agents/me`, {
98 headers: { authorization: `Bearer ${aliceKey.key}` },
99 }),
100 )
101 expect(stillWorks.ok).toBe(true)
102 })
103})