loopable / web /src /settings /SecurityPane.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
a5981db verified
Raw History Blame Contribute Delete
37.1 kB
// ---------------------------------------------------------------------------
// settings / SecurityPane.tsx - W57-T36, R15 / C12.
//
// Every stored account owns its second factor. W59-T31 also renders this pane
// before a session exists: R1 moves the enrollment screen, never the MFA wall.
// Settings reads status, never the installed secret, and can replace a phone
// only after password re-authentication and proof of the candidate factor.
// ---------------------------------------------------------------------------
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { FormEvent } from "react";
import { errorMessage, isAdmin, me, mfaEnrollConfirm, mfaEnrollStart, mfaStatus, regenerateRecoveryCodes, SERVER_UNAVAILABLE } from "../shell/session";
import type { MFASetup, MFAStatus, SessionUser } from "../shell/session";
import { API_V1, CREDENTIALS, checkTenant, currentTenant, signal, TOAST_EVENT, UNAUTHORIZED_EVENT } from "../apiContract";
import { useEscapeClose } from "../ui/useEscapeClose";
import { CodeInput } from "../ui/CodeInput";
import { encodeQr } from "../shell/qrcode";
import "../styles/sdlc84/settings-security.css";
function SetupQr({ uri }: { uri: string }) {
const drawing = useMemo(() => {
try {
const qr = encodeQr(uri);
const quiet = 4;
// One path keeps the modal's DOM small; the four-module light border
// belongs in the viewBox so responsive sizing cannot crop it away.
const path = qr.modules.flatMap((row, y) => row.flatMap((dark, x) =>
dark ? [`M${x + quiet} ${y + quiet}h1v1h-1z`] : [])).join("");
return { extent: qr.size + 2 * quiet, path };
} catch {
// Keep enrollment usable, but never draw a plausible square on failure.
return null;
}
}, [uri]);
if (!drawing) return <p className="security-qr-help">The QR code could not be drawn.</p>;
return (
<>
<p className="security-qr-help">Or scan this code with your authenticator app.</p>
<svg className="security-qr-image" viewBox={`0 0 ${drawing.extent} ${drawing.extent}`}
shapeRendering="crispEdges" role="img" aria-label="Setup code as a QR code" focusable="false">
<rect className="security-qr-field" width={drawing.extent} height={drawing.extent} />
<path fill="currentColor" d={drawing.path} />
</svg>
</>
);
}
/** W57-T36 / C12: one show-once treatment in both doors. Copy is a quiet,
* explicit export to the person's clipboard, never persistence on their behalf.
* Only the acknowledgement can dismiss this surface; Escape names what remains.
* Browser reload/close can only be warned about, never made impossible by a page. */
export function RecoveryCodes({ codes, onSaved, onError }: {
codes: string[];
onSaved: () => void;
onError: (message: string) => void;
}) {
const [copied, setCopied] = useState<boolean>(false);
const [copying, setCopying] = useState<boolean>(false);
useEscapeClose(true, () => onError("Save your recovery codes before continuing."));
useEffect(() => {
const warn = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = "";
};
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, []);
async function copy() {
if (copying) return;
setCopying(true);
try {
await navigator.clipboard.writeText(codes.join("\n"));
setCopied(true);
onError("");
} catch {
setCopied(false);
onError("Copy did not work. Select the codes and copy them manually.");
} finally {
setCopying(false);
}
}
return (
<>
<p className="security-help">These recovery codes are shown only once.</p>
<p className="security-help">Save them somewhere safe. Each code works once if you lose your authenticator.</p>
<ul className="security-codes" aria-label="Recovery codes">
{codes.map((code) => <li key={code}><code>{code}</code></li>)}
</ul>
<div className="security-copy-row">
<button type="button" className="set-secondary" onClick={() => void copy()} disabled={copying}>
{copying ? "Copying…" : "Copy codes"}
</button>
<span className="security-copy-status" role="status">{copied ? "Copied" : ""}</span>
</div>
{/* A type=button acknowledgement cannot be submitted by Enter left over
from the previous code field. There is no Back or secondary exit. */}
<button type="button" className="set-primary" onClick={onSaved} disabled={copying}>
I have saved these codes
</button>
</>
);
}
type AuthFailure = { ok: false; message: string };
function showRefusal(text: string) {
window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }));
}
// Keep the literal fetch doors visible to D-48. These session-scoped helpers
// mirror authPost's tenant guard and error policy without creating a second session module.
async function startDevice(password: string): Promise<({ ok: true } & MFASetup) | AuthFailure> {
let res: Response;
try {
res = await fetch(`${API_V1}/auth/mfa/device`, {
method: "POST", credentials: CREDENTIALS, cache: "no-store",
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }),
});
} catch {
return { ok: false, message: errorMessage(0, null) };
}
if (checkTenant(res)) return { ok: false, message: SERVER_UNAVAILABLE };
const body = await res.json().catch(() => null);
if (!res.ok) return { ok: false, message: errorMessage(res.status, body) };
if (!body || typeof body.secret !== "string" || !body.secret.trim()
|| typeof body.otpauthUri !== "string" || !body.otpauthUri.trim()
|| typeof body.issuer !== "string" || !body.issuer.trim())
return { ok: false, message: SERVER_UNAVAILABLE };
return { ok: true, secret: body.secret, otpauthUri: body.otpauthUri, issuer: body.issuer };
}
async function confirmDevice(password: string, secret: string, code: string): Promise<
{ ok: true; recoveryCodes: string[] } | AuthFailure
> {
let res: Response;
try {
res = await fetch(`${API_V1}/auth/mfa/device/confirm`, {
method: "POST", credentials: CREDENTIALS, cache: "no-store",
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password, secret, code }),
});
} catch {
return { ok: false, message: errorMessage(0, null) };
}
if (checkTenant(res)) return { ok: false, message: SERVER_UNAVAILABLE };
const body = await res.json().catch(() => null);
if (!res.ok) return { ok: false, message: errorMessage(res.status, body) };
const codes: unknown = body?.recoveryCodes;
// Accept the whole fresh set or refuse success, just like the existing issuers.
if (!Array.isArray(codes) || codes.length === 0
|| !codes.every((value): value is string => typeof value === "string" && value.trim().length > 0)
|| new Set(codes).size !== codes.length)
return { ok: false, message: SERVER_UNAVAILABLE };
return { ok: true, recoveryCodes: codes };
}
export type EnrolmentGate = {
username: string;
password: string;
onEnrolled: (user: SessionUser, recoveryCodes: string[]) => void;
onBack: () => void;
};
type SecurityEvent = {
kind: string;
user: string;
tenant: string;
detail: Record<string, string | number | boolean>;
at: string;
};
const EVENTS_UNAVAILABLE = "Security events could not be loaded.";
const EVENT_LABELS: Record<string, string> = {
"auth.login": "Signed in",
"auth.login_failed": "Sign-in failed",
"auth.lockout": "Account locked",
"auth.mfa_enrolled": "Two-step sign-in set up",
"auth.mfa_failed": "Two-step sign-in failed",
"auth.logout": "Signed out",
"admin.grant": "Access changed",
"credential.added": "Credential added",
"credential.rotated": "Credential replaced",
"credential.revoked": "Credential revoked",
"amazon.sync": "Amazon sync",
"amazon.throttled": "Amazon request limited",
"amazon.authorization_lost": "Amazon authorization lost",
"amazon.deletion_scheduled": "Amazon deletion scheduled",
"amazon.personal_read": "Amazon personal data read",
"customer.personal_read": "Customer personal data read",
"data.purge": "Data deleted",
"data.restore": "Data restored",
"config.changed": "Setting changed",
"external.query": "External query",
"external.write": "External change",
};
function readableLabel(value: string) {
const words = value.replace(/[._-]+/g, " ").trim().toLowerCase();
return words ? words[0].toUpperCase() + words.slice(1) : "Security event";
}
function SecuritySkeleton({ label }: { label: string }) {
return <div className="set-skeleton security-skeleton" role="status" aria-label={label} aria-busy="true">
<span className="set-skeleton-line" aria-hidden="true" />
<span className="set-skeleton-line" aria-hidden="true" />
</div>;
}
function SecurityEvents() {
const [denied, setDenied] = useState(false);
const [events, setEvents] = useState<SecurityEvent[]>([]);
const [loading, setLoading] = useState(true);
const [problem, setProblem] = useState("");
const [revision, setRevision] = useState(0);
useEffect(() => {
const controller = new AbortController();
let active = true;
const clear = () => {
active = false;
controller.abort();
setDenied(true); setEvents([]); setProblem(""); setLoading(false);
};
setDenied(false); setEvents([]); setLoading(true); setProblem("");
async function load() {
try {
const identity = await me();
if (!active) return;
if (!identity?.tenant) throw new Error(EVENTS_UNAVAILABLE);
if (currentTenant() !== null && currentTenant() !== identity.tenant) {
setDenied(true); return;
}
if (!isAdmin(identity)) { setDenied(true); return; }
const response = await fetch(`${API_V1}/security/events`, {
credentials: CREDENTIALS, cache: "no-store", signal: controller.signal,
});
if (!active || checkTenant(response)) return;
if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
if (response.status === 403) { setDenied(true); return; }
if (!response.ok) throw new Error(EVENTS_UNAVAILABLE);
const body = await response.json();
if (!active) return;
if (!body || !Array.isArray(body.events)) throw new Error(EVENTS_UNAVAILABLE);
const entries: SecurityEvent[] = [];
for (const event of body.events) {
if (!event || event.tenant !== identity.tenant) continue;
if (typeof event.kind !== "string" || !event.kind.trim()
|| typeof event.principal !== "string" || !event.principal.trim()
|| !event.detail || typeof event.detail !== "object" || Array.isArray(event.detail)
|| !Object.values(event.detail).every((value) => typeof value === "string"
|| typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))
|| typeof event.ts !== "number" || !Number.isFinite(event.ts)
|| !Number.isFinite(new Date(event.ts * 1000).getTime())) throw new Error(EVENTS_UNAVAILABLE);
entries.push({ kind: event.kind, user: event.principal, tenant: event.tenant,
detail: event.detail, at: new Date(event.ts * 1000).toISOString() });
}
setEvents(entries.reverse());
} catch {
if (active) { setEvents([]); setProblem(EVENTS_UNAVAILABLE); }
} finally {
if (active) setLoading(false);
}
}
window.addEventListener(UNAUTHORIZED_EVENT, clear);
window.addEventListener("aios:signed-out", clear);
void load();
return () => {
active = false;
controller.abort();
window.removeEventListener(UNAUTHORIZED_EVENT, clear);
window.removeEventListener("aios:signed-out", clear);
};
}, [revision]);
return <section className="security-events" aria-labelledby="security-events-heading">
<h4 className="set-h4" id="security-events-heading">Security events</h4>
{loading ? <SecuritySkeleton label="Loading security events" /> : problem ? <div className="set-error" role="alert"><span>{problem}</span>
<button type="button" className="set-secondary" onClick={() => setRevision((value) => value + 1)}>Retry</button>
</div> : denied ? <p className="security-help" role="status">Only administrators can view security events</p>
: events.length ? <div className="security-event-scroll" role="region" aria-label="Security event log" tabIndex={0}>
<table className="set-table" aria-label="Security events">
<thead><tr><th scope="col">Event</th><th scope="col">User</th><th scope="col">Details</th><th scope="col">Time (UTC)</th></tr></thead>
<tbody>{events.map((event, index) => <tr key={`${event.at}:${index}`}>
<td><span>{Object.hasOwn(EVENT_LABELS, event.kind) ? EVENT_LABELS[event.kind] : readableLabel(event.kind)}</span>
<span className="security-event-kind">{event.kind}</span></td>
<td>{event.user}</td>
<td>{Object.entries(event.detail).map(([key, value]) => `${readableLabel(key)}: ${String(value)}`).join(" · ") || "No details"}</td>
<td><time dateTime={event.at}>{event.at.replace("T", " ").replace("Z", " UTC")}</time></td>
</tr>)}</tbody>
</table>
</div> : <p className="security-help" role="status">No security events yet</p>}
</section>;
}
function BrowserSecurity() {
const [user, setUser] = useState<SessionUser | null>(null);
const [enabled, setEnabled] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
const [denied, setDenied] = useState(false);
const [busy, setBusy] = useState(false);
const [problem, setProblem] = useState("");
const [signOutProblem, setSignOutProblem] = useState("");
const [operation, setOperation] = useState<"load" | "save" | "logout">("load");
const retryValue = useRef<boolean | null>(null);
const [revision, setRevision] = useState(0);
const scope = useRef<AbortController | null>(null);
const flight = useRef(false);
useEffect(() => {
const controller = new AbortController();
scope.current = controller;
const clear = () => {
controller.abort();
setUser(null); setEnabled(null); setProblem(""); setSignOutProblem("");
setBusy(false); setLoading(false); setDenied(true);
flight.current = false;
};
setUser(null); setEnabled(null); setProblem(""); setSignOutProblem("");
setLoading(true); setDenied(false); setOperation("load"); retryValue.current = null;
async function load() {
try {
const identity = await me();
if (controller.signal.aborted) return;
if (!identity?.tenant) throw new Error("identity");
if (currentTenant() !== null && currentTenant() !== identity.tenant) { setDenied(true); return; }
setUser(identity);
if (!isAdmin(identity)) { setDenied(true); return; }
const response = await fetch(`${API_V1}/security/trusted-browser`, {
credentials: CREDENTIALS, cache: "no-store", signal: controller.signal,
});
if (controller.signal.aborted || checkTenant(response)) return;
if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
if (response.status === 403) { setDenied(true); return; }
const body: unknown = await response.json().catch(() => null);
if (controller.signal.aborted) return;
if (!response.ok || !body || typeof (body as { enabled?: unknown }).enabled !== "boolean")
throw new Error("policy");
setEnabled((body as { enabled: boolean }).enabled);
} catch {
if (!controller.signal.aborted) setProblem("Remembered browser settings could not be loaded.");
} finally {
if (!controller.signal.aborted) setLoading(false);
}
}
window.addEventListener(UNAUTHORIZED_EVENT, clear);
window.addEventListener("aios:signed-out", clear);
void load();
return () => {
controller.abort();
window.removeEventListener(UNAUTHORIZED_EVENT, clear);
window.removeEventListener("aios:signed-out", clear);
};
}, [revision]);
async function save(next: boolean) {
const request = scope.current?.signal;
if (!request || request.aborted || flight.current || !isAdmin(user) || denied || enabled === null) return;
flight.current = true; setBusy(true); setProblem(""); setOperation("save"); retryValue.current = next;
try {
const response = await fetch(`${API_V1}/security/trusted-browser`, {
method: "PUT", credentials: CREDENTIALS, cache: "no-store", signal: request,
headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled: next }),
});
if (request.aborted || checkTenant(response)) return;
if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
if (response.status === 403) { setDenied(true); return; }
const body: unknown = await response.json().catch(() => null);
if (request.aborted) return;
if (!response.ok || !body || typeof (body as { enabled?: unknown }).enabled !== "boolean")
throw new Error("policy");
setEnabled((body as { enabled: boolean }).enabled);
} catch {
if (!request.aborted) setProblem("Remembered browser settings could not be saved.");
} finally {
if (!request.aborted) { flight.current = false; setBusy(false); }
}
}
async function signOutEverywhere() {
const request = scope.current?.signal;
if (!request || request.aborted || flight.current || !user) return;
flight.current = true; setBusy(true); setSignOutProblem(""); setOperation("logout");
try {
const response = await fetch(`${API_V1}/auth/logout-everywhere`, {
method: "POST", credentials: CREDENTIALS, cache: "no-store", signal: request,
});
if (request.aborted || checkTenant(response)) return;
if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return; }
if (!response.ok) throw new Error("sign out");
signal(UNAUTHORIZED_EVENT);
} catch {
if (!request.aborted) setSignOutProblem("Your account could not be signed out everywhere.");
} finally {
if (!request.aborted) { flight.current = false; setBusy(false); }
}
}
return <>
<section className="security-control" aria-labelledby="security-browsers-heading" data-testid="trusted-browser-settings">
<div className="security-control-head">
<div className="security-control-copy">
<h4 className="set-h4" id="security-browsers-heading">Remembered browsers</h4>
<p className="security-help">Allow browsers to skip two-step sign-in for 7 days</p>
</div>
<button id="security-trusted-browser" type="button" role="switch" aria-checked={enabled === true}
aria-label="Allow remembered browsers for 7 days" className="set-secondary security-control-action"
disabled={busy || loading || denied || enabled === null} onClick={() => void save(!enabled)}>
{loading ? "Loading…" : busy && operation === "save" ? "Saving…" : enabled === null ? "Unavailable" : enabled ? "On" : "Off"}
</button>
</div>
{loading ? <SecuritySkeleton label="Loading remembered browser settings" />
: denied ? <p className="security-help" role="status">Only administrators can change this setting</p> : null}
{problem ? <div className="set-error" role="alert"><span>{problem}</span>
<button type="button" className="set-secondary" disabled={busy} onClick={() => {
if (retryValue.current !== null) void save(retryValue.current);
else setRevision((value) => value + 1);
}}>Retry</button>
</div> : null}
</section>
<section className="security-control" aria-labelledby="security-signout-heading">
<div className="security-control-head">
<div className="security-control-copy">
<h4 className="set-h4" id="security-signout-heading">Sign out everywhere</h4>
<p className="security-help">End all sessions for your account, including this one</p>
</div>
<button type="button" className="set-secondary security-control-action security-destructive"
disabled={busy || loading || !user} onClick={() => void signOutEverywhere()}>
{busy && operation === "logout" ? "Signing out…" : "Sign out everywhere"}
</button>
</div>
{loading ? <SecuritySkeleton label="Loading sign-out settings" />
: !user ? <p className="security-help" role="status">Sign-out controls are unavailable until your account loads</p> : null}
{signOutProblem ? <div className="set-error" role="alert"><span>{signOutProblem}</span>
<button type="button" className="set-secondary" disabled={busy} onClick={() => void signOutEverywhere()}>Retry</button>
</div> : null}
</section>
</>;
}
export default function SecurityPane({ gate }: { gate?: EnrolmentGate } = {}) {
const [status, setStatus] = useState<MFAStatus | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [reload, setReload] = useState<number>(0);
const [password, setPassword] = useState<string>("");
const [busy, setBusy] = useState<boolean>(false);
const [codes, setCodes] = useState<string[] | null>(null);
const [error, setError] = useState<string>("");
const [device, setDevice] = useState<boolean>(false);
const [recovering, setRecovering] = useState(false);
const [setup, setSetup] = useState<MFASetup | null>(null);
const [code, setCode] = useState<string>("");
const [preparing, setPreparing] = useState<boolean>(false);
const [setupRetry, setSetupRetry] = useState<number>(0);
const [enrolledUser, setEnrolledUser] = useState<SessionUser | null>(null);
const flight = useRef<boolean>(false);
const dialog = useRef<HTMLDialogElement>(null);
const passwordField = useRef<HTMLInputElement>(null);
const recoveryAction = useRef<HTMLButtonElement>(null);
const enrolForm = useRef<HTMLFormElement>(null);
const focusCodeOnRetry = useRef<boolean>(false);
const heading = useRef<HTMLHeadingElement>(null);
const locked = busy || codes !== null;
const gateUsername = gate?.username;
const gatePassword = gate?.password;
const requestScope = useRef<AbortController | null>(null);
useLayoutEffect(() => {
const scope = new AbortController();
requestScope.current = scope;
const clear = () => {
flight.current = false;
focusCodeOnRetry.current = false;
setPassword(""); setCode(""); setSetup(null); setCodes(null); setEnrolledUser(null);
setError(""); setBusy(false); setPreparing(false); setDevice(false); setRecovering(false); setStatus(null);
};
clear();
const invalidate = () => { scope.abort(); clear(); };
window.addEventListener(UNAUTHORIZED_EVENT, invalidate);
window.addEventListener("aios:signed-out", invalidate);
return () => {
scope.abort();
window.removeEventListener(UNAUTHORIZED_EVENT, invalidate);
window.removeEventListener("aios:signed-out", invalidate);
};
}, [gateUsername, gatePassword]);
useEffect(() => {
if (gate) return;
let current = true;
const request = requestScope.current?.signal;
setLoading(true);
setError("");
void mfaStatus().then((next) => {
if (!current || !request || request.aborted) return;
setStatus(next);
setLoading(false);
if (!next) setError("Security status could not be loaded.");
});
return () => { current = false; };
}, [gate, reload]);
// Scalar dependencies keep a parent re-render from replacing the candidate.
// Starting setup is read-only; ignore a late response after Back or a retry.
useEffect(() => {
if (gateUsername === undefined || gatePassword === undefined) return;
let current = true;
const request = requestScope.current?.signal;
heading.current?.focus();
setPreparing(true);
setSetup(null);
setCode("");
setError("");
void mfaEnrollStart(gateUsername, gatePassword).then((result) => {
if (!current || !request || request.aborted) return;
setPreparing(false);
if (result.ok === false) setError(result.message);
else setSetup(result);
});
return () => { current = false; };
}, [gateUsername, gatePassword, setupRetry]);
// Lock BEFORE issuing codes, not only after receiving them: closing Settings
// during the POST would throw away its only clear response. A native modal
// makes the rail, close button and backdrop inert without changing the parent.
// The shared Escape arbiter stops Settings' older window listener as well.
useEscapeClose(busy, () => setError("Wait for your recovery codes before leaving."));
useEffect(() => {
if (!locked) return;
const node = dialog.current;
if (!node) return;
node.showModal();
return () => {
node.close();
(passwordField.current ?? recoveryAction.current)?.focus();
};
}, [locked]);
// Retry focus follows the busy dialog's password focus restoration.
useEffect(() => {
if (locked || preparing || !setup || !focusCodeOnRetry.current) return;
focusCodeOnRetry.current = false;
enrolForm.current?.querySelector<HTMLInputElement>("#security-enrol-code")?.focus();
}, [locked, preparing, setup]);
async function generate(event: FormEvent) {
event.preventDefault();
const request = requestScope.current?.signal;
if (!request || request.aborted) return;
if (flight.current || codes || !status?.enrolled || !password) return;
flight.current = true;
setBusy(true);
setError("");
const result = await regenerateRecoveryCodes(password);
if (request.aborted) return;
// No password survives a write attempt. The response is the new set only;
// do not re-read or cache it, and do not offer generation while it is shown.
setPassword("");
if (result.ok === false) {
setError("");
showRefusal(result.message);
} else {
setCodes(result.recoveryCodes);
setStatus((previous) => previous
? { ...previous, recoveryCodesRemaining: result.recoveryCodes.length } : null);
}
flight.current = false;
setBusy(false);
}
async function enrol(event: FormEvent) {
event.preventDefault();
const request = requestScope.current?.signal;
if (!request || request.aborted) return;
if (flight.current || locked || preparing) return;
if (!setup) {
if (gate) {
setSetupRetry((value) => value + 1);
return;
}
if (!status?.enrolled || !password) return;
flight.current = true;
setPreparing(true);
setError("");
try {
const result = await startDevice(password);
if (request.aborted) return;
if (result.ok === false) {
setError("");
showRefusal(result.message);
setPassword("");
} else setSetup(result);
} finally {
if (!request.aborted) {
flight.current = false;
setPreparing(false);
}
}
return;
}
if (!/^[0-9]{6}$/.test(code) || (!gate && (!status?.enrolled || !password))) return;
flight.current = true;
setBusy(true);
setError("");
try {
const result: { ok: true; user?: SessionUser; recoveryCodes: string[] } | AuthFailure = gate
? await mfaEnrollConfirm(gate.username, gate.password, setup.secret, code)
: await confirmDevice(password, setup.secret, code);
if (request.aborted) return;
if (result.ok === false) {
focusCodeOnRetry.current = true;
if (gate) setError(result.message);
else {
setError("");
showRefusal(result.message);
}
} else {
// A cookie exists only now. The frame still waits for the show-once acknowledgement.
if (result.user) setEnrolledUser(result.user);
setCodes(result.recoveryCodes);
setSetup(null);
setDevice(false);
}
} finally {
if (!request.aborted) {
setPassword("");
setCode("");
flight.current = false;
setBusy(false);
}
}
}
const enrollmentForm = (gate || device) && !locked ? (
<form className="security-form" ref={enrolForm} onSubmit={enrol}>
{!gate ? (
<>
<p className="security-help">A new device replaces your recovery codes and signs out your other sessions.</p>
<label className="security-label" htmlFor="security-device-password">Account password</label>
<input id="security-device-password" className="security-input" type="password" autoComplete="current-password"
ref={passwordField} value={password} disabled={preparing} required
aria-invalid={error ? true : undefined} aria-describedby="security-message"
onChange={(event) => { setPassword(event.target.value); setError(""); }} />
</>
) : null}
{setup ? (
<>
{/* The in-app encoder adds no dependency or external QR service.
Keep manual setup available even when the QR cannot be drawn. */}
<p className="security-help">Type this setup code into any authenticator app.</p>
<span className="security-label">{setup.issuer} setup code</span>
<code className="login-mfa-secret">{setup.secret.match(/.{1,4}/g)?.join(" ")}</code>
<div className="security-qr-setup">
<SetupQr uri={setup.otpauthUri} />
<span className="security-label">Authenticator setup link</span>
<code className="login-mfa-uri">{setup.otpauthUri}</code>
</div>
<label className="security-label" htmlFor="security-enrol-code">First authenticator code</label>
<CodeInput id="security-enrol-code" value={code} disabled={busy || preparing}
onChange={(value) => { setCode(value); setError(""); }}
invalid={Boolean(error)} describedBy="security-message" />
</>
) : preparing ? <SecuritySkeleton label="Preparing your setup code" /> : null}
<button type="submit" className="set-primary"
disabled={preparing || (!gate && !password) || (setup !== null && !/^[0-9]{6}$/.test(code))}>
{preparing ? "Preparing setup…" : setup ? "Confirm setup" : gate ? "Try setup again" : "Set up new device"}
</button>
{gate ? <button type="button" className="set-secondary" disabled={preparing} onClick={gate.onBack}>
Back to sign in
</button> : null}
</form>
) : null;
return (
<div className="set-pane set-security">
<h3 className="set-h" ref={heading} tabIndex={gate ? -1 : undefined}>Security</h3>
{gate ? <>
<p className="security-help">Two-step sign-in is required before the rest of the app opens.</p>
{enrollmentForm}
</> : <div className="security-controls">
<section className="security-control" aria-labelledby="security-factor-heading">
<div className="security-control-head">
<div className="security-control-copy">
<h4 className="set-h4" id="security-factor-heading">Two-step sign-in</h4>
<p className="security-help">{status && !status.enrolled
? "Sign in again to set up your authenticator app" : "Use an authenticator app to protect your account"}</p>
</div>
<button type="button" className="set-secondary security-control-action"
disabled={loading || locked || preparing || !status?.enrolled} aria-expanded={device}
aria-controls={device ? "security-device-setup" : undefined} onClick={() => {
setDevice(!device); setRecovering(false); setPassword(""); setCode(""); setSetup(null); setError("");
}}>{device ? "Cancel" : "Enrol a new device"}</button>
</div>
{loading ? <SecuritySkeleton label="Loading two-step sign-in status" />
: status ? <p className={`security-control-status ${status.enrolled ? "is-positive" : "is-attention"}`}>
{status.enrolled ? "On" : "Not set up"}
{status.enrolled && status.enrolledAt ? <> · Since <time dateTime={status.enrolledAt}>
{new Date(status.enrolledAt).toLocaleDateString()}</time></> : null}
</p> : <div className="set-error" role="alert">
<span>Security status could not be loaded.</span>
<button type="button" className="set-secondary" onClick={() => setReload((value) => value + 1)}>Retry</button>
</div>}
{device ? <div id="security-device-setup">{enrollmentForm}</div> : null}
</section>
<section className="security-control" aria-labelledby="security-recovery-heading">
<div className="security-control-head">
<div className="security-control-copy">
<h4 className="set-h4" id="security-recovery-heading">Recovery codes</h4>
<p className="security-help">Use a saved code if you lose your authenticator</p>
</div>
<button type="button" ref={recoveryAction} className="set-secondary security-control-action"
disabled={loading || locked || preparing || !status?.enrolled} aria-expanded={recovering}
aria-controls={recovering && !locked ? "security-recovery-setup" : undefined} onClick={() => {
setRecovering(!recovering); setDevice(false); setPassword(""); setCode(""); setSetup(null); setError("");
}}>{recovering ? "Cancel" : "Generate codes"}</button>
</div>
{loading ? <SecuritySkeleton label="Loading recovery code status" />
: status?.enrolled ? <p className={`security-control-status ${status.recoveryCodesRemaining === 0 ? "is-attention" : ""}`}>
{status.recoveryCodesRemaining === 0 ? "No recovery codes left" : `${status.recoveryCodesRemaining} codes left`}
</p> : <p className="security-help">{status ? "Set up two-step sign-in to use recovery codes" : "Recovery code status is unavailable"}</p>}
{recovering && !locked ? <form id="security-recovery-setup" className="security-form" onSubmit={generate}>
<p className="security-help">New codes replace your old codes and sign out your other sessions.</p>
<label className="security-label" htmlFor="security-password">Account password</label>
<input id="security-password" className="security-input" type="password" autoComplete="current-password"
ref={passwordField} value={password} disabled={busy} required autoFocus
aria-invalid={error ? true : undefined} aria-describedby="security-message"
onChange={(event) => { setPassword(event.target.value); setError(""); }} />
<button type="submit" className="set-primary" disabled={!password || busy}>Generate new recovery codes</button>
</form> : null}
</section>
<BrowserSecurity />
</div>}
<p className="security-message" id="security-message" role="status" aria-live="polite">{locked || (!gate && !status) ? "" : error}</p>
{!gate ? <SecurityEvents /> : null}
{/* R15/C12's explicit acknowledgement is the exception to ordinary
dismissible dialogs. Native cancel is prevented, outside clicks have
no close handler, and there is no close control or method=dialog form. */}
{locked ? (
<dialog ref={dialog} className="security-codes-dialog" aria-labelledby="security-codes-heading"
onCancel={(event) => event.preventDefault()}>
<h4 id="security-codes-heading" className="set-h4" tabIndex={-1} autoFocus>Recovery codes</h4>
<div className="security-form">
{codes ? (
<RecoveryCodes codes={codes} onError={setError} onSaved={() => {
if (gate) {
if (!enrolledUser) return;
gate.onEnrolled(enrolledUser, codes);
setEnrolledUser(null);
setCodes(null);
return;
}
setCodes(null);
setError("");
setRecovering(false);
// Count only, independently re-read after acknowledgement.
setReload((value) => value + 1);
}} />
) : (
<>
<p className="security-help" role="status">Generating your recovery codes…</p>
<button type="button" className="set-primary" disabled>Generating codes…</button>
</>
)}
</div>
<p className="security-message" role="status" aria-live="polite">{error}</p>
</dialog>
) : null}
</div>
);
}