feat(web): account security page and MFA enrolment wizard

This commit is contained in:
2026-09-16 09:26:54 +00:00
parent 26825841fa
commit 32fd11cde7
5 changed files with 409 additions and 18 deletions
+278
View File
@@ -0,0 +1,278 @@
"use client";
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { me, type MePasskey } from "@/lib/api";
import { isPasskeySupported, toCreateOptions, credentialToJSON } from "@/lib/webauthn";
import { AsyncBoundary, Badge, Button, Card, CardHeader, CardTitle, ConfirmDialog, friendlyMessage, Modal, useToast } from "@/components/ui";
import { MfaEnrolWizard, type MfaEnrolEndpoints } from "@/components/mfa/MfaEnrolWizard";
import { RecoveryCodes } from "@/components/mfa/RecoveryCodes";
/**
* Adapts the /api/me/* client methods to the shape MfaEnrolWizard expects.
* The only mismatch is the field name: the server calls it `otpauth_uri`
* here (it is `otpauth_url` on the ticket-scoped enrolment endpoints from
* Task 10, which this page does not use).
*/
const SESSION_ENDPOINTS: MfaEnrolEndpoints = {
totpSetup: async () => {
const res = await me.totpSetup();
return { secret: res.secret, otpauth_url: res.otpauth_uri };
},
totpConfirm: (code) => me.totpConfirm(code),
passkeyBegin: () => me.passkeyRegisterBegin(),
passkeyFinish: (ceremonyId, credential, name) => me.passkeyRegisterFinish(ceremonyId, credential, name),
};
function formatDate(value?: string): string {
if (!value) return "Never";
return new Date(value).toLocaleString();
}
export default function SecurityPage() {
const queryClient = useQueryClient();
const toast = useToast();
const { data: status, isLoading, error } = useQuery({ queryKey: ["me-mfa"], queryFn: me.mfa });
const [wizardOpen, setWizardOpen] = useState(false);
const [removingTotp, setRemovingTotp] = useState(false);
const [removingPasskey, setRemovingPasskey] = useState<MePasskey | null>(null);
const [renamingPasskey, setRenamingPasskey] = useState<MePasskey | null>(null);
const [renameValue, setRenameValue] = useState("");
const [newRecoveryCodes, setNewRecoveryCodes] = useState<string[] | null>(null);
const invalidate = () => queryClient.invalidateQueries({ queryKey: ["me-mfa"] });
const removeTotp = useMutation({
mutationFn: () => me.removeTotp(),
onSuccess: () => {
invalidate();
toast.success("Authenticator app removed.");
setRemovingTotp(false);
},
});
const deletePasskey = useMutation({
mutationFn: (id: string) => me.deletePasskey(id),
onSuccess: (_data, id) => {
invalidate();
toast.success("Passkey removed.");
if (removingPasskey?.id === id) setRemovingPasskey(null);
},
});
const renamePasskey = useMutation({
mutationFn: () => me.renamePasskey(renamingPasskey!.id, renameValue),
onSuccess: () => {
invalidate();
setRenamingPasskey(null);
},
});
const regenerateRecovery = useMutation({
mutationFn: () => me.regenerateRecovery(),
onSuccess: (res) => setNewRecoveryCodes(res.recovery_codes),
});
const addPasskeyDirect = useMutation({
mutationFn: async () => {
const { publicKey, ceremony_id } = await me.passkeyRegisterBegin();
const cred = (await navigator.credentials.create({ publicKey: toCreateOptions(publicKey) })) as PublicKeyCredential;
return me.passkeyRegisterFinish(ceremony_id, credentialToJSON(cred));
},
onSuccess: () => invalidate(),
});
function factorCount(s: NonNullable<typeof status>): number {
return (s.totp_enabled ? 1 : 0) + s.passkeys.length;
}
return (
<div className="mx-auto max-w-3xl space-y-6 p-4 sm:p-6 lg:p-8">
<h1 className="text-2xl font-bold text-text-primary">Security</h1>
<AsyncBoundary isLoading={isLoading} error={error}>
{status && !status.applicable ? (
<Card>
<p className="text-sm text-text-secondary">
Your sign-in is managed by this instance's identity provider. Two-factor authentication and passkeys are configured there, not here.
</p>
</Card>
) : status ? (
<>
{status.require_mfa && (
<div className="rounded-lg border border-warning/30 bg-warning/10 px-3 py-2 text-sm text-warning">
This instance requires a second sign-in factor. You cannot remove your last one.
</div>
)}
<Card>
<CardHeader className="mb-4">
<CardTitle>Authenticator app</CardTitle>
<Badge variant={status.totp_enabled ? "success" : "neutral"}>{status.totp_enabled ? "Enabled" : "Not set up"}</Badge>
</CardHeader>
<p className="mb-4 text-sm text-text-secondary">Generates a 6-digit code every 30 seconds in an app like Google Authenticator or 1Password.</p>
{status.totp_enabled ? (
<Button
variant="danger"
size="sm"
disabled={status.require_mfa && factorCount(status) <= 1}
title={status.require_mfa && factorCount(status) <= 1 ? "This instance requires at least one factor." : undefined}
onClick={() => setRemovingTotp(true)}
>
Remove
</Button>
) : (
<Button variant="secondary" size="sm" onClick={() => setWizardOpen(true)}>
Set up
</Button>
)}
</Card>
<Card>
<CardHeader className="mb-4">
<CardTitle>Passkeys</CardTitle>
{isPasskeySupported() && (
<Button variant="secondary" size="sm" loading={addPasskeyDirect.isPending} onClick={() => addPasskeyDirect.mutate()}>
Add a passkey
</Button>
)}
</CardHeader>
{addPasskeyDirect.error && <p className="mb-3 text-sm text-danger">{friendlyMessage(addPasskeyDirect.error)}</p>}
{status.passkeys.length === 0 ? (
<p className="text-sm text-text-secondary">No passkeys registered.</p>
) : (
<ul className="divide-y divide-border">
{status.passkeys.map((pk) => {
const lastFactor = status.require_mfa && !status.totp_enabled && status.passkeys.length <= 1;
return (
<li key={pk.id} className="flex flex-col gap-2 py-3 sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0">
<p className="truncate text-sm font-medium text-text-primary">{pk.name}</p>
<p className="text-xs text-text-secondary">
Added {formatDate(pk.created_at)} · Last used {formatDate(pk.last_used_at)}
</p>
</div>
<div className="flex shrink-0 gap-2">
<Button
variant="secondary"
size="sm"
onClick={() => {
setRenamingPasskey(pk);
setRenameValue(pk.name);
}}
>
Rename
</Button>
<Button
variant="danger"
size="sm"
disabled={lastFactor}
title={lastFactor ? "This instance requires at least one factor." : undefined}
onClick={() => setRemovingPasskey(pk)}
>
Remove
</Button>
</div>
</li>
);
})}
</ul>
)}
</Card>
<Card>
<CardHeader className="mb-4">
<CardTitle>Recovery codes</CardTitle>
</CardHeader>
<p className="mb-4 text-sm text-text-secondary">
{status.recovery_remaining} unused code{status.recovery_remaining === 1 ? "" : "s"} remaining. Regenerating invalidates every existing code.
</p>
<Button variant="secondary" size="sm" loading={regenerateRecovery.isPending} onClick={() => regenerateRecovery.mutate()}>
Regenerate
</Button>
{regenerateRecovery.error && <p className="mt-3 text-sm text-danger">{friendlyMessage(regenerateRecovery.error)}</p>}
</Card>
</>
) : null}
</AsyncBoundary>
<Modal open={wizardOpen} title="Set up a second factor" onClose={() => setWizardOpen(false)}>
<MfaEnrolWizard
mode="session"
endpoints={SESSION_ENDPOINTS}
onCancel={() => setWizardOpen(false)}
onComplete={() => {
invalidate();
setWizardOpen(false);
}}
/>
</Modal>
<Modal open={newRecoveryCodes !== null} title="New recovery codes" onClose={() => setNewRecoveryCodes(null)}>
{newRecoveryCodes && (
<RecoveryCodes
codes={newRecoveryCodes}
onAcknowledge={() => {
invalidate();
setNewRecoveryCodes(null);
}}
/>
)}
</Modal>
<Modal open={renamingPasskey !== null} title="Rename passkey" onClose={() => setRenamingPasskey(null)}>
<form
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
renamePasskey.mutate();
}}
>
<input
autoFocus
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
className="w-full rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-text-primary focus:border-accent/50 focus:outline-none focus:ring-1 focus:ring-accent/30"
/>
{renamePasskey.error && <p className="text-sm text-danger">{friendlyMessage(renamePasskey.error)}</p>}
<div className="flex justify-end gap-2">
<Button type="button" variant="secondary" onClick={() => setRenamingPasskey(null)}>
Cancel
</Button>
<Button type="submit" variant="primary" loading={renamePasskey.isPending} disabled={!renameValue.trim()}>
Save
</Button>
</div>
</form>
</Modal>
<ConfirmDialog
open={removingTotp}
title="Remove authenticator app"
confirmLabel="Remove"
loading={removeTotp.isPending}
error={removeTotp.error ? friendlyMessage(removeTotp.error) : null}
onClose={() => setRemovingTotp(false)}
onConfirm={() => removeTotp.mutate()}
body={<p>You will no longer be asked for a code from your authenticator app when signing in.</p>}
/>
<ConfirmDialog
open={removingPasskey !== null}
title="Remove passkey"
confirmLabel="Remove"
loading={deletePasskey.isPending}
error={deletePasskey.error ? friendlyMessage(deletePasskey.error) : null}
onClose={() => setRemovingPasskey(null)}
onConfirm={() => removingPasskey && deletePasskey.mutate(removingPasskey.id)}
body={
<p>
<span className="text-text-primary">{removingPasskey?.name}</span> will no longer be accepted for sign-in.
</p>
}
/>
</div>
);
}
+1
View File
@@ -204,6 +204,7 @@ const navGroups: NavGroup[] = [
// keys, capped at their own role, so gating the page would hide a
// capability they have.
{ href: "/tokens", label: "API Keys", icon: <TokenIcon /> },
{ href: "/account/security", label: "Security", icon: <ShieldIcon /> },
],
},
{
+2 -18
View File
@@ -5,6 +5,7 @@ import QRCode from "qrcode";
import { auth } from "@/lib/api";
import { isPasskeySupported, toCreateOptions, credentialToJSON } from "@/lib/webauthn";
import { Button } from "@/components/ui";
import { RecoveryCodes } from "./RecoveryCodes";
/**
* The calls a wizard step makes to set up a second factor. Defaults to the
@@ -53,7 +54,6 @@ export function MfaEnrolWizard({ mode, endpoints, onComplete, onCancel }: MfaEnr
// Recovery codes state
const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]);
const [savedConfirmed, setSavedConfirmed] = useState(false);
if (!api) {
return <div className="rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">This wizard was not given its endpoints for session mode.</div>;
@@ -165,21 +165,5 @@ export function MfaEnrolWizard({ mode, endpoints, onComplete, onCancel }: MfaEnr
}
// step === "recovery"
return (
<div className="space-y-4">
<p className="text-sm text-text-secondary">Save these recovery codes somewhere safe. Each can be used once if you lose access to your other factor.</p>
<div className="grid grid-cols-2 gap-2 rounded-lg border border-border bg-surface-2 p-3 font-mono text-xs text-text-primary">
{recoveryCodes.map((code) => (
<div key={code}>{code}</div>
))}
</div>
<label className="flex items-center gap-2 text-sm text-text-secondary">
<input type="checkbox" checked={savedConfirmed} onChange={(e) => setSavedConfirmed(e.target.checked)} className="h-4 w-4 rounded border-border" />
I have saved these codes
</label>
<Button type="button" variant="primary" className="w-full justify-center" disabled={!savedConfirmed} onClick={() => onComplete(recoveryCodes)}>
Continue
</Button>
</div>
);
return <RecoveryCodes codes={recoveryCodes} onAcknowledge={() => onComplete(recoveryCodes)} />;
}
+64
View File
@@ -0,0 +1,64 @@
"use client";
import { useState } from "react";
import { Button } from "@/components/ui";
interface RecoveryCodesProps {
codes: string[];
onAcknowledge: () => void;
}
/**
* Shows a fresh batch of recovery codes exactly once, either at the end of
* enrolment (via MfaEnrolWizard) or after a regenerate on the security page.
* The server never returns a previously issued batch, so this is the only
* place in the app these codes are ever visible.
*/
export function RecoveryCodes({ codes, onAcknowledge }: RecoveryCodesProps) {
const [savedConfirmed, setSavedConfirmed] = useState(false);
const [copied, setCopied] = useState(false);
async function copyAll() {
await navigator.clipboard.writeText(codes.join("\n"));
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}
function downloadAll() {
const blob = new Blob([codes.join("\n") + "\n"], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "vantage-recovery-codes.txt";
a.click();
URL.revokeObjectURL(url);
}
return (
<div className="space-y-4">
<p className="text-sm text-text-secondary">
Save these recovery codes somewhere safe. Each can be used once if you lose access to your other factor. They are shown here exactly once.
</p>
<div className="grid grid-cols-2 gap-2 rounded-lg border border-border bg-surface-2 p-3 font-mono text-xs text-text-primary">
{codes.map((code) => (
<div key={code}>{code}</div>
))}
</div>
<div className="flex flex-wrap gap-2">
<Button type="button" variant="secondary" size="sm" onClick={copyAll}>
{copied ? "Copied" : "Copy all"}
</Button>
<Button type="button" variant="secondary" size="sm" onClick={downloadAll}>
Download as .txt
</Button>
</div>
<label className="flex items-center gap-2 text-sm text-text-secondary">
<input type="checkbox" checked={savedConfirmed} onChange={(e) => setSavedConfirmed(e.target.checked)} className="h-4 w-4 rounded border-border" />
I have saved these codes
</label>
<Button type="button" variant="primary" className="w-full justify-center" disabled={!savedConfirmed} onClick={onAcknowledge}>
Continue
</Button>
</div>
);
}
+64
View File
@@ -790,6 +790,70 @@ export const auth = {
},
};
export interface MePasskey {
id: string;
name: string;
created_at: string;
last_used_at?: string;
transports?: string[];
}
export interface MeMfaStatus {
totp_enabled: boolean;
passkeys: MePasskey[];
recovery_remaining: number;
/** The instance's require_mfa policy: a removal leaving no factor is refused. */
require_mfa: boolean;
/** False when an identity provider owns this user's authentication. */
applicable: boolean;
}
/**
* The signed-in user's own factors, at /api/me/*. Several of these are
* guarded by step-up and answer 403 `step_up_required`; that interception is
* handled globally elsewhere, not here.
*/
export const me = {
mfa(): Promise<MeMfaStatus> {
return request<MeMfaStatus>("/me/mfa");
},
totpSetup(): Promise<{ secret: string; otpauth_uri: string }> {
return request("/me/mfa/totp/setup", { method: "POST" });
},
totpConfirm(code: string): Promise<{ ok: true; recovery_codes?: string[] }> {
return request("/me/mfa/totp/confirm", { method: "POST", body: JSON.stringify({ code }) });
},
removeTotp(): Promise<void> {
return request<void>("/me/mfa/totp", { method: "DELETE" });
},
regenerateRecovery(): Promise<{ recovery_codes: string[] }> {
return request("/me/mfa/recovery/regenerate", { method: "POST" });
},
passkeyRegisterBegin(): Promise<{ publicKey: any; ceremony_id: string }> {
return request("/me/passkeys/begin", { method: "POST" });
},
passkeyRegisterFinish(ceremonyId: string, credential: unknown, name?: string): Promise<{ ok: true; recovery_codes?: string[] }> {
return request("/me/passkeys/finish", {
method: "POST",
body: JSON.stringify({ ceremony_id: ceremonyId, credential, name }),
});
},
renamePasskey(id: string, name: string): Promise<void> {
return request<void>(`/me/passkeys/${id}`, { method: "PATCH", body: JSON.stringify({ name }) });
},
deletePasskey(id: string): Promise<void> {
return request<void>(`/me/passkeys/${id}`, { method: "DELETE" });
},
};
export const api = {
listInstanceUsers(): Promise<InstanceUser[]> {
return request<InstanceUser[]>("/instance/users");