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
@@ -14,3 +14,5 @@ CREATE TABLE "RecoveryCode" (
CREATE UNIQUE INDEX "RecoveryCode_codeHash_key" ON "RecoveryCode"("codeHash");
CREATE INDEX "RecoveryCode_userId_idx" ON "RecoveryCode"("userId");
ALTER TABLE "RecoveryCode" ADD CONSTRAINT "RecoveryCode_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TYPE "SecurityEventType" ADD VALUE 'recovery_code_used';
ALTER TYPE "SecurityEventType" ADD VALUE 'recovery_codes_replaced';
+3
View File
@@ -52,6 +52,9 @@ enum SecurityEventType {
password_reset
two_factor_enabled
two_factor_disabled
// 2.3.0: a recovery code signed in (the app or phone may be lost); a new set was made.
recovery_code_used
recovery_codes_replaced
}
enum TwoFactorMethod {
@@ -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,
+6 -1
View File
@@ -16,7 +16,8 @@ const auth = require('../config/auth') as {
};
const twoFactor = require('../utils/twoFactor') as {
createChallenge(user: any, purpose: string, method: string): Promise<{ challengeId: string; method: string; destination: string | null }>;
verifyChallenge(challengeId: string, code: string, purpose: string): Promise<{ userId: string; method: string }>;
verifyChallenge(challengeId: string, code: string, purpose: string): Promise<{ userId: string; method: string; usedRecoveryCode?: boolean }>;
recoveryCodesLeft(userId: string): Promise<number>;
issueTrustedDevice(userId: string, userAgent?: string): Promise<string>;
isTrustedDevice(userId: string, deviceToken?: string): Promise<boolean>;
clearTrustedDevices(userId: string): Promise<unknown>;
@@ -279,6 +280,10 @@ export async function verifyLoginCode(input: { challengeId: string; code: string
user = await prisma.user.update({ where: { id: user.id }, data: { twoFactorEnabled: true, twoFactorMethod: challenge.method as 'email' | 'whatsapp', updatedAt: new Date() }, select: LOGIN_USER_SELECT });
logSecurityEvent({ userId: user.id, type: 'two_factor_enabled', ip: info.ip, userAgent: info.userAgent }).catch(() => {});
}
// 2.3.0: a recovery code was used instead (the app or phone may be lost): it's in the activity log.
if (challenge.usedRecoveryCode) {
logSecurityEvent({ userId: user.id, type: 'recovery_code_used', ip: info.ip, userAgent: info.userAgent }).catch(() => {});
}
const extra = input.rememberDevice === true ? { deviceToken: await twoFactor.issueTrustedDevice(user.id, info.userAgent) } : {};
return completeLogin(user, info, extra);
}
+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,
+2
View File
@@ -51,6 +51,8 @@ export const user = obj({
role: z.enum(['admin', 'supervisor', 'staff', 'user']),
isActive: optBool,
notificationPreference: z.enum(['email', 'whatsapp', 'both']).nullish(),
twoFactorEnabled: optBool,
twoFactorMethod: z.enum(['email', 'whatsapp', 'authenticator']).nullish().describe('How their sign-in codes come (2.3.0: authenticator = an app)'),
homeCampusId: optStr,
createdAt: optDate,
});
+5 -1
View File
@@ -26,7 +26,7 @@ const toMe = (u: MeRow): z.input<typeof me> => ({
});
/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */
const { requiresTwoFactor } = require('../../utils/twoFactor') as { requiresTwoFactor(user: object): boolean };
const { requiresTwoFactor, recoveryCodesLeft } = require('../../utils/twoFactor') as { requiresTwoFactor(user: object): boolean; recoveryCodesLeft(userId: string): Promise<number> };
const privacyNotice = require('../../utils/privacyNotice') as { noticePromptPending(u: { noticeVersionAccepted: unknown }): Promise<false | 'first' | 'updated'> };
const campusScope = require('../../utils/campusScope') as { scopeFor(req: unknown): Promise<{ campusIds: string[] | null } | null> };
@@ -39,6 +39,8 @@ export const getMe = defineRoute({
access: 'user',
response: single(me.extend({
twoFactorRequired: z.boolean().describe('Their role must use two-step sign-in'),
twoFactorMethod: z.enum(['email', 'whatsapp', 'authenticator']).nullable().describe('How their codes come (2.3.0: authenticator = an app)'),
recoveryCodesLeft: z.number().int().describe('Unused recovery codes (0 with two-step sign-in off)'),
newsPromptPending: z.boolean(),
noticePromptPending: z.union([z.literal(false), z.enum(['first', 'updated'])]),
campusScope: z.array(id).nullable(),
@@ -54,6 +56,8 @@ export const getMe = defineRoute({
data: {
...toMe(u),
twoFactorRequired: requiresTwoFactor(u),
twoFactorMethod: u.twoFactorEnabled ? (u.twoFactorMethod ?? null) : null,
recoveryCodesLeft: u.twoFactorEnabled ? await recoveryCodesLeft(u.id) : 0,
newsPromptPending: !u.newsAskedAt && !impersonating,
noticePromptPending: impersonating ? false as const : await privacyNotice.noticePromptPending({ noticeVersionAccepted: u.noticeVersionAccepted }),
campusScope: (await campusScope.scopeFor(req))?.campusIds ?? null,
@@ -42,7 +42,7 @@ const SCOPE_LIST = 'scopeList (the handler filters by listWhere)';
// ─── Documented shapes (docs.ts) ─────────────────────────────────────────────
const challenge = D.obj({ challengeId: D.str, method: z.enum(['email', 'whatsapp']), destination: D.str.describe('Where the code went, partly hidden') });
const challenge = D.obj({ challengeId: D.str, method: z.enum(['email', 'whatsapp', 'authenticator']), destination: D.str.describe('Where the code went, partly hidden') });
const signedIn = D.obj({ message: D.optStr, id: D.str, name: D.str, email: D.str, role: D.str, token: D.str.describe('A new sign-in token') });
const kind = z.enum(['update', 'news']).describe('update: about something they booked (always sent). news: needs their news consent');
const attendeeFilter = D.obj({
@@ -90,8 +90,9 @@ v1Route({ method: 'post', path: '/me/sessions/revoke', tag: 'Me', summary: 'Sign
v1Route({ method: 'post', path: '/me/close', tag: 'Me', summary: 'Close my account', description: 'Needs the password. Personal details are removed; payment records stay, anonymised.', access: 'user', body: loose, documented: { body: D.obj({ password: D.str, deleteData: D.optBool.describe('Also ask for my personal information to be deleted') }), response: D.message }, v1: users.closeAccount });
v1Route({ method: 'get', path: '/me/activity', tag: 'Me', summary: 'Recent sign-ins and changes to my account', access: 'user', documented: { response: z.array(D.obj({ id: D.str, type: D.str.describe('login, password_changed, two_factor_enabled…'), device: D.optStr, createdAt: D.date })) }, v1: users.getMyActivity });
v1Route({ method: 'post', path: '/me/verify-password', tag: 'Me', summary: 'Check my password (before a sensitive change)', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.ok }, v1: users.verifyPassword });
v1Route({ method: 'post', path: '/me/two-factor/enable', tag: 'Me', summary: 'Start turning on two-step sign-in', description: 'Sends a code to confirm with.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ method: z.enum(['email', 'whatsapp']), password: D.str }), response: challenge }, v1: users.startEnableTwoFactor });
v1Route({ method: 'post', path: '/me/two-factor/confirm', tag: 'Me', summary: 'Confirm two-step sign-in with the code', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ challengeId: D.str, code: D.str }), response: D.obj({ twoFactorEnabled: z.literal(true), twoFactorMethod: D.str }) }, v1: users.confirmEnableTwoFactor });
v1Route({ method: 'post', path: '/me/two-factor/enable', tag: 'Me', summary: 'Start turning on two-step sign-in', description: 'Sends a code to confirm with, or for `authenticator` (2.3.0) answers with `secret` and `otpauthUrl` to show as a QR code; the app\x27s first code confirms it.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ method: z.enum(['email', 'whatsapp', 'authenticator']), password: D.str }), response: challenge.extend({ secret: D.optStr.describe('authenticator: the key to type in by hand'), otpauthUrl: D.optStr.describe('authenticator: show as a QR code') }) }, v1: users.startEnableTwoFactor });
v1Route({ method: 'post', path: '/me/two-factor/confirm', tag: 'Me', summary: 'Confirm two-step sign-in with the code', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ challengeId: D.str, code: D.str }), response: D.obj({ twoFactorEnabled: z.literal(true), twoFactorMethod: D.str, recoveryCodes: z.array(D.str).describe('Shown once: single-use codes for when the app or phone is lost') }) }, v1: users.confirmEnableTwoFactor });
v1Route({ method: 'post', path: '/me/two-factor/recovery-codes', tag: 'Me', summary: 'A new set of recovery codes', description: 'Needs the password. The old codes stop working; the new ones are shown once.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.obj({ recoveryCodes: z.array(D.str) }) }, v1: users.replaceMyRecoveryCodes });
v1Route({ method: 'post', path: '/me/two-factor/disable', tag: 'Me', summary: 'Turn off two-step sign-in', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.obj({ twoFactorEnabled: z.literal(false), twoFactorMethod: z.null() }) }, v1: users.disableTwoFactor });
v1Route({
method: 'get', path: '/users/exists', tag: 'Accounts', summary: 'Is there an account with this email or phone?',
@@ -0,0 +1,163 @@
// Two-factor with an authenticator app and recovery codes (2.3.0): setting it up, signing in with
// the app's code (once only), recovery codes (single use), and turning it off.
process.env.JWT_SECRET = 'test-secret';
process.env.NODE_ENV = 'test';
function matches(row, where = {}) {
return Object.entries(where).every(([key, cond]) => {
if (key === 'OR') return cond.some(c => matches(row, c));
const value = row[key];
if (cond === null) return value == null;
if (cond && typeof cond === 'object' && !(cond instanceof Date)) {
if ('gt' in cond && !(value > cond.gt)) return false;
if ('lt' in cond && !(value != null && value < cond.lt)) return false;
return true;
}
return value === cond;
});
}
function model(defaults = () => ({})) {
let rows = [];
let seq = 0;
const apply = (row, data) => { for (const [k, v] of Object.entries(data)) row[k] = v && typeof v === 'object' && 'increment' in v ? row[k] + v.increment : v; };
return {
rows: () => rows,
reset: () => { rows = []; },
create: async ({ data }) => { const r = { id: `id-${++seq}`, ...defaults(), ...data }; rows.push(r); return { ...r }; },
createMany: async ({ data }) => { for (const d of data) rows.push({ id: `id-${++seq}`, ...defaults(), ...d }); return { count: data.length }; },
findUnique: async ({ where, include, select }) => {
const r = rows.find(x => matches(x, where));
if (!r) return null;
const out = { ...r };
if (include?.user) out.user = { ...mockDb.user.rows().find(u => u.id === r.userId) };
if (select) return Object.fromEntries(Object.keys(select).map(k => [k, r[k]]));
return out;
},
update: async ({ where, data }) => { const r = rows.find(x => matches(x, where)); apply(r, data); return { ...r }; },
updateMany: async ({ where, data }) => { const hit = rows.filter(x => matches(x, where)); hit.forEach(r => apply(r, data)); return { count: hit.length }; },
deleteMany: async ({ where }) => { const before = rows.length; rows = rows.filter(x => !matches(x, where)); return { count: before - rows.length }; },
count: async ({ where }) => rows.filter(x => matches(x, where)).length,
};
}
const mockDb = {
user: model(),
twoFactorChallenge: model(() => ({ attempts: 0, usedAt: null, lastSentAt: new Date(), createdAt: new Date(), pendingSecret: null })),
recoveryCode: model(() => ({ usedAt: null, createdAt: new Date() })),
trustedDevice: model(),
};
jest.mock('../src/config/db', () => mockDb);
jest.mock('../src/utils/settingsCache', () => ({ getSettingSync: (_key, fallback) => fallback }));
const twoFactor = require('../src/utils/twoFactor');
const totp = require('../src/utils/totp');
const { decrypt } = require('../src/utils/encryption');
const STEP_MS = totp.STEP * 1000;
const codeNow = (secret, offsetSteps = 0) => totp.codeAt(secret, Math.floor(Date.now() / STEP_MS) + offsetSteps);
beforeEach(() => {
for (const m of Object.values(mockDb)) m.reset();
mockDb.user.rows().push({ id: 'u1', name: 'Jane', email: 'jane@example.com', role: 'admin', twoFactorEnabled: false, totpSecret: null, totpLastStep: null });
});
async function setUpApp() {
const user = mockDb.user.rows()[0];
const ch = await twoFactor.createChallenge(user, 'enable', 'authenticator');
return { ch, user };
}
describe('setting up an authenticator app', () => {
test('gives a secret and an otpauth link, keeps it only encrypted, and sends nothing', async () => {
const { ch } = await setUpApp();
expect(ch).toMatchObject({ method: 'authenticator', destination: 'your authenticator app' });
expect(ch.secret).toMatch(/^[A-Z2-7]{32}$/);
expect(ch.otpauthUrl).toMatch(/^otpauth:\/\/totp\/.+secret=[A-Z2-7]{32}&issuer=/);
const row = mockDb.twoFactorChallenge.rows()[0];
expect(row.pendingSecret).not.toContain(ch.secret);
expect(decrypt(row.pendingSecret)).toBe(ch.secret);
});
test('the app\'s current code confirms it; a wrong code doesn\'t', async () => {
const { ch } = await setUpApp();
await expect(twoFactor.verifyChallenge(ch.challengeId, '000000', 'enable', 'u1')).rejects.toThrow(/Incorrect code/);
const ok = await twoFactor.verifyChallenge(ch.challengeId, codeNow(ch.secret), 'enable', 'u1');
expect(ok.method).toBe('authenticator');
expect(decrypt(ok.pendingSecret)).toBe(ch.secret);
});
test('resend is refused: nothing is sent for an app', async () => {
const { ch } = await setUpApp();
await expect(twoFactor.resendChallenge(ch.challengeId, 'enable', 'u1')).rejects.toThrow(/authenticator app/);
});
test('it\'s always among the available methods', async () => {
expect(await twoFactor.availableMethods({ email: 'x@guest.local', phoneNumber: null })).toEqual(['authenticator']);
});
});
describe('signing in with the app', () => {
let secret;
beforeEach(async () => {
const { ch } = await setUpApp();
secret = ch.secret;
Object.assign(mockDb.user.rows()[0], { twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: mockDb.twoFactorChallenge.rows()[0].pendingSecret });
});
test('the current code works once; the same code again is refused', async () => {
const user = mockDb.user.rows()[0];
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
expect(a.secret).toBeUndefined();
const code = codeNow(secret);
await expect(twoFactor.verifyChallenge(a.challengeId, code, 'login')).resolves.toMatchObject({ usedRecoveryCode: false });
const b = await twoFactor.createChallenge(user, 'login', 'authenticator');
await expect(twoFactor.verifyChallenge(b.challengeId, code, 'login')).rejects.toThrow(/Incorrect code/);
});
test('a code from the step before still works (clock drift); one from two steps back doesn\'t', async () => {
const user = mockDb.user.rows()[0];
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
await expect(twoFactor.verifyChallenge(a.challengeId, codeNow(secret, -2), 'login')).rejects.toThrow(/Incorrect/);
await expect(twoFactor.verifyChallenge(a.challengeId, codeNow(secret, -1), 'login')).resolves.toBeTruthy();
});
test('no app set up: signing in with it is refused', async () => {
mockDb.user.rows()[0].totpSecret = null;
await expect(twoFactor.createChallenge(mockDb.user.rows()[0], 'login', 'authenticator')).rejects.toThrow(/No authenticator app/);
});
});
describe('recovery codes', () => {
test('ten codes, single use, accepted at sign-in in place of the app\'s code', async () => {
const { ch } = await setUpApp();
Object.assign(mockDb.user.rows()[0], { twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: mockDb.twoFactorChallenge.rows()[0].pendingSecret });
const codes = await twoFactor.replaceRecoveryCodes('u1', mockDb);
expect(codes).toHaveLength(10);
expect(new Set(codes).size).toBe(10);
codes.forEach(c => expect(c).toMatch(/^[a-z2-9]{5}-[a-z2-9]{5}$/));
expect(JSON.stringify(mockDb.recoveryCode.rows())).not.toContain(codes[0]);
const user = mockDb.user.rows()[0];
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
await expect(twoFactor.verifyChallenge(a.challengeId, codes[3].toUpperCase().replace('-', ' '), 'login')).resolves.toMatchObject({ usedRecoveryCode: true });
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(9);
const b = await twoFactor.createChallenge(user, 'login', 'authenticator');
await expect(twoFactor.verifyChallenge(b.challengeId, codes[3], 'login')).rejects.toThrow(/Incorrect/);
expect(ch).toBeTruthy();
});
test('a new set replaces the old one', async () => {
const first = await twoFactor.replaceRecoveryCodes('u1', mockDb);
await twoFactor.replaceRecoveryCodes('u1', mockDb);
expect(await twoFactor.useRecoveryCode('u1', first[0])).toBe(false);
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(10);
});
test('turning 2FA off removes them and the app\'s secret', async () => {
await twoFactor.replaceRecoveryCodes('u1', mockDb);
const data = await twoFactor.clearTwoFactor('u1', mockDb);
expect(data).toEqual({ twoFactorEnabled: false, twoFactorMethod: null, totpSecret: null, totpLastStep: null });
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(0);
});
});
@@ -117,15 +117,15 @@ afterEach(() => jest.restoreAllMocks());
describe('availableMethods', () => {
test('offers WhatsApp only with a valid phone and a configured gateway', async () => {
expect(await availableMethods(USER)).toEqual(['email', 'whatsapp']);
expect(await availableMethods(USER)).toEqual(['email', 'whatsapp', 'authenticator']);
mockWhatsApp.configured = false;
expect(await availableMethods(USER)).toEqual(['email']);
expect(await availableMethods(USER)).toEqual(['email', 'authenticator']);
mockWhatsApp.configured = true;
expect(await availableMethods({ ...USER, phoneNumber: null })).toEqual(['email']);
expect(await availableMethods({ ...USER, phoneNumber: null })).toEqual(['email', 'authenticator']);
});
test('offers nothing by email for a guest placeholder address', async () => {
expect(await availableMethods({ ...USER, email: 'x@guest.local' })).toEqual(['whatsapp']);
expect(await availableMethods({ ...USER, email: 'x@guest.local' })).toEqual(['whatsapp', 'authenticator']);
});
});