// ---------------------------------------------------------------------------
// 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
The QR code could not be drawn.
;
return (
<>
Or scan this code with your authenticator app.
>
);
}
/** 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(false);
const [copying, setCopying] = useState(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 (
<>
These recovery codes are shown only once.
Save them somewhere safe. Each code works once if you lose your authenticator.
{codes.map((code) =>
{code}
)}
{copied ? "Copied" : ""}
{/* A type=button acknowledgement cannot be submitted by Enter left over
from the previous code field. There is no Back or secondary exit. */}
>
);
}
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;
at: string;
};
const EVENTS_UNAVAILABLE = "Security events could not be loaded.";
const EVENT_LABELS: Record = {
"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
;
}
function SecurityEvents() {
const [denied, setDenied] = useState(false);
const [events, setEvents] = useState([]);
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
{status ? "Set up two-step sign-in to use recovery codes" : "Recovery code status is unavailable"}
}
{recovering && !locked ? : null}
}
{locked || (!gate && !status) ? "" : error}
{!gate ? : 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 ? (
) : null}