import { randomUUID } from 'node:crypto'; import { Hono } from 'hono'; import type pg from 'pg'; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { auth } from '@server/auth'; import { adminStatusAfter } from '@server/auth/admin-status'; import { ADMIN_BOOTSTRAP_LOCK_KEY, bootstrapAdmin, withAdminBootstrapLock, } from '@server/auth/bootstrap-admin'; import { ensureAdminAtStartup } from '@server/db/startup'; import { isSuperAdmin } from '@server/lib/auth'; import { logger } from '@server/lib/logger'; import { csrfProtection } from '@server/middleware/csrf'; import { sessionMiddleware } from '@server/middleware/session'; import { authRoutes } from '@server/routes/v1/auth'; import type { HonoVariables } from '@server/types'; import { connectTestDb, dbTestsEnabled } from './_helpers'; /** * The in-process auth against a real database: sign-up, sign-in and * sign-out through `auth.handler`, the session middleware, the account * lockout, the startup admin bootstrap, and the CSRF origin check. * * The app below is wired the way server/index.ts wires it (CSRF, then the * /api/auth mount, then the session middleware), minus the rate limiters. */ const ORIGIN = 'http://app.test'; // SITE_URL in tests/_helpers/setup-db.ts const PASSWORD = 'correct-horse-battery'; // Capture auth emails instead of sending (or logging) them. const sentEmails = vi.hoisted(() => [] as { kind: string; to: string; url: string }[]); // Whether sign-in links can be emailed (MAGIC_LINK_ENABLED and SMTP); on by // default here so the magic-link flows run, switched off per test. const magicLink = vi.hoisted(() => ({ available: true })); vi.mock('@server/auth/email', () => ({ sendAuthEmail: async (kind: string, to: string, url: string) => { sentEmails.push({ kind, to, url }); }, magicLinkAvailable: () => magicLink.available, })); function buildApp() { const app = new Hono<{ Variables: HonoVariables }>(); app.use('/api/*', csrfProtection()); app.on(['GET', 'POST'], '/api/auth/*', (c) => auth.handler(c.req.raw)); app.use('/api/*', sessionMiddleware); app.get('/api/v1/whoami', (c) => { const user = c.get('user'); if (!user) return c.json({ error: 'Unauthorized' }, 401); return c.json({ id: user.id, email: user.email, role: user.role, aal: c.get('session')?.twoFactorVerified ? 'aal2' : 'aal1', serverSeesToken: Boolean(c.get('session')?.token), }); }); app.post('/api/v1/echo', (c) => { if (!c.get('user')) return c.json({ error: 'Unauthorized' }, 401); return c.json({ ok: true }); }); app.post('/api/webhooks/test', (c) => c.json({ received: true })); app.route('/api/v1/auth', authRoutes); app.get('/api/v1/admin/ping', (c) => { const user = c.get('user'); if (!user) return c.json({ error: 'Unauthorized' }, 401); if (!isSuperAdmin(user)) return c.json({ error: 'Super admin access required' }, 403); return c.json({ ok: true }); }); return app; } /** `Set-Cookie` headers of a response as a `Cookie` request header. */ function cookieHeader(res: Response, only?: string): string { return res.headers .getSetCookie() .map((c) => c.split(';')[0]) .filter((pair) => !pair.endsWith('=')) .filter((pair) => (only ? pair.startsWith(`${only}=`) : true)) .join('; '); } const TOKEN_COOKIE = 'better-auth.session_token'; describe.skipIf(!dbTestsEnabled)('auth (real database)', () => { let db: pg.Client; let app: ReturnType; const emails: string[] = []; const newEmail = () => { const email = `auth-test-${randomUUID()}@example.test`; emails.push(email); return email; }; const post = (path: string, body: unknown, headers: Record = {}) => app.request(path, { method: 'POST', headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, body: JSON.stringify(body), }); const signUp = (email: string, password = PASSWORD) => post('/api/auth/sign-up/email', { email, password, name: 'Auth Test' }); const signIn = (email: string, password: string, ip = '203.0.113.10') => post('/api/auth/sign-in/email', { email, password }, { 'x-forwarded-for': ip }); const failureCount = async (email: string, ip: string) => { const { rows } = await db.query<{ n: number }>( 'select count(*)::int as n from public.failed_login_attempts where email = $1 and ip_address = $2::inet', [email.toLowerCase(), ip], ); return rows[0].n; }; beforeAll(async () => { db = await connectTestDb(); app = buildApp(); }); afterAll(async () => { if (emails.length) { const lower = emails.map((e) => e.toLowerCase()); await db.query('delete from public."user" where email = any($1::text[])', [lower]); await db.query('delete from public.failed_login_attempts where email = any($1::text[])', [ lower, ]); } await db.end(); }); describe('sign-up, sign-in, sign-out and the session middleware', () => { it('signs up with a uuid id, the default role, and onboarding not done', async () => { const email = newEmail(); const res = await signUp(email); expect(res.status).toBe(200); const { rows } = await db.query( 'select id, role, onboarding_completed, email_verified from public."user" where email = $1', [email], ); expect(rows[0].id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/); expect(rows[0]).toMatchObject({ role: 'user', onboarding_completed: false }); // No SMTP in tests, so verification is not required. expect(rows[0].email_verified).toBe(false); }); it('a client cannot sign itself up as super_admin', async () => { const email = newEmail(); const res = await post('/api/auth/sign-up/email', { email, password: PASSWORD, name: 'Sneaky', role: 'super_admin', }); // Refused outright: role is not a sign-up input. expect(res.status).toBe(400); const { rows } = await db.query('select role from public."user" where email = $1', [email]); expect(rows).toEqual([]); }); it('signs in, and the session cookie makes the middleware set user and aal1', async () => { const email = newEmail(); await signUp(email); const res = await signIn(email, PASSWORD); expect(res.status).toBe(200); const setCookies = res.headers.getSetCookie().join('\n'); expect(setCookies).toMatch(/better-auth\.session_token=[^;]+;.*HttpOnly/i); expect(setCookies).toMatch(/SameSite=Lax/i); const me = await app.request('/api/v1/whoami', { headers: { cookie: cookieHeader(res) } }); expect(me.status).toBe(200); expect(await me.json()).toMatchObject({ email, role: 'user', aal: 'aal1' }); }); it('no cookie, or a forged one, leaves user null', async () => { expect((await app.request('/api/v1/whoami')).status).toBe(401); const forged = await app.request('/api/v1/whoami', { headers: { cookie: `${TOKEN_COOKIE}=not-a-real-token.signature` }, }); expect(forged.status).toBe(401); }); it('aal is aal2 only when this session passed a second factor', async () => { const email = newEmail(); await signUp(email); const res = await signIn(email, PASSWORD); // The token cookie alone forces a database read (no cached session). const cookie = cookieHeader(res, TOKEN_COOKIE); const { rows } = await db.query('select id from public."user" where email = $1', [email]); await db.query('update public.session set two_factor_verified = true where user_id = $1', [ rows[0].id, ]); const me = await app.request('/api/v1/whoami', { headers: { cookie } }); expect((await me.json()).aal).toBe('aal2'); }); it('sign-out ends the session', async () => { const email = newEmail(); await signUp(email); const res = await signIn(email, PASSWORD); const cookie = cookieHeader(res, TOKEN_COOKIE); const out = await post('/api/auth/sign-out', {}, { cookie }); expect(out.status).toBe(200); const me = await app.request('/api/v1/whoami', { headers: { cookie } }); expect(me.status).toBe(401); }); }); describe('the session token never reaches page JS', () => { /** The raw session token: the cookie value before the `.signature`. */ const rawToken = (res: Response) => decodeURIComponent(cookieHeader(res, TOKEN_COOKIE).split('=')[1]).split('.')[0]; it('sign-up, sign-in, get-session and list-sessions bodies carry no token; the cookie still works', async () => { const email = newEmail(); const up = await signUp(email); const upToken = rawToken(up); expect(upToken.length).toBeGreaterThan(10); const upText = await up.text(); expect(upText).not.toContain(upToken); expect(JSON.parse(upText)).not.toHaveProperty('token'); expect(JSON.parse(upText).user.email).toBe(email); const res = await signIn(email, PASSWORD, '203.0.113.11'); const token = rawToken(res); const text = await res.text(); expect(text).not.toContain(token); expect(JSON.parse(text)).not.toHaveProperty('token'); expect(JSON.parse(text).user.email).toBe(email); // Token cookie only, so get-session reads the database row. const cookie = cookieHeader(res, TOKEN_COOKIE); const session = await app.request('/api/auth/get-session', { headers: { cookie } }); expect(session.status).toBe(200); const sessionText = await session.text(); expect(sessionText).not.toContain(token); const sessionBody = JSON.parse(sessionText); expect(sessionBody.user.email).toBe(email); expect(sessionBody.session).not.toHaveProperty('token'); // And with the cached-session cookie too (the cookie-cache path). const cached = await app.request('/api/auth/get-session', { headers: { cookie: cookieHeader(res) }, }); expect(await cached.text()).not.toContain(token); const list = await app.request('/api/auth/list-sessions', { headers: { cookie } }); expect(list.status).toBe(200); const listText = await list.text(); expect(listText).not.toContain(token); expect(listText).not.toContain(upToken); // The cookie still authenticates, and server code still gets the token. const me = await app.request('/api/v1/whoami', { headers: { cookie } }); expect(await me.json()).toMatchObject({ email, serverSeesToken: true }); }); }); describe('revocation takes effect on the next request, not after the cookie cache', () => { /** A super admin signed in, with BOTH cookies (token + cached session). */ const signedInAdmin = async (ip: string) => { const email = newEmail(); await bootstrapAdmin({ email, password: PASSWORD }); const res = await signIn(email, PASSWORD, ip); const cookie = cookieHeader(res); expect(cookie).toContain('better-auth.session_data='); const { rows } = await db.query('select id from public."user" where email = $1', [email]); return { email, id: rows[0].id as string, cookie }; }; it('a revoked session is refused by an admin route immediately', async () => { const admin = await signedInAdmin('203.0.113.51'); expect((await app.request('/api/v1/admin/ping', { headers: { cookie: admin.cookie } })).status).toBe(200); await db.query('delete from public.session where user_id = $1', [admin.id]); const after = await app.request('/api/v1/admin/ping', { headers: { cookie: admin.cookie } }); expect(after.status).toBe(401); }); it('a demoted super admin loses admin routes immediately', async () => { const admin = await signedInAdmin('203.0.113.52'); await db.query("update public.\"user\" set role = 'user' where id = $1", [admin.id]); const after = await app.request('/api/v1/admin/ping', { headers: { cookie: admin.cookie } }); expect(after.status).toBe(403); }); it('a banned user whose session row survived is still treated as signed out', async () => { const email = newEmail(); await signUp(email); const cookie = cookieHeader(await signIn(email, PASSWORD, '203.0.113.56')); // Ban in the database only: the session row stays (defence in depth). await db.query('update public."user" set banned = true where email = $1', [email]); expect((await app.request('/api/v1/whoami', { headers: { cookie } })).status).toBe(401); // An expired ban no longer applies. await db.query( "update public.\"user\" set ban_expires = now() - interval '1 minute' where email = $1", [email], ); expect((await app.request('/api/v1/whoami', { headers: { cookie } })).status).toBe(200); }); it('a banned user is signed out of the API immediately', async () => { const admin = await signedInAdmin('203.0.113.53'); const email = newEmail(); await signUp(email); const victim = cookieHeader(await signIn(email, PASSWORD, '203.0.113.54')); expect((await app.request('/api/v1/whoami', { headers: { cookie: victim } })).status).toBe(200); const { rows } = await db.query('select id from public."user" where email = $1', [email]); // ban-user is not served over HTTP (no UI uses it); server code can still call it. await auth.api.banUser({ body: { userId: rows[0].id }, headers: new Headers({ cookie: admin.cookie }), }); expect((await app.request('/api/v1/whoami', { headers: { cookie: victim } })).status).toBe(401); }); it("Better Auth's own admin endpoints refuse a revoked session immediately", async () => { const admin = await signedInAdmin('203.0.113.55'); // An id nobody has: 404 USER_NOT_FOUND means the admin got past every gate. const impersonateNobody = () => post( '/api/auth/admin/impersonate-user', { userId: randomUUID() }, { cookie: admin.cookie }, ); const before = await impersonateNobody(); expect(before.status).toBe(404); expect((await before.json()).code).toBe('USER_NOT_FOUND'); await db.query('delete from public.session where user_id = $1', [admin.id]); expect((await impersonateNobody()).status).toBe(401); }); }); describe('account lockout (5 failures per email + IP)', () => { it('locks after 5 wrong passwords: the right password then gets 429', async () => { const email = newEmail(); const ip = '203.0.113.21'; await signUp(email); for (let i = 0; i < 5; i++) { expect((await signIn(email, 'wrong-password', ip)).status).toBe(401); } expect(await failureCount(email, ip)).toBe(5); const locked = await signIn(email, PASSWORD, ip); expect(locked.status).toBe(429); const body = await locked.json(); expect(body.code).toBe('ACCOUNT_LOCKED'); expect(body.message).toMatch(/try again in \d+ minute/); expect(locked.headers.getSetCookie().join('')).not.toContain(TOKEN_COOKIE); // A refused attempt is not counted as another failure. expect(await failureCount(email, ip)).toBe(5); }); it('the lock is per (email, IP): the same account from another IP still signs in', async () => { const email = newEmail(); const ip = '203.0.113.22'; await signUp(email); for (let i = 0; i < 5; i++) await signIn(email, 'wrong-password', ip); expect((await signIn(email, PASSWORD, '203.0.113.23')).status).toBe(200); }); it('a successful sign-in clears the failures for that pair', async () => { const email = newEmail(); const ip = '203.0.113.24'; await signUp(email); for (let i = 0; i < 4; i++) await signIn(email, 'wrong-password', ip); expect(await failureCount(email, ip)).toBe(4); expect((await signIn(email, PASSWORD, ip)).status).toBe(200); expect(await failureCount(email, ip)).toBe(0); }); it('counts failures for an unknown email too, under the same generic 401', async () => { const email = newEmail(); const ip = '203.0.113.25'; const res = await signIn(email, 'whatever-password', ip); expect(res.status).toBe(401); expect((await res.json()).code).toBe('INVALID_EMAIL_OR_PASSWORD'); expect(await failureCount(email, ip)).toBe(1); }); it('keys on the trusted proxy hop, not a client-supplied leftmost X-Forwarded-For', async () => { const email = newEmail(); await signUp(email); // TRUSTED_PROXY_HOPS=1: the rightmost entry is the one the proxy wrote. for (let i = 0; i < 5; i++) { await signIn(email, 'wrong-password', `198.51.100.${i}, 203.0.113.26`); } expect(await failureCount(email, '203.0.113.26')).toBe(5); expect((await signIn(email, PASSWORD, '198.51.100.99, 203.0.113.26')).status).toBe(429); }); }); describe('startup admin bootstrap', () => { const roleOf = async (email: string) => ( await db.query( 'select role, email_verified, onboarding_completed from public."user" where email = $1', [email], ) ).rows[0]; // /api/health's adminReady (what `vibecarbon deploy` waits for). it('reports the admin ready only when it can sign in', () => { expect(adminStatusAfter('created')).toBe('ready'); expect(adminStatusAfter('promoted')).toBe('ready'); expect(adminStatusAfter('unchanged')).toBe('ready'); expect(adminStatusAfter('skipped')).toBe('skipped'); expect(adminStatusAfter('refused')).toBe('refused'); }); it('does nothing without both ADMIN_EMAIL and ADMIN_PASSWORD', async () => { expect(await bootstrapAdmin({ email: newEmail() })).toBe('skipped'); expect(await bootstrapAdmin({ password: PASSWORD })).toBe('skipped'); }); it('creates a verified super admin past onboarding who can sign in', async () => { const email = newEmail(); expect(await bootstrapAdmin({ email, password: PASSWORD })).toBe('created'); expect(await roleOf(email)).toEqual({ role: 'super_admin', email_verified: true, onboarding_completed: true, }); const res = await signIn(email, PASSWORD, '203.0.113.31'); expect(res.status).toBe(200); const me = await app.request('/api/v1/whoami', { headers: { cookie: cookieHeader(res) } }); expect((await me.json()).role).toBe('super_admin'); }); it('is idempotent and never resets an existing password', async () => { const email = newEmail(); await bootstrapAdmin({ email, password: PASSWORD }); expect(await bootstrapAdmin({ email, password: 'test-different-password' })).toBe('unchanged'); const { rows } = await db.query( 'select count(*)::int as n from public."user" where email = $1', [email], ); expect(rows[0].n).toBe(1); expect((await signIn(email, PASSWORD, '203.0.113.32')).status).toBe(200); expect((await signIn(email, 'test-different-password', '203.0.113.33')).status).toBe(401); }); it("refuses to promote an account someone else registered with ADMIN_EMAIL", async () => { // Open sign-up, no email verification without SMTP: an attacker can // register the admin address first. Their password is not the // operator's, so the account must stay a plain user. const email = newEmail(); await signUp(email, 'attacker-password'); const errors = vi.spyOn(logger, 'error'); try { expect(await bootstrapAdmin({ email, password: PASSWORD })).toBe('refused'); expect(await bootstrapAdmin({ email, password: PASSWORD })).toBe('refused'); const logged = JSON.stringify(errors.mock.calls); expect(logged).toContain(email); expect(logged).not.toContain(PASSWORD); expect(logged).not.toContain('attacker-password'); } finally { errors.mockRestore(); } expect((await roleOf(email)).role).toBe('user'); const { rows } = await db.query( 'select count(*)::int as n from public."user" where email = $1', [email], ); expect(rows[0].n).toBe(1); // The attacker's password still works for their plain account; the // operator's does not grant anything. expect((await signIn(email, PASSWORD, '203.0.113.37')).status).toBe(401); }); it('refuses an account with no password at all (OAuth or magic-link only)', async () => { const email = newEmail(); await db.query( 'insert into public."user" (name, email, role) values ($1, $2, $3)', ['No Password', email, 'user'], ); expect(await bootstrapAdmin({ email, password: PASSWORD })).toBe('refused'); expect((await roleOf(email)).role).toBe('user'); }); it('finishes a super admin left without a password: ADMIN_PASSWORD becomes its password', async () => { // A bootstrap interrupted between the user row and its password (a pod // killed mid-start, seen on a k8s-ha deploy 2026-11-07). Under the // advisory lock no other replica can be mid-create, so this is a real // leftover. Refusing it left an admin nobody could sign in as. const email = newEmail(); await db.query('insert into public."user" (name, email, role) values ($1, $2, $3)', [ 'Half Made', email, 'super_admin', ]); expect(await bootstrapAdmin({ email, password: PASSWORD })).toBe('created'); expect((await signIn(email, PASSWORD, '203.0.113.94')).status).toBe(200); // Settled now: a later ADMIN_PASSWORD change resets nothing. expect(await bootstrapAdmin({ email, password: 'test-different-password' })).toBe( 'unchanged', ); expect((await signIn(email, 'test-different-password', '203.0.113.95')).status).toBe(401); }); it('fills in a credential account that has no password rather than adding a second', async () => { const email = newEmail(); const { rows } = await db.query( 'insert into public."user" (name, email, role) values ($1, $2, $3) returning id', ['Half Linked', email, 'super_admin'], ); const userId = rows[0].id; await db.query( `insert into public.account (account_id, provider_id, user_id) values ($1::text, 'credential', $1::uuid)`, [userId], ); expect(await bootstrapAdmin({ email, password: PASSWORD })).toBe('created'); const credentials = await db.query( `select count(*)::int as n from public.account where user_id = $1 and provider_id = 'credential'`, [userId], ); expect(credentials.rows[0].n).toBe(1); expect((await signIn(email, PASSWORD, '203.0.113.96')).status).toBe(200); }); it('the bootstrap lock is exclusive and released afterwards', async () => { const held = await db.query( 'select pg_try_advisory_lock($1::bigint) as got', [ADMIN_BOOTSTRAP_LOCK_KEY], ); expect(held.rows[0].got).toBe(true); try { // Another session (the bootstrap's own pool client) must wait. let ran = false; const pending = withAdminBootstrapLock(async () => { ran = true; }); await new Promise((r) => setTimeout(r, 200)); expect(ran).toBe(false); await db.query('select pg_advisory_unlock($1::bigint)', [ADMIN_BOOTSTRAP_LOCK_KEY]); await pending; expect(ran).toBe(true); } finally { await db.query('select pg_advisory_unlock_all()'); } // Released: this session can take it again at once. const again = await db.query('select pg_try_advisory_lock($1::bigint) as got', [ ADMIN_BOOTSTRAP_LOCK_KEY, ]); expect(again.rows[0].got).toBe(true); await db.query('select pg_advisory_unlock_all()'); }); // k8s runs two app replicas; both bootstrap at startup. Better Auth's // createUser writes the user row, hashes, then links the password with // no transaction, so an unserialized second replica could see a super // admin without a password. The advisory lock makes the second replica // wait for the first to finish, so it sees the settled admin and reports // ready; it is never refused. it('two replicas bootstrapping at once both end ready, never refused', async () => { const email = newEmail(); const statuses: string[][] = [[], []]; const replica = (i: number) => ensureAdminAtStartup({ bootstrap: () => bootstrapAdmin({ email, password: PASSWORD }), setStatus: (st) => statuses[i].push(st), log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() }, retryMs: 50, }); const results = await Promise.all([replica(0), replica(1)]); expect(results).toEqual(['ready', 'ready']); expect(statuses.flat()).not.toContain('refused'); const { rows } = await db.query( 'select count(*)::int as n from public."user" where email = $1', [email], ); expect(rows[0].n).toBe(1); expect((await signIn(email, PASSWORD, '203.0.113.39')).status).toBe(200); }); it("promotes the operator's own account when its password is ADMIN_PASSWORD", async () => { const email = newEmail(); await signUp(email, PASSWORD); expect(await bootstrapAdmin({ email, password: PASSWORD })).toBe('promoted'); expect((await roleOf(email)).role).toBe('super_admin'); expect(await bootstrapAdmin({ email, password: PASSWORD })).toBe('unchanged'); expect((await signIn(email, PASSWORD, '203.0.113.34')).status).toBe(200); }); it('matches ADMIN_EMAIL case-insensitively', async () => { const email = newEmail(); await signUp(email); expect(await bootstrapAdmin({ email: email.toUpperCase(), password: PASSWORD })).toBe( 'promoted', ); }); it('no HTTP path assigns roles: set-role is disabled even for a super admin', async () => { const email = newEmail(); await bootstrapAdmin({ email, password: PASSWORD }); const res = await signIn(email, PASSWORD, '203.0.113.36'); const cookie = cookieHeader(res); const target = newEmail(); await signUp(target); const { rows } = await db.query('select id from public."user" where email = $1', [target]); const setRole = await post( '/api/auth/admin/set-role', { userId: rows[0].id, role: 'super_admin' }, { cookie }, ); expect(setRole.status).toBe(404); const update = await post( '/api/auth/admin/update-user', { userId: rows[0].id, data: { role: 'super_admin' } }, { cookie }, ); // update-user is not served over HTTP at all (auth/index.ts disabledPaths). expect(update.status).toBe(404); expect((await roleOf(target)).role).toBe('user'); }); }); describe('magic link without a way to email it', () => { afterEach(() => { magicLink.available = true; }); it('the public settings advertise magic link only when it can be sent', async () => { const enabled = async () => ((await (await app.request('/api/v1/auth/settings')).json()) as { settings: { magicLinkEnabled: boolean }; }).settings.magicLinkEnabled; expect(await enabled()).toBe(true); magicLink.available = false; expect(await enabled()).toBe(false); }); it('the send endpoint refuses with a clear code, and nothing is stored or sent', async () => { const email = newEmail(); await signUp(email); sentEmails.length = 0; magicLink.available = false; const res = await post('/api/auth/sign-in/magic-link', { email }); expect(res.status).toBe(400); const body = (await res.json()) as { code: string; message: string }; expect(body.code).toBe('MAGIC_LINK_UNAVAILABLE'); expect(body.message).toMatch(/email/i); expect(sentEmails).toHaveLength(0); const { rows } = await db.query( `select 1 from public.verification where identifier like 'magic-link:%' and value like $1`, [`%${email}%`], ); expect(rows).toHaveLength(0); }); }); describe('password reset', () => { const resetToken = (email: string) => { const mail = sentEmails.find((m) => m.kind === 'password reset' && m.to === email); const token = mail && /\/reset-password\/([^/?]+)/.exec(mail.url)?.[1]; if (!token) throw new Error(`no password reset email for ${email}`); return token; }; it('signs every existing session out, so a stolen cookie dies with the old password', async () => { const email = newEmail(); const signedUp = await signUp(email); const thief = cookieHeader(await signIn(email, PASSWORD, '203.0.113.71'), TOKEN_COOKIE); const owner = cookieHeader(signedUp, TOKEN_COOKIE); for (const cookie of [thief, owner]) { expect((await app.request('/api/v1/whoami', { headers: { cookie } })).status).toBe(200); } sentEmails.length = 0; expect( (await post('/api/auth/request-password-reset', { email, redirectTo: '/reset-password' })) .status, ).toBe(200); const newPassword = 'a-brand-new-passphrase'; expect( (await post('/api/auth/reset-password', { token: resetToken(email), newPassword })).status, ).toBe(200); for (const cookie of [thief, owner]) { expect((await app.request('/api/v1/whoami', { headers: { cookie } })).status).toBe(401); } expect((await signIn(email, newPassword, '203.0.113.72')).status).toBe(200); }); }); describe('emailed links always use SITE_URL', () => { const spoofed = (path: string, body: unknown) => app.request(`http://evil.example${path}`, { method: 'POST', headers: { host: 'evil.example', 'x-forwarded-host': 'evil.example', 'x-forwarded-proto': 'https', 'content-type': 'application/json', origin: ORIGIN, 'x-forwarded-for': '203.0.113.61', }, body: JSON.stringify(body), }); it('password reset and magic link ignore a spoofed Host header', async () => { const email = newEmail(); await signUp(email); sentEmails.length = 0; expect( (await spoofed('/api/auth/request-password-reset', { email, redirectTo: '/reset-password' })) .status, ).toBe(200); expect((await spoofed('/api/auth/sign-in/magic-link', { email })).status).toBe(200); expect(sentEmails.map((m) => m.kind).sort()).toEqual(['magic link', 'password reset']); for (const m of sentEmails) { expect(m.to).toBe(email); expect(m.url.startsWith(`${ORIGIN}/api/auth/`)).toBe(true); expect(m.url).not.toContain('evil.example'); } }); }); describe('CSRF origin check on cookie-authenticated API routes', () => { let cookie: string; beforeAll(async () => { const email = newEmail(); await signUp(email); cookie = cookieHeader(await signIn(email, PASSWORD, '203.0.113.41')); }); const simplePost = (headers: Record) => app.request('/api/v1/echo', { method: 'POST', headers: { 'content-type': 'text/plain', cookie, ...headers }, body: 'x', }); it('refuses a cross-origin form-style POST that carries the session cookie', async () => { expect((await simplePost({ origin: 'https://evil.example' })).status).toBe(403); expect( (await simplePost({ origin: 'https://evil.example', 'sec-fetch-site': 'cross-site' })) .status, ).toBe(403); expect((await simplePost({})).status).toBe(403); }); it('refuses a cross-origin JSON POST that carries the session cookie', async () => { const res = await app.request('/api/v1/echo', { method: 'POST', headers: { 'content-type': 'application/json', cookie, origin: 'https://evil.example' }, body: '{}', }); expect(res.status).toBe(403); }); it('lets the same request through from our own origin', async () => { expect((await simplePost({ origin: ORIGIN })).status).toBe(200); expect((await simplePost({ 'sec-fetch-site': 'same-origin' })).status).toBe(200); }); it('leaves webhooks reachable cross-site (they verify signatures instead)', async () => { const res = await app.request('/api/webhooks/test', { method: 'POST', headers: { 'content-type': 'text/plain', origin: 'https://provider.example', cookie }, body: 'x', }); expect(res.status).toBe(200); }); it('auth endpoints refuse a cross-origin sign-out (Better Auth checks its own)', async () => { const res = await post('/api/auth/sign-out', {}, { cookie, origin: 'https://evil.example' }); expect(res.status).toBe(403); }); }); });