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
+108 -4
View File
@@ -16,7 +16,9 @@ const RESEND_COOLDOWN_MS = 60 * 1000; // minimum gap between sends
const CHALLENGE_MAX_AGE_MS = 30 * 60 * 1000; // after this, log in again rather than resend
const TRUSTED_DEVICE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const METHODS = ['email', 'whatsapp'];
// 2.3.0: 'authenticator' — codes from an app (TOTP, utils/totp.js); nothing is sent.
const METHODS = ['email', 'whatsapp', 'authenticator'];
const RECOVERY_CODE_COUNT = 10;
// Roles that must use two-factor authentication.
const REQUIRED_ROLES = ['admin', 'supervisor'];
@@ -67,9 +69,75 @@ async function availableMethods(user) {
const methods = [];
if (hasRealEmail(user)) methods.push('email');
if (isValidZAPhone(user?.phoneNumber) && (await isConfigured())) methods.push('whatsapp');
// An authenticator app needs nothing from the site, so it's always possible.
methods.push('authenticator');
return methods;
}
// ─── Authenticator app (2.3.0) ───────────────────────────────────────────────
const totp = require('./totp');
const { encrypt, decrypt } = require('./encryption');
/** A new secret for setting up an app, with the link and text to show (not saved yet). */
function newAuthenticatorSecret(user) {
const { getSettingSync } = require('./settingsCache');
const issuer = getSettingSync('org_name', process.env.ORG_NAME || 'Cross Events');
const secret = totp.generateSecret();
return { secret, otpauthUrl: totp.otpauthUrl(secret, user.email, issuer) };
}
// Recovery codes: xxxxx-xxxxx from an alphabet without look-alikes; stored as an HMAC.
const RECOVERY_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';
const normaliseRecovery = (code) => String(code || '').toLowerCase().replace(/[^a-z0-9]/g, '');
const hashRecovery = (code) => hmac(`2fa-recovery:${normaliseRecovery(code)}`);
const looksLikeRecoveryCode = (code) => normaliseRecovery(code).length === 10;
function randomRecoveryCode() {
let s = '';
for (let i = 0; i < 10; i++) s += RECOVERY_ALPHABET[crypto.randomInt(0, RECOVERY_ALPHABET.length)];
return `${s.slice(0, 5)}-${s.slice(5)}`;
}
/** A new set of recovery codes (the old ones stop working). Returns the codes to show once. */
async function replaceRecoveryCodes(userId, db = prisma) {
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, randomRecoveryCode);
await db.recoveryCode.deleteMany({ where: { userId } });
await db.recoveryCode.createMany({ data: codes.map(c => ({ userId, codeHash: hashRecovery(c) })) });
return codes;
}
async function recoveryCodesLeft(userId) {
return prisma.recoveryCode.count({ where: { userId, usedAt: null } });
}
/** Uses a recovery code if it's one of this user's unused ones (single use, race-safe). */
async function useRecoveryCode(userId, code) {
if (!looksLikeRecoveryCode(code)) return false;
const used = await prisma.recoveryCode.updateMany({ where: { userId, codeHash: hashRecovery(code), usedAt: null }, data: { usedAt: new Date() } });
return used.count === 1;
}
/**
* Checks an app code against `secret` and records its step, so the same code can't be used again
* (the update only succeeds if no later step was recorded meanwhile).
*/
async function useAuthenticatorCode(user, secret, code) {
const step = totp.matchStep(secret, code, { afterStep: user.totpLastStep ?? -1 });
if (step === null) return false;
const saved = await prisma.user.updateMany({
where: { id: user.id, OR: [{ totpLastStep: null }, { totpLastStep: { lt: step } }] },
data: { totpLastStep: step },
});
return saved.count === 1;
}
/** Turns 2FA off completely: the app's secret and the recovery codes go too. */
async function clearTwoFactor(userId, db = prisma) {
await db.recoveryCode.deleteMany({ where: { userId } });
return { twoFactorEnabled: false, twoFactorMethod: null, totpSecret: null, totpLastStep: null };
}
/**
* True when this user's role must use two-factor authentication.
* TWO_FACTOR_REQUIRED_ROLES=false turns the requirement off (break-glass).
@@ -143,6 +211,20 @@ async function deliverCode(user, method, code, { allowFallback = true } = {}) {
* purpose for this user is discarded, so only the newest code works.
*/
async function createChallenge(user, purpose, method, options) {
if (method === 'authenticator') {
// Nothing is sent: the code comes from the app. Setting it up carries the new secret,
// encrypted, until the first code proves the app has it.
const setup = purpose === 'enable' ? newAuthenticatorSecret(user) : null;
// (Looked up here: the user passed in may be a selection that leaves the secret out.)
if (purpose !== 'enable' && !(await prisma.user.findUnique({ where: { id: user.id }, select: { totpSecret: true } }))?.totpSecret) {
throw fail('No authenticator app is set up for this account.', 400);
}
await prisma.twoFactorChallenge.deleteMany({ where: { userId: user.id, purpose } });
const challenge = await prisma.twoFactorChallenge.create({
data: { userId: user.id, purpose, method: 'authenticator', codeHash: '', pendingSecret: setup ? encrypt(setup.secret) : null, expiresAt: new Date(Date.now() + CODE_TTL_MS) },
});
return { challengeId: challenge.id, method: 'authenticator', destination: 'your authenticator app', ...(setup ? { secret: setup.secret, otpauthUrl: setup.otpauthUrl } : {}) };
}
const code = generateCode();
const sent = await deliverCode(user, method, code, options);
@@ -185,9 +267,23 @@ async function verifyChallenge(challengeId, code, purpose, userId) {
if (counted.count !== 1) throw invalid();
const challenge = await prisma.twoFactorChallenge.findUnique({ where: { id: challengeId }, include: { user: true } });
if (!challenge || !safeEqual(challenge.codeHash, hashCode(submitted))) {
let ok = false;
let usedRecoveryCode = false;
if (challenge?.method === 'authenticator') {
const stored = purpose === 'enable' ? challenge.pendingSecret : challenge.user?.totpSecret;
ok = !!stored && (await useAuthenticatorCode(challenge.user, decrypt(stored), submitted));
} else if (challenge) {
ok = safeEqual(challenge.codeHash, hashCode(submitted));
}
// At sign-in, a recovery code works in place of any code (2.3.0).
if (!ok && challenge && purpose === 'login' && challenge.user?.twoFactorEnabled && (await useRecoveryCode(challenge.userId, code))) {
ok = true;
usedRecoveryCode = true;
}
if (!ok) {
const left = challenge ? MAX_ATTEMPTS - challenge.attempts : 0;
throw fail(left > 0 ? `Incorrect code. ${left} attempt${left === 1 ? '' : 's'} left.` : 'Too many incorrect attempts. Please request a new code.');
const again = challenge?.method === 'authenticator' ? 'Please log in again.' : 'Please request a new code.';
throw fail(left > 0 ? `Incorrect code. ${left} attempt${left === 1 ? '' : 's'} left.` : `Too many incorrect attempts. ${again}`);
}
// Single use — if two requests race with the right code, only one wins.
@@ -197,7 +293,7 @@ async function verifyChallenge(challengeId, code, purpose, userId) {
});
if (used.count !== 1) throw invalid();
return challenge;
return { ...challenge, usedRecoveryCode };
}
/** Replaces the code on an existing challenge and sends it again. */
@@ -208,6 +304,7 @@ async function resendChallenge(challengeId, purpose, userId) {
const challenge = await prisma.twoFactorChallenge.findUnique({ where: { id: challengeId }, include: { user: true } });
if (!challenge || challenge.purpose !== purpose || challenge.usedAt || (userId && challenge.userId !== userId)) throw expired();
if (Date.now() - challenge.createdAt.getTime() > CHALLENGE_MAX_AGE_MS) throw expired();
if (challenge.method === 'authenticator') throw fail('Nothing is sent for an authenticator app: open the app for the current code, or use one of your recovery codes.');
const wait = RESEND_COOLDOWN_MS - (Date.now() - challenge.lastSentAt.getTime());
if (wait > 0) throw fail(`Please wait ${Math.ceil(wait / 1000)} seconds before requesting another code.`, 429);
@@ -264,6 +361,13 @@ async function clearTrustedDevices(userId) {
module.exports = {
METHODS,
RECOVERY_CODE_COUNT,
replaceRecoveryCodes,
recoveryCodesLeft,
useRecoveryCode,
useAuthenticatorCode,
clearTwoFactor,
newAuthenticatorSecret,
REQUIRED_ROLES,
requiresTwoFactor,
enforcementMethod,