"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.getProfile = getProfile; exports.updateProfile = updateProfile; exports.changePassword = changePassword; exports.setupTotp = setupTotp; exports.enableTotp = enableTotp; exports.verifyTotp = verifyTotp; exports.verifyToken = verifyToken; exports.requireRole = requireRole; const argon2_1 = __importDefault(require("argon2")); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const otplib_1 = require("otplib"); const QRCode = __importStar(require("qrcode")); const config_1 = require("../config"); const crypto_1 = require("../utils/crypto"); const userRepository = __importStar(require("../repositories/userRepository")); const refreshTokenRepository = __importStar(require("../repositories/refreshTokenRepository")); const auditLogRepository = __importStar(require("../repositories/auditLogRepository")); const settingsRepository = __importStar(require("../repositories/settingsRepository")); const userAdminStatsService_1 = require("./userAdminStatsService"); 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 userGender_1 = require("../models/userGender"); const roleRepository = __importStar(require("../repositories/roleRepository")); const uuid_1 = require("uuid"); otplib_1.authenticator.options = { digits: 6, step: 30 }; /** 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, }; } /** 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_1.hashForIndex)(normalizedEmail); const existing = await userRepository.findByEmailHash(emailHash); if (existing) throw new Error('Email already registered'); let phoneHash = null; let phoneEncrypted = null; if (input.phone?.trim()) { const normalizedPhone = input.phone.trim(); phoneHash = (0, crypto_1.hashForPhone)(normalizedPhone); const existingPhone = await userRepository.findByPhoneHash(phoneHash); if (existingPhone) throw new Error('Phone number already registered'); phoneEncrypted = (0, crypto_1.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_1.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) { const emailHash = (0, crypto_1.hashForIndex)(email); const user = await userRepository.findByEmailHash(emailHash); if (!user) throw new Error('Invalid credentials'); 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'); const ok = await argon2_1.default.verify(user.password_hash, password); if (!ok) throw new Error('Invalid credentials'); const settings = await settingsRepository.getSettings(); 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'); const secret = user.totp_secret_encrypted ? (0, crypto_1.decrypt)(user.totp_secret_encrypted) : ''; const valid = otplib_1.authenticator.verify({ token: totpCode, secret }); if (!valid) throw new Error('Invalid 2FA code'); } 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_1.hashToken)(refreshToken), expiresAt); if (auditContext) { await auditLogRepository.create({ userId: user.id, action: 'login', ipAddress: auditContext.ipAddress, userAgent: auditContext.userAgent, }); (0, userAdminStatsService_1.queueUserAdminStatsRefresh)(user.id); } 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 token from a valid refresh token. * @param refreshToken Opaque refresh token issued at login * @returns New access token and remaining lifetime in seconds * @throws {Error} When refresh token is invalid or user no longer exists */ async function refreshTokens(refreshToken) { const tokenHash = (0, crypto_1.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'); 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 decoded = jsonwebtoken_1.default.decode(accessToken); return { accessToken, expiresIn: decoded.exp - Math.floor(Date.now() / 1000) }; } /** * 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); 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: row.email_encrypted ? (0, crypto_1.decrypt)(row.email_encrypted) : null, phone: row.phone_encrypted ? (0, crypto_1.decrypt)(row.phone_encrypted) : null, 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_1.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_1.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_1.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_1.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) { 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); } /** * 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) { const user = await userRepository.findById(userId); if (!user) throw new Error('User not found'); const secret = otplib_1.authenticator.generateSecret(); const encrypted = (0, crypto_1.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); 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) { const user = await userRepository.findById(userId); if (!user || !user.totp_secret_encrypted) throw new Error('2FA not set up'); const secret = (0, crypto_1.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); } /** * Verifies TOTP for sensitive actions (e.g. transfer). No-op when 2FA is disabled. * @param userId User UUID * @param totpCode Optional six-digit TOTP code * @throws {Error} When user not found, 2FA enabled but code missing/invalid */ async function verifyTotp(userId, totpCode) { const user = await userRepository.findById(userId); if (!user) throw new Error('User not found'); if (!user.totp_enabled) return; if (!totpCode) throw new Error('2FA required'); const secret = user.totp_secret_encrypted ? (0, crypto_1.decrypt)(user.totp_secret_encrypted) : ''; const valid = otplib_1.authenticator.verify({ token: totpCode, secret }); if (!valid) throw new Error('Invalid 2FA code'); } /** * 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') && roles.includes('super_admin')); if (!ok) throw new Error('Forbidden'); }; } //# sourceMappingURL=authService.js.map