/** * Authentication and user identity service. * Handles registration, login, JWT issuance, profile management, password changes, and TOTP 2FA. */ import argon2 from 'argon2'; import jwt from 'jsonwebtoken'; import { authenticator } from 'otplib'; import { randomBytes } from 'crypto'; import * as QRCode from 'qrcode'; import { config } from '../config'; import { hashForIndex, hashForPhone, hashToken, decrypt, encrypt } from '../utils/crypto'; import * as userRepository from '../repositories/userRepository'; import * as refreshTokenRepository from '../repositories/refreshTokenRepository'; import * as auditLogRepository from '../repositories/auditLogRepository'; import * as totpRecoveryRepository from '../repositories/totpRecoveryRepository'; import * as settingsRepository from '../repositories/settingsRepository'; import { queueUserAdminStatsRefresh } from './userAdminStatsService'; import * as loginLockoutService from './loginLockoutService'; import { logSecurityEvent } from '../utils/securityAudit'; import { sendVerificationAfterRegister } from './emailVerificationService'; import * as referralRepository from '../repositories/referralRepository'; import * as referralService from './referralService'; import * as countryService from './countryService'; import { mergeVisitorSupportForUser } from './supportService'; import { registerLoginFingerprint } from '../repositories/loginFingerprintRepository'; import * as securityNotificationService from './securityNotificationService'; import * as captchaService from './captchaService'; import { assessLoginRisk, recordLoginRisk } from './loginRiskService'; import { enforceConcurrentSessionLimit } from './sessionService'; import { SystemSettings } from '../models'; import { parseUserGender, type UserGender } from '../models/userGender'; import { JwtPayload, RoleName } from '../types'; import * as roleRepository from '../repositories/roleRepository'; import { hasAdminAccess } from '../utils/roleAccess'; import { v4 as uuidv4 } from 'uuid'; authenticator.options = { digits: 6, step: 30 }; const RECOVERY_CODE_COUNT = 10; function generateRecoveryCodes(): string[] { const codes: string[] = []; for (let i = 0; i < RECOVERY_CODE_COUNT; i++) { codes.push(randomBytes(5).toString('hex').toUpperCase()); } return codes; } function normalizeRecoveryCode(code: string): string { return code.trim().replace(/\s+/g, '').toUpperCase(); } async function verifySecondFactor(userId: string, code?: string): Promise<'totp' | 'recovery'> { const user = await userRepository.findById(userId); if (!user || !user.totp_enabled) throw new Error('2FA not enabled'); if (!code?.trim()) throw new Error('2FA required'); const secret = user.totp_secret_encrypted ? decrypt(user.totp_secret_encrypted) : ''; if (authenticator.verify({ token: code.trim(), secret })) return 'totp'; const normalized = normalizeRecoveryCode(code); if (normalized.length >= 8) { const ok = await totpRecoveryRepository.consumeCode(userId, hashForIndex(normalized)); if (ok) return 'recovery'; } throw new Error('Invalid 2FA code'); } /** Builds JWT claims from current DB roles and permissions. */ export async function buildJwtPayload(user: { id: string; email_hash: string; token_version?: number; }): Promise { const roles = await roleRepository.getUserRoleNames(user.id); const permissions = await roleRepository.getUserPermissions(user.id); const primaryRole = roleRepository.resolvePrimaryRole(roles); return { userId: user.id, emailHash: user.email_hash, roles, permissions, primaryRole, role: primaryRole, tv: user.token_version ?? 1, }; } /** Normalizes legacy JWT payloads that only contain a single `role`. */ export function normalizeJwtPayload(decoded: JwtPayload): JwtPayload { const roles = decoded.roles?.length ? decoded.roles : decoded.role ? [decoded.role] : (['user'] as RoleName[]); const primaryRole = roleRepository.resolvePrimaryRole(roles); return { ...decoded, roles, permissions: decoded.permissions ?? [], primaryRole, role: primaryRole, }; } /** * Converts a duration string (e.g. "7d", "15m") to milliseconds. * Falls back to 7 days when the format is unrecognized. * @param expiry Duration string with numeric value and unit (s, m, h, d) * @returns Duration in milliseconds */ function parseExpiryToMs(expiry: string): number { const m = expiry.match(/^(\d+)(m|h|d|s)$/i); if (!m) return 7 * 24 * 60 * 60 * 1000; const n = parseInt(m[1], 10); const unit = m[2].toLowerCase(); if (unit === 's') return n * 1000; if (unit === 'm') return n * 60 * 1000; if (unit === 'h') return n * 60 * 60 * 1000; if (unit === 'd') return n * 24 * 60 * 60 * 1000; return 7 * 24 * 60 * 60 * 1000; } /** * Validates a password against the system password policy from settings. * @param password Plain-text password to validate * @param policy System settings containing password rules * @throws {Error} When the password fails any configured policy rule */ export function validatePassword(password: string, policy: SystemSettings): void { if (password.length < policy.password_min_length) { throw new Error(`Password must be at least ${policy.password_min_length} characters`); } if (policy.password_require_uppercase && !/[A-Z]/.test(password)) { throw new Error('Password must include at least one uppercase letter'); } if (policy.password_require_lowercase && !/[a-z]/.test(password)) { throw new Error('Password must include at least one lowercase letter'); } if (policy.password_require_number && !/\d/.test(password)) { throw new Error('Password must include at least one number'); } if (policy.password_require_special && !/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password)) { throw new Error('Password must include at least one special character'); } } /** * Registers a new user with profile, country, and optional referral code. */ export async function register(input: { email: string; password: string; fullName: string; phone?: string; countryOfResidence: string; nationality?: string; gender: string; referralCode?: string; registrationIp?: string; userAgent?: string; visitorSupportToken?: string | null; }): Promise<{ userId: string; referralCode: string; emailVerificationRequired: boolean }> { const policy = await settingsRepository.getSettings(); validatePassword(input.password, policy); const normalizedEmail = input.email.trim().toLowerCase(); if (!normalizedEmail) throw new Error('Email is required'); const fullName = input.fullName.trim(); if (fullName.length < 2) throw new Error('Full name is required'); const country = input.countryOfResidence.trim().toUpperCase(); if (!/^[A-Z]{2}$/.test(country)) { throw new Error('Country of residence must be a 2-letter ISO code (e.g. FR, US)'); } await countryService.assertCountryAllowedForRegistration(country); const nationality = input.nationality?.trim().toUpperCase() || null; if (nationality && !/^[A-Z]{2}$/.test(nationality)) { throw new Error('Nationality must be a 2-letter ISO code'); } const gender = parseUserGender(input.gender); const emailHash = hashForIndex(normalizedEmail); const existing = await userRepository.findByEmailHash(emailHash); if (existing) { throw new Error('Email is already registered'); } let phoneHash: string | null = null; let phoneEncrypted: string | null = null; if (input.phone?.trim()) { const normalizedPhone = input.phone.trim(); phoneHash = hashForPhone(normalizedPhone); const existingPhone = await userRepository.findByPhoneHash(phoneHash); if (existingPhone) throw new Error('Phone number already registered'); phoneEncrypted = encrypt(normalizedPhone); } const referredByUserId = await referralService.resolveReferrerId(input.referralCode); if (referredByUserId) { await referralService.assertReferrerEligible(referredByUserId); } const nameParts = fullName.split(/\s+/); const firstName = nameParts[0] ?? fullName; const lastName = nameParts.length > 1 ? nameParts.slice(1).join(' ') : null; const passwordHash = await argon2.hash(input.password, { type: argon2.argon2id }); const userReferralCode = await referralRepository.generateUniqueReferralCode(); const user = await userRepository.create({ emailHash, emailEncrypted: encrypt(normalizedEmail), passwordHash, roleId: 1, firstName, lastName, phoneHash, phoneEncrypted, countryOfResidence: country, nationality, gender, referralCode: userReferralCode, referredByUserId, registrationIp: input.registrationIp?.trim() || null, }); await auditLogRepository.create({ userId: user.id, action: 'register', resourceType: 'user', resourceId: user.id, ipAddress: input.registrationIp ?? null, userAgent: input.userAgent ?? null, metadata: referredByUserId ? { referred_by_user_id: referredByUserId } : null, }); void sendVerificationAfterRegister(user.id); void mergeVisitorSupportForUser(user.id, input.visitorSupportToken); return { userId: user.id, referralCode: userReferralCode, emailVerificationRequired: true, }; } /** * Authenticates a user and issues access and refresh tokens. * @param email User email for lookup * @param password Plain-text password * @param totpCode Optional TOTP code when 2FA is enabled * @param auditContext Optional IP and user agent for login audit log * @returns Access token, refresh token, expiry seconds, and basic user info * @throws {Error} On invalid credentials, disabled/locked account, or failed 2FA */ export async function login( email: string, password: string, totpCode?: string, auditContext?: { ipAddress?: string; userAgent?: string; visitorSupportToken?: string | null }, captchaToken?: string ): Promise<{ accessToken: string; refreshToken: string; expiresIn: number; user: { id: string; emailHash: string; role: RoleName; roles: RoleName[]; permissions: string[]; primaryRole: RoleName; }; }> { const emailHash = hashForIndex(email); const user = await userRepository.findByEmailHash(emailHash); const auditIp = auditContext?.ipAddress; const auditUa = auditContext?.userAgent; if (!user) { logSecurityEvent('login_failed', { ipAddress: auditIp ?? null, userAgent: auditUa ?? null, metadata: { reason: 'invalid_credentials' }, }); throw new Error('Invalid credentials'); } if (user.deleted_at) { logSecurityEvent('login_failed', { userId: user.id, ipAddress: auditIp ?? null, userAgent: auditUa ?? null, metadata: { reason: 'account_deleted' }, }); throw new Error('Invalid credentials'); } try { await loginLockoutService.assertLoginNotLocked(user.id); } catch (e) { logSecurityEvent('login_failed', { userId: user.id, ipAddress: auditIp ?? null, userAgent: auditUa ?? null, metadata: { reason: 'account_locked' }, }); throw e; } const settings = await settingsRepository.getSettings(); const failedCount = await userRepository.getFailedLoginCount(user.id); const afterFailures = settings.login_captcha_after_failures; if (afterFailures > 0 && failedCount >= afterFailures) { try { await captchaService.verifyCaptchaToken(captchaToken, auditIp); } catch (e) { throw captchaService.withCaptchaChallenge(e as Error & { code?: string }); } } if (user.is_enabled === false) { logSecurityEvent('login_failed', { userId: user.id, ipAddress: auditIp ?? null, userAgent: auditUa ?? null, metadata: { reason: 'account_disabled' }, }); throw new Error('Account is disabled'); } if (user.is_account_non_locked === false) { logSecurityEvent('login_failed', { userId: user.id, ipAddress: auditIp ?? null, userAgent: auditUa ?? null, metadata: { reason: 'account_locked_admin' }, }); throw new Error('Account is locked'); } if (user.is_account_non_expired === false) { throw new Error('Account has expired'); } if (user.is_credentials_non_expired === false) { throw new Error('Credentials have expired'); } const ok = await argon2.verify(user.password_hash, password); if (!ok) { await loginLockoutService.recordFailedLogin(user.id, { ipAddress: auditIp, userAgent: auditUa, reason: 'invalid_password', }); await loginLockoutService.assertLoginNotLocked(user.id); throw new Error('Invalid credentials'); } if (settings.require_email_verification_for_login && !user.email_verified) { const err = new Error( 'Please verify your email before signing in. Check your inbox for the confirmation link.' ) as Error & { code?: string }; err.code = 'EMAIL_NOT_VERIFIED'; throw err; } if (user.totp_enabled) { if (!totpCode) throw new Error('2FA required'); try { await verifySecondFactor(user.id, totpCode); } catch { await loginLockoutService.recordFailedLogin(user.id, { ipAddress: auditIp, userAgent: auditUa, reason: 'invalid_2fa', }); await loginLockoutService.assertLoginNotLocked(user.id); throw new Error('Invalid 2FA code'); } } await loginLockoutService.clearLoginFailures(user.id); const payload = await buildJwtPayload(user); const accessExpiry = settings.access_token_expiry || config.jwt.accessExpiry; const accessToken = jwt.sign(payload, config.jwt.secret, { expiresIn: accessExpiry } as jwt.SignOptions); const refreshToken = uuidv4(); const refreshExpiryMs = parseExpiryToMs(settings.refresh_token_expiry || config.jwt.refreshExpiry); const expiresAt = new Date(Date.now() + refreshExpiryMs); await refreshTokenRepository.create(user.id, hashToken(refreshToken), expiresAt, { ipAddress: auditContext?.ipAddress, userAgent: auditContext?.userAgent, }); await enforceConcurrentSessionLimit(user.id, auditContext); if (auditContext) { await auditLogRepository.create({ userId: user.id, action: 'login', ipAddress: auditContext.ipAddress, userAgent: auditContext.userAgent, }); queueUserAdminStatsRefresh(user.id); const fingerprint = await registerLoginFingerprint( user.id, auditContext.ipAddress, auditContext.userAgent ); const notifyCtx = { ipAddress: auditContext.ipAddress, userAgent: auditContext.userAgent, countryCode: fingerprint.countryCode, }; if (fingerprint.isNewDevice) { void securityNotificationService.notifyNewLogin(user.id, notifyCtx); } if (fingerprint.isNewCountry && fingerprint.countryCode) { void securityNotificationService.notifyNewCountryLogin(user.id, notifyCtx); } const risk = assessLoginRisk(fingerprint); void recordLoginRisk(user.id, risk, notifyCtx); } void mergeVisitorSupportForUser(user.id, auditContext?.visitorSupportToken); const decoded = jwt.decode(accessToken) as { exp: number }; return { accessToken, refreshToken, expiresIn: decoded.exp - Math.floor(Date.now() / 1000), user: { id: user.id, emailHash: user.email_hash, role: payload.primaryRole, roles: payload.roles, permissions: payload.permissions, primaryRole: payload.primaryRole, }, }; } /** * Issues a new access/refresh token pair from a valid refresh token (rotation). * @param refreshToken Opaque refresh token issued at login * @returns New access token, rotated refresh token, and remaining lifetime in seconds * @throws {Error} When refresh token is invalid or user no longer exists / is disabled */ export async function refreshTokens(refreshToken: string): Promise<{ accessToken: string; refreshToken: string; expiresIn: number; }> { const tokenHash = hashToken(refreshToken); const row = await refreshTokenRepository.findByTokenHash(tokenHash); if (!row) throw new Error('Invalid refresh token'); const user = await userRepository.findById(row.user_id); if (!user) throw new Error('User not found'); if (user.deleted_at) throw new Error('Account is not available'); if (user.is_enabled === false) throw new Error('Account is disabled'); if (user.is_account_non_locked === false) throw new Error('Account is locked'); if (user.is_account_non_expired === false) throw new Error('Account has expired'); if (user.is_credentials_non_expired === false) throw new Error('Credentials have expired'); await refreshTokenRepository.deleteByTokenHash(tokenHash); const settings = await settingsRepository.getSettings(); const accessExpiry = settings.access_token_expiry || config.jwt.accessExpiry; const payload = await buildJwtPayload(user); const accessToken = jwt.sign(payload, config.jwt.secret, { expiresIn: accessExpiry } as jwt.SignOptions); const newRefreshToken = uuidv4(); const refreshExpiryMs = parseExpiryToMs(settings.refresh_token_expiry || config.jwt.refreshExpiry); const expiresAt = new Date(Date.now() + refreshExpiryMs); await refreshTokenRepository.create(user.id, hashToken(newRefreshToken), expiresAt); await enforceConcurrentSessionLimit(user.id); const decoded = jwt.decode(accessToken) as { exp: number }; return { accessToken, refreshToken: newRefreshToken, expiresIn: decoded.exp - Math.floor(Date.now() / 1000), }; } /** * Revokes the current refresh token (logout). */ export async function logout( refreshToken: string, auditContext?: { ipAddress?: string; userAgent?: string } ): Promise { const tokenHash = hashToken(refreshToken); const row = await refreshTokenRepository.findByTokenHash(tokenHash); if (!row) return; await refreshTokenRepository.deleteByTokenHash(tokenHash); await auditLogRepository.create({ userId: row.user_id, action: 'logout', ipAddress: auditContext?.ipAddress ?? null, userAgent: auditContext?.userAgent ?? null, }); } /** * Revokes all refresh tokens for the user (logout everywhere). */ export async function logoutAll( userId: string, auditContext?: { ipAddress?: string; userAgent?: string } ): Promise { await refreshTokenRepository.deleteByUserId(userId); await userRepository.incrementTokenVersion(userId); await auditLogRepository.create({ userId, action: 'logout_all', ipAddress: auditContext?.ipAddress ?? null, userAgent: auditContext?.userAgent ?? null, }); } /** * Returns decrypted profile fields for the authenticated user. * @param userId User UUID * @returns Profile fields (names, date of birth, email, phone) * @throws {Error} When user is not found */ export async function getProfile(userId: string): Promise<{ id: string; firstName: string | null; middleName: string | null; lastName: string | null; dateOfBirth: string | null; email: string | null; phone: string | null; countryOfResidence: string | null; nationality: string | null; gender: UserGender | null; role: string; emailVerified: boolean; totpEnabled: boolean; createdAt: string; }> { const row = await userRepository.getSelfProfileForUser(userId); if (!row) throw new Error('User not found'); const dob = row.date_of_birth; const createdAt = row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at); return { id: row.id, firstName: row.first_name ?? null, middleName: row.middle_name ?? null, lastName: row.last_name ?? null, dateOfBirth: dob != null ? (typeof dob === 'string' ? dob : (dob as Date).toISOString().slice(0, 10)) : null, email: row.email_encrypted ? decrypt(row.email_encrypted) : null, phone: row.phone_encrypted ? decrypt(row.phone_encrypted) : null, countryOfResidence: row.country_of_residence ?? null, nationality: row.nationality ?? null, gender: (row.gender as UserGender | null) ?? null, role: row.role_name, emailVerified: row.email_verified, totpEnabled: row.totp_enabled, createdAt, }; } /** * Updates user profile fields; email and phone are re-hashed and encrypted. * @param userId User UUID * @param updates Partial profile updates (undefined fields are skipped) * @throws {Error} When user not found, email/phone empty, or already used by another account */ export async function updateProfile( userId: string, updates: { firstName?: string | null; middleName?: string | null; lastName?: string | null; dateOfBirth?: string | null; email?: string; phone?: string | null; countryOfResidence?: string | null; nationality?: string | null; gender?: string; } ): Promise { const existing = await userRepository.findById(userId); if (!existing) throw new Error('User not found'); const data: Parameters[1] = {}; if (updates.firstName !== undefined) data.first_name = (updates.firstName ?? '').trim() || null; if (updates.middleName !== undefined) data.middle_name = (updates.middleName ?? '').trim() || null; if (updates.lastName !== undefined) data.last_name = (updates.lastName ?? '').trim() || null; if (updates.dateOfBirth !== undefined) data.date_of_birth = (updates.dateOfBirth ?? '').trim() || null; if (updates.email !== undefined) { const newEmail = updates.email.trim().toLowerCase(); if (!newEmail) throw new Error('Email cannot be empty'); const newEmailHash = hashForIndex(newEmail); const existingByEmail = await userRepository.findByEmailHash(newEmailHash); if (existingByEmail && existingByEmail.id !== userId) { throw new Error('Email is already in use by another account'); } data.emailHash = newEmailHash; data.emailEncrypted = encrypt(newEmail); await userRepository.setEmailVerified(userId, false); } if (updates.phone !== undefined) { if (updates.phone === null || updates.phone.trim() === '') { data.phoneHash = null; data.phoneEncrypted = null; } else { const normalized = updates.phone.trim(); const newPhoneHash = hashForPhone(normalized); const existingByPhone = await userRepository.findByPhoneHash(newPhoneHash); if (existingByPhone && existingByPhone.id !== userId) { throw new Error('Phone number is already in use by another account'); } data.phoneHash = newPhoneHash; data.phoneEncrypted = encrypt(normalized); } } if (updates.countryOfResidence !== undefined) { const country = (updates.countryOfResidence ?? '').trim().toUpperCase(); if (!country) throw new Error('Country of residence is required'); if (!/^[A-Z]{2}$/.test(country)) { throw new Error('Country of residence must be a 2-letter ISO code (e.g. FR, US)'); } await countryService.assertCountryAllowedForRegistration(country); data.country_of_residence = country; } if (updates.nationality !== undefined) { if (updates.nationality === null || updates.nationality.trim() === '') { data.nationality = null; } else { const nat = updates.nationality.trim().toUpperCase(); if (!/^[A-Z]{2}$/.test(nat)) { throw new Error('Nationality must be a 2-letter ISO code'); } data.nationality = nat; } } if (updates.gender !== undefined) { data.gender = parseUserGender(updates.gender); } if (Object.keys(data).length > 0) { await userRepository.updateProfile(userId, data); } } /** * Changes the user's password after verifying the current one. * @param userId User UUID * @param currentPassword Existing plain-text password * @param newPassword New plain-text password (validated against policy) * @throws {Error} When user not found, current password wrong, or new password fails policy */ export async function changePassword( userId: string, currentPassword: string, newPassword: string, auditContext?: { ipAddress?: string; userAgent?: string } ): Promise { const user = await userRepository.findById(userId); if (!user) throw new Error('User not found'); const ok = await argon2.verify(user.password_hash, currentPassword); if (!ok) throw new Error('Current password is incorrect'); const policy = await settingsRepository.getSettings(); validatePassword(newPassword, policy); const passwordHash = await argon2.hash(newPassword, { type: argon2.argon2id }); await userRepository.updatePassword(userId, passwordHash); await refreshTokenRepository.deleteByUserId(userId); await auditLogRepository.create({ userId, action: 'password_changed', ipAddress: auditContext?.ipAddress ?? null, userAgent: auditContext?.userAgent ?? null, }); void securityNotificationService.notifyPasswordChanged(userId, { ipAddress: auditContext?.ipAddress, userAgent: auditContext?.userAgent, }); } /** * Generates a new TOTP secret and QR code for 2FA setup (not yet enabled until confirmed). * @param userId User UUID * @returns Base32 secret and data-URL QR code for authenticator apps * @throws {Error} When user is not found */ export async function setupTotp( userId: string, opts?: { password?: string; totpCode?: string; auditContext?: { ipAddress?: string; userAgent?: string } } ): Promise<{ secret: string; qrCodeUrl: string }> { const user = await userRepository.findById(userId); if (!user) throw new Error('User not found'); if (user.totp_enabled) { if (!opts?.password || !opts?.totpCode) { throw new Error('Password and current 2FA code are required to reset 2FA setup'); } const pwOk = await argon2.verify(user.password_hash, opts.password); if (!pwOk) throw new Error('Current password is incorrect'); await verifySecondFactor(userId, opts.totpCode); await totpRecoveryRepository.deleteCodesForUser(userId); await userRepository.updateTotp(userId, null, false); await auditLogRepository.create({ userId, action: 'totp_setup_reset', ipAddress: opts.auditContext?.ipAddress ?? null, userAgent: opts.auditContext?.userAgent ?? null, }); } const secret = authenticator.generateSecret(); const encrypted = encrypt(secret); const otpauth = authenticator.keyuri(user.email_hash, 'Prediqo', secret); const qrCodeUrl = await QRCode.toDataURL(otpauth); await userRepository.updateTotp(userId, encrypted, false); await auditLogRepository.create({ userId, action: 'totp_setup_started', ipAddress: opts?.auditContext?.ipAddress ?? null, userAgent: opts?.auditContext?.userAgent ?? null, }); return { secret, qrCodeUrl }; } /** * Confirms and enables 2FA after the user verifies a TOTP code from setup. * @param userId User UUID * @param code Six-digit TOTP code from authenticator app * @throws {Error} When 2FA was not set up or code is invalid */ export async function enableTotp( userId: string, code: string, auditContext?: { ipAddress?: string; userAgent?: string } ): Promise<{ recoveryCodes: string[] }> { const user = await userRepository.findById(userId); if (!user || !user.totp_secret_encrypted) throw new Error('2FA not set up'); const secret = decrypt(user.totp_secret_encrypted); const valid = authenticator.verify({ token: code, secret }); if (!valid) throw new Error('Invalid 2FA code'); await userRepository.updateTotp(userId, user.totp_secret_encrypted, true); const recoveryCodes = generateRecoveryCodes(); await totpRecoveryRepository.replaceCodesForUser( userId, recoveryCodes.map((c) => hashForIndex(normalizeRecoveryCode(c))) ); await auditLogRepository.create({ userId, action: 'totp_enabled', ipAddress: auditContext?.ipAddress ?? null, userAgent: auditContext?.userAgent ?? null, metadata: { recoveryCodesIssued: recoveryCodes.length }, }); void securityNotificationService.notifyTotpEnabled(userId, { ipAddress: auditContext?.ipAddress, userAgent: auditContext?.userAgent, }); return { recoveryCodes }; } /** * Verifies TOTP for sensitive actions (e.g. transfer). No-op when 2FA is disabled * unless platform policy requires withdrawal 2FA (see assertWithdrawalSecondFactor). */ export async function verifyTotp(userId: string, totpCode?: string): Promise { const user = await userRepository.findById(userId); if (!user) throw new Error('User not found'); if (!user.totp_enabled) return; await verifySecondFactor(userId, totpCode); } /** * Enforces platform withdrawal/transfer 2FA policy. * When require_withdrawal_2fa is enabled, user must have 2FA on and provide a valid code. */ export async function assertWithdrawalSecondFactor(userId: string, totpCode?: string): Promise { const settings = await settingsRepository.getSettings(); if (!settings.require_withdrawal_2fa) { await verifyTotp(userId, totpCode); return; } const user = await userRepository.findById(userId); if (!user) throw new Error('User not found'); if (!user.totp_enabled) { const err = new Error( '2FA must be enabled before withdrawals or transfers. Enable two-factor authentication in your profile.' ) as Error & { code?: string }; err.code = 'WITHDRAWAL_2FA_REQUIRED'; throw err; } await verifySecondFactor(userId, totpCode); } /** * Disables 2FA after verifying password and TOTP / recovery code. */ export async function disableTotp( userId: string, password: string, code: string, auditContext?: { ipAddress?: string; userAgent?: string } ): Promise { const user = await userRepository.findById(userId); if (!user) throw new Error('User not found'); if (!user.totp_enabled) throw new Error('2FA is not enabled'); const pwOk = await argon2.verify(user.password_hash, password); if (!pwOk) throw new Error('Current password is incorrect'); await verifySecondFactor(userId, code); await userRepository.updateTotp(userId, null, false); await totpRecoveryRepository.deleteCodesForUser(userId); await auditLogRepository.create({ userId, action: 'totp_disabled', ipAddress: auditContext?.ipAddress ?? null, userAgent: auditContext?.userAgent ?? null, }); void securityNotificationService.notifyTotpDisabled(userId, { ipAddress: auditContext?.ipAddress, userAgent: auditContext?.userAgent, }); } /** * Issues new recovery codes (invalidates previous). Requires valid TOTP. */ export async function regenerateRecoveryCodes( userId: string, totpCode: string, auditContext?: { ipAddress?: string; userAgent?: string } ): Promise<{ recoveryCodes: string[] }> { const user = await userRepository.findById(userId); if (!user?.totp_enabled) throw new Error('2FA is not enabled'); const secret = user.totp_secret_encrypted ? decrypt(user.totp_secret_encrypted) : ''; if (!authenticator.verify({ token: totpCode, secret })) { throw new Error('Invalid 2FA code'); } const recoveryCodes = generateRecoveryCodes(); await totpRecoveryRepository.replaceCodesForUser( userId, recoveryCodes.map((c) => hashForIndex(normalizeRecoveryCode(c))) ); await auditLogRepository.create({ userId, action: 'totp_recovery_regenerated', ipAddress: auditContext?.ipAddress ?? null, userAgent: auditContext?.userAgent ?? null, metadata: { count: recoveryCodes.length }, }); return { recoveryCodes }; } /** * Verifies and decodes a JWT access token. * @param accessToken Signed JWT string * @returns Decoded payload with userId, emailHash, and role * @throws jwt.JsonWebTokenError When token is invalid or expired */ export async function verifyToken(accessToken: string): Promise { const decoded = jwt.verify(accessToken, config.jwt.secret) as JwtPayload; return normalizeJwtPayload(decoded); } /** * Returns a guard function that throws if the JWT payload role is not allowed. * @param allowed Roles permitted for the protected route * @returns Callback that validates payload.role against allowed list * @throws {Error} Forbidden when role is not in allowed */ export function requireRole(allowed: RoleName[]): (payload: JwtPayload) => void { return (payload: JwtPayload) => { const roles = payload.roles ?? (payload.role ? [payload.role] : []); const ok = allowed.some((r) => roles.includes(r)) || (allowed.includes('admin') && hasAdminAccess(payload)); if (!ok) throw new Error('Forbidden'); }; }