feat(web): step-up modal and MFA settings controls
Adds the global re-authentication modal for guarded routes and the owner/admin MFA controls on the settings page. request() in lib/api.ts now intercepts a 403 step_up_required response, awaits re-authentication through a callback registered by StepUpModal (lib/stepup.ts), and retries the original request exactly once. The modal offers TOTP, recovery code and password, since the webauthn step-up routes (/me/step-up/webauthn/begin and /finish) are not registered server-side yet; it omits the passkey option rather than calling a route that does not exist. me.stepUp posts one factor to /api/me/step-up. The settings page gains an owner-only "Require MFA" toggle and the members table gains an MFA column and a "Reset MFA" action, both routed through the existing PUT /api/settings and DELETE /api/org/users/:id/mfa.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { AuthProvider } from "@/components/AuthProvider";
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { StepUpModal } from "@/components/mfa/StepUpModal";
|
||||
|
||||
export default function AppLayout({
|
||||
children,
|
||||
@@ -9,6 +10,7 @@ export default function AppLayout({
|
||||
return (
|
||||
<AuthProvider>
|
||||
<AppShell>{children}</AppShell>
|
||||
<StepUpModal />
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -51,6 +51,18 @@ function DocumentIcon() {
|
||||
);
|
||||
}
|
||||
|
||||
function ShieldIcon() {
|
||||
return (
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function KeyIcon() {
|
||||
return (
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
|
||||
@@ -127,7 +139,7 @@ function SecretsTokenCard({ tokenSet, rotatedAt }: { tokenSet: boolean; rotatedA
|
||||
|
||||
export default function SettingsPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { instance, isAdmin } = useAuth();
|
||||
const { instance, isAdmin, user } = useAuth();
|
||||
|
||||
const { data: settings, isLoading } = useQuery({
|
||||
queryKey: ["settings"],
|
||||
@@ -145,6 +157,7 @@ export default function SettingsPage() {
|
||||
const [logRetentionDays, setLogRetentionDays] = useState(30);
|
||||
const [offlineChannelIds, setOfflineChannelIds] = useState<string[]>([]);
|
||||
const [apiTokenMaxDays, setApiTokenMaxDays] = useState(0);
|
||||
const [requireMfa, setRequireMfa] = useState(false);
|
||||
const toast = useToast();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -153,6 +166,7 @@ export default function SettingsPage() {
|
||||
setLogRetentionDays(settings.workflow_log_retention_days ?? 30);
|
||||
setOfflineChannelIds(settings.alerts.offline_channel_ids ?? []);
|
||||
setApiTokenMaxDays(settings.api_token_max_days ?? 0);
|
||||
setRequireMfa(settings.require_mfa ?? false);
|
||||
}, [settings]);
|
||||
|
||||
// The one place the in-progress form is turned into a payload. Both the
|
||||
@@ -235,6 +249,36 @@ export default function SettingsPage() {
|
||||
save({ ...currentPayload(), local_login_enabled: v });
|
||||
}}
|
||||
/>
|
||||
{user?.role === "owner" && (
|
||||
<SectionCard
|
||||
title="Require MFA"
|
||||
description="Require a second factor for every password sign-in on this instance."
|
||||
icon={<ShieldIcon />}
|
||||
>
|
||||
<label className="flex items-center gap-2 text-sm text-text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={requireMfa}
|
||||
onChange={(e) => {
|
||||
if (!settings) return;
|
||||
const v = e.target.checked;
|
||||
setRequireMfa(v);
|
||||
// Same in-progress form state the main Save button
|
||||
// submits, not the stale loaded `settings` object -
|
||||
// otherwise an unsaved edit elsewhere on this page is
|
||||
// silently reverted the moment this toggle is flipped.
|
||||
save({ ...currentPayload(), require_mfa: v });
|
||||
}}
|
||||
className="h-4 w-4 rounded-sm border-border bg-surface-2 accent-accent"
|
||||
/>
|
||||
Require MFA for password sign-in
|
||||
</label>
|
||||
<p className="mt-1.5 text-xs text-text-tertiary">
|
||||
Members without a second factor already set up must enrol one at their next sign-in. Members who sign in through
|
||||
a provider or a passkey are unaffected.
|
||||
</p>
|
||||
</SectionCard>
|
||||
)}
|
||||
</Group>
|
||||
|
||||
<Group label="Monitoring">
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { me } from "@/lib/api";
|
||||
import { registerStepUpPrompt } from "@/lib/stepup";
|
||||
import { Button, Modal, friendlyMessage } from "@/components/ui";
|
||||
|
||||
// The server may also offer "webauthn" (a passkey), but /me/step-up/webauthn
|
||||
// isn't wired up server-side yet, so this modal only ever offers the three
|
||||
// methods it can actually complete.
|
||||
const SUPPORTED = ["totp", "recovery", "password"] as const;
|
||||
type SupportedMethod = (typeof SUPPORTED)[number];
|
||||
|
||||
const LABELS: Record<SupportedMethod, string> = {
|
||||
totp: "Authenticator app",
|
||||
recovery: "Recovery code",
|
||||
password: "Password",
|
||||
};
|
||||
|
||||
const INPUT_LABELS: Record<SupportedMethod, string> = {
|
||||
totp: "6-digit code",
|
||||
recovery: "Recovery code",
|
||||
password: "Password",
|
||||
};
|
||||
|
||||
/**
|
||||
* Mounted once in the (app) layout. Registers itself as the step-up prompt on
|
||||
* mount, so `request()` in lib/api.ts can reach it without importing React.
|
||||
*/
|
||||
export function StepUpModal() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [methods, setMethods] = useState<SupportedMethod[]>([]);
|
||||
const [method, setMethod] = useState<SupportedMethod | null>(null);
|
||||
const [value, setValue] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const resolveRef = useRef<(() => void) | null>(null);
|
||||
const rejectRef = useRef<((e: Error) => void) | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
registerStepUpPrompt((requested) => {
|
||||
const supported = requested.filter((m): m is SupportedMethod => (SUPPORTED as readonly string[]).includes(m));
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
setMethods(supported);
|
||||
setMethod(supported[0] ?? null);
|
||||
setValue("");
|
||||
setError("");
|
||||
resolveRef.current = resolve;
|
||||
rejectRef.current = reject;
|
||||
setOpen(true);
|
||||
});
|
||||
});
|
||||
// Unregistering on unmount matches "no prompt registered fails rather
|
||||
// than hangs": outside the app shell there is nothing to reach.
|
||||
return () => registerStepUpPrompt(null);
|
||||
}, []);
|
||||
|
||||
function cancel(reason: string) {
|
||||
setOpen(false);
|
||||
rejectRef.current?.(new Error(reason));
|
||||
resolveRef.current = null;
|
||||
rejectRef.current = null;
|
||||
}
|
||||
|
||||
async function submit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!method) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const factor = method === "totp" ? { totp: value } : method === "recovery" ? { recovery: value } : { password: value };
|
||||
await me.stepUp(factor);
|
||||
setOpen(false);
|
||||
resolveRef.current?.();
|
||||
resolveRef.current = null;
|
||||
rejectRef.current = null;
|
||||
} catch (err) {
|
||||
setError(friendlyMessage(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal open={open} title="Confirm it's you" onClose={() => cancel("re-authentication was cancelled")}>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-text-secondary">This action reveals a credential, so please confirm it is you.</p>
|
||||
|
||||
{methods.length === 0 ? (
|
||||
<>
|
||||
<p className="text-sm text-danger">No supported re-authentication method is available for this account.</p>
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="secondary" onClick={() => cancel("no re-authentication method available")}>
|
||||
Close
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{methods.length > 1 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{methods.map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setMethod(m);
|
||||
setValue("");
|
||||
setError("");
|
||||
}}
|
||||
className={`rounded px-3 py-1.5 text-sm transition-colors ${
|
||||
method === m ? "bg-accent text-white" : "bg-surface-2 text-text-secondary hover:text-text-primary"
|
||||
}`}
|
||||
>
|
||||
{LABELS[m]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="step-up-value" className="mb-1.5 block text-sm font-medium text-text-secondary">
|
||||
{method ? INPUT_LABELS[method] : ""}
|
||||
</label>
|
||||
<input
|
||||
id="step-up-value"
|
||||
type={method === "password" ? "password" : "text"}
|
||||
inputMode={method === "totp" ? "numeric" : undefined}
|
||||
autoComplete={method === "password" ? "current-password" : "one-time-code"}
|
||||
autoFocus
|
||||
required
|
||||
maxLength={method === "totp" ? 6 : undefined}
|
||||
value={value}
|
||||
onChange={(e) => setValue(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"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && <div className="rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger">{error}</div>}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="ghost" onClick={() => cancel("re-authentication was cancelled")}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" loading={busy}>
|
||||
Confirm
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -38,6 +38,7 @@ export function MembersCard() {
|
||||
const toast = useToast();
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const [removing, setRemoving] = useState<Member | null>(null);
|
||||
const [resettingMfa, setResettingMfa] = useState<Member | null>(null);
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [role, setRole] = useState<Role>("member");
|
||||
@@ -84,6 +85,20 @@ export function MembersCard() {
|
||||
},
|
||||
});
|
||||
|
||||
const {
|
||||
mutate: resetMfa,
|
||||
isPending: isResettingMfa,
|
||||
error: resetMfaError,
|
||||
reset: resetResetMfa,
|
||||
} = useMutation({
|
||||
mutationFn: (member: Member) => api.resetMemberMFA(member.id),
|
||||
onSuccess: (_data, member) => {
|
||||
invalidate();
|
||||
toast.success(`Cleared MFA for ${member.email}.`);
|
||||
setResettingMfa(null);
|
||||
},
|
||||
});
|
||||
|
||||
// Removal failures are shown inside the confirm dialog that raised them, so
|
||||
// only the inline role change lands here - otherwise the same sentence
|
||||
// appears twice on screen.
|
||||
@@ -121,6 +136,7 @@ export function MembersCard() {
|
||||
<Th>Email</Th>
|
||||
<Th>Role</Th>
|
||||
<Th>Sign-in</Th>
|
||||
<Th>MFA</Th>
|
||||
<Th>Last login</Th>
|
||||
<Th className="text-right">Actions</Th>
|
||||
</Tr>
|
||||
@@ -158,6 +174,13 @@ export function MembersCard() {
|
||||
<Td label="Sign-in">
|
||||
<Badge variant="neutral">{u.auth_source === "oidc" ? "SSO" : u.auth_source === "hq" ? "Vantage HQ" : "Password"}</Badge>
|
||||
</Td>
|
||||
<Td label="MFA">
|
||||
{managedByHQ ? (
|
||||
<span className="text-xs text-text-tertiary">-</span>
|
||||
) : (
|
||||
<Badge variant={u.mfa_enabled ? "success" : "neutral"}>{u.mfa_enabled ? "Enabled" : "Not set up"}</Badge>
|
||||
)}
|
||||
</Td>
|
||||
<Td label="Last login" className="text-text-secondary">{u.last_login ? new Date(u.last_login).toLocaleString() : "Never"}</Td>
|
||||
<Td label="Actions" className="text-right">
|
||||
{managedByHQ ? (
|
||||
@@ -169,16 +192,29 @@ export function MembersCard() {
|
||||
<span className="text-xs text-text-tertiary">Managed in Vantage HQ</span>
|
||||
)
|
||||
) : (
|
||||
!locked && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-danger hover:text-danger"
|
||||
onClick={() => setRemoving({ id: u.user_id, email: u.email })}
|
||||
>
|
||||
Remove<span className="sr-only"> {u.email}</span>
|
||||
</Button>
|
||||
)
|
||||
<div className="flex justify-end gap-2">
|
||||
{/* Only an owner may reset an owner's MFA - the same rule the
|
||||
server enforces, so admins never see a button that would 403. */}
|
||||
{u.mfa_enabled && (isOwner || u.role !== "owner") && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setResettingMfa({ id: u.user_id, email: u.email })}
|
||||
>
|
||||
Reset MFA<span className="sr-only"> for {u.email}</span>
|
||||
</Button>
|
||||
)}
|
||||
{!locked && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-danger hover:text-danger"
|
||||
onClick={() => setRemoving({ id: u.user_id, email: u.email })}
|
||||
>
|
||||
Remove<span className="sr-only"> {u.email}</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Td>
|
||||
</Tr>
|
||||
@@ -212,6 +248,25 @@ export function MembersCard() {
|
||||
}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
open={resettingMfa !== null}
|
||||
title="Reset MFA"
|
||||
confirmLabel="Reset MFA"
|
||||
loading={isResettingMfa}
|
||||
error={resetMfaError ? friendlyMessage(resetMfaError) : null}
|
||||
onClose={() => {
|
||||
resetResetMfa();
|
||||
setResettingMfa(null);
|
||||
}}
|
||||
onConfirm={() => resettingMfa && resetMfa(resettingMfa)}
|
||||
body={
|
||||
<p>
|
||||
<span className="text-text-primary">{resettingMfa?.email}</span> loses every enrolled factor and recovery code. If this
|
||||
instance requires MFA for password sign-in, they must set up a new factor the next time they sign in.
|
||||
</p>
|
||||
}
|
||||
/>
|
||||
|
||||
<Modal open={addOpen} title="Add member" onClose={() => setAddOpen(false)}>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
|
||||
+43
-3
@@ -1,3 +1,5 @@
|
||||
import { requestStepUp } from "./stepup";
|
||||
|
||||
export type ServerStatus = "pending" | "active" | "offline";
|
||||
export type KeySource = "uploaded" | "generated";
|
||||
|
||||
@@ -297,6 +299,8 @@ export interface Settings {
|
||||
workflow_log_retention_days?: number | null;
|
||||
local_login_enabled?: boolean;
|
||||
api_token_max_days?: number | null;
|
||||
/** Owner-only: members without a factor must enrol at their next sign-in. */
|
||||
require_mfa?: boolean;
|
||||
}
|
||||
|
||||
export type ApiToken = {
|
||||
@@ -564,6 +568,7 @@ export interface InstanceUser {
|
||||
hq_user_id?: string;
|
||||
created_at: string;
|
||||
last_login?: string;
|
||||
mfa_enabled: boolean;
|
||||
}
|
||||
|
||||
export interface OrgUserInput {
|
||||
@@ -641,7 +646,10 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
/** RequestInit plus the internal flag that stops a step-up retry from looping. */
|
||||
type ApiRequestInit = RequestInit & { __retried?: boolean };
|
||||
|
||||
async function request<T>(path: string, options?: ApiRequestInit): Promise<T> {
|
||||
const res = await fetch(`/api${path}`, {
|
||||
credentials: "include",
|
||||
headers: {
|
||||
@@ -655,11 +663,28 @@ async function request<T>(path: string, options?: RequestInit): Promise<T> {
|
||||
const text = await res.text().catch(() => "");
|
||||
|
||||
let message = text || res.statusText || `HTTP ${res.status}`;
|
||||
let code: string | undefined;
|
||||
let methods: string[] | undefined;
|
||||
try {
|
||||
const body = JSON.parse(text);
|
||||
const body = JSON.parse(text || "{}");
|
||||
if (body?.error) message = body.error;
|
||||
if (body?.code) code = body.code;
|
||||
if (Array.isArray(body?.methods)) methods = body.methods;
|
||||
} catch {}
|
||||
throw new ApiError(res.status, message);
|
||||
|
||||
// A guarded route answers 403 with the factors that would satisfy it.
|
||||
// Re-authenticate once through the shared modal, then retry the
|
||||
// original request exactly once - a loop here would prompt forever
|
||||
// against a server that keeps refusing. This is outside the parse
|
||||
// try/catch above: a cancelled step-up rejects, and that rejection
|
||||
// must propagate, not be swallowed as a JSON parse failure.
|
||||
if (res.status === 403 && code === "step_up_required" && !options?.__retried) {
|
||||
await requestStepUp(methods ?? ["password"]);
|
||||
return request<T>(path, { ...options, __retried: true });
|
||||
}
|
||||
|
||||
const retryAfter = res.status === 429 ? Number(res.headers.get("Retry-After")) : undefined;
|
||||
throw new ApiError(res.status, message, code, Number.isFinite(retryAfter) ? retryAfter : undefined);
|
||||
}
|
||||
|
||||
if (res.status === 204) {
|
||||
@@ -852,6 +877,15 @@ export const me = {
|
||||
deletePasskey(id: string): Promise<void> {
|
||||
return request<void>(`/me/passkeys/${id}`, { method: "DELETE" });
|
||||
},
|
||||
|
||||
/**
|
||||
* Re-authenticates the current session against exactly one factor. Called
|
||||
* by the StepUpModal, and by `request()` internally never - the modal is
|
||||
* the only caller, so the retry-once guarantee lives entirely in `request`.
|
||||
*/
|
||||
stepUp(factor: { totp: string } | { recovery: string } | { password: string }): Promise<{ ok: true }> {
|
||||
return request("/me/step-up", { method: "POST", body: JSON.stringify(factor) });
|
||||
},
|
||||
};
|
||||
|
||||
export const api = {
|
||||
@@ -874,6 +908,11 @@ export const api = {
|
||||
return request<void>(`/instance/users/${userId}`, { method: "DELETE" });
|
||||
},
|
||||
|
||||
/** Owner or admin; an admin cannot reset an owner's MFA (403). Step-up guarded. */
|
||||
resetMemberMFA(userId: string): Promise<void> {
|
||||
return request<void>(`/org/users/${userId}/mfa`, { method: "DELETE" });
|
||||
},
|
||||
|
||||
listAuthPresets(): Promise<AuthPreset[]> {
|
||||
return request<AuthPreset[]>("/auth/presets");
|
||||
},
|
||||
@@ -1152,6 +1191,7 @@ export const api = {
|
||||
workflow_log_retention_days?: number | null;
|
||||
local_login_enabled?: boolean;
|
||||
api_token_max_days?: number | null;
|
||||
require_mfa?: boolean;
|
||||
}): Promise<{ saved: boolean }> {
|
||||
return request<{ saved: boolean }>("/settings", {
|
||||
method: "PUT",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// The step-up broker. `request()` in api.ts lives outside React, so it cannot
|
||||
// render a dialog itself; instead it calls back into whatever prompt the
|
||||
// StepUpModal registered when it mounted inside the (app) layout.
|
||||
|
||||
type Prompt = (methods: string[]) => Promise<void>;
|
||||
|
||||
let prompt: Prompt | null = null;
|
||||
|
||||
// The provider registers the real prompt at mount. Before that, or outside the
|
||||
// app shell, step-up simply fails rather than hanging forever.
|
||||
export function registerStepUpPrompt(fn: Prompt | null) {
|
||||
prompt = fn;
|
||||
}
|
||||
|
||||
export async function requestStepUp(methods: string[]): Promise<void> {
|
||||
if (!prompt) throw new Error("re-authentication is required");
|
||||
return prompt(methods);
|
||||
}
|
||||
Reference in New Issue
Block a user