Files
accounted/app/api/account/email/route.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

103 lines
4.0 KiB
TypeScript

import { NextResponse } from 'next/server'
import { z } from 'zod'
import { requireAuth } from '@/lib/auth/require-auth'
import { resolveRequestAppOrigin } from '@/lib/domains/trusted-app-origin'
import { validateBody } from '@/lib/api/validate'
import { createLogger } from '@/lib/logger'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const log = createLogger('api/account/email')
const ChangeEmailSchema = z.object({
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
})
/**
* POST /api/account/email
*
* Server-routed login-email change. Always writes via the USER session so
* Supabase's AAL2 guard fires: an email change is a credential rotation, and
* a stolen AAL1 cookie must not be able to move the account to another
* mailbox. (Contrast app/api/account/password/route.ts, whose first-time-set
* path may bypass AAL2 because there is no existing credential to protect;
* an email change always has one.)
*
* Nothing changes immediately: with secure email change enabled, Supabase
* sends `email_change_current` to the old address and `email_change` to the
* new one (templates in lib/email/auth-templates.ts via the send-email hook),
* and the address flips only after confirmation. The links verify through
* /auth/callback, which already handles type=email_change.
*
* The account itself is keyed by user id everywhere (company_members,
* user_preferences, ...), so a confirmed change moves nothing but the login
* identifier and contact address. profiles.email mirrors auth.users.email via
* the sync_profile_email trigger (migration 20260828191950), so member lists,
* notification recipients, and AGI/KU contact fields follow the change.
*/
export async function POST(request: Request) {
const { user, supabase, error: authError } = await requireAuth()
if (authError) return authError
const result = await validateBody(request, ChangeEmailSchema)
if (!result.success) return result.response
const { email } = result.data
if (user.email && email === user.email.toLowerCase()) {
return NextResponse.json(
{ error: 'Det är redan din e-postadress.' },
{ status: 400 },
)
}
// Re-requesting the address that is already awaiting confirmation is a
// no-op success rather than another GoTrue round trip (which would re-send
// both confirmation mails and eat into the send rate limit). new_email is
// absent on the claims-mapped fast path; then GoTrue's own rate limit is
// the backstop.
if (user.new_email && email === user.new_email.toLowerCase()) {
return NextResponse.json({ data: { ok: true, pending_email: email } })
}
// Trusted-origin resolution, not request.url: behind a proxy request.url
// can be an internal origin (dead confirmation links on self-hosted), and
// auth links may never follow an attacker-chosen host. Registered
// white-label hosts pass through so the mail carries the right brand.
const origin = resolveRequestAppOrigin(request)
const { error: updateError } = await supabase.auth.updateUser(
{ email },
{ emailRedirectTo: `${origin}/auth/callback` },
)
if (updateError) {
log.warn('email change request failed', {
userId: user.id,
code: updateError.code,
status: updateError.status,
})
// Addresses are unique per auth user: a change to an already-registered
// address is refused by GoTrue, never merged. Accounts are consolidated
// via company invitations, not email changes.
if (
updateError.code === 'email_exists' ||
/already.*registered/i.test(updateError.message ?? '')
) {
return NextResponse.json(
{ error: 'E-postadressen används redan av ett annat konto.' },
{ status: 409 },
)
}
return NextResponse.json(
{
error:
getUserErrorMessage(updateError) ||
'Kunde inte begära e-poständring. Försök igen.',
},
{ status: 400 },
)
}
log.info('email change requested', { userId: user.id })
return NextResponse.json({ data: { ok: true, pending_email: email } })
}