diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index 81cefc2..8f0836a 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -3,12 +3,19 @@ import argon2 from 'argon2'; import type Database from 'better-sqlite3'; import * as OTPAuth from 'otpauth'; import QRCode from 'qrcode'; +import { + SecuritySettingsSchema, + type SecuritySettings, + type StepUpPolicy, +} from '../../shared/schemas/settings.schema.js'; +import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js'; +import type { VaultService } from './vault.js'; const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; -const STEP_UP_TTL_MS = 5 * 60 * 1000; const BOOTSTRAP_TTL_MS = 15 * 60 * 1000; const TOTP_PERIOD_SEC = 30; +const DEFAULT_SECURITY = SecuritySettingsSchema.parse({}); export const SESSION_COOKIE_NAME = 'gcoord_sid'; @@ -36,6 +43,33 @@ export interface SessionSummary { current: boolean; } +export interface PublicAuthRequirements { + requireTotpOnLogin: boolean; + passwordMode: 'any' | 'all'; + passwordCount: number; + passwordLabels: Array<{ id: string; label: string }>; + totpMode: 'any' | 'all'; + totpCount: number; + totpLabels: Array<{ id: string; label: string }>; + stepUpPolicy: StepUpPolicy; + stepUpMethod: SecuritySettings['stepUpMethod']; +} + +export type StepUpInput = + | string + | { + code?: string; + codes?: string[]; + password?: string; + passwords?: string[]; + }; + +export interface AuthServiceOptions { + getSecuritySettings?: () => SecuritySettings; + recoveryStore?: EmergencyRecoveryService; + vaultService?: VaultService; +} + interface AdminRow { id: number; username: string; @@ -45,6 +79,22 @@ interface AdminRow { last_stepup_totp_step: number | null; } +interface PasswordRow { + id: string; + label: string; + password_hash: string; + created_at: number; +} + +interface TotpRow { + id: string; + label: string; + secret_base32: string; + last_login_step: number | null; + last_stepup_step: number | null; + created_at: number; +} + interface SessionRow { id_hash: string; csrf_token_hash: string; @@ -75,10 +125,10 @@ function normalizeRecoveryCode(input: string): string { return input.trim().toUpperCase().replace(/[^A-Z0-9]/g, ''); } -function buildTotp(secretBase32: string, username: string): OTPAuth.TOTP { +function buildTotp(secretBase32: string, label: string): OTPAuth.TOTP { return new OTPAuth.TOTP({ issuer: 'GCoordinator', - label: username, + label, algorithm: 'SHA1', digits: 6, period: TOTP_PERIOD_SEC, @@ -86,16 +136,89 @@ function buildTotp(secretBase32: string, username: string): OTPAuth.TOTP { }); } +function computeElevatedUntil( + nowMs: number, + policy: StepUpPolicy, + sessionExpiresAt: number, + fromLogin = false, +): number | null { + switch (policy) { + case 'off': + return null; + case 'every-action': + return fromLogin ? null : nowMs + 60_000; + case '5m': + return nowMs + 5 * 60 * 1000; + case '1h': + return nowMs + 60 * 60 * 1000; + case '24h': + return nowMs + 24 * 60 * 60 * 1000; + case 'session': + return sessionExpiresAt; + } +} + export class AuthService { private pendingBootstrap: { secretBase32: string; createdAt: number } | null = null; + private readonly pendingEnrollments = new Map< + string, + { label: string; secretBase32: string; createdAt: number } + >(); + private readonly getSecurity: () => SecuritySettings; + private recoveryStore?: EmergencyRecoveryService; + private vaultService?: VaultService; - constructor(private readonly db: Database.Database) {} + constructor( + private readonly db: Database.Database, + options: AuthServiceOptions = {}, + ) { + this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY); + this.recoveryStore = options.recoveryStore; + this.vaultService = options.vaultService; + } + + attachRecoveryDependencies( + recoveryStore: EmergencyRecoveryService, + vaultService: VaultService, + ): void { + this.recoveryStore = recoveryStore; + this.vaultService = vaultService; + } isBootstrapped(): boolean { const row = this.db.prepare('SELECT id FROM admin_users WHERE id = 1').get(); return Boolean(row); } + getAdminUsername(): string | null { + const row = this.db + .prepare('SELECT username FROM admin_users WHERE id = 1') + .get() as { username: string } | undefined; + return row?.username ?? null; + } + + getPublicAuthRequirements(): PublicAuthRequirements { + const sec = this.getSecurity(); + const passwords = this.db + .prepare('SELECT id, label FROM admin_passwords ORDER BY created_at ASC, id ASC') + .all() as Array<{ id: string; label: string }>; + const totps = this.db + .prepare('SELECT id, label FROM admin_totps ORDER BY created_at ASC, id ASC') + .all() as Array<{ id: string; label: string }>; + + return { + requireTotpOnLogin: sec.requireTotpOnLogin, + passwordMode: sec.passwordMode, + passwordCount: passwords.length, + passwordLabels: passwords, + totpMode: sec.totpMode, + totpCount: totps.length, + totpLabels: totps, + stepUpPolicy: sec.stepUpPolicy, + stepUpMethod: sec.stepUpMethod, + }; + } + async beginBootstrap(username = 'admin'): Promise<{ secretBase32: string; otpauthUri: string; @@ -188,6 +311,19 @@ export class AuthService { ) .run(username, passwordHash, secretBase32, matchedStep, nowMs, nowMs); + this.db + .prepare( + 'INSERT INTO admin_passwords (id, label, password_hash, created_at) VALUES (?, ?, ?, ?)', + ) + .run('pw-primary', 'Primary Password', passwordHash, nowMs); + + this.db + .prepare( + `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) + VALUES (?, ?, ?, ?, NULL, ?)`, + ) + .run('totp-primary', 'Primary Authenticator', secretBase32, matchedStep, nowMs); + const insertRec = this.db.prepare( 'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)', ); @@ -198,6 +334,17 @@ export class AuthService { tx(); this.pendingBootstrap = null; + this.syncRecovery({ + passwordPlaintextUpdate: { + id: 'pw-primary', + label: 'Primary Password', + password: params.password, + createdAt: nowMs, + }, + newRecoveryCodes: recoveryCodes, + snapshotReason: 'bootstrap', + }); + const created = this.createSession( params.ip, params.userAgent, @@ -208,8 +355,10 @@ export class AuthService { async login(params: { username?: string; - password: string; - code: string; + password?: string; + passwords?: string[]; + code?: string; + codes?: string[]; ip: string; userAgent: string; initialSafeMode?: boolean; @@ -223,46 +372,34 @@ export class AuthService { return null; } - const passwordValid = await argon2.verify(admin.password_hash, params.password); - if (!passwordValid) return null; + const sec = this.getSecurity(); + const suppliedPasswords = ( + params.passwords ?? (params.password !== undefined ? [params.password] : []) + ).filter((p) => p.length > 0); + if (suppliedPasswords.length === 0) return null; - const trimmedCode = params.code.trim(); - const nowMs = Date.now(); + const pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode); + if (!pwOk) return null; - if (/^\d{6}$/.test(trimmedCode)) { - const totp = buildTotp(admin.totp_secret, admin.username); - const delta = totp.validate({ token: trimmedCode, window: 1, timestamp: nowMs }); - if (delta === null) return null; + const totpRows = this.listTotpRows(); + if (sec.requireTotpOnLogin && totpRows.length > 0) { + const suppliedCodes = ( + params.codes ?? (params.code !== undefined ? [params.code] : []) + ) + .map((c) => c.trim()) + .filter((c) => c.length > 0); - const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; - if ( - admin.last_login_totp_step !== null && - matchedStep <= admin.last_login_totp_step - ) { - return null; - } + if (suppliedCodes.length === 0) return null; - this.db - .prepare('UPDATE admin_users SET last_login_totp_step = ?, updated_at = ? WHERE id = 1') - .run(matchedStep, nowMs); - return this.createSession( - params.ip, - params.userAgent, - Boolean(params.initialSafeMode), + const mfaOk = this.verifyTotpsOrRecovery( + suppliedCodes, + sec.totpMode, + 'login', + admin.username, ); + if (!mfaOk) return null; } - // Fallback: single-use recovery code - const normalized = normalizeRecoveryCode(trimmedCode); - if (normalized.length < 8) return null; - const codeHash = sha256Hex(normalized); - const updated = this.db - .prepare( - 'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL', - ) - .run(nowMs, codeHash); - - if (updated.changes !== 1) return null; return this.createSession( params.ip, params.userAgent, @@ -304,50 +441,77 @@ export class AuthService { }; } - stepUp(idHash: string, totpCode: string): { ok: true; elevatedUntil: number } | { ok: false; reason: string } { + async stepUp( + idHash: string, + input: StepUpInput, + ): Promise<{ ok: true; elevatedUntil: number | null } | { ok: false; reason: string }> { const admin = this.db .prepare('SELECT * FROM admin_users WHERE id = 1') .get() as AdminRow | undefined; if (!admin) return { ok: false, reason: 'not_bootstrapped' }; const session = this.db - .prepare('SELECT safe_mode FROM sessions WHERE id_hash = ?') - .get(idHash) as { safe_mode: number } | undefined; + .prepare('SELECT safe_mode, expires_at FROM sessions WHERE id_hash = ?') + .get(idHash) as { safe_mode: number; expires_at: number } | undefined; if (!session) return { ok: false, reason: 'invalid_session' }; + + const sec = this.getSecurity(); + if (sec.stepUpPolicy === 'off') { + return { ok: true, elevatedUntil: null }; + } + if (session.safe_mode === 1) { return { ok: false, reason: 'safe_mode_active' }; } - const trimmed = totpCode.trim(); - if (!/^\d{6}$/.test(trimmed)) { - return { ok: false, reason: 'invalid_totp' }; + const reqObj = typeof input === 'string' ? { code: input } : input; + const suppliedCodes = ( + reqObj.codes ?? (reqObj.code !== undefined ? [reqObj.code] : []) + ) + .map((c) => c.trim()) + .filter(Boolean); + const suppliedPasswords = ( + reqObj.passwords ?? (reqObj.password !== undefined ? [reqObj.password] : []) + ).filter((p) => p.length > 0); + + if (sec.stepUpMethod === 'password' || sec.stepUpMethod === 'both') { + if (suppliedPasswords.length === 0) { + return { ok: false, reason: 'password_required' }; + } + const pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode); + if (!pwOk) { + return { ok: false, reason: 'invalid_password' }; + } + } + + if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') { + const totpRows = this.listTotpRows(); + if (totpRows.length > 0) { + if (suppliedCodes.length === 0) { + return { ok: false, reason: 'invalid_totp' }; + } + const totpResult = this.verifyTotpRows( + suppliedCodes, + sec.totpMode, + 'stepup', + admin.username, + ); + if (!totpResult.ok) { + return { ok: false, reason: totpResult.reason }; + } + } } const nowMs = Date.now(); - const totp = buildTotp(admin.totp_secret, admin.username); - const delta = totp.validate({ token: trimmed, window: 1, timestamp: nowMs }); - if (delta === null) { - return { ok: false, reason: 'invalid_totp' }; - } - - const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; - if ( - admin.last_stepup_totp_step !== null && - matchedStep <= admin.last_stepup_totp_step - ) { - return { ok: false, reason: 'totp_replayed' }; - } - - const elevatedUntil = nowMs + STEP_UP_TTL_MS; - const tx = this.db.transaction(() => { - this.db - .prepare('UPDATE admin_users SET last_stepup_totp_step = ?, updated_at = ? WHERE id = 1') - .run(matchedStep, nowMs); - this.db - .prepare('UPDATE sessions SET elevated_until = ? WHERE id_hash = ?') - .run(elevatedUntil, idHash); - }); - tx(); + const elevatedUntil = computeElevatedUntil( + nowMs, + sec.stepUpPolicy, + session.expires_at, + false, + ); + this.db + .prepare('UPDATE sessions SET elevated_until = ? WHERE id_hash = ?') + .run(elevatedUntil, idHash); return { ok: true, elevatedUntil }; } @@ -359,15 +523,17 @@ export class AuthService { } setSafeMode(idHash: string, enabled: boolean): AuthSession | null { - if (enabled) { + const sec = this.getSecurity(); + if (enabled && !sec.keepElevationOnSafeMode) { this.db .prepare('UPDATE sessions SET safe_mode = 1, elevated_until = NULL WHERE id_hash = ?') .run(idHash); } else { this.db - .prepare('UPDATE sessions SET safe_mode = 0 WHERE id_hash = ?') - .run(idHash); + .prepare('UPDATE sessions SET safe_mode = ? WHERE id_hash = ?') + .run(enabled ? 1 : 0, idHash); } + const row = this.db .prepare('SELECT * FROM sessions WHERE id_hash = ?') .get(idHash) as SessionRow | undefined; @@ -387,6 +553,241 @@ export class AuthService { }; } + listFactors(): { + passwords: Array<{ id: string; label: string; createdAt: number }>; + totps: Array<{ id: string; label: string; createdAt: number }>; + unusedRecoveryCodes: number; + } { + const passwords = this.db + .prepare('SELECT id, label, created_at AS createdAt FROM admin_passwords ORDER BY created_at ASC') + .all() as Array<{ id: string; label: string; createdAt: number }>; + const totps = this.db + .prepare('SELECT id, label, created_at AS createdAt FROM admin_totps ORDER BY created_at ASC') + .all() as Array<{ id: string; label: string; createdAt: number }>; + const rec = this.db + .prepare('SELECT COUNT(*) AS cnt FROM recovery_codes WHERE used_at IS NULL') + .get() as { cnt: number }; + + return { passwords, totps, unusedRecoveryCodes: rec.cnt }; + } + + async addPassword( + label: string, + password: string, + ): Promise<{ id: string; label: string; createdAt: number }> { + const cleanLabel = label.trim(); + if (cleanLabel.length < 1 || cleanLabel.length > 64) { + throw new Error('Password label must be 1–64 characters'); + } + if (password.length < 8) { + throw new Error('Additional password must be at least 8 characters'); + } + + const id = `pw-${crypto.randomBytes(4).toString('hex')}`; + const createdAt = Date.now(); + const hash = await argon2.hash(password, { + type: argon2.argon2id, + memoryCost: 65536, + timeCost: 3, + parallelism: 1, + }); + + this.db + .prepare( + 'INSERT INTO admin_passwords (id, label, password_hash, created_at) VALUES (?, ?, ?, ?)', + ) + .run(id, cleanLabel, hash, createdAt); + + this.syncRecovery({ + passwordPlaintextUpdate: { + id, + label: cleanLabel, + password, + createdAt, + }, + snapshotReason: 'password-added', + }); + + return { id, label: cleanLabel, createdAt }; + } + + removePassword(id: string): boolean { + const count = ( + this.db.prepare('SELECT COUNT(*) AS cnt FROM admin_passwords').get() as { cnt: number } + ).cnt; + if (count <= 1) { + throw new Error('Cannot remove the only remaining admin password'); + } + const res = this.db.prepare('DELETE FROM admin_passwords WHERE id = ?').run(id); + if (res.changes > 0) { + this.syncRecovery({ removedPasswordId: id, snapshotReason: 'password-removed' }); + } + return res.changes > 0; + } + + async beginTotpEnrollment(label: string): Promise<{ + enrollmentId: string; + label: string; + secretBase32: string; + otpauthUri: string; + qrSvg: string; + }> { + const cleanLabel = label.trim(); + if (cleanLabel.length < 1 || cleanLabel.length > 64) { + throw new Error('Authenticator label must be 1–64 characters'); + } + + // Sweep expired pending enrollments + const now = Date.now(); + for (const [k, v] of this.pendingEnrollments.entries()) { + if (now - v.createdAt > BOOTSTRAP_TTL_MS) this.pendingEnrollments.delete(k); + } + + const enrollmentId = crypto.randomBytes(12).toString('hex'); + const secret = new OTPAuth.Secret({ size: 20 }); + this.pendingEnrollments.set(enrollmentId, { + label: cleanLabel, + secretBase32: secret.base32, + createdAt: now, + }); + + const username = this.getAdminUsername() ?? 'admin'; + const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`); + const otpauthUri = totp.toString(); + const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }); + return { + enrollmentId, + label: cleanLabel, + secretBase32: secret.base32, + otpauthUri, + qrSvg, + }; + } + + confirmTotpEnrollment( + enrollmentId: string, + totpCode: string, + ): { id: string; label: string; createdAt: number } { + const pending = this.pendingEnrollments.get(enrollmentId); + if (!pending || Date.now() - pending.createdAt > BOOTSTRAP_TTL_MS) { + this.pendingEnrollments.delete(enrollmentId); + throw new Error('TOTP enrollment expired; start again'); + } + + const username = this.getAdminUsername() ?? 'admin'; + const nowMs = Date.now(); + const totp = buildTotp(pending.secretBase32, `${username} (${pending.label})`); + const delta = totp.validate({ + token: totpCode.trim(), + window: 1, + timestamp: nowMs, + }); + if (delta === null) { + throw new Error('Invalid 6-digit TOTP verification code'); + } + + const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; + const id = `totp-${crypto.randomBytes(4).toString('hex')}`; + this.db + .prepare( + `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) + VALUES (?, ?, ?, ?, ?, ?)`, + ) + .run(id, pending.label, pending.secretBase32, matchedStep, matchedStep, nowMs); + + this.pendingEnrollments.delete(enrollmentId); + this.syncRecovery({ snapshotReason: 'totp-added' }); + return { id, label: pending.label, createdAt: nowMs }; + } + + removeTotp(id: string): boolean { + const sec = this.getSecurity(); + const count = ( + this.db.prepare('SELECT COUNT(*) AS cnt FROM admin_totps').get() as { cnt: number } + ).cnt; + const totpNeeded = + sec.requireTotpOnLogin || + (sec.stepUpPolicy !== 'off' && sec.stepUpMethod !== 'password'); + if (count <= 1 && totpNeeded) { + throw new Error( + 'Cannot remove the last TOTP authenticator while TOTP is required for login or step-up', + ); + } + + const res = this.db.prepare('DELETE FROM admin_totps WHERE id = ?').run(id); + if (res.changes > 0) { + this.syncRecovery({ snapshotReason: 'totp-removed' }); + } + return res.changes > 0; + } + + regenerateRecoveryCodes(): string[] { + const recoveryCodes: string[] = []; + for (let i = 0; i < 8; i++) { + recoveryCodes.push(generateRecoveryCode()); + } + + const tx = this.db.transaction(() => { + this.db.prepare('DELETE FROM recovery_codes').run(); + const stmt = this.db.prepare( + 'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)', + ); + for (const code of recoveryCodes) { + stmt.run(sha256Hex(normalizeRecoveryCode(code))); + } + }); + tx(); + + this.syncRecovery({ + newRecoveryCodes: recoveryCodes, + snapshotReason: 'recovery-codes-regenerated', + }); + return recoveryCodes; + } + + syncRecovery( + overrides: { + passwordPlaintextUpdate?: { + id: string; + label: string; + password: string; + createdAt?: number; + }; + removedPasswordId?: string; + newRecoveryCodes?: string[]; + snapshotReason?: string; + } = {}, + ): void { + if (!this.recoveryStore || !this.vaultService) return; + const sec = this.getSecurity(); + if (!sec.enableEmergencySecretsBackup) return; + + const username = this.getAdminUsername(); + const pwMeta = this.db + .prepare('SELECT id, label, created_at AS createdAt FROM admin_passwords ORDER BY created_at ASC') + .all() as Array<{ id: string; label: string; createdAt: number }>; + const totpRows = this.listTotpRows(); + const totps: SavedTotpEntry[] = totpRows.map((t) => ({ + id: t.id, + label: t.label, + secretBase32: t.secret_base32, + otpauthUri: buildTotp( + t.secret_base32, + username ? `${username} (${t.label})` : t.label, + ).toString(), + createdAt: new Date(t.created_at).toISOString(), + })); + + this.recoveryStore.syncState({ + enabled: sec.enableEmergencySecretsBackup, + vault: this.vaultService, + username, + totps, + passwordMetaList: pwMeta, + ...overrides, + }); + } + listSessions(currentIdHash: string): SessionSummary[] { const now = Date.now(); this.db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(now); @@ -428,6 +829,147 @@ export class AuthService { return this.db.prepare('DELETE FROM sessions').run().changes; } + private listTotpRows(): TotpRow[] { + return this.db + .prepare('SELECT * FROM admin_totps ORDER BY created_at ASC, id ASC') + .all() as TotpRow[]; + } + + private async verifyPasswords( + suppliedPasswords: string[], + mode: 'any' | 'all', + ): Promise { + const rows = this.db + .prepare('SELECT * FROM admin_passwords ORDER BY created_at ASC') + .all() as PasswordRow[]; + if (rows.length === 0) return false; + + if (mode === 'any') { + for (const row of rows) { + for (const candidate of suppliedPasswords) { + if (await argon2.verify(row.password_hash, candidate)) { + return true; + } + } + } + return false; + } + + // 'all': every configured password must be matched + for (const row of rows) { + let rowMatched = false; + for (const candidate of suppliedPasswords) { + if (await argon2.verify(row.password_hash, candidate)) { + rowMatched = true; + break; + } + } + if (!rowMatched) return false; + } + return true; + } + + private verifyTotpsOrRecovery( + suppliedCodes: string[], + mode: 'any' | 'all', + purpose: 'login' | 'stepup', + username: string, + ): boolean { + const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username); + if (totpRes.ok) return true; + + // In 'any' mode, a single-use recovery code may replace TOTP + if (mode === 'any') { + for (const raw of suppliedCodes) { + if (/^\d{6}$/.test(raw)) continue; + const normalized = normalizeRecoveryCode(raw); + if (normalized.length < 8) continue; + const updated = this.db + .prepare( + 'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL', + ) + .run(Date.now(), sha256Hex(normalized)); + if (updated.changes === 1) return true; + } + } + return false; + } + + private verifyTotpRows( + suppliedCodes: string[], + mode: 'any' | 'all', + purpose: 'login' | 'stepup', + username: string, + ): { ok: true } | { ok: false; reason: string } { + const rows = this.listTotpRows(); + if (rows.length === 0) return { ok: true }; + + const numericCodes = suppliedCodes.filter((c) => /^\d{6}$/.test(c)); + if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' }; + + const nowMs = Date.now(); + const stepCol = purpose === 'login' ? 'last_login_step' : 'last_stepup_step'; + + if (mode === 'any') { + let sawReplay = false; + for (const row of rows) { + const totp = buildTotp(row.secret_base32, username); + const lastStep = + purpose === 'login' ? row.last_login_step : row.last_stepup_step; + for (const code of numericCodes) { + const delta = totp.validate({ token: code, window: 1, timestamp: nowMs }); + if (delta === null) continue; + const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; + if (lastStep !== null && matchedStep <= lastStep) { + sawReplay = true; + continue; + } + this.db + .prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`) + .run(matchedStep, row.id); + return { ok: true }; + } + } + return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; + } + + // 'all': every configured TOTP authenticator must match a supplied valid non-replayed code + const matchedUpdates: Array<{ id: string; step: number }> = []; + for (const row of rows) { + const totp = buildTotp(row.secret_base32, username); + const lastStep = + purpose === 'login' ? row.last_login_step : row.last_stepup_step; + let rowStep: number | null = null; + let sawReplay = false; + + for (const code of numericCodes) { + const delta = totp.validate({ token: code, window: 1, timestamp: nowMs }); + if (delta === null) continue; + const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; + if (lastStep !== null && matchedStep <= lastStep) { + sawReplay = true; + continue; + } + rowStep = matchedStep; + break; + } + + if (rowStep === null) { + return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; + } + matchedUpdates.push({ id: row.id, step: rowStep }); + } + + const tx = this.db.transaction(() => { + const stmt = this.db.prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`); + for (const upd of matchedUpdates) { + stmt.run(upd.step, upd.id); + } + }); + tx(); + return { ok: true }; + } + private createSession( ip: string, userAgent: string, @@ -439,16 +981,24 @@ export class AuthService { const csrfTokenHash = sha256Hex(csrfToken); const now = Date.now(); const expiresAt = now + SESSION_TTL_MS; + const sec = this.getSecurity(); + + const shouldElevate = + sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode); + const elevatedUntil = shouldElevate + ? computeElevatedUntil(now, sec.stepUpPolicy, expiresAt, true) + : null; this.db .prepare( `INSERT INTO sessions (id_hash, csrf_token_hash, safe_mode, elevated_until, ip, user_agent, created_at, last_seen_at, expires_at) - VALUES (?, ?, ?, NULL, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .run( idHash, csrfTokenHash, safeMode ? 1 : 0, + elevatedUntil, ip, userAgent.slice(0, 256), now, @@ -463,7 +1013,7 @@ export class AuthService { idHash, csrfTokenHash, safeMode, - elevatedUntil: null, + elevatedUntil, ip, userAgent: userAgent.slice(0, 256), createdAt: now, diff --git a/src/server/security/guards.ts b/src/server/security/guards.ts index 32e3151..470383d 100644 --- a/src/server/security/guards.ts +++ b/src/server/security/guards.ts @@ -1,5 +1,6 @@ import crypto from 'node:crypto'; import type { NextFunction, Request, Response } from 'express'; +import type { StepUpPolicy } from '../../shared/schemas/settings.schema.js'; import { SESSION_COOKIE_NAME, sha256Hex, @@ -148,6 +149,39 @@ export function enforceSafeMode(req: Request, res: Response, next: NextFunction) next(); } +export function createStepUpGuard( + authService: AuthService, + getStepUpPolicy: () => StepUpPolicy, +) { + return (req: Request, res: Response, next: NextFunction): void => { + const session = req.authSession; + if (!session) { + res.status(401).json({ error: 'UNAUTHENTICATED' }); + return; + } + + const policy = getStepUpPolicy(); + if (policy === 'off') { + next(); + return; + } + + if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { + res.status(403).json({ + error: 'STEP_UP_REQUIRED', + message: 'Re-authentication verification is required for this sensitive operation.', + }); + return; + } + + if (policy === 'every-action') { + authService.dropElevation(session.idHash); + } + + next(); + }; +} + export function requireStepUp(req: Request, res: Response, next: NextFunction): void { const session = req.authSession; if (!session) { @@ -157,7 +191,7 @@ export function requireStepUp(req: Request, res: Response, next: NextFunction): if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { res.status(403).json({ error: 'STEP_UP_REQUIRED', - message: 'Fresh TOTP step-up verification is required for this sensitive operation.', + message: 'Re-authentication verification is required for this sensitive operation.', }); return; }