* fix(auth): email-change recovery re-send and confirmation feedback A half-completed secure email change was a dead end: the pending-address short-circuit in /api/account/email swallowed every retry without re-sending mails, so once the confirmation links expired the user could never recover, and confirmation clicks landed on the dashboard with no feedback at all. - /api/account/email: only short-circuit a repeat request while the pending mails are fresh (30 min); a stale pending change falls through to GoTrue, which restarts the change and re-sends both mails - /auth/callback: type=email_change now redirects to a status page (/auth/email-change) that says whether one click remains, the change is complete, or the link was dead, instead of landing silently - auth mail templates: both email-change mails explain that two mails are sent and both links must be clicked - settings: the save button re-enables for the pending address as Skicka igen, so users can trigger the re-send themselves Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018sbGMZQE5W7KfSVFjK7E4p * fix(auth): exempt email-change confirmations from the authenticated /auth bounce (skeptic findings) - middleware: let /auth/email-change and /auth/callback?type=email_change through for authenticated users; the bounce to / swallowed confirmation clicks before verifyOtp ran (pre-existing since #2017) - email-change done page resolves the WL-14 landing destination for the CTA - /api/account/email returns resent flag; settings toast says mails were already sent instead of claiming a fresh send 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>
216 lines
6.7 KiB
TypeScript
216 lines
6.7 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 while the pending mails are fresh', async () => {
|
|
const { updateUser } = mockUserClient({
|
|
user: {
|
|
id: 'user-1',
|
|
email: 'old@testbrand.example',
|
|
new_email: 'pending@testbrand.example',
|
|
email_change_sent_at: new Date(Date.now() - 60_000).toISOString(),
|
|
} 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('re-sends when the pending change is stale (expired-link recovery)', async () => {
|
|
const { updateUser } = mockUserClient({
|
|
user: {
|
|
id: 'user-1',
|
|
email: 'old@testbrand.example',
|
|
new_email: 'pending@testbrand.example',
|
|
email_change_sent_at: new Date(
|
|
Date.now() - 2 * 60 * 60 * 1000,
|
|
).toISOString(),
|
|
} as { id: string; email?: string },
|
|
})
|
|
|
|
const req = createMockRequest('/api/account/email', {
|
|
method: 'POST',
|
|
body: { email: 'pending@testbrand.example' },
|
|
})
|
|
const { status } = await parseJsonResponse(await POST(req))
|
|
|
|
expect(status).toBe(200)
|
|
expect(updateUser).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('re-sends when the pending change has no sent timestamp', 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 } = await parseJsonResponse(await POST(req))
|
|
|
|
expect(status).toBe(200)
|
|
expect(updateUser).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
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')
|
|
})
|
|
})
|