Files
accounted/app/api/account/email/__tests__/route.test.ts
T
MattssonandClaude Fable 5 7f0f25b558 feat(account): self-service login email change with double confirmation (#2017)
* feat(account): self-service login email change with double confirmation

New POST /api/account/email requests the change via the user session so
Supabase's AAL2 guard applies, and the account settings page gets an email
row with pending-confirmation state. Confirmation mails (both addresses)
and the /auth/callback email_change verification already existed; this
wires the missing initiation.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018sbGMZQE5W7KfSVFjK7E4p

* feat(account): map email_exists to a 409 with Swedish copy

Changing to an address that already has an account is refused by GoTrue
(addresses are unique per auth user); surface that as a clear conflict
instead of the generic fallback.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018sbGMZQE5W7KfSVFjK7E4p

* fix(account): trusted redirect origin + profiles.email sync trigger (skeptic findings)

- emailRedirectTo now derives from resolveRequestAppOrigin(): request.url
  can be an internal origin behind a proxy (dead confirmation links on
  self-hosted) and auth links must not follow attacker-chosen hosts;
  registered white-label hosts keep their brand.
- New migration 20260828191950: sync_profile_email trigger mirrors
  auth.users.email changes into profiles.email (member lists, notification
  recipients, AGI/KU contact, invite dedup all read profiles.email), plus a
  backfill for already-diverged rows. pg-real test included.
- Save button disabled while the same address awaits confirmation (no
  rate-limit re-fires); GoTrue's 'error sending email change email' now maps
  to the Swedish SMTP guidance.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018sbGMZQE5W7KfSVFjK7E4p

* fix(account): idempotent repeat request for the pending address

CodeRabbit follow-up: a second POST for the address already awaiting
confirmation now returns the pending state without another GoTrue round
trip (no duplicate confirmation mails, no rate-limit burn). Claims-mapped
sessions lack new_email; GoTrue's send rate limit remains the backstop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018sbGMZQE5W7KfSVFjK7E4p

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-28 22:12:20 +02:00

174 lines
5.4 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
import { POST } from '../route'
function mockUserClient(opts: {
user: { id: string; email?: string } | null
updateUserError?: { message: string; status?: number; code?: string } | null
}) {
const updateUser = vi.fn().mockResolvedValue({
data: {},
error: opts.updateUserError ?? null,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const supabase = { auth: { updateUser } } as any
if (opts.user) {
requireAuthMock.mockResolvedValue({ user: opts.user, supabase, error: null })
} else {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
}
return { updateUser }
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('POST /api/account/email', () => {
it('returns 401 when unauthenticated', async () => {
mockUserClient({ user: null })
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'new@testbrand.example' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(401)
})
it('returns 400 for an invalid email', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'not-an-email' },
})
const { status } = await parseJsonResponse(await POST(req))
expect(status).toBe(400)
expect(updateUser).not.toHaveBeenCalled()
})
it('returns 400 when the new email equals the current one (case-insensitive)', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'Old@Testbrand.example' },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'old@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(body.error).toBe('Det är redan din e-postadress.')
expect(updateUser).not.toHaveBeenCalled()
})
it('requests the change via the user session with a callback redirect', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'New@Testbrand.example' },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean; pending_email: string }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.ok).toBe(true)
// Normalized to lowercase before it reaches Supabase.
expect(body.data?.pending_email).toBe('new@testbrand.example')
expect(updateUser).toHaveBeenCalledTimes(1)
const [attrs, options] = updateUser.mock.calls[0]
expect(attrs).toEqual({ email: 'new@testbrand.example' })
expect(String(options.emailRedirectTo)).toMatch(/\/auth\/callback$/)
})
it('short-circuits a repeat request for the already-pending address', async () => {
const { updateUser } = mockUserClient({
user: {
id: 'user-1',
email: 'old@testbrand.example',
new_email: 'pending@testbrand.example',
} as { id: string; email?: string },
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'Pending@Testbrand.example' },
})
const { status, body } = await parseJsonResponse<{
data?: { ok: boolean; pending_email: string }
}>(await POST(req))
expect(status).toBe(200)
expect(body.data?.pending_email).toBe('pending@testbrand.example')
expect(updateUser).not.toHaveBeenCalled()
})
it('returns 409 when the address already belongs to another account', async () => {
mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
updateUserError: {
message: 'A user with this email address has already been registered',
status: 422,
code: 'email_exists',
},
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'taken@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(409)
expect(body.error).toBe('E-postadressen används redan av ett annat konto.')
})
it('returns 400 and surfaces the AAL2 error when Supabase rejects the update', async () => {
const { updateUser } = mockUserClient({
user: { id: 'user-1', email: 'old@testbrand.example' },
updateUserError: {
message:
'AAL2 session is required to update email or password when MFA is enabled',
status: 422,
},
})
const req = createMockRequest('/api/account/email', {
method: 'POST',
body: { email: 'new@testbrand.example' },
})
const { status, body } = await parseJsonResponse<{ error?: string }>(
await POST(req),
)
expect(status).toBe(400)
expect(updateUser).toHaveBeenCalled()
expect(body.error).toContain('AAL2')
})
})