const prisma = require('../config/db'); const { encrypt, decrypt } = require('./crypto'); // Hub settings Joshua edits on the Settings page, with their defaults. const DEFAULTS = { latest_version: '', alert_email: '', // Alert thresholds offline_minutes: '60', backup_max_age_hours: '48', 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 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 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(); } /** * 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 };