games_app/backend/src/services/emailService.ts

723 lines
24 KiB
TypeScript

/**
* Outbound email delivery for verification and transactional messages.
* Supports SMTP (production) and console logging (development).
*/
import nodemailer from 'nodemailer';
import type Transporter from 'nodemailer/lib/mailer';
import { PLATFORM_NAME, PLATFORM_WORDMARK } from '../brand/platformName';
import { config } from '../config';
let transporter: Transporter | null = null;
/** Gmail app passwords are often copied with spaces — strip them. */
export function normalizeSmtpPass(pass: string): string {
return pass.replace(/\s+/g, '');
}
function isGmailHost(host: string): boolean {
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).
*/
export function usesConsoleEmailTransport(): boolean {
return config.email.transport === 'console';
}
/**
* Returns true when SMTP is fully configured for real email delivery.
*/
export function isSmtpConfigured(): boolean {
const { host, user, pass, from } = config.email;
return !!(host && user && pass && from);
}
function buildTransportOptions() {
const host = config.email.host;
const port = config.email.port;
const user = config.email.user.trim();
const pass = normalizeSmtpPass(config.email.pass);
const gmail = isGmailHost(host);
return {
host,
port,
// Port 465 = implicit TLS; 587 = STARTTLS (Gmail default).
secure: port === 465 ? true : config.email.secure,
requireTLS: port === 587,
auth: { user, pass },
...(gmail ? { tls: { minVersion: 'TLSv1.2' as const } } : {}),
};
}
/**
* Lazily creates the nodemailer SMTP transporter.
* @throws When transport is smtp but required env vars are missing
*/
function getSmtpTransporter(): Transporter {
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.createTransport(buildTransportOptions());
return transporter;
}
/** Verifies SMTP credentials (call on deploy or via CLI). */
export async function verifySmtpConnection(): Promise<void> {
const transport = getSmtpTransporter();
await transport.verify();
}
function formatEmailSendError(context: string, e: unknown): Error {
const detail = e instanceof Error ? e.message : String(e);
console.error(`[email] ${context} SMTP send failed:`, detail);
if (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).
*/
export function resolveFromAddress(): string {
const from = (config.email.from || '').trim();
const user = config.email.user;
if (!from) return user ? `"${PLATFORM_NAME}" <${user}>` : `"${PLATFORM_NAME}"`;
return from;
}
/** Reply-To: EMAIL_REPLY_TO, else the address inside EMAIL_FROM. */
export function resolveReplyToAddress(): string | undefined {
const explicit = (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: string, bodyHtml: string): string {
return `
<div style="font-family:system-ui,-apple-system,Segoe UI,sans-serif;max-width:520px;margin:0 auto;padding:24px;background:#0B0F1A;color:#F8FAFC;border-radius:12px;">
<div style="font-weight:900;font-size:20px;letter-spacing:0.3px;color:#10B981;margin:0 0 16px;">${PLATFORM_WORDMARK}</div>
<h2 style="color:#F8FAFC;margin:0 0 16px;font-size:22px;">${title}</h2>
${bodyHtml}
<p style="font-size:11px;color:#64748B;margin:28px 0 0;border-top:1px solid #1E2740;padding-top:14px;">
${PLATFORM_NAME} — premium prediction platform
</p>
</div>
`;
}
const CTA_STYLE =
'background:#10B981;color:#0B0F1A;text-decoration:none;padding:12px 24px;border-radius:8px;font-weight:700;display:inline-block;';
/**
* @param to - Recipient email address
* @param verifyUrl - Full URL opened by the user to confirm ownership
*/
export async function sendVerificationEmail(to: string, verifyUrl: string): Promise<void> {
const subject = 'Verify your Tloto email address';
const text = [
'Welcome to Tloto!',
'',
'Please verify your email address by opening this link:',
verifyUrl,
'',
`This link expires in ${config.email.verificationExpiryHours} hours.`,
'If you did not create an account, you can ignore this email.',
].join('\n');
const html = brandEmailHtml(
'Verify your email',
`
<p style="color:#94A3B8;line-height:1.5;">Thanks for joining <strong style="color:#F8FAFC;">Tloto</strong>. Confirm your email address to secure your account.</p>
<p style="margin:24px 0;">
<a href="${verifyUrl}" style="${CTA_STYLE}">Verify email</a>
</p>
<p style="font-size:13px;color:#64748B;">Or copy this link:<br/><a href="${verifyUrl}" style="color:#34D399;">${verifyUrl}</a></p>
<p style="font-size:12px;color:#64748B;">Link expires in ${config.email.verificationExpiryHours} hours.</p>
`
);
if (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.
*/
export async function sendPasswordResetEmail(to: string, resetUrl: string): Promise<void> {
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.email.passwordResetExpiryHours} hour(s).`,
'If you did not request this, you can ignore this email.',
].join('\n');
const html = brandEmailHtml(
'Reset your password',
`
<p style="color:#94A3B8;line-height:1.5;">We received a request to reset the password for your <strong style="color:#F8FAFC;">Tloto</strong> account.</p>
<p style="margin:24px 0;">
<a href="${resetUrl}" style="${CTA_STYLE}">Reset password</a>
</p>
<p style="font-size:13px;color:#64748B;">Or copy this link:<br/><a href="${resetUrl}" style="color:#34D399;">${resetUrl}</a></p>
<p style="font-size:12px;color:#64748B;">Link expires in ${config.email.passwordResetExpiryHours} hour(s). If you did not request this, ignore this email.</p>
`
);
if (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);
}
}
type SecurityAlertPayload = {
alertId: string;
severity: string;
type: string;
title: string;
details: string;
userId: string | null;
createdAt: Date;
};
/**
* Sends a security alert notification to an administrator email address.
*/
export async function sendSecurityAlertEmail(
to: string,
alert: SecurityAlertPayload
): Promise<void> {
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 = `
<div style="font-family:system-ui,sans-serif;max-width:560px;margin:0 auto;padding:24px;">
<h2 style="color:#EF5350;margin:0 0 16px;">Security alert</h2>
<p><strong>${alert.title}</strong></p>
<ul style="font-size:14px;line-height:1.6;">
<li><strong>Severity:</strong> ${alert.severity}</li>
<li><strong>Type:</strong> ${alert.type}</li>
<li><strong>User:</strong> ${alert.userId ?? 'n/a'}</li>
<li><strong>Alert ID:</strong> ${alert.alertId}</li>
</ul>
<pre style="background:#f5f5f5;padding:12px;border-radius:8px;font-size:13px;white-space:pre-wrap;">${alert.details || ''}</pre>
</div>
`;
if (config.email.transport === 'console') {
console.log('[email] Security alert (console transport)');
console.log(` To: ${to}`);
console.log(` Subject: ${subject}`);
console.log(text);
return;
}
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,
html,
});
}
type SecurityEmailContext = {
ipAddress?: string;
userAgent?: string;
countryCode?: string | null;
};
function formatSecurityContext(ctx: SecurityEmailContext): string {
const ip = ctx.ipAddress?.trim() || 'unknown';
const ua = ctx.userAgent?.trim() || 'unknown device';
const country = ctx.countryCode?.trim();
const lines = [`IP: ${ip}`, `Device: ${ua}`];
if (country) lines.push(`Country: ${country}`);
return lines.join('\n');
}
function formatSecurityContextHtml(ctx: SecurityEmailContext): string {
const ip = ctx.ipAddress?.trim() || 'unknown';
const ua = ctx.userAgent?.trim() || 'unknown device';
const country = ctx.countryCode?.trim();
const countryLine = country ? `<li><strong>Country:</strong> ${country}</li>` : '';
return `<li><strong>IP address:</strong> ${ip}</li><li><strong>Device:</strong> ${ua}</li>${countryLine}`;
}
async function sendUserSecurityEmail(
to: string,
subject: string,
title: string,
bodyLines: string[],
htmlBody: string
): Promise<void> {
const text = bodyLines.join('\n');
if (config.email.transport === 'console') {
console.log('[email] User security message (console transport)');
console.log(` To: ${to}`);
console.log(` Subject: ${subject}`);
console.log(text);
return;
}
const html = `
<div style="font-family:system-ui,sans-serif;max-width:520px;margin:0 auto;padding:24px;">
<h2 style="color:#D6B25E;margin:0 0 16px;">${title}</h2>
${htmlBody}
<p style="font-size:12px;color:#888;margin-top:24px;">
If you did not perform this action, contact support immediately and change your password.
</p>
</div>
`;
try {
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,
html,
});
} catch (e) {
throw formatEmailSendError('security notification', e);
}
}
/** Notifies the user of a sign-in from a new IP or device. */
export async function sendNewLoginEmail(to: string, ctx: SecurityEmailContext): Promise<void> {
await sendUserSecurityEmail(
to,
'New sign-in to your Tloto account',
'New sign-in detected',
[
'We detected a sign-in to your Tloto account from a new IP address or device.',
'',
formatSecurityContext(ctx),
'',
`Time: ${new Date().toISOString()}`,
'',
'If this was you, no action is needed.',
],
`<p>We detected a sign-in from a new IP address or device.</p>
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Notifies the user of a sign-in from a new country. */
export async function sendNewCountryLoginEmail(to: string, ctx: SecurityEmailContext): Promise<void> {
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.',
],
`<p>We detected a sign-in from a new country (<strong>${country}</strong>).</p>
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Notifies the user that their password was changed. */
export async function sendPasswordChangedEmail(to: string, ctx: SecurityEmailContext): Promise<void> {
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()}`,
],
`<p>The password for your Tloto account was just changed.</p>
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Notifies the user that two-factor authentication was enabled. */
export async function sendTotpEnabledEmail(to: string, ctx: SecurityEmailContext): Promise<void> {
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()}`,
],
`<p>Two-factor authentication was enabled on your account.</p>
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Notifies the user that two-factor authentication was disabled. */
export async function sendTotpDisabledEmail(to: string, ctx: SecurityEmailContext): Promise<void> {
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()}`,
],
`<p>Two-factor authentication was disabled on your account.</p>
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Notifies the user that their platform roles were updated. */
export async function sendRolesChangedEmail(
to: string,
roles: string[],
ctx: SecurityEmailContext
): Promise<void> {
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()}`,
],
`<p>An administrator updated your account roles.</p>
<p><strong>New roles:</strong> ${roleList}</p>
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Notifies the user that their effective permissions were updated. */
export async function sendPermissionsChangedEmail(
to: string,
permissions: string[],
ctx: SecurityEmailContext
): Promise<void> {
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()}`,
],
`<p>An administrator updated your account permissions.</p>
<p><strong>Effective permissions:</strong> ${permList}</p>
<ul style="font-size:14px;line-height:1.6;">${formatSecurityContextHtml(ctx)}</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
type WalletEmailPayload = {
amountUsdt: string;
feeUsdt?: string;
totalUsdt?: string;
toAddressMasked?: string | null;
network?: string;
pendingApproval?: boolean;
statusNote?: string;
blockchainTxId?: string | null;
reason?: string;
counterpartyEmailMasked?: string;
};
async function sendUserWalletEmail(
to: string,
subject: string,
title: string,
bodyLines: string[],
htmlBody: string
): Promise<void> {
const text = bodyLines.join('\n');
if (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 = `
<div style="font-family:system-ui,sans-serif;max-width:520px;margin:0 auto;padding:24px;">
<h2 style="color:#D6B25E;margin:0 0 16px;">${title}</h2>
${htmlBody}
<p style="font-size:12px;color:#888;margin-top:24px;">
If you did not initiate this action, contact support immediately and secure your account.
</p>
</div>
`;
try {
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,
html,
});
} catch (e) {
throw formatEmailSendError('wallet notification', e);
}
}
function walletAmountLines(p: WalletEmailPayload): string[] {
const lines = [`Amount: ${p.amountUsdt} USDT`];
if (p.feeUsdt) lines.push(`Network fee: ${p.feeUsdt} USDT`);
if (p.totalUsdt) lines.push(`Total debited: ${p.totalUsdt} USDT`);
if (p.toAddressMasked) lines.push(`Destination: ${p.toAddressMasked}`);
if (p.network) lines.push(`Network: ${p.network}`);
if (p.blockchainTxId) lines.push(`On-chain TX: ${p.blockchainTxId}`);
return lines;
}
function walletAmountHtml(p: WalletEmailPayload): string {
const items = [`<li><strong>Amount:</strong> ${p.amountUsdt} USDT</li>`];
if (p.feeUsdt) items.push(`<li><strong>Network fee:</strong> ${p.feeUsdt} USDT</li>`);
if (p.totalUsdt) items.push(`<li><strong>Total debited:</strong> ${p.totalUsdt} USDT</li>`);
if (p.toAddressMasked) items.push(`<li><strong>Destination:</strong> ${p.toAddressMasked}</li>`);
if (p.network) items.push(`<li><strong>Network:</strong> ${p.network}</li>`);
if (p.blockchainTxId) items.push(`<li><strong>On-chain TX:</strong> ${p.blockchainTxId}</li>`);
return `<ul style="font-size:14px;line-height:1.6;">${items.join('')}</ul>`;
}
/** Withdrawal request received (pending review or processing). */
export async function sendWithdrawalSubmittedEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
const note =
p.statusNote ||
(p.pendingApproval
? 'Your withdrawal is pending review before it is sent on-chain.'
: 'Your withdrawal request was received and is being processed.');
await sendUserWalletEmail(
to,
'Your Tloto withdrawal was submitted',
'Withdrawal submitted',
[
note,
'',
...walletAmountLines(p),
'',
`Time: ${new Date().toISOString()}`,
],
`<p>${note}</p>${walletAmountHtml(p)}
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Withdrawal completed on-chain. */
export async function sendWithdrawalCompletedEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
await sendUserWalletEmail(
to,
'Your Tloto withdrawal was completed',
'Withdrawal completed',
[
'Your withdrawal was sent successfully.',
'',
...walletAmountLines(p),
'',
`Time: ${new Date().toISOString()}`,
],
`<p>Your withdrawal was sent successfully.</p>${walletAmountHtml(p)}
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Technical problem during payout: the request is kept and will be reviewed (no refund). */
export async function sendWithdrawalFailedEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
const message =
'Processing of your withdrawal ran into a technical problem. Your request remains registered and will be reviewed.';
const lines = [message, '', `Amount: ${p.amountUsdt} USDT`];
if (p.toAddressMasked) lines.push(`Destination: ${p.toAddressMasked}`);
lines.push('', `Time: ${new Date().toISOString()}`);
const destHtml = p.toAddressMasked
? `<li><strong>Destination:</strong> ${p.toAddressMasked}</li>`
: '';
await sendUserWalletEmail(
to,
'Your Tloto withdrawal is under review',
'Withdrawal under review',
lines,
`<p>${message}</p>
<ul style="font-size:14px;line-height:1.6;">
<li><strong>Amount:</strong> ${p.amountUsdt} USDT</li>
${destHtml}
</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Withdrawal declined by an admin or cancelled by the user: reserved amount credited back. */
export async function sendWithdrawalRefundedEmail(
to: string,
p: { kind: 'rejected' | 'cancelled'; refundedUsdt: string }
): Promise<void> {
const message =
p.kind === 'rejected'
? 'Your withdrawal request was declined. The corresponding amount has been credited back to your account.'
: 'Your withdrawal request was cancelled. The corresponding amount has been credited back to your account.';
const title = p.kind === 'rejected' ? 'Withdrawal declined' : 'Withdrawal cancelled';
await sendUserWalletEmail(
to,
p.kind === 'rejected' ? 'Your Tloto withdrawal was declined' : 'Your Tloto withdrawal was cancelled',
title,
[message, '', `Credited back: ${p.refundedUsdt} USDT`, '', `Time: ${new Date().toISOString()}`],
`<p>${message}</p>
<ul style="font-size:14px;line-height:1.6;">
<li><strong>Credited back:</strong> ${p.refundedUsdt} USDT</li>
</ul>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Peer transfer sent confirmation. */
export async function sendTransferSentEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
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()}`,
],
`<p>You sent <strong>${p.amountUsdt} USDT</strong> to <strong>${counterparty}</strong>.</p>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}
/** Peer transfer received notification. */
export async function sendTransferReceivedEmail(
to: string,
p: WalletEmailPayload
): Promise<void> {
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()}`,
],
`<p>You received <strong>${p.amountUsdt} USDT</strong> from <strong>${counterparty}</strong>.</p>
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
);
}