"use strict"; /** * Outbound email delivery for verification and transactional messages. * Supports SMTP (production) and console logging (development). */ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.normalizeSmtpPass = normalizeSmtpPass; exports.usesConsoleEmailTransport = usesConsoleEmailTransport; exports.isSmtpConfigured = isSmtpConfigured; exports.verifySmtpConnection = verifySmtpConnection; exports.resolveFromAddress = resolveFromAddress; exports.resolveReplyToAddress = resolveReplyToAddress; exports.sendVerificationEmail = sendVerificationEmail; exports.sendPasswordResetEmail = sendPasswordResetEmail; exports.sendSecurityAlertEmail = sendSecurityAlertEmail; exports.sendNewLoginEmail = sendNewLoginEmail; exports.sendNewCountryLoginEmail = sendNewCountryLoginEmail; exports.sendPasswordChangedEmail = sendPasswordChangedEmail; exports.sendTotpEnabledEmail = sendTotpEnabledEmail; exports.sendTotpDisabledEmail = sendTotpDisabledEmail; exports.sendRolesChangedEmail = sendRolesChangedEmail; exports.sendPermissionsChangedEmail = sendPermissionsChangedEmail; exports.sendWithdrawalSubmittedEmail = sendWithdrawalSubmittedEmail; exports.sendWithdrawalCompletedEmail = sendWithdrawalCompletedEmail; exports.sendWithdrawalFailedEmail = sendWithdrawalFailedEmail; exports.sendTransferSentEmail = sendTransferSentEmail; exports.sendTransferReceivedEmail = sendTransferReceivedEmail; const nodemailer_1 = __importDefault(require("nodemailer")); const platformName_1 = require("../brand/platformName"); const config_1 = require("../config"); let transporter = null; /** Gmail app passwords are often copied with spaces — strip them. */ function normalizeSmtpPass(pass) { return pass.replace(/\s+/g, ''); } function isGmailHost(host) { const h = host.toLowerCase(); return h.includes('gmail.com') || h.includes('googlemail.com'); } /** * Returns true when emails are logged to stdout instead of SMTP (local Docker default). */ function usesConsoleEmailTransport() { return config_1.config.email.transport === 'console'; } /** * Returns true when SMTP is fully configured for real email delivery. */ function isSmtpConfigured() { const { host, user, pass, from } = config_1.config.email; return !!(host && user && pass && from); } function buildTransportOptions() { const host = config_1.config.email.host; const port = config_1.config.email.port; const user = config_1.config.email.user.trim(); const pass = normalizeSmtpPass(config_1.config.email.pass); const gmail = isGmailHost(host); return { host, port, // Port 465 = implicit TLS; 587 = STARTTLS (Gmail default). secure: port === 465 ? true : config_1.config.email.secure, requireTLS: port === 587, auth: { user, pass }, ...(gmail ? { tls: { minVersion: 'TLSv1.2' } } : {}), }; } /** * Lazily creates the nodemailer SMTP transporter. * @throws When transport is smtp but required env vars are missing */ function getSmtpTransporter() { if (transporter) return transporter; if (!isSmtpConfigured()) { throw new Error('SMTP is not configured. Set SMTP_HOST, SMTP_USER, SMTP_PASS, and EMAIL_FROM.'); } transporter = nodemailer_1.default.createTransport(buildTransportOptions()); return transporter; } /** Verifies SMTP credentials (call on deploy or via CLI). */ async function verifySmtpConnection() { const transport = getSmtpTransporter(); await transport.verify(); } function formatEmailSendError(context, e) { const detail = e instanceof Error ? e.message : String(e); console.error(`[email] ${context} SMTP send failed:`, detail); if (config_1.config.env === 'production') { return new Error('Unable to send email at the moment. Please try again in a few minutes or contact support.'); } return new Error(`Failed to send ${context}: ${detail}`); } /** * Visible From header (EMAIL_FROM). * Tloto production uses Microsoft 365: SMTP_USER=admin@…, EMAIL_FROM=info@… (alias). */ function resolveFromAddress() { const from = (config_1.config.email.from || '').trim(); const user = config_1.config.email.user; if (!from) return user ? `"${platformName_1.PLATFORM_NAME}" <${user}>` : `"${platformName_1.PLATFORM_NAME}"`; return from; } /** Reply-To: EMAIL_REPLY_TO, else the address inside EMAIL_FROM. */ function resolveReplyToAddress() { const explicit = (config_1.config.email.replyTo || '').trim(); if (explicit) return explicit; const from = resolveFromAddress(); const angled = from.match(/<([^>]+)>/)?.[1]; return angled?.trim() || undefined; } /** Shared branded HTML shell (no external image — works in all mail clients). */ function brandEmailHtml(title, bodyHtml) { return `
${platformName_1.PLATFORM_NAME} — premium prediction platform
Thanks for joining Tloto. Confirm your email address to secure your account.
Or copy this link:
${verifyUrl}
Link expires in ${config_1.config.email.verificationExpiryHours} hours.
`); if (config_1.config.email.transport === 'console') { console.log('[email] Verification message (console transport)'); console.log(` To: ${to}`); console.log(` Subject: ${subject}`); console.log(` Verify: ${verifyUrl}`); return; } try { const transport = getSmtpTransporter(); await transport.sendMail({ from: resolveFromAddress(), replyTo: resolveReplyToAddress(), to, subject, text, html, }); } catch (e) { throw formatEmailSendError('verification email', e); } } /** * Sends a password reset message with a clickable link. */ async function sendPasswordResetEmail(to, resetUrl) { const subject = 'Reset your Tloto password'; const text = [ 'You requested a password reset for your Tloto account.', '', 'Open this link to choose a new password:', resetUrl, '', `This link expires in ${config_1.config.email.passwordResetExpiryHours} hour(s).`, 'If you did not request this, you can ignore this email.', ].join('\n'); const html = brandEmailHtml('Reset your password', `We received a request to reset the password for your Tloto account.
Or copy this link:
${resetUrl}
Link expires in ${config_1.config.email.passwordResetExpiryHours} hour(s). If you did not request this, ignore this email.
`); if (config_1.config.email.transport === 'console') { console.log('[email] Password reset message (console transport)'); console.log(` To: ${to}`); console.log(` Subject: ${subject}`); console.log(` Reset: ${resetUrl}`); return; } try { const transport = getSmtpTransporter(); await transport.sendMail({ from: resolveFromAddress(), replyTo: resolveReplyToAddress(), to, subject, text, html, }); } catch (e) { throw formatEmailSendError('password reset email', e); } } /** * Sends a security alert notification to an administrator email address. */ async function sendSecurityAlertEmail(to, alert) { const subject = `[Tloto Security ${alert.severity.toUpperCase()}] ${alert.title}`; const text = [ 'A security alert was raised on the Tloto platform.', '', `Alert ID: ${alert.alertId}`, `Severity: ${alert.severity}`, `Type: ${alert.type}`, `User ID: ${alert.userId ?? 'n/a'}`, `Time: ${new Date(alert.createdAt).toISOString()}`, '', alert.details || '(no additional details)', '', 'Review this alert in the admin security panel.', ].join('\n'); const html = `${alert.title}
${alert.details || ''}
If you did not perform this action, contact support immediately and change your password.
We detected a sign-in from a new IP address or device.
Time: ${new Date().toISOString()}
`); } /** Notifies the user of a sign-in from a new country. */ async function sendNewCountryLoginEmail(to, ctx) { const country = ctx.countryCode?.trim() || 'unknown'; await sendUserSecurityEmail(to, 'Sign-in from a new country on your Tloto account', 'New country sign-in', [ `We detected a sign-in to your Tloto account from a new country (${country}).`, '', formatSecurityContext(ctx), '', `Time: ${new Date().toISOString()}`, '', 'If this was you, no action is needed.', ], `We detected a sign-in from a new country (${country}).
Time: ${new Date().toISOString()}
`); } /** Notifies the user that their password was changed. */ async function sendPasswordChangedEmail(to, ctx) { await sendUserSecurityEmail(to, 'Your Tloto password was changed', 'Password changed', [ 'The password for your Tloto account was just changed.', '', formatSecurityContext(ctx), '', `Time: ${new Date().toISOString()}`, ], `The password for your Tloto account was just changed.
Time: ${new Date().toISOString()}
`); } /** Notifies the user that two-factor authentication was enabled. */ async function sendTotpEnabledEmail(to, ctx) { await sendUserSecurityEmail(to, 'Two-factor authentication enabled on Tloto', '2FA enabled', [ 'Two-factor authentication was enabled on your Tloto account.', '', formatSecurityContext(ctx), '', `Time: ${new Date().toISOString()}`, ], `Two-factor authentication was enabled on your account.
Time: ${new Date().toISOString()}
`); } /** Notifies the user that two-factor authentication was disabled. */ async function sendTotpDisabledEmail(to, ctx) { await sendUserSecurityEmail(to, 'Two-factor authentication disabled on Tloto', '2FA disabled', [ 'Two-factor authentication was disabled on your Tloto account.', '', formatSecurityContext(ctx), '', `Time: ${new Date().toISOString()}`, ], `Two-factor authentication was disabled on your account.
Time: ${new Date().toISOString()}
`); } /** Notifies the user that their platform roles were updated. */ async function sendRolesChangedEmail(to, roles, ctx) { const roleList = roles.join(', ') || '(none)'; await sendUserSecurityEmail(to, 'Your Tloto account roles were updated', 'Account roles updated', [ 'An administrator updated the roles assigned to your Tloto account.', '', `New roles: ${roleList}`, '', formatSecurityContext(ctx), '', `Time: ${new Date().toISOString()}`, ], `An administrator updated your account roles.
New roles: ${roleList}
Time: ${new Date().toISOString()}
`); } /** Notifies the user that their effective permissions were updated. */ async function sendPermissionsChangedEmail(to, permissions, ctx) { const permList = permissions.join(', ') || '(none)'; await sendUserSecurityEmail(to, 'Your Tloto account permissions were updated', 'Account permissions updated', [ 'An administrator updated the permissions assigned to your Tloto account.', '', `Effective permissions: ${permList}`, '', formatSecurityContext(ctx), '', `Time: ${new Date().toISOString()}`, ], `An administrator updated your account permissions.
Effective permissions: ${permList}
Time: ${new Date().toISOString()}
`); } async function sendUserWalletEmail(to, subject, title, bodyLines, htmlBody) { const text = bodyLines.join('\n'); if (config_1.config.email.transport === 'console') { console.log('[email] User wallet message (console transport)'); console.log(` To: ${to}`); console.log(` Subject: ${subject}`); console.log(text); return; } const html = `If you did not initiate this action, contact support immediately and secure your account.
${note}
${walletAmountHtml(p)}Time: ${new Date().toISOString()}
`); } /** Withdrawal completed on-chain. */ async function sendWithdrawalCompletedEmail(to, p) { await sendUserWalletEmail(to, 'Your Tloto withdrawal was completed', 'Withdrawal completed', [ 'Your withdrawal was sent successfully.', '', ...walletAmountLines(p), '', `Time: ${new Date().toISOString()}`, ], `Your withdrawal was sent successfully.
${walletAmountHtml(p)}Time: ${new Date().toISOString()}
`); } /** Withdrawal failed or cancelled; funds returned. */ async function sendWithdrawalFailedEmail(to, p) { const reason = p.reason?.trim(); const lines = [ 'Your withdrawal could not be completed. The reserved amount was returned to your available balance.', '', `Amount: ${p.amountUsdt} USDT`, ]; if (p.toAddressMasked) lines.push(`Destination: ${p.toAddressMasked}`); if (reason) lines.push(`Reason: ${reason}`); lines.push('', `Time: ${new Date().toISOString()}`); const reasonHtml = reason ? `Reason: ${reason}
` : ''; const destHtml = p.toAddressMasked ? `Your withdrawal could not be completed. Funds were returned to your available balance.
Time: ${new Date().toISOString()}
`); } /** Peer transfer sent confirmation. */ async function sendTransferSentEmail(to, p) { const counterparty = p.counterpartyEmailMasked || 'another user'; await sendUserWalletEmail(to, 'You sent a Tloto transfer', 'Transfer sent', [ `You sent ${p.amountUsdt} USDT to ${counterparty}.`, '', `Time: ${new Date().toISOString()}`, ], `You sent ${p.amountUsdt} USDT to ${counterparty}.
Time: ${new Date().toISOString()}
`); } /** Peer transfer received notification. */ async function sendTransferReceivedEmail(to, p) { const counterparty = p.counterpartyEmailMasked || 'another Tloto user'; await sendUserWalletEmail(to, 'You received a Tloto transfer', 'Transfer received', [ `You received ${p.amountUsdt} USDT from ${counterparty}.`, '', `Time: ${new Date().toISOString()}`, ], `You received ${p.amountUsdt} USDT from ${counterparty}.
Time: ${new Date().toISOString()}
`); } //# sourceMappingURL=emailService.js.map