/** * 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 { config } from '../config'; let transporter: Transporter | null = null; /** * 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); } /** * 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({ host: config.email.host, port: config.email.port, secure: config.email.secure, auth: { user: config.email.user, pass: config.email.pass, }, }); return transporter; } function resolveFromAddress(): string { const from = config.email.from!; const user = config.email.user; if (!user) return from; const fromEmail = from.match(/<([^>]+)>/)?.[1] ?? from.trim(); const host = config.email.host.toLowerCase(); const usesGmail = host.includes('gmail.com') || host.includes('googlemail.com'); if (usesGmail && user.endsWith('@gmail.com') && !fromEmail.endsWith('@gmail.com')) { return `"Prediqo" <${user}>`; } return from; } /** * @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 { const subject = 'Verify your Prediqo email address'; const text = [ 'Welcome to Prediqo!', '', '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 = `

Verify your email

Thanks for joining Prediqo. Confirm your email address to secure your account.

Verify email

Or copy this link:
${verifyUrl}

Link expires in ${config.email.verificationExpiryHours} hours.

`; 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(), to, subject, text, html, }); } catch (e) { const detail = e instanceof Error ? e.message : String(e); console.error('[email] Verification SMTP send failed:', detail); throw new Error(`Failed to send verification email: ${detail}`); } } /** * Sends a password reset message with a clickable link. */ export async function sendPasswordResetEmail(to: string, resetUrl: string): Promise { const subject = 'Reset your Prediqo password'; const text = [ 'You requested a password reset for your Prediqo 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 = `

Reset your password

We received a request to reset the password for your Prediqo account.

Reset password

Or copy this link:
${resetUrl}

Link expires in ${config.email.passwordResetExpiryHours} hour(s). If you did not request this, ignore this email.

`; 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(), to, subject, text, html, }); } catch (e) { const detail = e instanceof Error ? e.message : String(e); console.error('[email] Password reset SMTP send failed:', detail); throw new Error(`Failed to send password reset email: ${detail}`); } } 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 { const subject = `[Prediqo Security ${alert.severity.toUpperCase()}] ${alert.title}`; const text = [ 'A security alert was raised on the Prediqo 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 = `

Security alert

${alert.title}

  • Severity: ${alert.severity}
  • Type: ${alert.type}
  • User: ${alert.userId ?? 'n/a'}
  • Alert ID: ${alert.alertId}
${alert.details || ''}
`; 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(), to, subject, text, html, }); }