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>
This commit is contained in:
Mattsson
2026-08-28 22:12:20 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent a1cafe495f
commit 7f0f25b558
8 changed files with 493 additions and 1 deletions
@@ -23,6 +23,7 @@ import {
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import { useSettings } from '@/components/settings/useSettings'
import { resetAnalyticsIdentity } from '@/lib/analytics/reset'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { useToast } from '@/components/ui/use-toast'
import { SUPPORTED_LOCALES, type Locale } from '@/i18n/config'
import { PalettePicker } from '@/components/settings/PalettePicker'
@@ -48,6 +49,10 @@ export function AccountSettingsContent() {
const [initialName, setInitialName] = useState('')
const [nameLoading, setNameLoading] = useState(true)
const [savingName, setSavingName] = useState(false)
const [email, setEmail] = useState('')
const [currentEmail, setCurrentEmail] = useState('')
const [savingEmail, setSavingEmail] = useState(false)
const [pendingEmail, setPendingEmail] = useState<string | null>(null)
useEffect(() => { setMounted(true) }, [])
@@ -58,6 +63,12 @@ export function AccountSettingsContent() {
;(async () => {
const { data: { user } } = await supabase.auth.getUser()
if (!user) { if (active) setNameLoading(false); return }
if (active && user.email) {
setEmail(user.email)
setCurrentEmail(user.email)
}
// A change already awaiting confirmation survives a page reload.
if (active && user.new_email) setPendingEmail(user.new_email.toLowerCase())
const { data } = await supabase
.from('profiles')
.select('full_name')
@@ -94,6 +105,44 @@ export function AccountSettingsContent() {
}
}
async function handleSaveEmail() {
const trimmed = email.trim().toLowerCase()
if (!trimmed || trimmed === currentEmail.toLowerCase() || savingEmail) return
setSavingEmail(true)
try {
const res = await fetch('/api/account/email', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: trimmed }),
})
const json = await res.json().catch(() => null)
if (!res.ok) {
toast({
title: tSettings('email_change_failed'),
description: getErrorMessage(json, {
statusCode: res.status,
locale: activeLocale,
}),
variant: 'destructive',
})
return
}
setPendingEmail(trimmed)
toast({
title: tSettings('email_change_requested'),
description: tSettings('email_change_requested_help'),
})
} catch (err) {
toast({
title: tSettings('email_change_failed'),
description: getErrorMessage(err, { locale: activeLocale }),
variant: 'destructive',
})
} finally {
setSavingEmail(false)
}
}
async function handleLogout() {
resetAnalyticsIdentity()
await supabase.auth.signOut()
@@ -167,6 +216,41 @@ export function AccountSettingsContent() {
</SettingsRowEnd>
</SettingsRow>
<SettingsRow
label={tSettings('email_label')}
htmlFor="account_email"
help={
pendingEmail
? tSettings('email_change_pending', { email: pendingEmail })
: tSettings('email_description')
}
align="baseline"
>
<SettingsInput
id="account_email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={!currentEmail || savingEmail}
maxLength={320}
/>
<SettingsRowEnd>
<Button
size="sm"
onClick={handleSaveEmail}
disabled={
!currentEmail ||
savingEmail ||
!email.trim() ||
email.trim().toLowerCase() === currentEmail.toLowerCase() ||
email.trim().toLowerCase() === pendingEmail
}
>
{savingEmail ? tCommon('saving') : tCommon('save')}
</Button>
</SettingsRowEnd>
</SettingsRow>
<SettingsRow label={tSettings('section_appearance')}>
{mounted && (
<SettingsSeg