392 lines
16 KiB
JavaScript
392 lines
16 KiB
JavaScript
"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.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;
|
|
const nodemailer_1 = __importDefault(require("nodemailer"));
|
|
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}`);
|
|
}
|
|
function resolveFromAddress() {
|
|
const from = config_1.config.email.from;
|
|
const user = config_1.config.email.user;
|
|
if (!user)
|
|
return from;
|
|
const fromEmail = from.match(/<([^>]+)>/)?.[1] ?? from.trim();
|
|
const host = config_1.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
|
|
*/
|
|
async function sendVerificationEmail(to, verifyUrl) {
|
|
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_1.config.email.verificationExpiryHours} hours.`,
|
|
'If you did not create an account, you can ignore this email.',
|
|
].join('\n');
|
|
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;">Verify your email</h2>
|
|
<p>Thanks for joining <strong>Prediqo</strong>. Confirm your email address to secure your account.</p>
|
|
<p style="margin:24px 0;">
|
|
<a href="${verifyUrl}" style="background:#D6B25E;color:#0B0E14;text-decoration:none;padding:12px 24px;border-radius:8px;font-weight:700;display:inline-block;">
|
|
Verify email
|
|
</a>
|
|
</p>
|
|
<p style="font-size:13px;color:#666;">Or copy this link:<br/><a href="${verifyUrl}">${verifyUrl}</a></p>
|
|
<p style="font-size:12px;color:#888;">Link expires in ${config_1.config.email.verificationExpiryHours} hours.</p>
|
|
</div>
|
|
`;
|
|
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(),
|
|
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 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_1.config.email.passwordResetExpiryHours} hour(s).`,
|
|
'If you did not request this, you can ignore this email.',
|
|
].join('\n');
|
|
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;">Reset your password</h2>
|
|
<p>We received a request to reset the password for your <strong>Prediqo</strong> account.</p>
|
|
<p style="margin:24px 0;">
|
|
<a href="${resetUrl}" style="background:#D6B25E;color:#0B0E14;text-decoration:none;padding:12px 24px;border-radius:8px;font-weight:700;display:inline-block;">
|
|
Reset password
|
|
</a>
|
|
</p>
|
|
<p style="font-size:13px;color:#666;">Or copy this link:<br/><a href="${resetUrl}">${resetUrl}</a></p>
|
|
<p style="font-size:12px;color:#888;">Link expires in ${config_1.config.email.passwordResetExpiryHours} hour(s). If you did not request this, ignore this email.</p>
|
|
</div>
|
|
`;
|
|
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(),
|
|
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 = `[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 = `
|
|
<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_1.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,
|
|
});
|
|
}
|
|
function formatSecurityContext(ctx) {
|
|
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) {
|
|
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, subject, title, bodyLines, htmlBody) {
|
|
const text = bodyLines.join('\n');
|
|
if (config_1.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(),
|
|
to,
|
|
subject,
|
|
text,
|
|
html,
|
|
});
|
|
}
|
|
catch (e) {
|
|
throw formatEmailSendError('security notification', e);
|
|
}
|
|
}
|
|
/** Notifies the user of a sign-in from a new IP or device. */
|
|
async function sendNewLoginEmail(to, ctx) {
|
|
await sendUserSecurityEmail(to, 'New sign-in to your Prediqo account', 'New sign-in detected', [
|
|
'We detected a sign-in to your Prediqo 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. */
|
|
async function sendNewCountryLoginEmail(to, ctx) {
|
|
const country = ctx.countryCode?.trim() || 'unknown';
|
|
await sendUserSecurityEmail(to, 'Sign-in from a new country on your Prediqo account', 'New country sign-in', [
|
|
`We detected a sign-in to your Prediqo 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. */
|
|
async function sendPasswordChangedEmail(to, ctx) {
|
|
await sendUserSecurityEmail(to, 'Your Prediqo password was changed', 'Password changed', [
|
|
'The password for your Prediqo account was just changed.',
|
|
'',
|
|
formatSecurityContext(ctx),
|
|
'',
|
|
`Time: ${new Date().toISOString()}`,
|
|
], `<p>The password for your Prediqo 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. */
|
|
async function sendTotpEnabledEmail(to, ctx) {
|
|
await sendUserSecurityEmail(to, 'Two-factor authentication enabled on Prediqo', '2FA enabled', [
|
|
'Two-factor authentication was enabled on your Prediqo 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. */
|
|
async function sendTotpDisabledEmail(to, ctx) {
|
|
await sendUserSecurityEmail(to, 'Two-factor authentication disabled on Prediqo', '2FA disabled', [
|
|
'Two-factor authentication was disabled on your Prediqo 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. */
|
|
async function sendRolesChangedEmail(to, roles, ctx) {
|
|
const roleList = roles.join(', ') || '(none)';
|
|
await sendUserSecurityEmail(to, 'Your Prediqo account roles were updated', 'Account roles updated', [
|
|
'An administrator updated the roles assigned to your Prediqo 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. */
|
|
async function sendPermissionsChangedEmail(to, permissions, ctx) {
|
|
const permList = permissions.join(', ') || '(none)';
|
|
await sendUserSecurityEmail(to, 'Your Prediqo account permissions were updated', 'Account permissions updated', [
|
|
'An administrator updated the permissions assigned to your Prediqo 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>`);
|
|
}
|
|
//# sourceMappingURL=emailService.js.map
|