Give password recovery the native sign-in layout

This commit is contained in:
Maurice
2026-12-02 10:10:25 +01:00
parent 10fecf4e80
commit dbcdecb6a7
10 changed files with 329 additions and 100 deletions
+31 -1
View File
@@ -9,9 +9,14 @@ import ForgotPasswordPage from './ForgotPasswordPage'
// forgotPassword/useForgotPassword.test.ts). The hook is mocked so the form,
// the sent screen and the SMTP hint can each be rendered on demand.
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown> }))
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown>, native: false }))
vi.mock('./forgotPassword/useForgotPassword', () => ({ useForgotPassword: () => mocks.forgot }))
vi.mock('../native/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../native/platform')>()),
isNativeApp: () => mocks.native,
}))
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }))
const navigate = vi.fn((_to: string) => {})
const setEmail = vi.fn((_v: string) => {})
@@ -32,6 +37,7 @@ function setForgot(over: Record<string, unknown> = {}) {
beforeEach(() => {
vi.clearAllMocks()
mocks.native = false
setForgot()
})
@@ -124,4 +130,28 @@ describe('ForgotPasswordPage', () => {
expect(screen.getByRole('heading', { name: 'Check your email' })).toBeInTheDocument()
expect(screen.getByText(/console/i)).toBeInTheDocument()
})
it('keeps the SMTP warning visible throughout native password recovery', () => {
mocks.native = true
setForgot({ smtpConfigured: false })
const { rerender } = render(<ForgotPasswordPage />)
expect(screen.getByRole('main')).toHaveClass('al-body')
expect(screen.getByRole('textbox', { name: 'Email' })).toHaveAttribute('autocomplete', 'email')
expect(screen.getByText(/hasn't configured SMTP/i)).toBeVisible()
setForgot({ smtpConfigured: false, submitted: true })
rerender(<ForgotPasswordPage />)
expect(screen.getByText(/hasn't configured SMTP/i)).toBeVisible()
expect(screen.queryByRole('heading', { name: 'Check your email' })).not.toBeInTheDocument()
})
it('lets a native user try again after a requester-wide rate limit', () => {
mocks.native = true
setForgot({ submitted: true, deliveryIssue: 'rateLimit' })
render(<ForgotPasswordPage />)
expect(screen.getByRole('alert')).toHaveTextContent('Too many attempts')
expect(screen.getByRole('button', { name: 'Send reset link' })).toBeEnabled()
})
})
+5 -1
View File
@@ -1,6 +1,8 @@
import React, { ChangeEvent } from 'react'
import { Mail, ArrowLeft, CheckCircle2, Terminal } from 'lucide-react'
import { useTranslation } from '../i18n'
import { isNativeApp } from '../native/platform'
import AppForgotPassword from './forgotPassword/AppForgotPassword'
import { useForgotPassword } from './forgotPassword/useForgotPassword'
const inputBase: React.CSSProperties = {
@@ -13,7 +15,9 @@ const inputBase: React.CSSProperties = {
function ForgotPasswordPage() {
const { t } = useTranslation()
// Page = wiring container: form state, the SMTP probe and submit live in the hook.
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = useForgotPassword()
const forgot = useForgotPassword()
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = forgot
if (isNativeApp()) return <AppForgotPassword forgot={forgot} />
return (
<div style={{
+20 -1
View File
@@ -9,9 +9,14 @@ import ResetPasswordPage from './ResetPasswordPage'
// resetPassword/useResetPassword.test.ts). The hook is mocked so the success,
// broken-link, password and MFA screens can each be rendered directly.
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown> }))
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown>, native: false }))
vi.mock('./resetPassword/useResetPassword', () => ({ useResetPassword: () => mocks.reset }))
vi.mock('../native/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../native/platform')>()),
isNativeApp: () => mocks.native,
}))
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }))
const navigate = vi.fn((_to: string) => {})
const setPw = vi.fn((_v: string) => {})
@@ -43,10 +48,24 @@ function setReset(over: Record<string, unknown> = {}) {
beforeEach(() => {
vi.clearAllMocks()
mocks.native = false
setReset()
})
describe('ResetPasswordPage', () => {
it('announces reset errors and supports backup codes on the native screen', () => {
mocks.native = true
setReset({ mfaRequired: true, error: 'The security code was rejected' })
render(<ResetPasswordPage />)
expect(screen.getByRole('main')).toHaveClass('al-body')
expect(screen.getByRole('alert')).toHaveTextContent('The security code was rejected')
const code = screen.getByRole('textbox', { name: '2FA code' })
expect(code).toHaveAttribute('autocomplete', 'one-time-code')
fireEvent.change(code, { target: { value: 'ABCD-EFGH' } })
expect(setMfaCode).toHaveBeenCalledWith('ABCD-EFGH')
})
it('FE-PAGE-RESETUI-001: renders the password form for a valid token', () => {
setReset()
render(<ResetPasswordPage />)
+5 -1
View File
@@ -1,6 +1,8 @@
import React, { ChangeEvent } from 'react'
import { Lock, KeyRound, CheckCircle2, AlertTriangle, Eye, EyeOff } from 'lucide-react'
import { useTranslation } from '../i18n'
import { isNativeApp } from '../native/platform'
import AppResetPassword from './resetPassword/AppResetPassword'
import { useResetPassword } from './resetPassword/useResetPassword'
import PasswordChecklist from '../components/shared/PasswordChecklist'
@@ -14,12 +16,14 @@ const inputBase: React.CSSProperties = {
function ResetPasswordPage() {
const { t } = useTranslation()
// Page = wiring container: token, form state, validation + submit live in the hook.
const reset = useResetPassword()
const {
navigate, token,
pw, setPw, pw2, setPw2, showPw, setShowPw,
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
handleSubmit,
} = useResetPassword()
} = reset
if (isNativeApp()) return <AppResetPassword reset={reset} />
const shell = (inner: React.ReactNode) => (
<div style={{
@@ -0,0 +1,61 @@
import { CheckCircle2 } from 'lucide-react';
import { useTranslation } from '../../i18n';
import { AppAuthScreen, Field, Notice } from '../login/AppAuthScreen';
import type { useForgotPassword } from './useForgotPassword';
export default function AppForgotPassword({ forgot }: { forgot: ReturnType<typeof useForgotPassword> }) {
const { t } = useTranslation();
const back = () => void forgot.navigate('/login');
const smtpOff = forgot.smtpConfigured === false;
const smtpNotice = smtpOff && <Notice tone="warn">{t('login.forgotPasswordSmtpHintOff')}</Notice>;
return (
<AppAuthScreen>
{forgot.submitted && !forgot.deliveryIssue ? (
<div className="al-form">
<div className="al-recovery-feedback" role="status">
{!smtpOff && <CheckCircle2 className="al-recovery-icon" size={28} aria-hidden="true" />}
<h1 className="al-title">{t(smtpOff ? 'login.forgotPasswordTitle' : 'login.forgotPasswordSentTitle')}</h1>
{!smtpOff && <p className="al-sub">{t('login.forgotPasswordSentBody')}</p>}
</div>
{smtpNotice}
<button type="button" className="al-cta" onClick={back}>
{t('login.backToLogin')}
</button>
</div>
) : (
<>
<form className="al-form" onSubmit={(event) => void forgot.handleSubmit(event)}>
<h1 className="al-title">{t('login.forgotPasswordTitle')}</h1>
<p className="al-sub">{t('login.forgotPasswordBody')}</p>
{smtpNotice}
{forgot.deliveryIssue && (
<Notice>
{t(forgot.deliveryIssue === 'rateLimit' ? 'common.tooManyAttempts' : 'native.connect.errorUnreachable')}
</Notice>
)}
<Field
label={t('common.email')}
name="email"
type="email"
autoComplete="email"
autoCapitalize="none"
enterKeyHint="send"
value={forgot.email}
onChange={(event) => forgot.setEmail(event.target.value)}
placeholder={t('login.emailPlaceholder')}
required
/>
<button type="submit" className="al-cta" disabled={forgot.isLoading}>
{forgot.isLoading && <span className="al-spin" aria-hidden="true" />}
{forgot.isLoading ? t('common.loading') : t('login.forgotPasswordSubmit')}
</button>
</form>
<button type="button" className="al-forgot" onClick={back}>
{t('login.backToLogin')}
</button>
</>
)}
</AppAuthScreen>
);
}
@@ -1,5 +1,6 @@
import { useState, useEffect, type FormEvent } from 'react'
import { useNavigate } from 'react-router'
import { isAxiosError } from 'axios'
import { authApi } from '../../api/client'
/**
@@ -14,6 +15,7 @@ export function useForgotPassword() {
const [submitted, setSubmitted] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [smtpConfigured, setSmtpConfigured] = useState<boolean | null>(null)
const [deliveryIssue, setDeliveryIssue] = useState<'connection' | 'rateLimit' | null>(null)
useEffect(() => {
// Probe whether SMTP is configured so we can warn the user up-front that the
@@ -29,15 +31,21 @@ export function useForgotPassword() {
const handleSubmit = async (e: FormEvent) => {
e.preventDefault()
if (isLoading) return
setDeliveryIssue(null)
setIsLoading(true)
try {
await authApi.forgotPassword({ email: email.trim() })
} catch {
// Enumeration-safe: success UX regardless of server outcome.
} catch (error) {
// These errors apply to the connection or requester, not to the mailbox.
// Keep every other outcome indistinguishable from an accepted request.
if (isAxiosError(error)) {
if (error.response?.status === 429) setDeliveryIssue('rateLimit')
else if (!error.response) setDeliveryIssue('connection')
}
}
setSubmitted(true)
setIsLoading(false)
}
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit }
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, deliveryIssue, handleSubmit }
}
+87
View File
@@ -0,0 +1,87 @@
import { AlertCircle, Globe, Lock } from 'lucide-react';
import { useEffect, useRef, type InputHTMLAttributes, type ReactNode } from 'react';
import { useNativeServer } from '../../components/Settings/useNativeServer';
import { useTranslation } from '../../i18n';
import { lightStatusBarIcons } from '../../native/appBoot';
import { reportNativeFailure } from '../../native/reportFailure';
import './appLogin.css';
export function AppAuthScreen({ children, leaving }: { children: ReactNode; leaving?: boolean }) {
useEffect(() => lightStatusBarIcons(), []);
return (
<div className={leaving ? 'app-login al-leaving' : 'app-login'}>
<AppAuthHero />
<main className="al-body">{children}</main>
</div>
);
}
function AppAuthHero() {
const { t } = useTranslation();
const { host, changeServer } = useNativeServer();
const hero = useRef<HTMLDivElement>(null);
useEffect(() => {
const box = hero.current;
if (!box) return;
let cancelled = false;
// Keep the landscape in the position where the address screen leaves it.
void import('../../../native-shell/scenery')
.then(({ startScenery, cameraForPlan }) => {
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
})
.catch(reportNativeFailure);
return () => {
cancelled = true;
box.querySelector('canvas.scenery')?.remove();
};
}, []);
return (
<div className="al-hero" ref={hero}>
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
{host && (
<div className="al-card">
<div className="al-card-text">
<small>
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
{t('native.connect.yourTrek')}
</small>
<div className="al-host" dir="ltr">
<Globe size={17} aria-hidden="true" />
<span>{host}</span>
</div>
</div>
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
{t('common.change')}
</button>
</div>
)}
</div>
);
}
export function Notice({ tone, children }: { tone?: 'warn'; children: ReactNode }) {
return (
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? 'status' : 'alert'}>
<AlertCircle size={18} aria-hidden="true" />
<div>{children}</div>
</div>
);
}
export function Field({
label,
after,
...input
}: { label: string; after?: ReactNode } & InputHTMLAttributes<HTMLInputElement>) {
return (
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
<label className="al-fld">
<span className="al-lab">{label}</span>
<input {...input} />
</label>
{after && <span className="al-after">{after}</span>}
</div>
);
}
+5 -92
View File
@@ -1,12 +1,8 @@
import { AlertCircle, Eye, EyeOff, Fingerprint, Globe, Lock, Shield } from 'lucide-react';
import React, { useEffect, useRef } from 'react';
import { Eye, EyeOff, Fingerprint, Shield } from 'lucide-react';
import ToggleSwitch from '../../components/Settings/ToggleSwitch';
import { useNativeServer } from '../../components/Settings/useNativeServer';
import PasswordChecklist from '../../components/shared/PasswordChecklist';
import { useTranslation } from '../../i18n';
import { lightStatusBarIcons } from '../../native/appBoot';
import { reportNativeFailure } from '../../native/reportFailure';
import './appLogin.css';
import { AppAuthScreen, Field, Notice } from './AppAuthScreen';
import { heading as headingOf, oidcLoginHref, oidcOnlyHref, submitLabel, type LoginStep } from './loginModel';
import { mfaCodeInputProps } from './mfaCodeInput';
import { IDP_LOGIN_URL, type useLogin } from './useLogin';
@@ -22,14 +18,10 @@ type Login = ReturnType<typeof useLogin>;
* (the device decides, see useLogin) differ.
*/
export default function AppLogin({ login }: { login: Login }) {
useEffect(() => lightStatusBarIcons(), []);
return (
<div className={login.showTakeoff ? 'app-login al-leaving' : 'app-login'}>
<AppLoginHero />
<main className="al-body">
<AppLoginContent login={login} />
</main>
</div>
<AppAuthScreen leaving={login.showTakeoff}>
<AppLoginContent login={login} />
</AppAuthScreen>
);
}
@@ -59,85 +51,6 @@ function AppLoginContent({ login }: { login: Login }) {
return <Credentials login={login} />;
}
/** The landscape of the address screen, with the server this screen signs in to. */
function AppLoginHero() {
const { t } = useTranslation();
const { host, changeServer } = useNativeServer();
const hero = useRef<HTMLDivElement>(null);
useEffect(() => {
const box = hero.current;
if (!box) return;
let cancelled = false;
// The same camera the address screen ends on, so the picture holds still
// across the change of screens. The scene stops drawing once its canvas
// has left the page.
void import('../../../native-shell/scenery')
.then(({ startScenery, cameraForPlan }) => {
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
})
// Without the landscape the box keeps its plain sea colour.
.catch(reportNativeFailure);
return () => {
cancelled = true;
box.querySelector('canvas.scenery')?.remove();
};
}, []);
return (
<div className="al-hero" ref={hero}>
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
{host && (
<div className="al-card">
<div className="al-card-text">
<small>
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
{t('native.connect.yourTrek')}
</small>
<div className="al-host" dir="ltr">
<Globe size={17} aria-hidden="true" />
<span>{host}</span>
</div>
</div>
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
{t('common.change')}
</button>
</div>
)}
</div>
);
}
function Notice({ tone, children }: { tone?: 'warn'; children: React.ReactNode }) {
return (
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? undefined : 'alert'}>
<AlertCircle size={18} aria-hidden="true" />
<div>{children}</div>
</div>
);
}
/**
* A field on a white card, the label above the input, as on the address screen.
* A control beside the input (the password's eye) sits outside the label, so
* the label names the input alone.
*/
function Field({
label,
after,
...input
}: { label: string; after?: React.ReactNode } & React.InputHTMLAttributes<HTMLInputElement>) {
return (
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
<label className="al-fld">
<span className="al-lab">{label}</span>
<input {...input} />
</label>
{after && <span className="al-after">{after}</span>}
</div>
);
}
function OidcOnly({ login }: { login: Login }) {
const { t } = useTranslation();
return (
+9 -1
View File
@@ -1,5 +1,5 @@
/*
* The sign-in screen inside the iOS and Android app (AppLogin.tsx). It is the
* The sign-in and password recovery screens inside the iOS and Android app. The sign-in is the
* next screen after the app's own address screen (native-shell/), so it wears
* that screen's look: the same landscape on top, the same glass card with the
* server on it, the same type, fields and buttons on the same warm page. The
@@ -295,6 +295,14 @@
line-height: 1.5;
color: var(--al-text);
}
.al-recovery-feedback {
display: grid;
gap: 8px;
justify-items: start;
}
.al-recovery-icon {
color: var(--al-good);
}
/* A field on a white card: the label above, the input below it. */
.al-fld {
@@ -0,0 +1,95 @@
import { CheckCircle2, Eye, EyeOff } from 'lucide-react';
import PasswordChecklist from '../../components/shared/PasswordChecklist';
import { useTranslation } from '../../i18n';
import { AppAuthScreen, Field, Notice } from '../login/AppAuthScreen';
import { mfaCodeInputProps } from '../login/mfaCodeInput';
import type { useResetPassword } from './useResetPassword';
type Reset = ReturnType<typeof useResetPassword>;
export default function AppResetPassword({ reset }: { reset: Reset }) {
const { t } = useTranslation();
return (
<AppAuthScreen>
{reset.success ? (
<div className="al-form">
<div className="al-recovery-feedback" role="status">
<CheckCircle2 className="al-recovery-icon" size={28} aria-hidden="true" />
<h1 className="al-title">{t('login.resetPasswordSuccessTitle')}</h1>
<p className="al-sub">{t('login.resetPasswordSuccessBody')}</p>
</div>
<button type="button" className="al-cta" onClick={() => void reset.navigate('/login')}>
{t('login.signIn')}
</button>
</div>
) : !reset.token ? (
<div className="al-form">
<h1 className="al-title">{t('login.resetPasswordInvalidLink')}</h1>
<Notice>{t('login.resetPasswordInvalidLinkBody')}</Notice>
<button type="button" className="al-cta" onClick={() => void reset.navigate('/forgot-password')}>
{t('login.forgotPasswordSubmit')}
</button>
</div>
) : (
<ResetForm reset={reset} />
)}
</AppAuthScreen>
);
}
function ResetForm({ reset }: { reset: Reset }) {
const { t } = useTranslation();
const inputType = reset.showPw ? 'text' : 'password';
const title = reset.mfaRequired ? t('login.mfaTitle') : t('login.resetPasswordTitle');
const action = reset.mfaRequired ? t('login.resetPasswordVerify') : t('login.resetPasswordSubmit');
return (
<form className="al-form" onSubmit={(event) => void reset.handleSubmit(event)}>
<h1 className="al-title">{title}</h1>
<p className="al-sub">{t(reset.mfaRequired ? 'login.resetPasswordMfaBody' : 'login.resetPasswordBody')}</p>
{reset.error && <Notice>{reset.error}</Notice>}
{reset.mfaRequired ? (
<Field
label={t('login.mfaCode')}
{...mfaCodeInputProps(reset.mfaCode, reset.setMfaCode, t('login.mfaPlaceholder'))}
/>
) : (
<>
<Field
label={t('login.newPassword')}
type={inputType}
name="new-password"
autoComplete="new-password"
value={reset.pw}
onChange={(event) => reset.setPw(event.target.value)}
required
after={
<button
type="button"
className="al-eye"
aria-label={t('native.claim.showPassword')}
aria-pressed={reset.showPw}
onClick={() => reset.setShowPw((visible) => !visible)}
>
{reset.showPw ? <EyeOff size={18} aria-hidden="true" /> : <Eye size={18} aria-hidden="true" />}
</button>
}
/>
<PasswordChecklist password={reset.pw} className="al-check" tone="light" />
<Field
label={t('login.confirmPassword')}
type={inputType}
name="confirm-password"
autoComplete="new-password"
value={reset.pw2}
onChange={(event) => reset.setPw2(event.target.value)}
required
/>
</>
)}
<button type="submit" className="al-cta" disabled={reset.isLoading}>
{reset.isLoading && <span className="al-spin" aria-hidden="true" />}
{reset.isLoading ? t('common.loading') : action}
</button>
</form>
);
}