import crypto from 'node:crypto'; import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse, type AuthenticationResponseJSON, type AuthenticatorTransportFuture, type RegistrationResponseJSON, } from '@simplewebauthn/server'; 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 BOOTSTRAP_TTL_MS = 15 * 60 * 1000; const WEBAUTHN_TTL_MS = 5 * 60 * 1000; const TOTP_PERIOD_SEC = 30; const DEFAULT_SECURITY = SecuritySettingsSchema.parse({}); export const SESSION_COOKIE_NAME = 'gcoord_sid'; export interface AuthSession { idHash: string; csrfTokenHash: string; safeMode: boolean; elevatedUntil: number | null; ip: string; userAgent: string; createdAt: number; lastSeenAt: number; expiresAt: number; } export interface SessionSummary { idPrefix: string; ip: string; userAgent: string; safeMode: boolean; elevatedUntil: number | null; createdAt: number; lastSeenAt: number; expiresAt: number; 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 }>; passkeyCount: number; stepUpPolicy: StepUpPolicy; stepUpMethod: SecuritySettings['stepUpMethod']; } interface WebAuthnRow { id: string; name: string; public_key: Buffer; counter: number; transports: string | null; created_at: number; } interface PendingWebAuthnChallenge { challenge: string; purpose: 'register' | 'login' | 'stepup'; rpID: string; expectedOrigin: string; label?: string; sessionIdHash?: string; createdAt: number; } 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; password_hash: string; totp_secret: string; last_login_totp_step: number | null; 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; safe_mode: number; elevated_until: number | null; ip: string; user_agent: string; created_at: number; last_seen_at: number; expires_at: number; } export function sha256Hex(value: string): string { return crypto.createHash('sha256').update(value, 'utf8').digest('hex'); } function generateRecoveryCode(): string { const bytes = crypto.randomBytes(10); let out = ''; for (let i = 0; i < 10; i++) { if (i === 5) out += '-'; out += RECOVERY_ALPHABET[bytes[i]! % RECOVERY_ALPHABET.length]; } return out; } function normalizeRecoveryCode(input: string): string { return input.trim().toUpperCase().replace(/[^A-Z0-9]/g, ''); } function buildTotp(secretBase32: string, label: string): OTPAuth.TOTP { return new OTPAuth.TOTP({ issuer: 'GCoordinator', label, algorithm: 'SHA1', digits: 6, period: TOTP_PERIOD_SEC, secret: OTPAuth.Secret.fromBase32(secretBase32), }); } 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 '15m': return nowMs + 15 * 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 pendingWebAuthn = new Map(); private readonly getSecurity: () => SecuritySettings; private recoveryStore?: EmergencyRecoveryService; private vaultService?: VaultService; 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 }>; const passkeyCount = ( this.db.prepare('SELECT COUNT(*) AS cnt FROM webauthn_credentials').get() as { cnt: number; } ).cnt; return { requireTotpOnLogin: sec.requireTotpOnLogin, passwordMode: sec.passwordMode, passwordCount: passwords.length, passwordLabels: passwords, totpMode: sec.totpMode, totpCount: totps.length, totpLabels: totps, passkeyCount, stepUpPolicy: sec.stepUpPolicy, stepUpMethod: sec.stepUpMethod, }; } async beginBootstrap(username = 'admin'): Promise<{ secretBase32: string; otpauthUri: string; qrSvg: string; }> { if (this.isBootstrapped()) { throw new Error('Admin account is already configured'); } if ( !this.pendingBootstrap || Date.now() - this.pendingBootstrap.createdAt > BOOTSTRAP_TTL_MS ) { const secret = new OTPAuth.Secret({ size: 20 }); this.pendingBootstrap = { secretBase32: secret.base32, createdAt: Date.now(), }; } const totp = buildTotp(this.pendingBootstrap.secretBase32, username); const otpauthUri = totp.toString(); const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }); return { secretBase32: this.pendingBootstrap.secretBase32, otpauthUri, qrSvg, }; } async completeBootstrap(params: { username: string; password: string; totpCode: string; secretBase32?: string; ip: string; userAgent: string; initialSafeMode?: boolean; }): Promise<{ sessionToken: string; csrfToken: string; session: AuthSession; recoveryCodes: string[]; }> { if (this.isBootstrapped()) { throw new Error('Admin account is already configured'); } const username = params.username.trim(); if (username.length < 2 || username.length > 64) { throw new Error('Username must be 2–64 characters'); } if (params.password.length < 10) { throw new Error('Password must be at least 10 characters'); } const secretBase32 = params.secretBase32 ?? this.pendingBootstrap?.secretBase32; if (!secretBase32) { throw new Error('Bootstrap enrollment session expired; reload setup'); } const nowMs = Date.now(); const totp = buildTotp(secretBase32, username); const delta = totp.validate({ token: params.totpCode.trim(), window: 1, timestamp: nowMs, }); if (delta === null) { throw new Error('Invalid TOTP verification code'); } const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; const passwordHash = await argon2.hash(params.password, { type: argon2.argon2id, memoryCost: 65536, timeCost: 3, parallelism: 1, }); const recoveryCodes: string[] = []; for (let i = 0; i < 8; i++) { recoveryCodes.push(generateRecoveryCode()); } const tx = this.db.transaction(() => { this.db .prepare( `INSERT INTO admin_users (id, username, password_hash, totp_secret, last_login_totp_step, last_stepup_totp_step, created_at, updated_at) VALUES (1, ?, ?, ?, ?, NULL, ?, ?)`, ) .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)', ); for (const code of recoveryCodes) { insertRec.run(sha256Hex(normalizeRecoveryCode(code))); } }); 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, Boolean(params.initialSafeMode), ); return { ...created, recoveryCodes }; } async login(params: { username?: string; password?: string; passwords?: string[]; code?: string; codes?: string[]; ip: string; userAgent: string; initialSafeMode?: boolean; }): Promise<{ sessionToken: string; csrfToken: string; session: AuthSession } | null> { const admin = this.db .prepare('SELECT * FROM admin_users WHERE id = 1') .get() as AdminRow | undefined; if (!admin) return null; if (params.username && params.username.trim() !== admin.username) { 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 pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode); if (!pwOk) 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); if (suppliedCodes.length === 0) return null; const mfaOk = this.verifyTotpsOrRecovery( suppliedCodes, sec.totpMode, 'login', admin.username, ); if (!mfaOk) return null; } return this.createSession( params.ip, params.userAgent, Boolean(params.initialSafeMode), ); } getSessionByToken(sessionToken: string | undefined): AuthSession | null { if (!sessionToken || sessionToken.length < 16) return null; const idHash = sha256Hex(sessionToken); const row = this.db .prepare('SELECT * FROM sessions WHERE id_hash = ?') .get(idHash) as SessionRow | undefined; if (!row) return null; const now = Date.now(); if (row.expires_at <= now) { this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); return null; } if (now - row.last_seen_at > 60_000) { this.db .prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?') .run(now, idHash); } return { idHash: row.id_hash, csrfTokenHash: row.csrf_token_hash, safeMode: row.safe_mode === 1, elevatedUntil: row.elevated_until && row.elevated_until > now ? row.elevated_until : null, ip: row.ip, userAgent: row.user_agent, createdAt: row.created_at, lastSeenAt: row.last_seen_at, expiresAt: row.expires_at, }; } 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, 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 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 === 'passkey') { return { ok: false, reason: 'passkey_required' }; } 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 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 }; } dropElevation(idHash: string): void { this.db .prepare('UPDATE sessions SET elevated_until = NULL WHERE id_hash = ?') .run(idHash); } setSafeMode(idHash: string, enabled: boolean): AuthSession | null { 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 = ? WHERE id_hash = ?') .run(enabled ? 1 : 0, idHash); } const row = this.db .prepare('SELECT * FROM sessions WHERE id_hash = ?') .get(idHash) as SessionRow | undefined; if (!row) return null; const now = Date.now(); return { idHash: row.id_hash, csrfTokenHash: row.csrf_token_hash, safeMode: row.safe_mode === 1, elevatedUntil: row.elevated_until && row.elevated_until > now ? row.elevated_until : null, ip: row.ip, userAgent: row.user_agent, createdAt: row.created_at, lastSeenAt: row.last_seen_at, expiresAt: row.expires_at, }; } listFactors(): { passwords: Array<{ id: string; label: string; createdAt: number }>; totps: Array<{ id: string; label: string; createdAt: number }>; passkeys: Array<{ id: string; name: string; transports: 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 passkeyRows = this.db .prepare( 'SELECT id, name, transports, created_at AS createdAt FROM webauthn_credentials ORDER BY created_at ASC', ) .all() as Array<{ id: string; name: string; transports: string | null; createdAt: number }>; const passkeys = passkeyRows.map((row) => { let transports: string[] = []; if (row.transports) { try { transports = JSON.parse(row.transports) as string[]; } catch { transports = []; } } return { id: row.id, name: row.name, transports, createdAt: row.createdAt }; }); const rec = this.db .prepare('SELECT COUNT(*) AS cnt FROM recovery_codes WHERE used_at IS NULL') .get() as { cnt: number }; return { passwords, totps, passkeys, unusedRecoveryCodes: rec.cnt }; } private sweepWebAuthnChallenges(): void { const cutoff = Date.now() - WEBAUTHN_TTL_MS; for (const [k, v] of this.pendingWebAuthn.entries()) { if (v.createdAt < cutoff) this.pendingWebAuthn.delete(k); } } private consumeWebAuthnChallenge( challengeId: string, purpose: PendingWebAuthnChallenge['purpose'], ): PendingWebAuthnChallenge | null { this.sweepWebAuthnChallenges(); const pending = this.pendingWebAuthn.get(challengeId); if (!pending) return null; this.pendingWebAuthn.delete(challengeId); if (pending.purpose !== purpose) return null; return pending; } private listPasskeyRows(): WebAuthnRow[] { return this.db .prepare('SELECT * FROM webauthn_credentials ORDER BY created_at ASC') .all() as WebAuthnRow[]; } async beginPasskeyRegistration(params: { label: string; rpID: string; expectedOrigin: string; }) { const username = this.getAdminUsername(); if (!username) { throw new Error('Admin account is not bootstrapped yet'); } const cleanLabel = params.label.trim(); if (cleanLabel.length < 1 || cleanLabel.length > 64) { throw new Error('Passkey label must be 1–64 characters'); } this.sweepWebAuthnChallenges(); const existing = this.listPasskeyRows(); const options = await generateRegistrationOptions({ rpName: 'GCoordinator', rpID: params.rpID, userName: username, userDisplayName: username, attestationType: 'none', excludeCredentials: existing.map((row) => ({ id: row.id, transports: row.transports ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, })), authenticatorSelection: { residentKey: 'preferred', userVerification: 'preferred', }, }); const challengeId = crypto.randomBytes(16).toString('hex'); this.pendingWebAuthn.set(challengeId, { challenge: options.challenge, purpose: 'register', rpID: params.rpID, expectedOrigin: params.expectedOrigin, label: cleanLabel, createdAt: Date.now(), }); return { challengeId, options }; } async completePasskeyRegistration(params: { challengeId: string; response: RegistrationResponseJSON; }): Promise<{ id: string; name: string; transports: string[]; createdAt: number }> { const pending = this.consumeWebAuthnChallenge(params.challengeId, 'register'); if (!pending) { throw new Error('Passkey registration challenge expired or not found'); } const verification = await verifyRegistrationResponse({ response: params.response, expectedChallenge: pending.challenge, expectedOrigin: pending.expectedOrigin, expectedRPID: pending.rpID, requireUserVerification: false, }); if (!verification.verified || !verification.registrationInfo) { throw new Error('Passkey registration verification failed'); } const { credential } = verification.registrationInfo; const transports = credential.transports ?? params.response.response.transports ?? []; const createdAt = Date.now(); const label = pending.label ?? 'Passkey'; this.db .prepare( `INSERT INTO webauthn_credentials (id, name, public_key, counter, transports, created_at) VALUES (?, ?, ?, ?, ?, ?)`, ) .run( credential.id, label, Buffer.from(credential.publicKey), credential.counter, JSON.stringify(transports), createdAt, ); return { id: credential.id, name: label, transports, createdAt }; } removePasskey(id: string): boolean { const sec = this.getSecurity(); const count = ( this.db.prepare('SELECT COUNT(*) AS cnt FROM webauthn_credentials').get() as { cnt: number; } ).cnt; if (count <= 1 && sec.stepUpPolicy !== 'off' && sec.stepUpMethod === 'passkey') { throw new Error( 'Cannot remove the last passkey while Step-Up Method is set to passkey', ); } const res = this.db.prepare('DELETE FROM webauthn_credentials WHERE id = ?').run(id); return res.changes > 0; } async beginPasskeyAuthentication(params: { purpose: 'login' | 'stepup'; rpID: string; expectedOrigin: string; sessionIdHash?: string; }) { const rows = this.listPasskeyRows(); if (rows.length === 0) { throw new Error('No passkeys registered'); } this.sweepWebAuthnChallenges(); const options = await generateAuthenticationOptions({ rpID: params.rpID, allowCredentials: rows.map((row) => ({ id: row.id, transports: row.transports ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, })), userVerification: 'preferred', }); const challengeId = crypto.randomBytes(16).toString('hex'); this.pendingWebAuthn.set(challengeId, { challenge: options.challenge, purpose: params.purpose, rpID: params.rpID, expectedOrigin: params.expectedOrigin, sessionIdHash: params.sessionIdHash, createdAt: Date.now(), }); return { challengeId, options }; } async loginWithPasskey(params: { challengeId: string; response: AuthenticationResponseJSON; ip: string; userAgent: string; initialSafeMode?: boolean; }): Promise<{ sessionToken: string; csrfToken: string; session: AuthSession } | null> { if (!this.isBootstrapped()) return null; const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login'); if (!pending) return null; const row = this.db .prepare('SELECT * FROM webauthn_credentials WHERE id = ?') .get(params.response.id) as WebAuthnRow | undefined; if (!row) return null; try { const verification = await verifyAuthenticationResponse({ response: params.response, expectedChallenge: pending.challenge, expectedOrigin: pending.expectedOrigin, expectedRPID: pending.rpID, credential: { id: row.id, publicKey: new Uint8Array(row.public_key), counter: row.counter, transports: row.transports ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, }, requireUserVerification: false, }); if (!verification.verified) return null; this.db .prepare('UPDATE webauthn_credentials SET counter = ? WHERE id = ?') .run(verification.authenticationInfo.newCounter, row.id); return this.createSession( params.ip, params.userAgent, Boolean(params.initialSafeMode), ); } catch { return null; } } async stepUpWithPasskey(params: { idHash: string; challengeId: string; response: AuthenticationResponseJSON; }): Promise<{ ok: true; elevatedUntil: number | null } | { ok: false; reason: string }> { const session = this.db .prepare('SELECT safe_mode, expires_at FROM sessions WHERE id_hash = ?') .get(params.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 pending = this.consumeWebAuthnChallenge(params.challengeId, 'stepup'); if (!pending || pending.sessionIdHash !== params.idHash) { return { ok: false, reason: 'invalid_challenge' }; } const row = this.db .prepare('SELECT * FROM webauthn_credentials WHERE id = ?') .get(params.response.id) as WebAuthnRow | undefined; if (!row) return { ok: false, reason: 'unknown_passkey' }; try { const verification = await verifyAuthenticationResponse({ response: params.response, expectedChallenge: pending.challenge, expectedOrigin: pending.expectedOrigin, expectedRPID: pending.rpID, credential: { id: row.id, publicKey: new Uint8Array(row.public_key), counter: row.counter, transports: row.transports ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, }, requireUserVerification: false, }); if (!verification.verified) { return { ok: false, reason: 'invalid_assertion' }; } this.db .prepare('UPDATE webauthn_credentials SET counter = ? WHERE id = ?') .run(verification.authenticationInfo.newCounter, row.id); const elevatedUntil = computeElevatedUntil( Date.now(), sec.stepUpPolicy, session.expires_at, false, ); this.db .prepare('UPDATE sessions SET elevated_until = ? WHERE id_hash = ?') .run(elevatedUntil, params.idHash); return { ok: true, elevatedUntil }; } catch { return { ok: false, reason: 'invalid_assertion' }; } } 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); const rows = this.db .prepare('SELECT * FROM sessions ORDER BY last_seen_at DESC') .all() as SessionRow[]; return rows.map((row) => ({ idPrefix: row.id_hash.slice(0, 12), ip: row.ip, userAgent: row.user_agent, safeMode: row.safe_mode === 1, elevatedUntil: row.elevated_until && row.elevated_until > now ? row.elevated_until : null, createdAt: row.created_at, lastSeenAt: row.last_seen_at, expiresAt: row.expires_at, current: row.id_hash === currentIdHash, })); } revokeSessionByHash(idHash: string): void { this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); } revokeSessionByPrefix(prefix: string): number { if (!/^[0-9a-f]{8,64}$/i.test(prefix)) return 0; const result = this.db .prepare('DELETE FROM sessions WHERE id_hash LIKE ?') .run(`${prefix}%`); return result.changes; } revokeAllSessions(exceptIdHash?: string): number { if (exceptIdHash) { return this.db .prepare('DELETE FROM sessions WHERE id_hash != ?') .run(exceptIdHash).changes; } 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, safeMode: boolean, ): { sessionToken: string; csrfToken: string; session: AuthSession } { const sessionToken = crypto.randomBytes(32).toString('base64url'); const csrfToken = crypto.randomBytes(32).toString('base64url'); const idHash = sha256Hex(sessionToken); 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 (?, ?, ?, ?, ?, ?, ?, ?, ?)`, ) .run( idHash, csrfTokenHash, safeMode ? 1 : 0, elevatedUntil, ip, userAgent.slice(0, 256), now, now, expiresAt, ); return { sessionToken, csrfToken, session: { idHash, csrfTokenHash, safeMode, elevatedUntil, ip, userAgent: userAgent.slice(0, 256), createdAt: now, lastSeenAt: now, expiresAt, }, }; } }