// 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); }); });