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 { createAuth } from './auth.ts'
6
7function makeAuth(captured: Array<{ email: string; otp: string }>) {
8 return createAuth(getDb(env), {
9 secret: 'vitest-only-better-auth-secret-0123456789',
10 baseUrl: 'http://otp.test',
11 sendOtp: (data) => {
12 captured.push(data)
13 return Promise.resolve()
14 },
15 })
16}
17
18describe('email OTP sign-in (task 9.2)', () => {
19 it('issues a code via the injected sender and signs the user in', async () => {
20 const captured: Array<{ email: string; otp: string }> = []
21 const auth = makeAuth(captured)
22
23 await auth.api.sendVerificationOTP({
24 body: { email: 'human@example.com', type: 'sign-in' },
25 })
26 expect(captured).toHaveLength(1)
27 expect(captured[0]?.email).toBe('human@example.com')
28 expect(captured[0]?.otp).toMatch(/^\d{6}$/)
29
30 const signedIn = await auth.api.signInEmailOTP({
31 body: { email: 'human@example.com', otp: captured[0]?.otp ?? '' },
32 })
33 expect(signedIn.token).toBeTruthy()
34 expect(signedIn.user.email).toBe('human@example.com')
35
36 // The bearer plugin accepts the session token for follow-up requests.
37 const session = await auth.api.getSession({
38 headers: new Headers({ authorization: `Bearer ${signedIn.token}` }),
39 })
40 expect(session?.user.email).toBe('human@example.com')
41 })
42
43 it('rejects wrong codes', async () => {
44 const captured: Array<{ email: string; otp: string }> = []
45 const auth = makeAuth(captured)
46 await auth.api.sendVerificationOTP({
47 body: { email: 'human2@example.com', type: 'sign-in' },
48 })
49 const wrong = captured[0]?.otp === '000000' ? '111111' : '000000'
50 // Via the HTTP handler: the server API throws AND leaves a floating
51 // rejection in better-auth's dispatch layer; the handler returns a 400.
52 const response = await auth.handler(
53 new Request('http://otp.test/api/auth/sign-in/email-otp', {
54 method: 'POST',
55 headers: { 'Content-Type': 'application/json' },
56 body: JSON.stringify({ email: 'human2@example.com', otp: wrong }),
57 }),
58 )
59 expect(response.status).toBe(400)
60 const body = (await response.json()) as { code?: string }
61 expect(body.code).toBe('INVALID_OTP')
62 })
63})