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

118 lines
4.0 KiB
TypeScript

/**
* TOTP (RFC 6238) + base32 (RFC 4648) unit tests.
*
* The 6-digit expectations are the RFC 6238 Appendix B reference vectors (SHA-1, ASCII secret
* "12345678901234567890"), truncated from the published 8-digit values.
*/
import { describe, expect, it } from 'vitest';
import {
base32Decode,
base32Encode,
currentStep,
generateTotpSecret,
otpauthUri,
totpCode,
verifyTotp,
} from '../src/totp';
const ASCII_SECRET = new TextEncoder().encode('12345678901234567890');
const ASCII_SECRET_B32 = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ';
describe('base32 (RFC 4648)', () => {
it('encodes the RFC 6238 reference secret', () => {
expect(base32Encode(ASCII_SECRET)).toBe(ASCII_SECRET_B32);
});
it('round-trips arbitrary bytes', () => {
const bytes = new Uint8Array([0, 1, 2, 3, 254, 255, 128, 64, 32, 7]);
expect(base32Decode(base32Encode(bytes))).toEqual(bytes);
});
it('decodes lowercase and ignores spaces (user-typed keys)', () => {
expect(base32Decode('gezd gnbv gy3t qojq gezd gnbv gy3t qojq')).toEqual(ASCII_SECRET);
});
it('rejects characters outside the alphabet', () => {
expect(() => base32Decode('GEZ1')).toThrow(); // '1' is not in RFC 4648 base32
});
});
describe('totpCode (RFC 6238 Appendix B vectors, SHA-1, 6 digits)', () => {
const vectors: Array<[number, string]> = [
[59, '287082'],
[1111111109, '081804'],
[1111111111, '050471'],
[1234567890, '005924'],
[2000000000, '279037'],
[20000000000, '353130'],
];
for (const [t, expected] of vectors) {
it(`T=${t} -> ${expected}`, async () => {
const step = Math.floor(t / 30);
expect(await totpCode(ASCII_SECRET_B32, step)).toBe(expected);
});
}
});
describe('currentStep', () => {
it('is unix time divided by the 30s period', () => {
expect(currentStep(59_000)).toBe(1);
expect(currentStep(1_111_111_109_000)).toBe(37037036);
});
});
describe('verifyTotp', () => {
const NOW = 1_111_111_109_000; // step 37037036, code 081804
it('accepts the current-step code and returns the matched step', async () => {
expect(await verifyTotp(ASCII_SECRET_B32, '081804', { nowMs: NOW })).toBe(37037036);
});
it('accepts one step of clock drift in both directions', async () => {
const prev = await totpCode(ASCII_SECRET_B32, 37037035);
const next = await totpCode(ASCII_SECRET_B32, 37037037);
expect(await verifyTotp(ASCII_SECRET_B32, prev, { nowMs: NOW })).toBe(37037035);
expect(await verifyTotp(ASCII_SECRET_B32, next, { nowMs: NOW })).toBe(37037037);
});
it('rejects a code from two steps away', async () => {
const stale = await totpCode(ASCII_SECRET_B32, 37037034);
expect(await verifyTotp(ASCII_SECRET_B32, stale, { nowMs: NOW })).toBeNull();
});
it('rejects a replayed code at or below minStep (anti-replay)', async () => {
expect(
await verifyTotp(ASCII_SECRET_B32, '081804', { nowMs: NOW, minStep: 37037037 })
).toBeNull();
expect(await verifyTotp(ASCII_SECRET_B32, '081804', { nowMs: NOW, minStep: 37037036 })).toBe(
37037036
);
});
it('rejects garbage input without throwing', async () => {
expect(await verifyTotp(ASCII_SECRET_B32, '', { nowMs: NOW })).toBeNull();
expect(await verifyTotp(ASCII_SECRET_B32, 'abcdef', { nowMs: NOW })).toBeNull();
expect(await verifyTotp(ASCII_SECRET_B32, '12345', { nowMs: NOW })).toBeNull();
});
});
describe('generateTotpSecret', () => {
it('produces 32 base32 chars (20 bytes) and unique values', () => {
const a = generateTotpSecret();
const b = generateTotpSecret();
expect(a).toMatch(/^[A-Z2-7]{32}$/);
expect(a).not.toBe(b);
expect(base32Decode(a).length).toBe(20);
});
});
describe('otpauthUri', () => {
it('builds a scannable otpauth URI with issuer and escaped label', () => {
const uri = otpauthUri(ASCII_SECRET_B32, 'user@example.com', 'Token Circles');
expect(uri).toBe(
'otpauth://totp/Token%20Circles:user%40example.com' +
`?secret=${ASCII_SECRET_B32}&issuer=Token%20Circles&algorithm=SHA1&digits=6&period=30`
);
});
});