Events 2.3.0 (phase 1c): two-factor with an authenticator app, recovery codes
- TOTP (RFC 6238) next to email and WhatsApp: QR code and key to set up, the app's first code confirms it, a code can't be used twice, nothing is sent. The secret is stored encrypted. - 10 single-use recovery codes whenever two-factor is turned on, shown once; accepted at sign-in in place of any code; a new set on request. - Admins see each account's method; Reset 2FA clears the app and codes. - Profile & Security, sign-in and Users pages; API types; 10 new tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -23,6 +23,7 @@ interface UserItem {
|
||||
phoneNumber?: string | null;
|
||||
notificationPreference?: string;
|
||||
twoFactorEnabled?: boolean;
|
||||
twoFactorMethod?: "email" | "whatsapp" | "authenticator" | null;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -34,6 +35,8 @@ type Role = typeof roleOptions[number];
|
||||
const notificationPreferenceOptions = ["email", "whatsapp", "both"] as const;
|
||||
|
||||
|
||||
const TWO_FACTOR_LABEL: Record<"email" | "whatsapp" | "authenticator", string> = { email: "email", whatsapp: "WhatsApp", authenticator: "app" };
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const { user, loading, token } = useAuth();
|
||||
const router = useRouter();
|
||||
@@ -418,6 +421,9 @@ export default function AdminUsersPage() {
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<RoleBadge role={u.role as RoleBadgeRole} />
|
||||
<div className="mt-1 text-xs text-gray-500" title="How their sign-in codes come">
|
||||
{u.twoFactorEnabled ? `2FA: ${TWO_FACTOR_LABEL[u.twoFactorMethod || "email"]}` : "No 2FA"}
|
||||
</div>
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<span>{u.phoneNumber || ""}</span>
|
||||
|
||||
@@ -14,17 +14,19 @@ import { useCampuses } from "@/hooks/useCampuses";
|
||||
import { apiV2, apiV2Data } from "@/lib/apiV2";
|
||||
import { useStateSync } from "@/lib/hooks";
|
||||
|
||||
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string };
|
||||
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled" | "recovery_code_used" | "recovery_codes_replaced"; device: string | null; createdAt: string };
|
||||
|
||||
const ACTIVITY_META: Record<ActivityEvent["type"], { label: (device: string | null) => string; icon: typeof LogIn }> = {
|
||||
login: { label: d => `Logged in${d ? ` from ${d}` : ""}`, icon: LogIn },
|
||||
password_changed: { label: () => "Password changed", icon: KeyRound },
|
||||
password_reset: { label: () => "Password reset via email link", icon: RotateCcw },
|
||||
two_factor_enabled: { label: () => "Two-factor authentication turned on", icon: ShieldCheck },
|
||||
recovery_code_used: { label: () => "Logged in with a recovery code", icon: ShieldAlert },
|
||||
recovery_codes_replaced: { label: () => "New recovery codes made", icon: ShieldCheck },
|
||||
two_factor_disabled: { label: () => "Two-factor authentication turned off", icon: ShieldOff },
|
||||
};
|
||||
|
||||
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp" };
|
||||
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp", authenticator: "an authenticator app" };
|
||||
|
||||
// Shared bits of the page (outside the component, so they aren't new components each render).
|
||||
const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
|
||||
@@ -185,12 +187,16 @@ export default function UserProfilePage() {
|
||||
// loaded once per page load, so it wouldn't reflect a change made here.
|
||||
const [tfEnabled, setTfEnabled] = useState(false);
|
||||
const [tfMethod, setTfMethod] = useState<TwoFactorMethod>("email");
|
||||
const [tfStep, setTfStep] = useState<"idle" | "code" | "disable" | "change">("idle");
|
||||
const [tfStep, setTfStep] = useState<"idle" | "code" | "disable" | "change" | "recovery">("idle");
|
||||
const [tfPassword, setTfPassword] = useState("");
|
||||
const [tfCode, setTfCode] = useState("");
|
||||
const [tfChallenge, setTfChallenge] = useState<TwoFactorChallenge | null>(null);
|
||||
const [tfMsg, setTfMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
|
||||
const [tfBusy, setTfBusy] = useState(false);
|
||||
// 2.3.0: recovery codes just made (shown once), how many are left, and the setup QR code.
|
||||
const [tfRecovery, setTfRecovery] = useState<string[] | null>(null);
|
||||
const [tfRecoveryLeft, setTfRecoveryLeft] = useState(0);
|
||||
const [tfQr, setTfQr] = useState<{ url: string; image: string } | null>(null);
|
||||
|
||||
// WhatsApp codes need the number that's actually saved, not one still being typed.
|
||||
const canWhatsAppCodes = isValidZAPhone(user?.phoneNumber || "");
|
||||
@@ -201,9 +207,19 @@ export default function UserProfilePage() {
|
||||
if (user) {
|
||||
setTfEnabled(!!user.twoFactorEnabled);
|
||||
setTfMethod(user.twoFactorMethod || "email");
|
||||
setTfRecoveryLeft((user as { recoveryCodesLeft?: number }).recoveryCodesLeft ?? 0);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// The setup QR code, drawn here from the otpauth:// link (the key never leaves the browser).
|
||||
useEffect(() => {
|
||||
const url = tfChallenge?.otpauthUrl;
|
||||
if (!url) return;
|
||||
let alive = true;
|
||||
import("qrcode").then(q => q.toDataURL(url, { margin: 1, width: 200 })).then(image => { if (alive) setTfQr({ url, image }); }).catch(() => {});
|
||||
return () => { alive = false; };
|
||||
}, [tfChallenge]);
|
||||
|
||||
const resetTwoFactorForm = () => {
|
||||
setTfStep("idle");
|
||||
setTfPassword("");
|
||||
@@ -241,12 +257,14 @@ export default function UserProfilePage() {
|
||||
const res = await (apiV2Data("post", "/me/two-factor/confirm", {
|
||||
authToken: token,
|
||||
body: { challengeId: tfChallenge.challengeId, code: tfCode },
|
||||
}) as Promise<{ twoFactorMethod: TwoFactorMethod }>);
|
||||
}) as Promise<{ twoFactorMethod: TwoFactorMethod; recoveryCodes?: string[] }>);
|
||||
const wasEnabled = tfEnabled;
|
||||
setTfEnabled(true);
|
||||
setTfMethod(res.twoFactorMethod);
|
||||
resetTwoFactorForm();
|
||||
setTfMsg({ type: "ok", text: wasEnabled ? `Codes will now be sent by ${TWO_FACTOR_METHOD_LABEL[res.twoFactorMethod]}.` : "Two-factor authentication is on." });
|
||||
setTfRecovery(res.recoveryCodes ?? null);
|
||||
setTfRecoveryLeft(res.recoveryCodes?.length ?? 0);
|
||||
setTfMsg({ type: "ok", text: wasEnabled ? `Your codes now come from ${TWO_FACTOR_METHOD_LABEL[res.twoFactorMethod]}.` : "Two-factor authentication is on." });
|
||||
loadActivity();
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Failed to verify the code." });
|
||||
@@ -255,6 +273,35 @@ export default function UserProfilePage() {
|
||||
}
|
||||
};
|
||||
|
||||
const newRecoveryCodes = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!token) return;
|
||||
setTfBusy(true);
|
||||
setTfMsg(null);
|
||||
try {
|
||||
const res = await (apiV2Data("post", "/me/two-factor/recovery-codes", { authToken: token, body: { password: tfPassword } }) as Promise<{ recoveryCodes: string[] }>);
|
||||
resetTwoFactorForm();
|
||||
setTfRecovery(res.recoveryCodes);
|
||||
setTfRecoveryLeft(res.recoveryCodes.length);
|
||||
loadActivity();
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Couldn't make new recovery codes." });
|
||||
} finally {
|
||||
setTfBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadRecovery = () => {
|
||||
if (!tfRecovery) return;
|
||||
const text = `Recovery codes for ${user?.email || "your account"} (${window.location.host})\nEach works once, in place of a code, if you lose your phone or app.\n\n${tfRecovery.join("\n")}\n`;
|
||||
const url = URL.createObjectURL(new Blob([text], { type: "text/plain" }));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "recovery-codes.txt";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const disableTwoFactor = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!token) return;
|
||||
@@ -266,6 +313,7 @@ export default function UserProfilePage() {
|
||||
body: { password: tfPassword },
|
||||
});
|
||||
setTfEnabled(false);
|
||||
setTfRecoveryLeft(0);
|
||||
resetTwoFactorForm();
|
||||
setTfMsg({ type: "ok", text: "Two-factor authentication is off." });
|
||||
loadActivity();
|
||||
@@ -424,9 +472,20 @@ export default function UserProfilePage() {
|
||||
|
||||
{tfStep === "code" && tfChallenge ? (
|
||||
<form onSubmit={confirmEnableTwoFactor} className="space-y-4">
|
||||
<p className="text-sm text-gray-500">
|
||||
We sent a 6-digit code to {tfChallenge.destination} by {TWO_FACTOR_METHOD_LABEL[tfChallenge.method]}. {tfEnabled ? "Enter it to switch your codes to this channel." : "Enter it to finish turning on two-factor authentication."}
|
||||
</p>
|
||||
{tfChallenge.method === "authenticator" ? (
|
||||
<div className="space-y-3 text-sm text-gray-600">
|
||||
<p>Scan this with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password, Authy…), then enter the 6-digit code it shows.</p>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- a data: URL drawn in the browser */}
|
||||
{tfQr && tfQr.url === tfChallenge.otpauthUrl && <img src={tfQr.image} alt="QR code to add this account to an authenticator app" width={200} height={200} className="rounded border" />}
|
||||
{tfChallenge.secret && (
|
||||
<p className="text-xs">Can't scan it? Type this key into the app: <code className="select-all break-all rounded bg-gray-100 px-1 py-0.5 font-mono">{tfChallenge.secret.replace(/(.{4})/g, "$1 ").trim()}</code></p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">
|
||||
We sent a 6-digit code to {tfChallenge.destination} by {TWO_FACTOR_METHOD_LABEL[tfChallenge.method]}. {tfEnabled ? "Enter it to switch your codes to this channel." : "Enter it to finish turning on two-factor authentication."}
|
||||
</p>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="profile-verification-code" className="block text-sm font-medium text-gray-700 mb-1">Verification code</label>
|
||||
<input
|
||||
@@ -446,16 +505,32 @@ export default function UserProfilePage() {
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" disabled={tfBusy || tfCode.length !== 6} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||||
{tfBusy ? "Verifying…" : "Turn on two-factor"}
|
||||
{tfBusy ? "Verifying…" : tfEnabled ? "Switch" : "Turn on two-factor"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : tfEnabled && tfStep !== "change" ? (
|
||||
<>
|
||||
<p className="text-sm text-gray-500 mb-4">
|
||||
<span className="font-medium text-green-700">On.</span> When you log in we send a 6-digit code by{" "}
|
||||
{TWO_FACTOR_METHOD_LABEL[tfMethod]}. Devices you've chosen to trust skip the code for 30 days.
|
||||
<span className="font-medium text-green-700">On.</span>{" "}
|
||||
{tfMethod === "authenticator" ? "When you log in, enter the 6-digit code from your authenticator app." : <>When you log in we send a 6-digit code by {TWO_FACTOR_METHOD_LABEL[tfMethod]}.</>}{" "}
|
||||
Devices you've chosen to trust skip the code for 30 days.
|
||||
</p>
|
||||
<div className="mb-4 rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm">
|
||||
<p className="text-gray-700"><span className="font-medium">Recovery codes:</span> {tfRecoveryLeft} of 10 left. Each works once in place of a code if you lose your phone or app.</p>
|
||||
{tfStep === "recovery" ? (
|
||||
<form onSubmit={newRecoveryCodes} className="mt-3 flex flex-wrap items-end gap-2">
|
||||
<div className="flex-1 min-w-[12rem]">
|
||||
<label htmlFor="profile-recovery-password" className="block text-xs font-medium text-gray-700 mb-1">Confirm with your password</label>
|
||||
<input id="profile-recovery-password" type="password" className={inputCls} value={tfPassword} onChange={e => setTfPassword(e.target.value)} required autoComplete="current-password" />
|
||||
</div>
|
||||
<button type="button" onClick={resetTwoFactorForm} className="px-3 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">Cancel</button>
|
||||
<button type="submit" disabled={tfBusy || !tfPassword} className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">{tfBusy ? "Making…" : "Make new codes"}</button>
|
||||
</form>
|
||||
) : (
|
||||
<button onClick={() => { setTfStep("recovery"); setTfPassword(""); setTfMsg(null); }} className="mt-2 text-sm text-brand-700 hover:underline">New recovery codes…</button>
|
||||
)}
|
||||
</div>
|
||||
{tfRequired ? (
|
||||
<>
|
||||
<p className="text-xs text-gray-500 mb-3">Required for your role, so it can't be turned off.</p>
|
||||
@@ -495,11 +570,12 @@ export default function UserProfilePage() {
|
||||
<p className="text-sm text-gray-500">
|
||||
{tfEnabled
|
||||
? "Choose where your login codes go. We'll send a code there first to check it reaches you."
|
||||
: "Add a second step to logging in: after your password, we send a 6-digit code that you need to enter."}
|
||||
: "Add a second step to logging in: after your password, a 6-digit code from an authenticator app, or one we send you."}
|
||||
</p>
|
||||
<div>
|
||||
<label htmlFor="profile-send-my-codes-by" className="block text-sm font-medium text-gray-700 mb-1">Send my codes by</label>
|
||||
<select id="profile-send-my-codes-by" className={inputCls} value={tfMethod} onChange={e => setTfMethod(e.target.value as TwoFactorMethod)}>
|
||||
<option value="authenticator">An authenticator app (most secure)</option>
|
||||
<option value="email">Email</option>
|
||||
{canWhatsAppCodes && <option value="whatsapp">WhatsApp</option>}
|
||||
</select>
|
||||
@@ -518,11 +594,23 @@ export default function UserProfilePage() {
|
||||
</button>
|
||||
)}
|
||||
<button type="submit" disabled={tfBusy || !tfPassword} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||||
{tfBusy ? "Sending code…" : "Send verification code"}
|
||||
{tfBusy ? (tfMethod === "authenticator" ? "Preparing…" : "Sending code…") : tfMethod === "authenticator" ? "Set up the app" : "Send verification code"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{tfRecovery && (
|
||||
<div className="mt-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-sm" role="region" aria-label="Your recovery codes">
|
||||
<p className="font-medium text-amber-900">Save your recovery codes now</p>
|
||||
<p className="mt-1 text-amber-900">Each works once, in place of a code, if you lose your phone or app. They won't be shown again.</p>
|
||||
<ul className="mt-3 grid grid-cols-2 gap-x-6 gap-y-1 font-mono text-sm sm:grid-cols-3">{tfRecovery.map(c => <li key={c}>{c}</li>)}</ul>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" onClick={downloadRecovery} className="px-3 py-2 rounded-lg bg-white border border-amber-300 text-sm font-medium hover:bg-amber-100">Download</button>
|
||||
<button type="button" onClick={() => navigator.clipboard?.writeText(tfRecovery.join("\n"))} className="px-3 py-2 rounded-lg bg-white border border-amber-300 text-sm font-medium hover:bg-amber-100">Copy</button>
|
||||
<button type="button" onClick={() => setTfRecovery(null)} className="px-3 py-2 rounded-lg bg-amber-600 text-white text-sm font-medium hover:bg-amber-700">I've saved them</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tfMsg && <Alert msg={tfMsg} />}
|
||||
</section>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user