"use strict"; /** * Authentication and user identity service. * Handles registration, login, JWT issuance, profile management, password changes, and TOTP 2FA. */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildJwtPayload = buildJwtPayload; exports.normalizeJwtPayload = normalizeJwtPayload; exports.validatePassword = validatePassword; exports.register = register; exports.login = login; exports.refreshTokens = refreshTokens; exports.logout = logout; exports.logoutAll = logoutAll; exports.getProfile = getProfile; exports.updateProfile = updateProfile; exports.changePassword = changePassword; exports.setupTotp = setupTotp; exports.enableTotp = enableTotp; exports.verifyTotp = verifyTotp; exports.assertWithdrawalSecondFactor = assertWithdrawalSecondFactor; exports.disableTotp = disableTotp; exports.regenerateRecoveryCodes = regenerateRecoveryCodes; exports.verifyToken = verifyToken; exports.requireRole = requireRole; const argon2_1 = __importDefault(require("argon2")); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const otplib_1 = require("otplib"); const crypto_1 = require("crypto"); const QRCode = __importStar(require("qrcode")); const config_1 = require("../config"); const crypto_2 = require("../utils/crypto"); const userRepository = __importStar(require("../repositories/userRepository")); const refreshTokenRepository = __importStar(require("../repositories/refreshTokenRepository")); const auditLogRepository = __importStar(require("../repositories/auditLogRepository")); const totpRecoveryRepository = __importStar(require("../repositories/totpRecoveryRepository")); const settingsRepository = __importStar(require("../repositories/settingsRepository")); const userAdminStatsService_1 = require("./userAdminStatsService"); const loginLockoutService = __importStar(require("./loginLockoutService")); const securityAudit_1 = require("../utils/securityAudit"); const emailVerificationService_1 = require("./emailVerificationService"); const referralRepository = __importStar(require("../repositories/referralRepository")); const referralService = __importStar(require("./referralService")); const countryService = __importStar(require("./countryService")); const supportService_1 = require("./supportService"); const loginFingerprintRepository_1 = require("../repositories/loginFingerprintRepository"); const securityNotificationService = __importStar(require("./securityNotificationService")); const captchaService = __importStar(require("./captchaService")); const loginRiskService_1 = require("./loginRiskService"); const sessionService_1 = require("./sessionService"); const userGender_1 = require("../models/userGender"); const roleRepository = __importStar(require("../repositories/roleRepository")); const roleAccess_1 = require("../utils/roleAccess"); const uuid_1 = require("uuid"); otplib_1.authenticator.options = { digits: 6, step: 30 }; const RECOVERY_CODE_COUNT = 10; function generateRecoveryCodes() { const codes = []; for (let i = 0; i < RECOVERY_CODE_COUNT; i++) { codes.push((0, crypto_1.randomBytes)(5).toString('hex').toUpperCase()); } return codes; } function normalizeRecoveryCode(code) { return code.trim().replace(/\s+/g, '').toUpperCase(); } async function verifySecondFactor(userId, code) { 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 ? (0, crypto_2.decrypt)(user.totp_secret_encrypted) : ''; if (otplib_1.authenticator.verify({ token: code.trim(), secret })) return 'totp'; const normalized = normalizeRecoveryCode(code); if (normalized.length >= 8) { const ok = await totpRecoveryRepository.consumeCode(userId, (0, crypto_2.hashForIndex)(normalized)); if (ok) return 'recovery'; } throw new Error('Invalid 2FA code'); } /** Builds JWT claims from current DB roles and permissions. */ async function buildJwtPayload(user) { 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`. */ function normalizeJwtPayload(decoded) { const roles = decoded.roles?.length ? decoded.roles : decoded.role ? [decoded.role] : ['user']; 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) { 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 */ function validatePassword(password, policy) { 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. */ async function register(input) { 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 = (0, userGender_1.parseUserGender)(input.gender); const emailHash = (0, crypto_2.hashForIndex)(normalizedEmail); const existing = await userRepository.findByEmailHash(emailHash); if (existing) { throw new Error('Email is already registered'); } let phoneHash = null; let phoneEncrypted = null; if (input.phone?.trim()) { const normalizedPhone = input.phone.trim(); phoneHash = (0, crypto_2.hashForPhone)(normalizedPhone); const existingPhone = await userRepository.findByPhoneHash(phoneHash); if (existingPhone) throw new Error('Phone number already registered'); phoneEncrypted = (0, crypto_2.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_1.default.hash(input.password, { type: argon2_1.default.argon2id }); const userReferralCode = await referralRepository.generateUniqueReferralCode(); const user = await userRepository.create({ emailHash, emailEncrypted: (0, crypto_2.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 (0, emailVerificationService_1.sendVerificationAfterRegister)(user.id); void (0, supportService_1.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 */ async function login(email, password, totpCode, auditContext, captchaToken) { const emailHash = (0, crypto_2.hashForIndex)(email); const user = await userRepository.findByEmailHash(emailHash); const auditIp = auditContext?.ipAddress; const auditUa = auditContext?.userAgent; if (!user) { (0, securityAudit_1.logSecurityEvent)('login_failed', { ipAddress: auditIp ?? null, userAgent: auditUa ?? null, metadata: { reason: 'invalid_credentials' }, }); throw new Error('Invalid credentials'); } if (user.deleted_at) { (0, securityAudit_1.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) { (0, securityAudit_1.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); } } if (user.is_enabled === false) { (0, securityAudit_1.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) { (0, securityAudit_1.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_1.default.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.'); 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_1.config.jwt.accessExpiry; const accessToken = jsonwebtoken_1.default.sign(payload, config_1.config.jwt.secret, { expiresIn: accessExpiry }); const refreshToken = (0, uuid_1.v4)(); const refreshExpiryMs = parseExpiryToMs(settings.refresh_token_expiry || config_1.config.jwt.refreshExpiry); const expiresAt = new Date(Date.now() + refreshExpiryMs); await refreshTokenRepository.create(user.id, (0, crypto_2.hashToken)(refreshToken), expiresAt, { ipAddress: auditContext?.ipAddress, userAgent: auditContext?.userAgent, }); await (0, sessionService_1.enforceConcurrentSessionLimit)(user.id, auditContext); if (auditContext) { await auditLogRepository.create({ userId: user.id, action: 'login', ipAddress: auditContext.ipAddress, userAgent: auditContext.userAgent, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(user.id); const fingerprint = await (0, loginFingerprintRepository_1.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 = (0, loginRiskService_1.assessLoginRisk)(fingerprint); void (0, loginRiskService_1.recordLoginRisk)(user.id, risk, notifyCtx); } void (0, supportService_1.mergeVisitorSupportForUser)(user.id, auditContext?.visitorSupportToken); const decoded = jsonwebtoken_1.default.decode(accessToken); 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 */ async function refreshTokens(refreshToken) { const tokenHash = (0, crypto_2.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_1.config.jwt.accessExpiry; const payload = await buildJwtPayload(user); const accessToken = jsonwebtoken_1.default.sign(payload, config_1.config.jwt.secret, { expiresIn: accessExpiry }); const newRefreshToken = (0, uuid_1.v4)(); const refreshExpiryMs = parseExpiryToMs(settings.refresh_token_expiry || config_1.config.jwt.refreshExpiry); const expiresAt = new Date(Date.now() + refreshExpiryMs); await refreshTokenRepository.create(user.id, (0, crypto_2.hashToken)(newRefreshToken), expiresAt); await (0, sessionService_1.enforceConcurrentSessionLimit)(user.id); const decoded = jsonwebtoken_1.default.decode(accessToken); return { accessToken, refreshToken: newRefreshToken, expiresIn: decoded.exp - Math.floor(Date.now() / 1000), }; } /** * Revokes the current refresh token (logout). */ async function logout(refreshToken, auditContext) { const tokenHash = (0, crypto_2.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). */ async function logoutAll(userId, auditContext) { 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 */ async function getProfile(userId) { 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); // PII decrypt must not block /me (e.g. after ENCRYPTION_KEY rotation): otherwise // Super Admins cannot re-enable 2FA from the profile page after break-glass. const safeDecrypt = (ciphertext, field) => { if (!ciphertext) return null; try { return (0, crypto_2.decrypt)(ciphertext); } catch (e) { const detail = e instanceof Error ? e.message : String(e); console.error(`[profile] Failed to decrypt ${field} for user ${userId}: ${detail}`); return null; } }; 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.toISOString().slice(0, 10)) : null, email: safeDecrypt(row.email_encrypted, 'email'), phone: safeDecrypt(row.phone_encrypted, 'phone'), countryOfResidence: row.country_of_residence ?? null, nationality: row.nationality ?? null, gender: row.gender ?? 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 */ async function updateProfile(userId, updates) { const existing = await userRepository.findById(userId); if (!existing) throw new Error('User not found'); const data = {}; 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 = (0, crypto_2.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 = (0, crypto_2.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 = (0, crypto_2.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 = (0, crypto_2.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 = (0, userGender_1.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 */ async function changePassword(userId, currentPassword, newPassword, auditContext) { const user = await userRepository.findById(userId); if (!user) throw new Error('User not found'); const ok = await argon2_1.default.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_1.default.hash(newPassword, { type: argon2_1.default.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 */ async function setupTotp(userId, opts) { 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_1.default.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 = otplib_1.authenticator.generateSecret(); const encrypted = (0, crypto_2.encrypt)(secret); const otpauth = otplib_1.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 */ async function enableTotp(userId, code, auditContext) { const user = await userRepository.findById(userId); if (!user || !user.totp_secret_encrypted) throw new Error('2FA not set up'); const secret = (0, crypto_2.decrypt)(user.totp_secret_encrypted); const valid = otplib_1.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) => (0, crypto_2.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). */ async function verifyTotp(userId, totpCode) { 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. */ async function assertWithdrawalSecondFactor(userId, totpCode) { 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.'); err.code = 'WITHDRAWAL_2FA_REQUIRED'; throw err; } await verifySecondFactor(userId, totpCode); } /** * Disables 2FA after verifying password and TOTP / recovery code. */ async function disableTotp(userId, password, code, auditContext) { 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_1.default.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. */ async function regenerateRecoveryCodes(userId, totpCode, auditContext) { const user = await userRepository.findById(userId); if (!user?.totp_enabled) throw new Error('2FA is not enabled'); const secret = user.totp_secret_encrypted ? (0, crypto_2.decrypt)(user.totp_secret_encrypted) : ''; if (!otplib_1.authenticator.verify({ token: totpCode, secret })) { throw new Error('Invalid 2FA code'); } const recoveryCodes = generateRecoveryCodes(); await totpRecoveryRepository.replaceCodesForUser(userId, recoveryCodes.map((c) => (0, crypto_2.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 */ async function verifyToken(accessToken) { const decoded = jsonwebtoken_1.default.verify(accessToken, config_1.config.jwt.secret); 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 */ function requireRole(allowed) { return (payload) => { const roles = payload.roles ?? (payload.role ? [payload.role] : []); const ok = allowed.some((r) => roles.includes(r)) || (allowed.includes('admin') && (0, roleAccess_1.hasAdminAccess)(payload)); if (!ok) throw new Error('Forbidden'); }; } //# sourceMappingURL=authService.js.map