SMTP settings on the Settings page, with a test (1.2.0)

SMTP server, port, user, password and from address are now Hub settings in
the database instead of SMTP_* in .env. The password is encrypted with
HUB_ENCRYPTION_KEY and never sent to the browser; a blank field keeps it.
POST /api/admin/settings/smtp-test logs in with the form's values (saved or
not) and sends a test email, returning the server's reason on failure; it is
rate limited and audited. On first start an existing SMTP_* setup is copied
into Settings once. The audit log no longer records the SMTP password.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ls1vMaqhrehXcHJe32jLL9
This commit is contained in:
2026-10-28 01:26:41 +02:00
co-authored by Claude Opus 5.5
parent ad01328ce3
commit 613a4450cb
13 changed files with 298 additions and 35 deletions
+50 -12
View File
@@ -1,27 +1,65 @@
const nodemailer = require('nodemailer');
const { smtpSettings } = require('./settings');
// SMTP is set on the Settings page; the transporter is rebuilt when those settings change.
let transporter = null;
let transporterFor = '';
function smtpConfigured() {
return !!process.env.SMTP_HOST;
function createTransport(smtp) {
return nodemailer.createTransport({
host: smtp.host,
port: smtp.port,
secure: smtp.port === 465,
auth: smtp.user ? { user: smtp.user, pass: smtp.pass } : undefined,
connectionTimeout: 15000,
greetingTimeout: 15000,
socketTimeout: 30000,
});
}
function fromAddress(smtp) {
return smtp.from || smtp.user || 'hub@localhost';
}
async function smtpConfigured() {
return !!(await smtpSettings()).host;
}
/** Send an email; without SMTP it's logged instead (development). */
async function sendMail({ to, subject, text }) {
if (!to) return;
if (!smtpConfigured()) {
const smtp = await smtpSettings();
if (!smtp.host) {
console.info(`[mail] (SMTP not set up) to=${to} subject="${subject}"\n${text}`);
return;
}
if (!transporter) {
transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT || '587', 10),
secure: String(process.env.SMTP_PORT) === '465',
auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } : undefined,
});
const key = JSON.stringify(smtp);
if (!transporter || transporterFor !== key) {
transporter = createTransport(smtp);
transporterFor = key;
}
await transporter.sendMail({ from: process.env.SMTP_FROM || 'hub@localhost', to, subject, text });
await transporter.sendMail({ from: fromAddress(smtp), to, subject, text });
}
module.exports = { sendMail, smtpConfigured };
/**
* Check SMTP settings (saved, or `overrides` from the form before saving): log in to the
* server, then send a test email to `to`. Throws with the server's reason if either fails.
*/
async function testSmtp(overrides, to) {
const smtp = await smtpSettings(overrides);
if (!smtp.host) throw new Error('Enter the SMTP server first.');
const t = createTransport(smtp);
try {
await t.verify();
await t.sendMail({
from: fromAddress(smtp),
to,
subject: 'Cross Events Hub: test email',
text: `This is a test email from the Cross Events Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`,
});
} finally {
t.close();
}
}
module.exports = { sendMail, smtpConfigured, testSmtp };
+60 -3
View File
@@ -1,4 +1,5 @@
const prisma = require('../config/db');
const { encrypt, decrypt } = require('./crypto');
// Hub settings Joshua edits on the Settings page, with their defaults.
const DEFAULTS = {
@@ -10,20 +11,76 @@ const DEFAULTS = {
disk_min_free_percent: '10',
errors_per_day: '50',
licence_expiry_warning_days: '14',
// Outgoing email. The password is stored encrypted and never sent to the browser.
smtp_host: '',
smtp_port: '587',
smtp_user: '',
smtp_pass: '',
smtp_from: '',
};
async function getSettings() {
async function rawSettings() {
const rows = await prisma.setting.findMany();
const saved = Object.fromEntries(rows.map(r => [r.key, r.value]));
return { ...DEFAULTS, ...saved };
}
/** Settings for the Settings page: the SMTP password only as "is one saved". */
async function getSettings() {
const { smtp_pass, ...settings } = await rawSettings();
return { ...settings, smtp_pass_set: smtp_pass ? 'true' : '' };
}
/**
* Save settings. A blank smtp_pass keeps the saved password (the page never has it);
* smtp_pass_clear removes it.
*/
async function setSettings(values) {
const updates = Object.entries(values || {}).filter(([k]) => k in DEFAULTS);
const input = { ...(values || {}) };
if (input.smtp_pass_clear) input.smtp_pass = '';
else if (input.smtp_pass) input.smtp_pass = encrypt(input.smtp_pass);
else delete input.smtp_pass;
const updates = Object.entries(input).filter(([k]) => k in DEFAULTS);
for (const [key, value] of updates) {
await prisma.setting.upsert({ where: { key }, update: { value: String(value ?? '') }, create: { key, value: String(value ?? '') } });
}
return getSettings();
}
module.exports = { DEFAULTS, getSettings, setSettings };
/**
* SMTP settings to send with, password decrypted. Pass `overrides` (from the Settings form)
* to try values before saving them; a blank password there means the saved one.
*/
async function smtpSettings(overrides) {
const saved = await rawSettings();
const pick = key => (overrides && overrides[key] != null ? String(overrides[key]).trim() : saved[key]);
let pass = overrides?.smtp_pass_clear ? '' : overrides?.smtp_pass || '';
if (!pass && !overrides?.smtp_pass_clear && saved.smtp_pass) pass = decrypt(saved.smtp_pass);
return {
host: pick('smtp_host'),
port: parseInt(pick('smtp_port') || '587', 10),
user: pick('smtp_user'),
pass,
from: pick('smtp_from'),
};
}
/**
* Before 1.2.0 SMTP was set with SMTP_* in backend/.env. If the database has no SMTP host yet,
* copy them over once, so an update doesn't stop the alert emails.
*/
async function importSmtpFromEnv() {
if (!process.env.SMTP_HOST) return false;
const saved = await rawSettings();
if (saved.smtp_host) return false;
await setSettings({
smtp_host: process.env.SMTP_HOST,
smtp_port: process.env.SMTP_PORT || '587',
smtp_user: process.env.SMTP_USER || '',
smtp_pass: process.env.SMTP_PASS || '',
smtp_from: process.env.SMTP_FROM || '',
});
return true;
}
module.exports = { DEFAULTS, getSettings, setSettings, smtpSettings, importSmtpFromEnv };