// --------------------------------------------------------------------------- // shell/LoginPage.tsx — X5: the branded door. // // DESIGN.md §4.5: every step shares one panel, form width and brand anchor. // // NO CLIENT-SIDE BACKOFF (X5: the server owns it). The only local rule is // single-flight — a second submit while one is in the air is dropped, which is // double-click protection, not rate limiting. // --------------------------------------------------------------------------- import { useEffect, useRef, useState } from "react"; import type { FormEvent } from "react"; import { Brand } from "./Brand"; import FreezeNotice from "./FreezeNotice"; import type { FreezeNoticeState } from "../settings/settingsApi"; import { changePassword, errorMessage, login, loginReason, parseUserEnvelope, passwordPolicy, SERVER_UNAVAILABLE } from "./session"; import type { LoginOutcome, PasswordPolicy, SessionUser } from "./session"; import { API_V1, CREDENTIALS } from "../apiContract"; import SecurityPane from "../settings/SecurityPane"; import { CodeInput } from "../ui/CodeInput"; import "../styles/wave57/login-mfa.css"; type Step = "credentials" | "expired" | "mfa" | "enrol"; async function loginRememberingBrowser(username: string, password: string, mfaCode: string): Promise { let response: Response; try { response = await fetch(`${API_V1}/auth/login`, { method: "POST", credentials: CREDENTIALS, cache: "no-store", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password, mfaCode, rememberBrowser: true }), }); } catch { return { ok: false, reason: loginReason(0, null), message: errorMessage(0, null) }; } const body: unknown = await response.json().catch(() => null); if (!response.ok) return { ok: false, reason: loginReason(response.status, body), message: errorMessage(response.status, body) }; const user = parseUserEnvelope(body); return user ? { ok: true, user } : { ok: false, reason: "server", message: SERVER_UNAVAILABLE }; } /** The reveal toggle the host's password field ships natively (BaseWeb's eye). * Two doors, one affordance. */ function EyeIcon({ off }: { off: boolean }) { return ( ); } export default function LoginPage({ onSignedIn, freezeNotice }: { onSignedIn: (user: SessionUser) => void; freezeNotice?: FreezeNoticeState; }) { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [reveal, setReveal] = useState(false); const [step, setStep] = useState("credentials"); const [newPassword, setNewPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [code, setCode] = useState(""); const [recovery, setRecovery] = useState(false); const [rememberBrowser, setRememberBrowser] = useState(false); const [policy, setPolicy] = useState(null); const [policyLoading, setPolicyLoading] = useState(false); const flight = useRef(false); const stepHeading = useRef(null); const focusCode = useRef(false); // The password rules belong to the server, including history. Show its // checklist without inventing a second policy or claiming a local green pass. useEffect(() => { if (step !== "expired") return; let current = true; setPolicy(null); setPolicyLoading(true); void passwordPolicy().then((next) => { if (!current) return; setPolicy(next); setPolicyLoading(false); }); return () => { current = false; }; }, [step]); // Initial credentials keep the original no-autofocus rule. Later steps name // the new task to assistive tech, and focus the heading rather than a submit. useEffect(() => { stepHeading.current?.focus(); }, [step]); // Refocus after the failed request re-enables either code field. useEffect(() => { if (step !== "mfa" || busy || !focusCode.current) return; focusCode.current = false; document.getElementById("login-mfa-code")?.focus(); }, [busy, step, error]); /** Correct credentials must survive a challenge. Clearing the password on * every 401 would make the second-factor POST an invalid-credentials loop. * It stays only in this mounted tree, and leaves with success or Back. */ async function accept(result: LoginOutcome) { if (result.ok === true) { setPassword(""); setCode(""); setRememberBrowser(false); onSignedIn(result.user); return; } setError(result.message); switch (result.reason) { case "password_expired": setPolicyLoading(true); setStep("expired"); setCode(""); setRememberBrowser(false); break; case "mfa_required": case "mfa_invalid": setStep("mfa"); setCode(""); if (result.reason === "mfa_invalid") focusCode.current = true; break; case "mfa_enrolment_required": setRememberBrowser(false); setStep("enrol"); break; default: // Keep the current challenge on network/backoff errors so retry uses // the proved password. A wrong initial credential is cleared as before. if (step === "credentials" && result.reason === "credentials") setPassword(""); } } async function submit(e?: FormEvent, codeOverride?: string) { e?.preventDefault(); if (flight.current) return; if (busy) return; flight.current = true; setBusy(true); setError(""); try { if (step === "expired") { if (newPassword !== confirmPassword) { setError("The new passwords do not match."); return; } const changed = await changePassword(username, password, newPassword); if (changed.ok === false) { setError(changed.message); return; } // Rotation invalidates the old credential. Reuse the new one right // away, with a retryable credentials step if the next request is lost. setPassword(newPassword); setNewPassword(""); setConfirmPassword(""); setStep("credentials"); await accept(await login(username, newPassword)); } else { await accept(step === "mfa" && rememberBrowser ? await loginRememberingBrowser(username, password, codeOverride ?? code) : await login(username, password, step === "mfa" ? codeOverride ?? code : undefined)); } } finally { flight.current = false; setBusy(false); } } function back() { if (flight.current) return; setStep("credentials"); setPassword(""); setNewPassword(""); setConfirmPassword(""); setCode(""); setRecovery(false); setRememberBrowser(false); focusCode.current = false; setReveal(false); setError(""); } function switchCode() { if (busy || flight.current) return; setRecovery((value) => !value); setCode(""); setError(""); } // An error that survives the correction is an error that reads as sticky. function edit(set: (v: string) => void) { return (e: { target: { value: string } }) => { if (error) setError(""); set(e.target.value); }; } return (
{/* One form column and one anchor across every step. The extra content grows downward; no alternate width, position or brand lockup. */} {step === "expired" || step === "mfa" ? (

{step === "expired" ? "New password" : "Two step sign in"}

) : null} {step === "enrol" ? ( { setPassword(""); setCode(""); onSignedIn(user); } }} /> ) : ( <>
{step === "credentials" ? ( <> {/* Labels are present and hidden, not absent. `gate()` collapses them because Streamlit gives no other way to get a placeholder-only field; here the label exists for assistive tech and the visual is identical. */} {/* No autoFocus: the other door cannot autofocus (Streamlit), and the focus ring it would paint on load reads as a highlighted error on an untouched form. */}
{/* tabIndex -1: Tab goes Username to Password to Log in; the reveal is a mouse affordance, same as the host's. */}
) : null} {step === "expired" ? ( <> {policy ? (
    {policy.rules.map((rule) =>
  • {rule.message}
  • )}
) : (

{policyLoading ? "Loading password requirements…" : "Password requirements could not be loaded. Submit a new password to check it."}

)} ) : null} {step === "mfa" ? ( <> {recovery ? ( ) : ( edit(setCode)({ target: { value } })} onKeyboardComplete={(value) => submit(undefined, value)} disabled={busy} invalid={Boolean(error)} describedBy="login-mfa-help login-message" autoFocus /> )}

{recovery ? "Enter one of your saved recovery codes." : "Enter the 6 digit code from your authenticator app."}

If you have lost both, ask an administrator to reset two step sign in.

) : null} {/* Disabled through THREE channels (the real attribute, the cursor and the opacity), never opacity alone — a control that only looks dead is a control that still takes the click. */} {step !== "credentials" ? ( ) : null} {/* The message line is ALWAYS in the layout (min-height: 1lh) so an arriving error does not move the form. `role="status"` rather than "alert": polite announcement, no interruption. */}

{error}

)}
); }