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:
2026-11-17 14:55:22 +02:00
co-authored by Claude Opus 5.5
parent b207d17db8
commit ee65ff358c
18 changed files with 815 additions and 60 deletions
@@ -11,6 +11,9 @@ const {
resendChallenge,
clearTrustedDevices,
requiresTwoFactor,
replaceRecoveryCodes,
recoveryCodesLeft,
clearTwoFactor,
} = require('../utils/twoFactor');
// ─── Helpers ────────────────────────────────────────────────────────────────
@@ -99,7 +102,7 @@ const startEnableTwoFactor = async (req, res) => {
}
if (!TWO_FACTOR_METHODS.includes(method)) {
res.status(400);
throw new Error('Choose email or WhatsApp for your verification codes');
throw new Error('Choose email, WhatsApp or an authenticator app for your verification codes');
}
if (!(await availableMethods(user)).includes(method)) {
res.status(400);
@@ -109,7 +112,8 @@ const startEnableTwoFactor = async (req, res) => {
}
// Unlike login, don't fall back to email here — the point of this step is to
// prove the channel the user picked actually reaches them.
// prove the channel the user picked actually reaches them. For an authenticator app the
// answer carries the secret and its otpauth:// link (shown as a QR code) until confirmed.
res.json(await createChallenge(user, 'enable', method, { allowFallback: false }));
} catch (error) {
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
@@ -124,13 +128,20 @@ const confirmEnableTwoFactor = async (req, res) => {
const { challengeId, code } = req.body || {};
const challenge = await verifyChallenge(challengeId, code, 'enable', req.user.id);
// An authenticator app: the confirmed secret is kept (encrypted). Another method: any app is
// forgotten. Either way a fresh set of recovery codes, shown once (2.3.0).
await prisma.user.update({
where: { id: req.user.id },
data: { twoFactorEnabled: true, twoFactorMethod: challenge.method, updatedAt: new Date() },
data: {
twoFactorEnabled: true, twoFactorMethod: challenge.method, updatedAt: new Date(),
...(challenge.method === 'authenticator' ? { totpSecret: challenge.pendingSecret } : { totpSecret: null, totpLastStep: null }),
},
});
await prisma.twoFactorChallenge.update({ where: { id: challenge.id }, data: { pendingSecret: null } }).catch(() => {});
const recoveryCodes = await replaceRecoveryCodes(req.user.id);
logSecurityEvent({ userId: req.user.id, type: 'two_factor_enabled', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
res.json({ twoFactorEnabled: true, twoFactorMethod: challenge.method });
res.json({ twoFactorEnabled: true, twoFactorMethod: challenge.method, recoveryCodes });
} catch (error) {
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
}
@@ -157,7 +168,7 @@ const disableTwoFactor = async (req, res) => {
await prisma.user.update({
where: { id: user.id },
data: { twoFactorEnabled: false, twoFactorMethod: null, updatedAt: new Date() },
data: { ...(await clearTwoFactor(user.id)), updatedAt: new Date() },
});
await clearTrustedDevices(user.id);
if (user.twoFactorEnabled) {
@@ -170,6 +181,27 @@ const disableTwoFactor = async (req, res) => {
}
};
// @desc A new set of recovery codes (the old ones stop working), shown once (2.3.0)
// @route POST /api/v2/me/two-factor/recovery-codes
// @access Private
const replaceMyRecoveryCodes = async (req, res) => {
try {
const { password } = req.body || {};
const user = await prisma.user.findUnique({ where: { id: req.user.id } });
if (!user) { res.status(404); throw new Error('User not found'); }
if (!user.twoFactorEnabled) { res.status(400); throw new Error('Turn on two-factor authentication first.'); }
if (typeof password !== 'string' || !(await comparePassword(password, user.password))) {
res.status(400);
throw new Error('Incorrect password');
}
const recoveryCodes = await replaceRecoveryCodes(user.id);
logSecurityEvent({ userId: user.id, type: 'recovery_codes_replaced', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
res.json({ recoveryCodes });
} catch (error) {
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
}
};
// @desc Re-confirm the logged-in user's password without starting a new session
// (the self-service kiosk uses this before letting the event be changed)
// @route POST /api/users/verify-password
@@ -220,7 +252,7 @@ const getUserProfile = async (req, res) => {
const noticePromptPending = !req.impersonation && await require('../utils/privacyNotice').noticePromptPending({ noticeVersionAccepted });
// Campus-scoped staff: the campuses they're limited to (null = every campus).
const campusScope = (await require('../utils/campusScope').scopeFor(req))?.campusIds || null;
res.json({ ...rest, twoFactorRequired: requiresTwoFactor(user), newsPromptPending: !newsAskedAt && !req.impersonation, noticePromptPending, campusScope });
res.json({ ...rest, twoFactorRequired: requiresTwoFactor(user), recoveryCodesLeft: user.twoFactorEnabled ? await recoveryCodesLeft(user.id) : 0, newsPromptPending: !newsAskedAt && !req.impersonation, noticePromptPending, campusScope });
} else {
res.status(404);
throw new Error('User not found');
@@ -253,7 +285,7 @@ const getUsers = async (req, res) => {
const select = {
id: true, name: true, email: true, role: true,
phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, createdAt: true, updatedAt: true, isActive: true
phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, twoFactorMethod: true, createdAt: true, updatedAt: true, isActive: true
};
// Build filters
@@ -406,8 +438,8 @@ const updateUser = async (req, res) => {
// but never on — enabling requires the user to prove the channel themselves.
const resetTwoFactor = twoFactorEnabled === false && user.twoFactorEnabled;
if (resetTwoFactor) {
data.twoFactorEnabled = false;
data.twoFactorMethod = null;
// The app's secret and the recovery codes go too (2.3.0).
Object.assign(data, await clearTwoFactor(user.id));
}
// Promoted to a role that requires 2FA without having it: end their sessions
@@ -443,6 +475,7 @@ const updateUser = async (req, res) => {
phoneNumber: true,
notificationPreference: true,
twoFactorEnabled: true,
twoFactorMethod: true,
createdAt: true,
updatedAt: true,
isActive: true,
@@ -820,6 +853,7 @@ module.exports = {
startEnableTwoFactor,
confirmEnableTwoFactor,
disableTwoFactor,
replaceMyRecoveryCodes,
verifyPassword,
getUserProfile,
updateUserProfile,