Files
KomediruzeckiandGitHub 113c7edb8a feat(auth): TOTP two-factor authentication with recovery codes (#500)
* feat(auth): TOTP two-factor authentication with recovery codes

Second factor for password and Google sign-in. Login now withholds the
session when the account has a confirmed TOTP credential: the browser
gets a 5-minute signed challenge cookie (fm_2fa) and /api/auth/2fa/verify
trades a valid authenticator or recovery code for the real session.

- RFC 6238 TOTP over WebCrypto (SHA-1/6/30 as authenticator apps expect),
  verified against the RFC's reference vectors; constant-time compares;
  last-used-step high-water mark so a code is never accepted twice.
- Secrets encrypted at rest (AES-256-GCM under an HKDF key from
  JWT_SECRET); decrypt failure fails CLOSED - the challenge remains and
  the SHA-256-hashed single-use recovery codes still sign you in.
- Enrollment in Settings: otpauth link + manual key, confirm with a live
  code, ten recovery codes shown exactly once. Disable demands a code.
- Rate limits on verify (10/15min/user), auth_logs twofa events, and the
  Google callback returns with ?twofa=1 so the SPA opens the code step.

* feat(2fa): QR enrollment and a full-loop e2e spec

- Enroll now shows a QR code of the otpauth URI, rendered locally with
  uqr — the shared secret never leaves the page, so external QR image
  services are not an option. White backing keeps it scannable in dark
  mode. Manual key entry and the open-directly link stay.
- New Playwright spec drives the whole loop through the real UI with a
  dedicated user: enroll (computing codes from the on-screen secret the
  way an authenticator app would), wrong-code rejection, TOTP challenge
  sign-in, recovery-code sign-in, disable via recovery code.
- tests/db.ts: shared local-D1 helpers (sql / sqlRows) so auth specs can
  arrange state the API deliberately refuses to expose.

* fix(2fa): close the review findings on the 2FA lifecycle

Security:
- /2fa/disable now shares the 2fa:<user> attempt bucket with /2fa/verify
  (and clears it on success). It accepts the same factors, so it must not
  hand an attacker a fresh guessing budget; before this, a stolen session
  could brute-force the disable endpoint unmetered.
- Enabling 2FA deletes every OTHER auth session. Sessions that predate
  enrollment got in on one factor — including the intruder the user may
  be enrolling against. Only the enrolling session survives.
- Account deletion now removes totp_credentials and recovery_codes; the
  encrypted secret and code hashes used to outlive the account.

UX / recoverability:
- "Create account" with an existing 2FA-protected email now lands on the
  code challenge instead of a silent reload loop (both login surfaces).
- Recovery codes: a Download button joins Copy (clipboard is unavailable
  in non-secure contexts and the codes are unrecoverable once revealed),
  and Settings warns loudly when 3 or fewer codes remain.
- The challenge's recovery/back controls are real buttons — keyboard and
  assistive-tech reachable; they were onClick-only anchors, invisible to
  the tab order, gating the only path in after a lost phone.
- Backing out of the challenge strips the ?twofa=1 marker, so a reload
  no longer reopens a dead challenge for an expired cookie.

Not addressed here (accepted, low): recovery-code spend before a failed
session write; the two-tab concurrent-setup race (second secret wins).
2026-08-30 18:13:52 +02:00

137 lines
6.0 KiB
TypeScript

/**
* 2FA storage layer: TOTP secret encryption at rest, enrollment lifecycle, recovery codes.
* Runs against the real D1 schema (migration 0028) in workerd.
*/
import { env } from 'cloudflare:test';
import { beforeEach, describe, expect, it } from 'vitest';
import {
confirmTotp,
consumeRecoveryCode,
decryptTotpSecret,
disableTotp,
encryptTotpSecret,
enrollTotp,
generateRecoveryCodes,
getTotpForLogin,
markTotpStepUsed,
storeRecoveryCodes,
totpStatus,
} from '../src/twofa';
const SECRET_KEY = 'test-jwt-secret-not-for-prod'; // JWT_SECRET binding from vitest.config
describe('TOTP secret encryption at rest', () => {
it('round-trips and never emits the same ciphertext twice (fresh IV)', async () => {
const a = await encryptTotpSecret('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', SECRET_KEY);
const b = await encryptTotpSecret('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', SECRET_KEY);
expect(a).not.toBe(b);
expect(a).not.toContain('GEZDGNBV');
expect(await decryptTotpSecret(a, SECRET_KEY)).toBe('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
});
it('returns null on tamper or wrong key instead of throwing', async () => {
const enc = await encryptTotpSecret('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ', SECRET_KEY);
expect(await decryptTotpSecret(enc, 'a-different-secret')).toBeNull();
const tampered = enc.slice(0, -2) + (enc.endsWith('AA') ? 'BB' : 'AA');
expect(await decryptTotpSecret(tampered, SECRET_KEY)).toBeNull();
});
});
describe('recovery codes', () => {
it('generates 10 unique codes shaped XXXXX-XXXXX', () => {
const codes = generateRecoveryCodes();
expect(codes).toHaveLength(10);
for (const c of codes) expect(c).toMatch(/^[A-Z2-7]{5}-[A-Z2-7]{5}$/);
expect(new Set(codes).size).toBe(10);
});
});
describe('enrollment lifecycle (D1)', () => {
let userId: number;
beforeEach(async () => {
await env.DB.prepare('DELETE FROM totp_credentials').run();
await env.DB.prepare('DELETE FROM recovery_codes').run();
await env.DB.prepare('DELETE FROM users').run();
const res = await env.DB.prepare(
"INSERT INTO users (email, password_hash, auth_provider) VALUES ('t@example.com', 'x', 'password')"
).run();
userId = res.meta.last_row_id as number;
});
it('enroll stores an unconfirmed secret; status stays disabled until confirmed', async () => {
await enrollTotp(env, userId, 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
expect(await totpStatus(env, userId)).toEqual({ enabled: false, recoveryCodesLeft: 0 });
expect(await getTotpForLogin(env, userId)).toBeNull(); // login must not challenge yet
await confirmTotp(env, userId);
expect((await totpStatus(env, userId)).enabled).toBe(true);
const cred = await getTotpForLogin(env, userId);
expect(cred?.secret).toBe('GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
expect(cred?.lastUsedStep).toBeNull();
});
it('re-enrolling before confirmation replaces the pending secret', async () => {
await enrollTotp(env, userId, 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
await enrollTotp(env, userId, 'MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43U');
await confirmTotp(env, userId);
expect((await getTotpForLogin(env, userId))?.secret).toBe('MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43U');
});
it('markTotpStepUsed persists the anti-replay high-water mark', async () => {
await enrollTotp(env, userId, 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
await confirmTotp(env, userId);
await markTotpStepUsed(env, userId, 37037036);
expect((await getTotpForLogin(env, userId))?.lastUsedStep).toBe(37037036);
});
it('recovery codes: consume works exactly once, wrong codes fail, count tracks', async () => {
await enrollTotp(env, userId, 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
await confirmTotp(env, userId);
const codes = generateRecoveryCodes();
await storeRecoveryCodes(env, userId, codes);
expect((await totpStatus(env, userId)).recoveryCodesLeft).toBe(10);
expect(await consumeRecoveryCode(env, userId, codes[3])).toBe(true);
expect(await consumeRecoveryCode(env, userId, codes[3])).toBe(false); // spent
expect(await consumeRecoveryCode(env, userId, 'AAAAA-AAAAA')).toBe(false);
// Case/spacing tolerance: users retype these from paper.
expect(await consumeRecoveryCode(env, userId, codes[4].toLowerCase())).toBe(true);
expect((await totpStatus(env, userId)).recoveryCodesLeft).toBe(8);
});
it('storing a fresh batch of recovery codes invalidates the old batch', async () => {
await enrollTotp(env, userId, 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
await confirmTotp(env, userId);
const first = generateRecoveryCodes();
await storeRecoveryCodes(env, userId, first);
const second = generateRecoveryCodes();
await storeRecoveryCodes(env, userId, second);
expect(await consumeRecoveryCode(env, userId, first[0])).toBe(false);
expect(await consumeRecoveryCode(env, userId, second[0])).toBe(true);
expect((await totpStatus(env, userId)).recoveryCodesLeft).toBe(9);
});
it('disable removes the credential and all recovery codes', async () => {
await enrollTotp(env, userId, 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
await confirmTotp(env, userId);
await storeRecoveryCodes(env, userId, generateRecoveryCodes());
await disableTotp(env, userId);
expect(await totpStatus(env, userId)).toEqual({ enabled: false, recoveryCodesLeft: 0 });
expect(await getTotpForLogin(env, userId)).toBeNull();
});
it('a corrupted secret (e.g. rotated JWT_SECRET) fails CLOSED: challenge stays, secret null', async () => {
await enrollTotp(env, userId, 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ');
await confirmTotp(env, userId);
await env.DB.prepare('UPDATE totp_credentials SET secret_enc = ? WHERE user_id = ?')
.bind('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', userId)
.run();
// The row is confirmed, so login must still demand a second factor — the user gets in with
// a recovery code (hashed, unaffected by key rotation), never with password alone.
const cred = await getTotpForLogin(env, userId);
expect(cred).not.toBeNull();
expect(cred?.secret).toBeNull();
});
});