diff --git a/apps/events/CHANGELOG.md b/apps/events/CHANGELOG.md index 0d3dd4c..ef25014 100644 --- a/apps/events/CHANGELOG.md +++ b/apps/events/CHANGELOG.md @@ -7,6 +7,25 @@ and this project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +Planned as 2.3.0 (ROADMAP-v3 phase 1c). + +### Added + +- **Two-factor with an authenticator app** (TOTP, RFC 6238) next to email and WhatsApp: Profile & + Security → Two-factor → "An authenticator app" shows a QR code (drawn in the browser) and the key; + the app's first code confirms it. Codes can't be used twice; nothing is sent, so there's no resend. + The secret is stored encrypted (`User.totpSecret`). +- **Recovery codes**: 10 single-use codes each time two-factor is turned on (any method), shown + once with Download and Copy; one works at sign-in in place of any code ("Use a recovery code"). + A new set from Profile & Security (password needed). Using one, and making a new set, show in + the account's activity. +- **Admins see each account's method** in Users ("2FA: app / email / WhatsApp"); Reset 2FA also + removes the app's secret and the recovery codes. +- API (v2): `authenticator` in `/me/two-factor/enable` (answers with `secret` and `otpauthUrl`), + `recoveryCodes` from `/me/two-factor/confirm`, `POST /me/two-factor/recovery-codes`; + `twoFactorMethod` and `recoveryCodesLeft` on `/me`, `twoFactorMethod` on users. +- Migration `20261118150000_authenticator_app`. + ## [2.2.0] - 2026-11-17 Cross Events moves into the `crosscode-platform` monorepo (ROADMAP-v3 phase 1b, diff --git a/apps/events/WHATS-NEW.md b/apps/events/WHATS-NEW.md index 68def4b..6a601a2 100644 --- a/apps/events/WHATS-NEW.md +++ b/apps/events/WHATS-NEW.md @@ -12,6 +12,17 @@ Write for church admins, not developers: no environment variables, endpoints or developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". --> +## 2.3.0 + +- **Sign in with an authenticator app.** Two-factor sign-in can now use an app on your phone + (Google Authenticator, Microsoft Authenticator, 1Password and others) instead of a code by email + or WhatsApp. It's the most secure option and works without signal. Set it up under Profile & + Security. +- **Recovery codes.** When you turn on two-factor you get 10 single-use recovery codes to keep + somewhere safe: if you lose your phone, one of them lets you sign in. +- **Admins can see how each person signs in**: the Users page shows whether each account uses an + app, email or WhatsApp for its codes. + ## 2.2.0 - **AI use is now shown in tokens.** Site settings → AI shows how much of this month's AI allowance diff --git a/apps/events/backend/prisma/migrations/20261118150000_authenticator_app/migration.sql b/apps/events/backend/prisma/migrations/20261118150000_authenticator_app/migration.sql index 767bb19..5124e19 100644 --- a/apps/events/backend/prisma/migrations/20261118150000_authenticator_app/migration.sql +++ b/apps/events/backend/prisma/migrations/20261118150000_authenticator_app/migration.sql @@ -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'; diff --git a/apps/events/backend/prisma/schema.prisma b/apps/events/backend/prisma/schema.prisma index 4ae709f..b9bc35a 100644 --- a/apps/events/backend/prisma/schema.prisma +++ b/apps/events/backend/prisma/schema.prisma @@ -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 { diff --git a/apps/events/backend/src/controllers/userController.js b/apps/events/backend/src/controllers/userController.js index 494bbcc..2400faa 100644 --- a/apps/events/backend/src/controllers/userController.js +++ b/apps/events/backend/src/controllers/userController.js @@ -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, diff --git a/apps/events/backend/src/services/auth.ts b/apps/events/backend/src/services/auth.ts index 197e0d4..41bf055 100644 --- a/apps/events/backend/src/services/auth.ts +++ b/apps/events/backend/src/services/auth.ts @@ -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; issueTrustedDevice(userId: string, userAgent?: string): Promise; isTrustedDevice(userId: string, deviceToken?: string): Promise; clearTrustedDevices(userId: string): Promise; @@ -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); } diff --git a/apps/events/backend/src/utils/twoFactor.js b/apps/events/backend/src/utils/twoFactor.js index a5b99a0..560237e 100644 --- a/apps/events/backend/src/utils/twoFactor.js +++ b/apps/events/backend/src/utils/twoFactor.js @@ -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, diff --git a/apps/events/backend/src/v2/docs.ts b/apps/events/backend/src/v2/docs.ts index 9b1b3ed..89c3f2e 100644 --- a/apps/events/backend/src/v2/docs.ts +++ b/apps/events/backend/src/v2/docs.ts @@ -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, }); diff --git a/apps/events/backend/src/v2/resources/me.ts b/apps/events/backend/src/v2/resources/me.ts index 9b98a2f..526770a 100644 --- a/apps/events/backend/src/v2/resources/me.ts +++ b/apps/events/backend/src/v2/resources/me.ts @@ -26,7 +26,7 @@ const toMe = (u: MeRow): z.input => ({ }); /* 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 }; const privacyNotice = require('../../utils/privacyNotice') as { noticePromptPending(u: { noticeVersionAccepted: unknown }): Promise }; 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, diff --git a/apps/events/backend/src/v2/resources/peopleMessaging.ts b/apps/events/backend/src/v2/resources/peopleMessaging.ts index 732618f..a49fc8e 100644 --- a/apps/events/backend/src/v2/resources/peopleMessaging.ts +++ b/apps/events/backend/src/v2/resources/peopleMessaging.ts @@ -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?', diff --git a/apps/events/backend/tests/twoFactorAuthenticator.test.js b/apps/events/backend/tests/twoFactorAuthenticator.test.js new file mode 100644 index 0000000..c6e80db --- /dev/null +++ b/apps/events/backend/tests/twoFactorAuthenticator.test.js @@ -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); + }); +}); diff --git a/apps/events/backend/tests/twoFactorFlow.test.js b/apps/events/backend/tests/twoFactorFlow.test.js index cc49d4e..2520ef2 100644 --- a/apps/events/backend/tests/twoFactorFlow.test.js +++ b/apps/events/backend/tests/twoFactorFlow.test.js @@ -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']); }); }); diff --git a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx index 9c4e57b..58b56d1 100644 --- a/apps/events/frontend/src/app/dashboard/admin/users/page.tsx +++ b/apps/events/frontend/src/app/dashboard/admin/users/page.tsx @@ -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() { +
+ {u.twoFactorEnabled ? `2FA: ${TWO_FACTOR_LABEL[u.twoFactorMethod || "email"]}` : "No 2FA"} +
{u.phoneNumber || ""} diff --git a/apps/events/frontend/src/app/dashboard/user/profile/page.tsx b/apps/events/frontend/src/app/dashboard/user/profile/page.tsx index 0579c89..e3d62cf 100644 --- a/apps/events/frontend/src/app/dashboard/user/profile/page.tsx +++ b/apps/events/frontend/src/app/dashboard/user/profile/page.tsx @@ -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 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 = { email: "email", whatsapp: "WhatsApp" }; +const TWO_FACTOR_METHOD_LABEL: Record = { 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("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(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(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 ? (
-

- 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."} -

+ {tfChallenge.method === "authenticator" ? ( +
+

Scan this with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password, Authy…), then enter the 6-digit code it shows.

+ {/* eslint-disable-next-line @next/next/no-img-element -- a data: URL drawn in the browser */} + {tfQr && tfQr.url === tfChallenge.otpauthUrl && QR code to add this account to an authenticator app} + {tfChallenge.secret && ( +

Can't scan it? Type this key into the app: {tfChallenge.secret.replace(/(.{4})/g, "$1 ").trim()}

+ )} +
+ ) : ( +

+ 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."} +

+ )}
) : tfEnabled && tfStep !== "change" ? ( <>

- On. 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. + On.{" "} + {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.

+
+

Recovery codes: {tfRecoveryLeft} of 10 left. Each works once in place of a code if you lose your phone or app.

+ {tfStep === "recovery" ? ( +
+
+ + setTfPassword(e.target.value)} required autoComplete="current-password" /> +
+ + +
+ ) : ( + + )} +
{tfRequired ? ( <>

Required for your role, so it can't be turned off.

@@ -495,11 +570,12 @@ export default function UserProfilePage() {

{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."}

@@ -518,11 +594,23 @@ export default function UserProfilePage() { )}
)} + {tfRecovery && ( +
+

Save your recovery codes now

+

Each works once, in place of a code, if you lose your phone or app. They won't be shown again.

+
    {tfRecovery.map(c =>
  • {c}
  • )}
+
+ + + +
+
+ )} {tfMsg && } diff --git a/apps/events/frontend/src/components/auth/LoginForm.tsx b/apps/events/frontend/src/components/auth/LoginForm.tsx index 4ae856d..d4d8583 100644 --- a/apps/events/frontend/src/components/auth/LoginForm.tsx +++ b/apps/events/frontend/src/components/auth/LoginForm.tsx @@ -27,6 +27,8 @@ export function LoginForm() { // Two-factor step — set once the password is accepted for an account with 2FA on. const [challenge, setChallenge] = useState(null); const [code, setCode] = useState(""); + // 2.3.0: a recovery code instead of the 6-digit code (xxxxx-xxxxx, single use). + const [useRecovery, setUseRecovery] = useState(false); const [rememberDevice, setRememberDevice] = useState(false); const [resendIn, setResendIn] = useState(0); @@ -109,6 +111,7 @@ export function LoginForm() { const backToPassword = () => { setChallenge(null); setCode(""); + setUseRecovery(false); setPassword(""); setError(null); }; @@ -124,20 +127,24 @@ export function LoginForm() {

)}

- We sent a 6-digit code to {challenge.destination} by {challenge.method === "whatsapp" ? "WhatsApp" : "email"}. It expires in 10 minutes. + {useRecovery + ? "Enter one of the recovery codes you saved when you turned on two-factor. Each works once." + : challenge.method === "authenticator" + ? "Open your authenticator app and enter the 6-digit code it shows for this site." + : <>We sent a 6-digit code to {challenge.destination} by {challenge.method === "whatsapp" ? "WhatsApp" : "email"}. It expires in 10 minutes.}

- + setCode(e.target.value.replace(/\D/g, ""))} + onChange={(e) => setCode(useRecovery ? e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "") : e.target.value.replace(/\D/g, ""))} className="w-full border rounded px-3 py-2 text-lg tracking-widest" autoFocus required @@ -158,7 +165,7 @@ export function LoginForm() { - + {!challenge.enrolling && ( + + )} + {challenge.method !== "authenticator" && !useRecovery && ( + + )}
); diff --git a/apps/events/frontend/src/lib/api-v2/openapi.json b/apps/events/frontend/src/lib/api-v2/openapi.json index 5ee91d2..9743f11 100644 --- a/apps/events/frontend/src/lib/api-v2/openapi.json +++ b/apps/events/frontend/src/lib/api-v2/openapi.json @@ -12950,6 +12950,28 @@ "type": "boolean", "description": "Their role must use two-step sign-in" }, + "twoFactorMethod": { + "anyOf": [ + { + "type": "string", + "enum": [ + "email", + "whatsapp", + "authenticator" + ] + }, + { + "type": "null" + } + ], + "description": "How their codes come (2.3.0: authenticator = an app)" + }, + "recoveryCodesLeft": { + "type": "integer", + "minimum": -9007199254740991, + "maximum": 9007199254740991, + "description": "Unused recovery codes (0 with two-step sign-in off)" + }, "newsPromptPending": { "type": "boolean" }, @@ -12995,6 +13017,8 @@ "homeCampusId", "createdAt", "twoFactorRequired", + "twoFactorMethod", + "recoveryCodesLeft", "newsPromptPending", "noticePromptPending", "campusScope" @@ -47764,7 +47788,8 @@ "type": "string", "enum": [ "email", - "whatsapp" + "whatsapp", + "authenticator" ] }, "destination": { @@ -48395,7 +48420,7 @@ "Me" ], "summary": "Start turning on two-step sign-in", - "description": "Sends a code to confirm with.\n\n**Who:** Any signed-in person.", + "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's first code confirms it.\n\n**Who:** Any signed-in person.", "operationId": "postMeTwo-factorEnable", "security": [ { @@ -48414,7 +48439,8 @@ "type": "string", "enum": [ "email", - "whatsapp" + "whatsapp", + "authenticator" ] }, "password": { @@ -48448,12 +48474,27 @@ "type": "string", "enum": [ "email", - "whatsapp" + "whatsapp", + "authenticator" ] }, "destination": { "type": "string", "description": "Where the code went, partly hidden" + }, + "secret": { + "description": "authenticator: the key to type in by hand", + "type": [ + "string", + "null" + ] + }, + "otpauthUrl": { + "description": "authenticator: show as a QR code", + "type": [ + "string", + "null" + ] } }, "required": [ @@ -48549,11 +48590,107 @@ }, "twoFactorMethod": { "type": "string" + }, + "recoveryCodes": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Shown once: single-use codes for when the app or phone is lost" } }, "required": [ "twoFactorEnabled", - "twoFactorMethod" + "twoFactorMethod", + "recoveryCodes" + ], + "additionalProperties": {} + } + }, + "required": [ + "data" + ], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "Validation failed (VALIDATION_FAILED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Not signed in (UNAUTHENTICATED)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/me/two-factor/recovery-codes": { + "post": { + "tags": [ + "Me" + ], + "summary": "A new set of recovery codes", + "description": "Needs the password. The old codes stop working; the new ones are shown once.\n\n**Who:** Any signed-in person.", + "operationId": "postMeTwo-factorRecovery-codes", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "password": { + "type": "string" + } + }, + "required": [ + "password" + ], + "additionalProperties": {} + } + } + } + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "object", + "properties": { + "recoveryCodes": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "recoveryCodes" ], "additionalProperties": {} } @@ -48975,6 +49112,28 @@ } ] }, + "twoFactorEnabled": { + "type": [ + "boolean", + "null" + ] + }, + "twoFactorMethod": { + "description": "How their sign-in codes come (2.3.0: authenticator = an app)", + "anyOf": [ + { + "type": "string", + "enum": [ + "email", + "whatsapp", + "authenticator" + ] + }, + { + "type": "null" + } + ] + }, "homeCampusId": { "type": [ "string", @@ -49148,6 +49307,28 @@ } ] }, + "twoFactorEnabled": { + "type": [ + "boolean", + "null" + ] + }, + "twoFactorMethod": { + "description": "How their sign-in codes come (2.3.0: authenticator = an app)", + "anyOf": [ + { + "type": "string", + "enum": [ + "email", + "whatsapp", + "authenticator" + ] + }, + { + "type": "null" + } + ] + }, "homeCampusId": { "type": [ "string", @@ -49385,6 +49566,28 @@ } ] }, + "twoFactorEnabled": { + "type": [ + "boolean", + "null" + ] + }, + "twoFactorMethod": { + "description": "How their sign-in codes come (2.3.0: authenticator = an app)", + "anyOf": [ + { + "type": "string", + "enum": [ + "email", + "whatsapp", + "authenticator" + ] + }, + { + "type": "null" + } + ] + }, "homeCampusId": { "type": [ "string", diff --git a/apps/events/frontend/src/lib/api-v2/schema.d.ts b/apps/events/frontend/src/lib/api-v2/schema.d.ts index 444e855..fb03a23 100644 --- a/apps/events/frontend/src/lib/api-v2/schema.d.ts +++ b/apps/events/frontend/src/lib/api-v2/schema.d.ts @@ -4787,7 +4787,7 @@ export interface paths { put?: never; /** * Start turning on two-step sign-in - * @description Sends a code to confirm with. + * @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's first code confirms it. * * **Who:** Any signed-in person. */ @@ -4818,6 +4818,28 @@ export interface paths { patch?: never; trace?: never; }; + "/me/two-factor/recovery-codes": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * A new set of recovery codes + * @description Needs the password. The old codes stop working; the new ones are shown once. + * + * **Who:** Any signed-in person. + */ + post: operations["postMeTwo-factorRecovery-codes"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/me/two-factor/disable": { parameters: { query?: never; @@ -12787,6 +12809,10 @@ export interface operations { createdAt: string; /** @description Their role must use two-step sign-in */ twoFactorRequired: boolean; + /** @description How their codes come (2.3.0: authenticator = an app) */ + twoFactorMethod: ("email" | "whatsapp" | "authenticator") | null; + /** @description Unused recovery codes (0 with two-step sign-in off) */ + recoveryCodesLeft: number; newsPromptPending: boolean; noticePromptPending: false | ("first" | "updated"); campusScope: string[] | null; @@ -28100,7 +28126,7 @@ export interface operations { data: { challengeId: string; /** @enum {string} */ - method: "email" | "whatsapp"; + method: "email" | "whatsapp" | "authenticator"; /** @description Where the code went, partly hidden */ destination: string; } & { @@ -28472,7 +28498,7 @@ export interface operations { content: { "application/json": { /** @enum {string} */ - method: "email" | "whatsapp"; + method: "email" | "whatsapp" | "authenticator"; password: string; } & { [key: string]: unknown; @@ -28490,9 +28516,13 @@ export interface operations { data: { challengeId: string; /** @enum {string} */ - method: "email" | "whatsapp"; + method: "email" | "whatsapp" | "authenticator"; /** @description Where the code went, partly hidden */ destination: string; + /** @description authenticator: the key to type in by hand */ + secret?: string | null; + /** @description authenticator: show as a QR code */ + otpauthUrl?: string | null; } & { [key: string]: unknown; }; @@ -28548,6 +28578,60 @@ export interface operations { /** @constant */ twoFactorEnabled: true; twoFactorMethod: string; + /** @description Shown once: single-use codes for when the app or phone is lost */ + recoveryCodes: string[]; + } & { + [key: string]: unknown; + }; + }; + }; + }; + /** @description Validation failed (VALIDATION_FAILED) */ + 400: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Not signed in (UNAUTHENTICATED) */ + 401: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + "postMeTwo-factorRecovery-codes": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + password: string; + } & { + [key: string]: unknown; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + data: { + recoveryCodes: string[]; } & { [key: string]: unknown; }; @@ -28738,6 +28822,9 @@ export interface operations { role: "admin" | "supervisor" | "staff" | "user"; isActive?: boolean | null; notificationPreference?: ("email" | "whatsapp" | "both") | null; + twoFactorEnabled?: boolean | null; + /** @description How their sign-in codes come (2.3.0: authenticator = an app) */ + twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null; homeCampusId?: string | null; createdAt?: string | null; } & { @@ -28810,6 +28897,9 @@ export interface operations { role: "admin" | "supervisor" | "staff" | "user"; isActive?: boolean | null; notificationPreference?: ("email" | "whatsapp" | "both") | null; + twoFactorEnabled?: boolean | null; + /** @description How their sign-in codes come (2.3.0: authenticator = an app) */ + twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null; homeCampusId?: string | null; createdAt?: string | null; /** @description Campuses they're limited to */ @@ -28972,6 +29062,9 @@ export interface operations { role: "admin" | "supervisor" | "staff" | "user"; isActive?: boolean | null; notificationPreference?: ("email" | "whatsapp" | "both") | null; + twoFactorEnabled?: boolean | null; + /** @description How their sign-in codes come (2.3.0: authenticator = an app) */ + twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null; homeCampusId?: string | null; createdAt?: string | null; } & { diff --git a/apps/events/frontend/src/lib/auth.ts b/apps/events/frontend/src/lib/auth.ts index 488c0fb..131bdfd 100644 --- a/apps/events/frontend/src/lib/auth.ts +++ b/apps/events/frontend/src/lib/auth.ts @@ -26,7 +26,7 @@ export type AuthResponse = AuthUser & { deviceToken?: string; }; -export type TwoFactorMethod = "email" | "whatsapp"; +export type TwoFactorMethod = "email" | "whatsapp" | "authenticator"; // What the login endpoint returns instead of a token when the account has 2FA on: // a code was sent to `destination` (masked) and must be exchanged for the token. @@ -37,6 +37,9 @@ export type TwoFactorChallenge = { destination: string; // The role requires 2FA and it wasn't on yet: verifying this code turns it on. enrolling?: boolean; + // 2.3.0, setting up an authenticator app: the key and its otpauth:// link (shown as a QR code). + secret?: string; + otpauthUrl?: string; }; export function isTwoFactorChallenge(res: unknown): res is TwoFactorChallenge {