Require two-factor authentication for admins and supervisors

Admins and supervisors without 2FA are sent a code at their next login,
and verifying it turns 2FA on. They can change the channel but not turn
it off. Older sessions without 2FA are rejected with TWO_FACTOR_REQUIRED,
and promoting a user ends their sessions so they enrol at next login.
The requirement is skipped when no email or WhatsApp channel can deliver
a code, and TWO_FACTOR_REQUIRED_ROLES=false switches it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 11:00:12 +02:00
co-authored by Claude Opus 5.5
parent 12832dea67
commit 3f3a8cad66
21 changed files with 356 additions and 55 deletions
+9
View File
@@ -117,6 +117,15 @@ export async function apiFetch<T = any>(path: string, options: ApiOptions = {}):
if (json?.message && typeof json.message === "string") message = json.message;
data = json;
} catch { /* not JSON — use raw text */ }
// An admin/supervisor session from before 2FA was required for their role:
// end it and send them to log in, where they enrol.
if (res.status === 401 && data?.code === "TWO_FACTOR_REQUIRED" && typeof window !== "undefined") {
localStorage.removeItem("hope_events_token");
if (!window.location.pathname.startsWith("/login")) {
const back = window.location.pathname + window.location.search;
window.location.href = `/login?reason=2fa&redirect=${encodeURIComponent(back)}`;
}
}
throw new ApiError(res.status, message, data);
}
const contentType = res.headers.get("content-type") || "";
+4
View File
@@ -7,6 +7,8 @@ export type AuthUser = {
notificationPreference?: "email" | "whatsapp" | "both";
twoFactorEnabled?: boolean;
twoFactorMethod?: TwoFactorMethod | null;
// True for roles that must use 2FA (admin, supervisor) — it can't be turned off.
twoFactorRequired?: boolean;
};
export type AuthResponse = AuthUser & {
@@ -24,6 +26,8 @@ export type TwoFactorChallenge = {
challengeId: string;
method: TwoFactorMethod;
destination: string;
// The role requires 2FA and it wasn't on yet: verifying this code turns it on.
enrolling?: boolean;
};
export function isTwoFactorChallenge(res: unknown): res is TwoFactorChallenge & { twoFactorRequired: true } {