From b207d17db8f3b5dbf8aa6a437f832c31691dc74b Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Tue, 17 Nov 2026 13:37:52 +0200 Subject: [PATCH] WIP Events 2.3.0: TOTP util, schema and migration for authenticator-app 2FA Not wired up yet: twoFactor.js, login, enable/confirm/disable, recovery codes endpoints and the frontend still to do. Co-Authored-By: Claude Opus 5.5 --- .../migration.sql | 16 ++++ apps/events/backend/prisma/schema.prisma | 21 +++++ apps/events/backend/src/utils/totp.js | 80 +++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 apps/events/backend/prisma/migrations/20261118150000_authenticator_app/migration.sql create mode 100644 apps/events/backend/src/utils/totp.js diff --git a/apps/events/backend/prisma/migrations/20261118150000_authenticator_app/migration.sql b/apps/events/backend/prisma/migrations/20261118150000_authenticator_app/migration.sql new file mode 100644 index 0000000..767bb19 --- /dev/null +++ b/apps/events/backend/prisma/migrations/20261118150000_authenticator_app/migration.sql @@ -0,0 +1,16 @@ +-- 2.3.0: two-factor with an authenticator app (TOTP), and recovery codes. +ALTER TYPE "TwoFactorMethod" ADD VALUE 'authenticator'; +ALTER TABLE "User" ADD COLUMN "totpSecret" TEXT; +ALTER TABLE "User" ADD COLUMN "totpLastStep" INTEGER; +ALTER TABLE "TwoFactorChallenge" ADD COLUMN "pendingSecret" TEXT; +CREATE TABLE "RecoveryCode" ( + "id" TEXT NOT NULL, + "userId" TEXT NOT NULL, + "codeHash" TEXT NOT NULL, + "usedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT "RecoveryCode_pkey" PRIMARY KEY ("id") +); +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; diff --git a/apps/events/backend/prisma/schema.prisma b/apps/events/backend/prisma/schema.prisma index 31aaff9..4ae709f 100644 --- a/apps/events/backend/prisma/schema.prisma +++ b/apps/events/backend/prisma/schema.prisma @@ -57,6 +57,8 @@ enum SecurityEventType { enum TwoFactorMethod { email whatsapp + // 2.3.0: codes from an authenticator app (TOTP); nothing is sent. + authenticator } model User { @@ -75,6 +77,11 @@ model User { notificationPreference NotificationPreference @default(email) twoFactorEnabled Boolean @default(false) twoFactorMethod TwoFactorMethod? + // 2.3.0: the authenticator app's secret (encrypted, utils/encryption.js) and the last 30-second + // step a code was used for, so a code can't be used twice. + totpSecret String? + totpLastStep Int? + recoveryCodes RecoveryCode[] // POPIA: opted in to "News & announcements" (marketing) bulk messages, per channel. // Event updates to registrants don't depend on these. History in CommunicationConsent. newsEmail Boolean @default(false) @@ -713,6 +720,8 @@ model TwoFactorChallenge { user User @relation(fields: [userId], references: [id], onDelete: Cascade) purpose String // 'login' | 'enable' method TwoFactorMethod + // 2.3.0: an authenticator app being set up: its secret (encrypted) until the first code confirms it. + pendingSecret String? codeHash String attempts Int @default(0) lastSentAt DateTime @default(now()) @@ -2353,3 +2362,15 @@ model AiCall { @@index([createdAt]) @@index([userId, createdAt]) } + +// 2.3.0: single-use codes for when the authenticator app (or phone) is lost. Only an HMAC is kept. +model RecoveryCode { + id String @id @default(uuid()) + userId String + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + codeHash String @unique + usedAt DateTime? + createdAt DateTime @default(now()) + + @@index([userId]) +} diff --git a/apps/events/backend/src/utils/totp.js b/apps/events/backend/src/utils/totp.js new file mode 100644 index 0000000..409af50 --- /dev/null +++ b/apps/events/backend/src/utils/totp.js @@ -0,0 +1,80 @@ +/** + * Codes from an authenticator app (2.3.0; RFC 6238 TOTP: SHA-1, 6 digits, 30 seconds), the same + * as Cross Code Hub's. `matchStep` says which 30-second step a code belongs to, so a code that was + * used once is refused the second time (utils/twoFactor.js keeps the last step used). + */ + +const crypto = require('crypto'); + +const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; +const STEP = 30; + +function base32Encode(buf) { + let bits = 0; + let value = 0; + let out = ''; + for (const byte of buf) { + value = (value << 8) | byte; + bits += 8; + while (bits >= 5) { + out += BASE32[(value >>> (bits - 5)) & 31]; + bits -= 5; + } + } + if (bits > 0) out += BASE32[(value << (5 - bits)) & 31]; + return out; +} + +function base32Decode(str) { + let bits = 0; + let value = 0; + const out = []; + for (const ch of String(str).toUpperCase().replace(/=+$/, '')) { + const idx = BASE32.indexOf(ch); + if (idx === -1) continue; + value = (value << 5) | idx; + bits += 5; + if (bits >= 8) { + out.push((value >>> (bits - 8)) & 255); + bits -= 8; + } + } + return Buffer.from(out); +} + +/** A new secret: 20 random bytes, base32 (what the app stores). */ +function generateSecret() { + return base32Encode(crypto.randomBytes(20)); +} + +function codeAt(secret, counter) { + const buf = Buffer.alloc(8); + buf.writeBigUInt64BE(BigInt(counter)); + const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest(); + const offset = hmac[hmac.length - 1] & 0xf; + const num = ((hmac[offset] & 0x7f) << 24) | (hmac[offset + 1] << 16) | (hmac[offset + 2] << 8) | hmac[offset + 3]; + return String(num % 1_000_000).padStart(6, '0'); +} + +/** + * The step `code` is right for (now, or one step either side for clock drift), or null. Steps at + * or before `afterStep` don't count: that code was already used. + */ +function matchStep(secret, code, { now = Date.now(), afterStep = -1 } = {}) { + const clean = String(code || '').replace(/\D/g, ''); + if (clean.length !== 6) return null; + const counter = Math.floor(now / 1000 / STEP); + for (const c of [counter - 1, counter, counter + 1]) { + if (c <= afterStep) continue; + if (crypto.timingSafeEqual(Buffer.from(codeAt(secret, c)), Buffer.from(clean))) return c; + } + return null; +} + +/** The otpauth:// link an authenticator app scans (as a QR code). */ +function otpauthUrl(secret, account, issuer) { + const label = `${issuer}:${account}`; + return `otpauth://totp/${encodeURIComponent(label)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`; +} + +module.exports = { STEP, generateSecret, codeAt, matchStep, otpauthUrl, base32Encode, base32Decode };