Merge branch 'feat/smtp-settings'

This commit is contained in:
2026-10-28 01:26:41 +02:00
13 changed files with 298 additions and 35 deletions
+17
View File
@@ -5,6 +5,23 @@ versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
## [1.2.0] - 2026-10-28
### Added
- **Email (SMTP) on the Settings page**: server, port, username, password and from address, stored
in the database (the password encrypted with `HUB_ENCRYPTION_KEY`, and never sent back to the
browser). **Send test** logs in to the mail server with what's in the form, saved or not, and
sends a test email, showing the server's reason if it fails. Tests and their results are in the
audit log.
### Changed
- SMTP is no longer read from `backend/.env`. On first start, an existing `SMTP_*` setup is copied
into Settings once; after that the `SMTP_*` lines can be removed. `ALERT_EMAIL` in
`.env.example` was never used (the alert address is a setting) and is gone.
- The audit log records that the SMTP password changed, never the password.
## [1.1.2] - 2026-10-27
### Added
+1 -7
View File
@@ -19,13 +19,7 @@ HUB_SIGNING_KEY_FILE=./keys/hub-signing-key.pem
# Behind a reverse proxy (nginx), so rate limits see real client IPs
TRUST_PROXY=1
# Alert emails (install offline, backups failing, disk low, licences expiring)
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
SMTP_FROM=hub@crosscode.co.za
ALERT_EMAIL=
# Alert emails: the SMTP server and the alert address are set on the Settings page.
# Background checks (alerts, heartbeat roll-up). false to switch off.
JOBS_ENABLED=true
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-backend",
"version": "1.1.2",
"version": "1.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-backend",
"version": "1.1.2",
"version": "1.2.0",
"hasInstallScript": true,
"dependencies": {
"@prisma/adapter-pg": "^7.10.1",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-backend",
"version": "1.1.2",
"version": "1.2.0",
"private": true,
"description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats",
"main": "src/index.js",
+6
View File
@@ -10,6 +10,7 @@ if (missing.length) {
const app = require('./app');
const { keyPair } = require('./utils/licenceToken');
const { runAlerts, rollupHeartbeats } = require('./utils/alerts');
const { importSmtpFromEnv } = require('./utils/settings');
// Fail early if the licence signing key is missing or wrong.
try {
@@ -19,6 +20,11 @@ try {
process.exit(1);
}
// SMTP moved from .env to the Settings page in 1.2.0; carry the old values over once.
importSmtpFromEnv()
.then(done => { if (done) console.log('[hub] Copied SMTP_* from .env to Settings. You can remove them from .env now.'); })
.catch(e => console.warn('[hub] Could not copy SMTP_* from .env:', e?.message || e));
const PORT = parseInt(process.env.PORT || '5200', 10);
app.listen(PORT, () => console.log(`[hub] Listening on ${PORT}`));
+39 -3
View File
@@ -1,6 +1,7 @@
/** The Hub dashboard's API (admin login required). */
const express = require('express');
const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { protect } = require('../middleware/auth');
const { licenceKey } = require('../utils/crypto');
@@ -8,10 +9,13 @@ const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const { problems, compareVersions } = require('../utils/alerts');
const licenceToken = require('../utils/licenceToken');
const { smtpConfigured, testSmtp } = require('../utils/mail');
const router = express.Router();
router.use(protect);
const smtpTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many test emails — wait a few minutes.' } });
const wrap = fn => (req, res) => fn(req, res).catch(e => {
const status = e.status || 500;
if (status >= 500) console.error('[admin]', e);
@@ -223,15 +227,47 @@ router.get('/audit', wrap(async (req, res) => {
// ─── Settings ─────────────────────────────────────────────────────────────────
router.get('/settings', wrap(async (req, res) => {
res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: !!process.env.SMTP_HOST });
res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: await smtpConfigured() });
}));
const SMTP_FIELDS = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_pass_clear', 'smtp_from'];
function checkSmtp(values) {
if (values.smtp_port != null && values.smtp_port !== '' && !/^\d{1,5}$/.test(String(values.smtp_port))) throw bad('SMTP port is a number, usually 587 or 465.');
if (values.smtp_host && /[\s/]/.test(String(values.smtp_host).trim())) throw bad('SMTP server is a host name like mail.example.com, without https:// or a path.');
}
// What the audit log records: never the password, only that it changed.
function auditValues(values) {
const { smtp_pass, smtp_pass_clear, ...rest } = values;
if (smtp_pass_clear) rest.smtp_pass = '(removed)';
else if (smtp_pass) rest.smtp_pass = '(changed)';
return rest;
}
router.put('/settings', wrap(async (req, res) => {
const values = req.body?.settings || {};
if (values.latest_version && !/^\d+\.\d+\.\d+$/.test(String(values.latest_version))) throw bad('Latest version looks like 1.41.0.');
checkSmtp(values);
const settings = await setSettings(values);
await audit(req, 'settings_updated', null, values);
res.json({ settings });
await audit(req, 'settings_updated', null, auditValues(values));
res.json({ settings, smtp: await smtpConfigured() });
}));
// Tries the SMTP settings in the form (unsaved is fine): logs in and sends a test email.
router.post('/settings/smtp-test', smtpTestLimiter, wrap(async (req, res) => {
const values = Object.fromEntries(SMTP_FIELDS.filter(k => req.body?.settings?.[k] != null).map(k => [k, req.body.settings[k]]));
checkSmtp(values);
const to = text(req.body?.to, 200) || (await getSettings()).alert_email || req.admin.email;
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(to)) throw bad('Send the test to a valid email address.');
try {
await testSmtp(values, to);
} catch (e) {
await audit(req, 'smtp_test_failed', null, { to, error: String(e.message).slice(0, 300) });
throw bad(`The test failed: ${e.message}`);
}
await audit(req, 'smtp_test_sent', null, { to });
res.json({ to });
}));
module.exports = router;
+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 };
+56
View File
@@ -0,0 +1,56 @@
// SMTP settings in the database: the password is encrypted, never sent to the page, and the
// old SMTP_* in .env are copied over once.
const mockRows = new Map();
jest.mock('../src/config/db', () => ({
setting: {
findMany: async () => [...mockRows].map(([key, value]) => ({ key, value })),
upsert: async ({ where, update }) => { mockRows.set(where.key, update.value); },
},
}));
process.env.HUB_ENCRYPTION_KEY = 'test-encryption-key-that-is-long-enough-123';
const { getSettings, setSettings, smtpSettings, importSmtpFromEnv } = require('../src/utils/settings');
const { testSmtp } = require('../src/utils/mail');
beforeEach(() => {
mockRows.clear();
for (const k of ['SMTP_HOST', 'SMTP_PORT', 'SMTP_USER', 'SMTP_PASS', 'SMTP_FROM']) delete process.env[k];
});
test('the password is stored encrypted and only shown as saved', async () => {
const shown = await setSettings({ smtp_host: 'mail.example.com', smtp_user: 'hub', smtp_pass: 'p@ss' });
expect(mockRows.get('smtp_pass')).toMatch(/^v1:/);
expect(shown.smtp_pass).toBeUndefined();
expect(shown.smtp_pass_set).toBe('true');
expect((await smtpSettings()).pass).toBe('p@ss');
});
test('a blank password keeps the saved one; clearing removes it', async () => {
await setSettings({ smtp_host: 'mail.example.com', smtp_pass: 'p@ss' });
await setSettings({ smtp_host: 'smtp.example.com', smtp_pass: '' });
expect((await smtpSettings()).pass).toBe('p@ss');
await setSettings({ smtp_pass_clear: true });
expect((await smtpSettings()).pass).toBe('');
expect((await getSettings()).smtp_pass_set).toBe('');
});
test('form values override the saved ones for a test, falling back to the saved password', async () => {
await setSettings({ smtp_host: 'mail.example.com', smtp_port: '587', smtp_pass: 'p@ss' });
const smtp = await smtpSettings({ smtp_host: ' other.example.com ', smtp_port: '465', smtp_pass: '' });
expect(smtp).toMatchObject({ host: 'other.example.com', port: 465, pass: 'p@ss' });
expect((await smtpSettings({ smtp_pass_clear: true })).pass).toBe('');
});
test('SMTP_* in .env are copied once, and never over saved settings', async () => {
Object.assign(process.env, { SMTP_HOST: 'env.example.com', SMTP_PORT: '465', SMTP_USER: 'u', SMTP_PASS: 'envpass', SMTP_FROM: 'hub@example.com' });
expect(await importSmtpFromEnv()).toBe(true);
expect(await smtpSettings()).toMatchObject({ host: 'env.example.com', port: 465, user: 'u', pass: 'envpass', from: 'hub@example.com' });
await setSettings({ smtp_host: 'changed.example.com' });
expect(await importSmtpFromEnv()).toBe(false);
expect((await smtpSettings()).host).toBe('changed.example.com');
});
test('the SMTP test reports why it failed', async () => {
await expect(testSmtp({ smtp_host: '' }, 'a@example.com')).rejects.toThrow('Enter the SMTP server first.');
await expect(testSmtp({ smtp_host: '127.0.0.1', smtp_port: '1' }, 'a@example.com')).rejects.toThrow(/ECONNREFUSED|connect/i);
});
+3 -2
View File
@@ -147,7 +147,6 @@ Set at least:
| `HUB_ENCRYPTION_KEY` | `openssl rand -base64 48`. **Never change this** once installs have registered |
| `HUB_SIGNING_KEY_FILE` | `./keys/hub-signing-key.pem` (the default) |
| `TRUST_PROXY` | `1` |
| `SMTP_*`, `ALERT_EMAIL` | your mail settings, so alerts get sent |
```bash
chmod 600 .env
@@ -259,7 +258,9 @@ curl -s https://events-hub.crosscode.co.za/api/health # {"ok":true}
```
Then open `https://events-hub.crosscode.co.za`, log in, and set up two-factor (required on
first login). In **Settings**, check that the public key shown matches the one in Cross Events.
first login). In **Settings**, check that the public key shown matches the one in Cross Events,
then fill in **Email (SMTP)** and the **Alert email**, and press **Send test** to check the mail
server accepts the login. Without SMTP, alerts are only logged.
Point Cross Events installs at the Hub with `HUB_URL=https://events-hub.crosscode.co.za` in their
`backend/.env`.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "1.1.2",
"version": "1.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "1.1.2",
"version": "1.2.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "1.1.2",
"version": "1.2.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",
+60 -2
View File
@@ -26,6 +26,9 @@ export default function SettingsPage() {
const [audit, setAudit] = useState<AuditRow[]>([]);
const [pw, setPw] = useState({ currentPassword: "", newPassword: "" });
const [msg, setMsg] = useState<Msg>(null);
const [smtpPass, setSmtpPass] = useState({ value: "", clear: false });
const [testTo, setTestTo] = useState("");
const [testing, setTesting] = useState(false);
useEffect(() => {
api<{ settings: Settings; publicKey: string; smtp: boolean }>("/api/admin/settings").then(r => { setSettings(r.settings); setPublicKey(r.publicKey); setSmtp(r.smtp); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
@@ -37,12 +40,39 @@ export default function SettingsPage() {
const save = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ settings: Settings }>("/api/admin/settings", { method: "PUT", body: { settings } });
const r = await api<{ settings: Settings; smtp: boolean }>("/api/admin/settings", { method: "PUT", body: { settings } });
setSettings(r.settings);
setSmtp(r.smtp);
setMsg({ type: "ok", text: "Settings saved." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const smtpValues = () => ({
smtp_host: settings.smtp_host, smtp_port: settings.smtp_port, smtp_user: settings.smtp_user, smtp_from: settings.smtp_from,
smtp_pass: smtpPass.value, smtp_pass_clear: smtpPass.clear,
});
const saveSmtp = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ settings: Settings; smtp: boolean }>("/api/admin/settings", { method: "PUT", body: { settings: smtpValues() } });
setSettings(r.settings);
setSmtp(r.smtp);
setSmtpPass({ value: "", clear: false });
setMsg({ type: "ok", text: "Email settings saved." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const testSmtp = async () => {
setTesting(true);
setMsg(null);
try {
const r = await api<{ to: string }>("/api/admin/settings/smtp-test", { method: "POST", body: { settings: smtpValues(), to: testTo } });
setMsg({ type: "ok", text: `Logged in to the mail server and sent a test email to ${r.to}. Check it arrived (and the spam folder).` });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setTesting(false);
};
const changePassword = async (e: React.FormEvent) => {
e.preventDefault();
try {
@@ -67,7 +97,6 @@ export default function SettingsPage() {
<div className="grid gap-6 lg:grid-cols-2">
<form onSubmit={save} className="card space-y-4">
<h2 className="font-semibold">Releases and alerts</h2>
{!smtp && <p className="rounded-lg bg-amber-50 p-3 text-sm text-amber-900">Email isn&apos;t set up on this server (SMTP_* in .env), so alerts are only logged.</p>}
{FIELDS.map(f => (
<div key={f.key}>
<label className="label" htmlFor={f.key}>{f.label}</label>
@@ -79,6 +108,35 @@ export default function SettingsPage() {
</form>
<div className="space-y-6">
<form onSubmit={saveSmtp} className="card space-y-3">
<h2 className="font-semibold">Email (SMTP)</h2>
<p className="text-sm text-slate-600">The mail server alert emails are sent through. The password is stored encrypted.</p>
{!smtp && <p className="rounded-lg bg-amber-50 p-3 text-sm text-amber-900">Email isn&apos;t set up, so alerts are only logged.</p>}
<div className="grid gap-3 sm:grid-cols-3">
<div className="sm:col-span-2"><label className="label" htmlFor="smtp_host">Server</label><input id="smtp_host" className="input" placeholder="mail.example.com" value={settings.smtp_host ?? ""} onChange={e => setSettings({ ...settings, smtp_host: e.target.value })} /></div>
<div><label className="label" htmlFor="smtp_port">Port</label><input id="smtp_port" className="input" type="number" value={settings.smtp_port ?? ""} onChange={e => setSettings({ ...settings, smtp_port: e.target.value })} /></div>
</div>
<p className="-mt-1 text-xs text-slate-500">587 uses STARTTLS; 465 uses TLS from the start.</p>
<div><label className="label" htmlFor="smtp_user">Username</label><input id="smtp_user" className="input" autoComplete="off" value={settings.smtp_user ?? ""} onChange={e => setSettings({ ...settings, smtp_user: e.target.value })} /></div>
<div>
<label className="label" htmlFor="smtp_pass">Password</label>
<input id="smtp_pass" className="input" type="password" autoComplete="new-password" disabled={smtpPass.clear} placeholder={settings.smtp_pass_set ? "Saved — leave blank to keep it" : ""} value={smtpPass.value} onChange={e => setSmtpPass({ ...smtpPass, value: e.target.value })} />
{settings.smtp_pass_set && (
<label className="mt-1 flex items-center gap-2 text-xs text-slate-600"><input type="checkbox" checked={smtpPass.clear} onChange={e => setSmtpPass({ value: "", clear: e.target.checked })} /> Remove the saved password</label>
)}
</div>
<div><label className="label" htmlFor="smtp_from">From address</label><input id="smtp_from" className="input" placeholder="Cross Events Hub <hub@crosscode.co.za>" value={settings.smtp_from ?? ""} onChange={e => setSettings({ ...settings, smtp_from: e.target.value })} /><p className="mt-1 text-xs text-slate-500">Blank uses the username.</p></div>
<button className="btn-primary">Save email settings</button>
<div className="border-t border-slate-100 pt-3">
<label className="label" htmlFor="smtp_test_to">Send a test email to</label>
<div className="flex flex-wrap gap-2">
<input id="smtp_test_to" className="input flex-1" type="email" placeholder={settings.alert_email || "you@example.com"} value={testTo} onChange={e => setTestTo(e.target.value)} />
<button type="button" className="btn-secondary" disabled={testing} onClick={testSmtp}>{testing ? "Testing…" : "Send test"}</button>
</div>
<p className="mt-1 text-xs text-slate-500">Tries what&apos;s in the form, saved or not. Blank sends to the alert email.</p>
</div>
</form>
<div className="card space-y-2">
<h2 className="font-semibold">Licence signing key</h2>
<p className="text-sm text-slate-600">Installs check licences with this public key (built into Cross Events: <code>backend/src/hub/publicKey.js</code>). The private key stays on this server only — keep a backup.</p>