diff --git a/CHANGELOG.md b/CHANGELOG.md index 60c1f32..05e5f63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,32 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [2.10.0] - 2026-11-20 + +### Changed + +- **Every email the Hub sends is laid out as Cross Events' and Accounts' are** + (`src/utils/emailLayout.js`): the Cross Code header with the logo, a white card with a heading, + a button for the one thing to do (with the link written out under it), coloured notes, tables, + a job's steps as ticks and crosses, log lines and nginx config in a code block, and a footer that + says why the email came. Each still has a plain-text version. That covers the job reports + (install, update, adopt, demo data, export, .env change, uninstall, batch stopped, missed job, + purge), the central server check, installs found on a server, install and server alerts, update + requests, an invoice that couldn't be sent, the SMTP test, notices to churches, and every email to + a site admin (update planned, reminder, done, didn't go through, postponed, cancelled, site ready, + data download, closing, maintenance), whose What's New notes are now a list. Billing emails keep + their own layout. `mail.sendMail` attaches the logo to any HTML that shows it. +- **The FastPanel email** (and the install's page) gives the backend location as nginx config to + paste, with `location ^~ /api/`. FastPanel's static-file handling adds a regex location for file + extensions that wins over a plain `/api`, so `/api/uploads/…/logo.png` reached the frontend and + logo uploads failed (Cross Events 3.6.1). deployment.md §8 uses `^~` for the Hub's own site too + (`/api/…/statement.pdf`). + +### Added + +- **Proxy done checks a file under /api** (`/api/proxy-check.png`): if the frontend answers + (`X-Powered-By: Next.js`), the site isn't made live and the page says to use `location ^~ /api/`. + ## [2.9.0] - 2026-11-20 Needs `@crosscode/contracts` 1.13.0 (vendored). The checks need Cross Events 3.5.0 (older ones don't diff --git a/backend/package-lock.json b/backend/package-lock.json index 7e8e7b8..184920d 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-backend", - "version": "2.9.0", + "version": "2.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "2.9.0", + "version": "2.10.0", "hasInstallScript": true, "dependencies": { "@anthropic-ai/sdk": "^1.3.0", diff --git a/backend/package.json b/backend/package.json index 2b5e10a..70be44f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "2.9.0", + "version": "2.10.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", diff --git a/backend/src/routes/installApi.js b/backend/src/routes/installApi.js index a08ccca..392e62e 100644 --- a/backend/src/routes/installApi.js +++ b/backend/src/routes/installApi.js @@ -18,6 +18,14 @@ const { getSettings } = require('../utils/settings'); const { compareVersions } = require('../utils/alerts'); const { requestMessage, requestedVersionOf, isOutdated } = require('../utils/updateRequests'); const { sendMail } = require('../utils/mail'); +const { render } = require('../utils/emailLayout'); + +/** An update-request email to Joshua (2.10.0: laid out as the Hub's other emails). */ +const updateRequestEmail = ({ heading, note, rows, link }) => render({ + heading, + blocks: [note, { rows }, { button: { label: 'Open the install', url: link } }], + footer: 'Sent by the Cross Code Hub to the alert address in Settings.', +}); const { releasesForInstall, latestVersions, unmetRequirementsFor, requirementMessage } = require('../utils/releases'); const { noticesForInstall } = require('../utils/notices'); const ai = require('../utils/ai'); @@ -296,7 +304,12 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) = await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: update request changed by ${name}`, - text: `${name} (${install.url}) now asks to be updated from ${current} to ${latest}${previous ? ` instead of ${previous}` : ''}.\n\n${link}`, + ...updateRequestEmail({ + heading: `${name} changed their update request`, + note: { note: { kind: 'info', text: `${name} now asks to be updated to ${latest}${previous ? ` instead of ${previous}` : ''}.` } }, + rows: [['Church', name], ['Site', install.url], ['Running', current], ['Wants', latest]], + link, + }), }).catch(e => console.warn('[update-request] email failed:', e?.message)); } return res.json({ requestedAt: now.toISOString(), version: latest, alreadyRequested: true, changed: true, previousVersion: previous }); @@ -308,7 +321,12 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) = await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: update requested by ${name}`, - text: `${name} (${install.url}) would like to be updated from ${current} to ${latest}.\n\n${link}`, + ...updateRequestEmail({ + heading: `${name} would like an update`, + note: { note: { kind: 'info', text: `${name} asked to be updated from ${current} to ${latest}.` } }, + rows: [['Church', name], ['Site', install.url], ['Running', current], ['Wants', latest]], + link, + }), }).catch(e => console.warn('[update-request] email failed:', e?.message)); } res.status(201).json({ requestedAt: event.createdAt.toISOString(), version: latest, alreadyRequested: false, changed: false }); @@ -338,7 +356,12 @@ router.post('/installs/update-request/cancel', updateRequestLimiter, async (req, await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: update request withdrawn by ${customer?.name || install.name}`, - text: `${customer?.name || install.name} (${install.url}) withdrew their update request. No need to update the site for now.\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`, + ...updateRequestEmail({ + heading: `${customer?.name || install.name} withdrew their update request`, + note: { note: { kind: 'success', text: 'No need to update the site for now.' } }, + rows: [['Church', customer?.name || install.name], ['Site', install.url]], + link: `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`, + }), }).catch(e => console.warn('[update-request] email failed:', e?.message)); } res.json({ cancelled: true }); diff --git a/backend/src/utils/alerts.js b/backend/src/utils/alerts.js index aacc799..5f9e790 100644 --- a/backend/src/utils/alerts.js +++ b/backend/src/utils/alerts.js @@ -7,6 +7,7 @@ const prisma = require('../config/db'); const { getSettings } = require('./settings'); const { sendMail } = require('./mail'); +const { render } = require('./emailLayout'); const MIN = 60 * 1000; const HOUR = 60 * MIN; @@ -155,7 +156,7 @@ async function runAlerts(now = new Date()) { if (openByType.has(p.type)) continue; await prisma.installEvent.create({ data: { installId: install.id, type: p.type, level: p.level, message: p.message, createdAt: now } }); opened++; - if (p.level !== 'info') newAlerts.push(`• ${install.customer?.name || install.name} (${install.url}): ${p.message}`); + if (p.level !== 'info') newAlerts.push({ level: p.level, who: install.customer?.name || install.name, url: install.url, message: p.message }); } const currentTypes = new Set(current.map(p => p.type)); for (const [type, event] of openByType) { @@ -165,11 +166,19 @@ async function runAlerts(now = new Date()) { } } if (newAlerts.length && settings.alert_email) { - await sendMail({ - to: settings.alert_email, - subject: `Cross Code Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`, - text: `${newAlerts.join('\n')}\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/`, - }).catch(e => console.warn('[alerts] email failed:', e?.message)); + const count = `${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`; + const critical = newAlerts.filter(a => a.level === 'critical'); + const email = render({ + heading: count, + sub: critical.length ? `${critical.length} critical` : undefined, + blocks: [ + ...critical.map(a => ({ note: { kind: 'danger', title: `${a.who} (${a.url})`, text: a.message } })), + { bullets: newAlerts.filter(a => a.level !== 'critical').map(a => `${a.who} (${a.url}): ${a.message}`) }, + { button: { label: 'Open the Hub', url: `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/` } }, + ], + footer: 'Sent by the Cross Code Hub to the alert address in Settings, once for each new problem.', + }); + await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: ${count}`, ...email }).catch(e => console.warn('[alerts] email failed:', e?.message)); } return { installs: installs.length, opened, resolved }; } diff --git a/backend/src/utils/billing/index.js b/backend/src/utils/billing/index.js index e92c8d0..137a42a 100644 --- a/backend/src/utils/billing/index.js +++ b/backend/src/utils/billing/index.js @@ -18,6 +18,7 @@ const { Prisma } = require('@prisma/client'); const prisma = require('../../config/db'); const { getSettings } = require('../settings'); const { sendMail } = require('../mail'); +const { render } = require('../emailLayout'); const compute = require('./compute'); const pdf = require('./pdf'); const { layout, sendBillingEmail } = require('./email'); @@ -192,7 +193,17 @@ async function sendInvoice(id, settings, now = new Date()) { if (!res.ok) { await prisma.invoice.update({ where: { id }, data: { status: 'approved', sentAt: null, sendError: res.error } }); if (!invoice.sendError && settings.alert_email) { - await sendMail({ to: settings.alert_email, subject: `Invoice ${invoice.number} couldn't be sent`, text: `Invoice ${invoice.number} for ${invoice.customer.name} couldn't be emailed to ${invoice.recipientEmail}: ${res.error}\n\nIt will be tried again. ${hubLink(`/billing/invoices/${id}`)}` }).catch(() => {}); + const email = render({ + heading: `Invoice ${invoice.number} couldn't be sent`, + blocks: [ + { note: { kind: 'danger', title: 'The email server said', text: res.error } }, + { rows: [['Invoice', invoice.number], ['Customer', invoice.customer.name], ['To', invoice.recipientEmail]] }, + { p: 'It will be tried again.' }, + { button: { label: 'Open the invoice', url: hubLink(`/billing/invoices/${id}`) } }, + ], + footer: 'Sent by the Cross Code Hub to the alert address in Settings.', + }); + await sendMail({ to: settings.alert_email, subject: `Invoice ${invoice.number} couldn't be sent`, ...email }).catch(() => {}); } throw bad(`It couldn't be emailed: ${res.error}`, 502); } diff --git a/backend/src/utils/emailLayout.js b/backend/src/utils/emailLayout.js new file mode 100644 index 0000000..d04c2ca --- /dev/null +++ b/backend/src/utils/emailLayout.js @@ -0,0 +1,188 @@ +/** + * The Hub's emails (2.10.0), laid out as Cross Events' and Accounts' are: a header (here Cross + * Code's, with the logo), a white card with a heading, a button for the one thing to do with the + * link written out under it, coloured notes, and a footer that says why the email came. + * + * An email is a heading and a list of blocks; render() makes both the HTML and the plain text + * from them, so every email still reads well in a mail app that shows only text. Everything put + * into the HTML is escaped, and only http(s) links go in an href. + * + * Blocks: + * { hello: name } "Hi Jane," + * { h: text } a subheading + * { p: text } a paragraph (links in it become clickable) + * { button: { label, url } } a button, with the link written out under it + * { note: { kind, title?, text } } kind: info | success | warning | danger + * { rows: [[label, value], …] } a summary table + * { bullets: [text, …] } a list + * { steps: [{ outcome, name, detail? }] } a job's steps: outcome ok | failed | anything else + * { numbered: [{ text, code? }, …] } instructions, each with an optional code block + * { code: text, label? } a code or log block + * { small: text } small grey print + * { divider: true } + * Billing keeps its own layout (billing/email.js), with the same colours. + */ +const fs = require('fs'); +const path = require('path'); + +const FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif"; +const MONO = "'SFMono-Regular',Consolas,'Liberation Mono',Menlo,monospace"; +const INK = '#11111f'; +const SKY = '#62b5e5'; +const BUTTON = '#1d6a9c'; + +const LOGO = path.join(__dirname, '..', '..', 'assets', 'logo.png'); +let logoBytes = null; +/** The logo's bytes, or null when the file isn't there. */ +function logo() { + if (logoBytes === null) { + try { logoBytes = fs.readFileSync(LOGO); } catch { logoBytes = false; } + } + return logoBytes || null; +} +/** The attachment the HTML's cid:logo points at. */ +const logoAttachment = () => (logo() ? { filename: 'logo.png', content: logo(), contentType: 'image/png', cid: 'logo' } : null); + +const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); +const safeUrl = u => (/^https?:\/\//i.test(String(u || '')) ? String(u) : '#'); + +/** Escaped text with its http(s) links made clickable and line breaks kept. */ +function linkify(text) { + return esc(text) + // Not the server's own addresses (http://127.0.0.1:20010): those are for FastPanel, not a browser. + .replace(/https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)]/g, u => (/^https?:\/\/(127\.0\.0\.1|localhost)[:/]/i.test(u) ? u : `${u}`)) + .replace(/\n/g, '
'); +} + +const NOTE = { + info: ['#eff6ff', '#3b82f6', '#1e3a8a'], + success: ['#f0fdf4', '#22c55e', '#166534'], + warning: ['#fffbeb', '#f59e0b', '#92400e'], + danger: ['#fef2f2', '#ef4444', '#991b1b'], +}; +const STEP = { ok: ['✓', '#16a34a'], failed: ['✗', '#dc2626'] }; + +function codeHtml(text, label) { + return `${label ? `

${esc(label)}

` : ''}` + + `
${esc(text)}
`; +} + +function blockHtml(b) { + if (b.hello !== undefined) return `

Hi ${esc(b.hello || 'there')},

`; + if (b.h !== undefined) return `

${esc(b.h)}

`; + if (b.p !== undefined) return `

${linkify(b.p)}

`; + if (b.button) { + const href = esc(safeUrl(b.button.url)); + return `
` + + `${esc(b.button.label)}
` + + `

Or open: ${esc(b.button.url)}

`; + } + if (b.note) { + const [bg, bar, ink] = NOTE[b.note.kind] || NOTE.info; + return `
` + + `${b.note.title ? `${esc(b.note.title)}${b.note.text ? '
' : ''}` : ''}${b.note.text ? linkify(b.note.text) : ''}
`; + } + if (b.rows) { + const rows = b.rows.filter(r => r && r[1] !== undefined && r[1] !== null && r[1] !== ''); + if (!rows.length) return ''; + return `` + + rows.map(([k, v], i) => `` + + ``).join('') + + '
${esc(k)}${linkify(v)}
'; + } + if (b.bullets) { + if (!b.bullets.length) return ''; + return ``; + } + if (b.steps) { + if (!b.steps.length) return ''; + return `` + + b.steps.map((s, i) => { + const [mark, colour] = STEP[s.outcome] || ['•', '#94a3b8']; + return `` + + ``; + }).join('') + + '
${mark}${esc(s.name)}${s.detail ? ` · ${esc(s.detail)}` : ''}
'; + } + if (b.numbered) { + return b.numbered.map((item, i) => `` + + `` + + `
${i + 1}
${linkify(item.text)}${item.code ? `
${codeHtml(item.code)}
` : ''}
`).join(''); + } + if (b.code !== undefined) return codeHtml(b.code, b.label); + if (b.small !== undefined) return `

${linkify(b.small)}

`; + if (b.divider) return '
'; + return ''; +} + +const indent = (t, by = ' ') => String(t).split('\n').map(l => by + l).join('\n'); + +function blockText(b) { + if (b.hello !== undefined) return `Hi ${b.hello || 'there'},`; + if (b.h !== undefined) return b.h; + if (b.p !== undefined) return b.p; + if (b.button) return `${b.button.label}: ${b.button.url}`; + if (b.note) return [b.note.title, b.note.text].filter(Boolean).join('\n'); + if (b.rows) return b.rows.filter(r => r && r[1] !== undefined && r[1] !== null && r[1] !== '').map(([k, v]) => `${k}: ${v}`).join('\n') || null; + if (b.bullets) return b.bullets.map(t => `• ${t}`).join('\n') || null; + if (b.steps) return b.steps.map(s => ` ${(STEP[s.outcome] || ['•'])[0]} ${s.name}${s.detail ? ` (${s.detail})` : ''}`).join('\n') || null; + if (b.numbered) return b.numbered.map((item, i) => `${i + 1}. ${item.text}${item.code ? `\n\n${indent(item.code, ' ')}` : ''}`).join('\n\n'); + if (b.code !== undefined) return `${b.label ? `${b.label}:\n` : ''}${b.code}`; + if (b.small !== undefined) return b.small; + if (b.divider) return '—'; + return null; +} + +/** + * The email as { html, text }. `label` is the line under the logo (default "Hub"); `footer` says + * why it came. Send it with mail.sendMail, which attaches the logo. + */ +function render({ heading, sub, preheader, blocks = [], label = 'Hub', footer = 'Sent by the Cross Code Hub.' }) { + const list = blocks.filter(Boolean); + const logoCell = logo() + ? `` + : ''; + const html = ` + + + + + +${esc(heading)} + + +
${esc(preheader || sub || heading)}‌ ‌ ‌ 
+ + +
+ + + + + +
+ + ${logoCell} + +
+
Cross Code
+
${esc(label)}
+
+
 
+
+

${esc(heading)}

+ ${sub ? `

${esc(sub)}

` : ''} + ${list.map(blockHtml).join('\n ')} +
+
+

Cross Code • crosscode.co.za

+

${esc(footer)}

+
+
+ +`; + const text = [heading, sub, ...list.map(blockText)].filter(x => x !== null && x !== undefined && x !== '').join('\n\n'); + return { html, text }; +} + +module.exports = { render, logoAttachment, esc }; diff --git a/backend/src/utils/jobs.js b/backend/src/utils/jobs.js index 2c6067c..5abf099 100644 --- a/backend/src/utils/jobs.js +++ b/backend/src/utils/jobs.js @@ -16,6 +16,7 @@ const prisma = require('../config/db'); const { decrypt } = require('./crypto'); const { verifyCode } = require('./totp'); const { sendMail } = require('./mail'); +const { render } = require('./emailLayout'); const { getSettings } = require('./settings'); const { PRODUCT_NAMES } = require('./products'); const { generateLicence } = require('./licences'); @@ -149,11 +150,24 @@ async function afterJob(job, { exportKey }, now) { const version = job.report?.result?.versions?.[deployment.product] || null; await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'waiting_for_proxy', version: version ? String(version).replace(/^.*@/, '') : null } }); await queueCentralCheck([deployment.webPort, deployment.apiPort], now); - await emailJoshua(`Installed: ${deployment.shortName} (${PRODUCT_NAMES[deployment.product]})`, `${jobReportText(job)}\n\n${await fastPanelText(deployment)}`); + const fp = await fastPanelSteps(deployment); + await emailJoshua(`Installed: ${deployment.shortName} (${PRODUCT_NAMES[deployment.product]})`, { + heading: `${deployment.domain} is installed`, + sub: 'Now set it up in FastPanel.', + blocks: [ + { note: { kind: 'success', title: `${PRODUCT_NAMES[deployment.product]} installed on ${deployment.server?.name || 'the server'}`, text: `Ports ${deployment.webPort} (frontend) and ${deployment.apiPort} (backend). It goes live when you click "Proxy done".` } }, + { h: `${fp.heading} (${fp.sub})` }, + { numbered: fp.steps }, + { button: { label: 'Proxy done: check and go live', url: fp.link } }, + { divider: true }, + { h: 'The install' }, + ...jobReportBlocks(job, { button: false }), + ], + }); } else { await prisma.deployment.update({ where: { id: deployment.id }, data: { status: 'failed' } }); await prisma.port.deleteMany({ where: { port: { in: [deployment.webPort, deployment.apiPort] } } }); - await emailJoshua(`Install failed: ${deployment.shortName}`, jobReportText(job)); + await emailJoshua(`Install failed: ${deployment.shortName}`, jobReport(job, `${deployment.domain} wasn't installed`, 'Its ports are free again. The steps and the last log lines are below.')); } break; case 'deploy': @@ -163,28 +177,49 @@ async function afterJob(job, { exportKey }, now) { if (ok && target) await prisma.deployment.update({ where: { id: deployment.id }, data: { version: target.replace(/^.*@/, ''), status: deployment.status === 'failed' ? 'live' : deployment.status } }); if (job.scheduled) { const name = PRODUCT_NAMES[deployment.product]; - if (ok) await emailSiteAdmin(deployment, `${name} was updated`, `${name} at ${deployment.domain} was updated${target ? ` to ${target.replace(/^.*@/, '')}` : ''}. Everything is running again.`); - else await emailSiteAdmin(deployment, `${name} update didn't go through`, `The planned update of ${name} at ${deployment.domain} didn't go through, so the site is running the previous version. Nothing else changed; we'll be in touch about a new time.`); + const version = target ? target.replace(/^.*@/, '') : null; + if (ok) { + await emailSiteAdmin(deployment, `${name} was updated`, { + heading: `${name} was updated`, + blocks: [ + { note: { kind: 'success', title: 'Everything is running again', text: `${name} at ${deployment.domain} was updated${version ? ` to ${version}` : ''}.` } }, + { button: { label: `Open ${name}`, url: `https://${deployment.domain}` } }, + ], + }); + } else { + await emailSiteAdmin(deployment, `${name} update didn't go through`, { + heading: 'The update didn\'t go through', + blocks: [ + { note: { kind: 'warning', title: 'Your site is running as before', text: `The planned update of ${name} at ${deployment.domain} didn't go through, so the site is running the previous version. Nothing else changed.` } }, + { p: 'We\'ll be in touch about a new time.' }, + ], + }); + } } - await emailJoshua(`${job.type === 'adopt' ? 'Adopt' : 'Update'} ${ok ? 'done' : job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReportText(job)); + await emailJoshua(`${job.type === 'adopt' ? 'Adopt' : 'Update'} ${ok ? 'done' : job.status.replace('_', ' ')}: ${deployment.shortName}`, + jobReport(job, `${job.type === 'adopt' ? 'Adopt' : 'Update'} of ${deployment.domain} ${ok ? 'done' : job.status.replace('_', ' ')}`, target ? `To ${target}.` : undefined)); break; } case 'seed-demo': if (!deployment) break; - await emailJoshua(`Demo data ${ok ? `(${job.args.profile}) loaded` : job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReportText(job)); + await emailJoshua(`Demo data ${ok ? `(${job.args.profile}) loaded` : job.status.replace('_', ' ')}: ${deployment.shortName}`, + jobReport(job, ok ? `Demo data loaded on ${deployment.domain}` : `Demo data on ${deployment.domain}: ${job.status.replace('_', ' ')}`, `Profile: ${job.args.profile}.`)); break; case 'export': if (!deployment) break; if (ok && exportKey) { const link = `${hubUrl()}/download/${job.args.exportId}#${exportKey}`; const exp = await prisma.export.findUnique({ where: { id: job.args.exportId } }); - await emailSiteAdmin(deployment, 'Your church\'s data from Cross Code', [ - `Here is all of ${deployment.customer?.name || 'your church'}'s data from ${PRODUCT_NAMES[deployment.product]}: events, people, registrations, payments, check-ins and rosters, with the uploaded files.`, - '', link, '', - `The link works until ${exp ? sast(exp.expiresAt) : `${EXPORT_DAYS} days from now`}. The file is encrypted, and only this link (the part after #) can open it: we can't read it, and we can't send the link again, so keep this email.`, - ].join('\n')); + await emailSiteAdmin(deployment, 'Your church\'s data from Cross Code', { + heading: 'Your data is ready to download', + blocks: [ + { p: `Here is all of ${deployment.customer?.name || 'your church'}'s data from ${PRODUCT_NAMES[deployment.product]}: events, people, registrations, payments, check-ins and rosters, with the uploaded files.` }, + { button: { label: 'Download your data', url: link } }, + { note: { kind: 'warning', title: 'Keep this email', text: `The link works until ${exp ? sast(exp.expiresAt) : `${EXPORT_DAYS} days from now`}. The file is encrypted, and only this link (the part after #) can open it: we can't read it, and we can't send the link again.` } }, + ], + }); } else if (!ok) { - await emailJoshua(`Export failed: ${deployment.shortName}`, jobReportText(job)); + await emailJoshua(`Export failed: ${deployment.shortName}`, jobReport(job, `The export of ${deployment.domain} failed`)); } break; case 'env-set': @@ -192,7 +227,7 @@ async function afterJob(job, { exportKey }, now) { if (deployment && ['succeeded', 'rolled_back'].includes(job.status)) { await makeJob(prisma, { serverId: deployment.serverId, type: 'env-read', args: { church: deployment.shortName, product: deployment.product }, deploymentId: deployment.id, createdById: job.createdById, notBefore: now }); } - if (deployment && !ok) await emailJoshua(`.env change ${job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReportText(job)); + if (deployment && !ok) await emailJoshua(`.env change ${job.status.replace('_', ' ')}: ${deployment.shortName}`, jobReport(job, `The .env change on ${deployment.domain}: ${job.status.replace('_', ' ')}`, job.status === 'rolled_back' ? 'The site didn\'t answer afterwards, so the file was put back.' : undefined)); break; case 'uninstall': if (!deployment) break; @@ -201,10 +236,18 @@ async function afterJob(job, { exportKey }, now) { await prisma.port.updateMany({ where: { port: { in: [deployment.webPort, deployment.apiPort] } }, data: { releasedAt: now, deploymentId: deployment.id } }); if (deployment.installId) await prisma.install.update({ where: { id: deployment.installId }, data: { releasedAt: now } }); await makeJob(prisma, { serverId: deployment.serverId, type: 'purge', args: { church: deployment.shortName }, deploymentId: deployment.id, notBefore: new Date(now.getTime() + EXPORT_DAYS * DAY), windowMinutes: 3 * 24 * 60 }); - await emailJoshua(`Uninstalled: ${deployment.shortName}`, `${jobReportText(job)}\n\nRemove the FastPanel site ${deployment.domain} (ports ${deployment.webPort}, ${deployment.apiPort}).\nThe final backup is kept on the server for ${EXPORT_DAYS} days, then purged.`); + await emailJoshua(`Uninstalled: ${deployment.shortName}`, { + heading: `${deployment.domain} is uninstalled`, + sub: 'One thing left to do by hand.', + blocks: [ + { note: { kind: 'warning', title: 'Remove the FastPanel site', text: `${deployment.domain} (ports ${deployment.webPort} and ${deployment.apiPort}).` } }, + { p: `The final backup is kept on the server for ${EXPORT_DAYS} days, then purged.` }, + ...jobReportBlocks(job), + ], + }); } else { await prisma.deployment.update({ where: { id: deployment.id }, data: { status: statusBeforeUninstall(deployment) } }); - await emailJoshua(`Uninstall failed: ${deployment.shortName}`, jobReportText(job)); + await emailJoshua(`Uninstall failed: ${deployment.shortName}`, jobReport(job, `${deployment.domain} wasn't uninstalled`, 'The site is as it was.')); } break; case 'purge': @@ -214,7 +257,16 @@ async function afterJob(job, { exportKey }, now) { } break; case 'check-ports': - if (!ok) await emailJoshua('Central server check: ports not ready', `${job.message || ''}\n\n${JSON.stringify(job.report?.result || {}, null, 2)}`); + if (!ok) { + await emailJoshua('Central server check: ports not ready', { + heading: 'The central server\'s ports aren\'t ready', + blocks: [ + { note: { kind: 'danger', title: 'frps check failed', text: job.message || 'No reason given.' } }, + { code: JSON.stringify(job.report?.result || {}, null, 2), label: 'What the central agent found' }, + { button: { label: 'Open the job', url: `${hubUrl()}/jobs/${job.id}` } }, + ], + }); + } break; case 'status': if (ok) await linkFromStatus(job, now); @@ -249,10 +301,17 @@ async function advanceBatch(job, now) { await prisma.port.deleteMany({ where: { port: { in: [j.deployment.webPort, j.deployment.apiPort] } } }); } if (j.deployment && j.scheduled && j.type === 'deploy') { - await emailSiteAdmin(j.deployment, `${PRODUCT_NAMES[j.deployment.product]} update postponed`, `The planned update of ${PRODUCT_NAMES[j.deployment.product]} at ${j.deployment.domain} has been postponed. Your site keeps running as it is; we'll let you know the new time.`); + const name = PRODUCT_NAMES[j.deployment.product]; + await emailSiteAdmin(j.deployment, `${name} update postponed`, { + heading: 'The update is postponed', + blocks: [ + { note: { kind: 'info', title: 'Your site keeps running as it is', text: `The planned update of ${name} at ${j.deployment.domain} has been postponed.` } }, + { p: 'We\'ll let you know the new time.' }, + ], + }); } } - await emailJoshua('Batch stopped', `${jobReportText(job)}\n\n${rest.length} job(s) after it were cancelled and their churches told the update is postponed.`); + await emailJoshua('Batch stopped', jobReport(job, 'A batch stopped', `${rest.length} job(s) after this one were cancelled, and their churches were told the update is postponed.`)); } // ─── The scheduler (every 30 s) ─────────────────────────────────────────────── @@ -263,7 +322,14 @@ async function tick(now = new Date()) { for (const job of missed) { const updated = await prisma.job.update({ where: { id: job.id }, data: { status: 'missed', message: `The agent on ${job.server.name} didn't pick it up between ${job.notBefore.toISOString()} and ${job.expiresAt.toISOString()}.`, finishedAt: now } }); if (job.noticeId) await endNotice(job.noticeId, now); - await emailJoshua(`Missed job: ${job.type} on ${job.server.name}`, `${updated.message}\nNothing ran. A new time needs a new notice to the church.\n\n${hubUrl()}/jobs/${job.id}`); + await emailJoshua(`Missed job: ${job.type} on ${job.server.name}`, { + heading: `A ${job.type} job was missed`, + blocks: [ + { note: { kind: 'warning', title: 'Nothing ran', text: updated.message } }, + { p: 'A new time needs a new notice to the church.' }, + { button: { label: 'Open the job', url: `${hubUrl()}/jobs/${job.id}` } }, + ], + }); if (job.batchId) await advanceBatch(updated, now); if ((job.type === 'install' || job.type === 'add-product') && job.deploymentId) { await prisma.deployment.update({ where: { id: job.deploymentId }, data: { status: 'failed' } }); @@ -274,14 +340,28 @@ async function tick(now = new Date()) { for (const job of soon) { await prisma.job.update({ where: { id: job.id }, data: { remindedAt: now } }); if (job.deployment && job.type !== 'uninstall') { - await emailSiteAdmin(job.deployment, `Reminder: ${PRODUCT_NAMES[job.deployment.product]} update at ${sast(job.notBefore)}`, `A reminder that ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} will be updated on ${sast(job.notBefore)}. The site will be unavailable for a few minutes.`); + const name = PRODUCT_NAMES[job.deployment.product]; + await emailSiteAdmin(job.deployment, `Reminder: ${name} update at ${sast(job.notBefore)}`, { + heading: 'Reminder: an update in an hour', + blocks: [ + { rows: [['Site', job.deployment.domain], ['When', sast(job.notBefore)]] }, + { p: `${name} will be unavailable for a few minutes while it's updated.` }, + ], + }); } } // Purges: Joshua is told 3 days before the kept backup is deleted. const purges = await prisma.job.findMany({ where: { type: 'purge', status: 'queued', remindedAt: null, notBefore: { lte: new Date(now.getTime() + 3 * DAY) } }, include: { deployment: true } }); for (const job of purges) { await prisma.job.update({ where: { id: job.id }, data: { remindedAt: now } }); - await emailJoshua(`Purge in 3 days: ${job.args.church}`, `${job.args.church}'s kept backup and its encrypted export will be deleted on ${sast(job.notBefore)}. To keep them 30 days longer, open the job: ${hubUrl()}/jobs/${job.id}`); + await emailJoshua(`Purge in 3 days: ${job.args.church}`, { + heading: `${job.args.church}'s data is deleted in 3 days`, + blocks: [ + { note: { kind: 'warning', text: `${job.args.church}'s kept backup and its encrypted export will be deleted on ${sast(job.notBefore)}.` } }, + { p: 'To keep them 30 days longer, open the job.' }, + { button: { label: 'Open the job', url: `${hubUrl()}/jobs/${job.id}` } }, + ], + }); } // Exports past their date. await prisma.export.updateMany({ where: { deletedAt: null, expiresAt: { lte: now } }, data: { data: null, deletedAt: now } }); @@ -290,22 +370,78 @@ async function tick(now = new Date()) { // ─── Emails ─────────────────────────────────────────────────────────────────── -async function emailJoshua(subject, text) { +/** `content` is { heading?, sub?, preheader?, blocks } (emailLayout.js), or plain text. */ +const asContent = content => (typeof content === 'string' ? { blocks: content.split(/\n{2,}/).map(p => ({ p })) } : content || { blocks: [] }); + +/** An email to Joshua at the alert address in Settings. */ +async function emailJoshua(subject, content) { const { alert_email: to } = await getSettings(); - if (to) await sendMail({ to, subject: `Cross Code Hub: ${subject}`, text }).catch(e => console.warn('[jobs] email failed:', e?.message)); + if (!to) return; + const c = asContent(content); + const email = render({ heading: c.heading || subject, sub: c.sub, preheader: c.preheader, blocks: c.blocks, footer: 'Sent by the Cross Code Hub to the alert address in Settings.' }); + await sendMail({ to, subject: `Cross Code Hub: ${subject}`, ...email }).catch(e => console.warn('[jobs] email failed:', e?.message)); } function siteAdminEmail(deployment) { return deployment.adminEmail || deployment.install?.adminContact?.email || null; } -async function emailSiteAdmin(deployment, subject, text) { +/** An email to a church's site admin: greeted by name and signed from Cross Code. */ +async function emailSiteAdmin(deployment, subject, content) { const to = siteAdminEmail(deployment); if (!to) return; const hello = deployment.adminName || deployment.install?.adminContact?.name; - await sendMail({ to, subject, text: `${hello ? `Hi ${hello},\n\n` : ''}${text}\n\nCross Code` }).catch(e => console.warn('[jobs] email failed:', e?.message)); + const c = asContent(content); + const product = PRODUCT_NAMES[deployment.product] || 'Cross Code'; + const email = render({ + heading: c.heading || subject, + sub: c.sub, + preheader: c.preheader, + label: product, + blocks: [hello ? { hello } : null, ...c.blocks, { p: 'Kind regards,\nThe Cross Code team' }], + footer: `You're getting this because you look after ${deployment.customer?.name ? `${deployment.customer.name}'s ` : 'the '}${product} site at ${deployment.domain}.`, + }); + await sendMail({ to, subject, ...email }).catch(e => console.warn('[jobs] email failed:', e?.message)); } +/** A job's report as email blocks: how it ended, its steps, the last log lines if it failed, a link. */ +function jobReportBlocks(job, { button = true } = {}) { + const r = job.report || {}; + const kind = job.status === 'succeeded' ? 'success' : ['failed', 'missed'].includes(job.status) ? 'danger' : 'warning'; + const log = job.status === 'succeeded' ? [] : (r.log || []).slice(-30); + return [ + { note: { kind, title: `${job.type}: ${job.status.replace(/_/g, ' ')}`, text: job.message || '' } }, + { steps: (r.steps || []).map(s => ({ outcome: s.outcome, name: s.name, detail: s.detail })) }, + log.length ? { code: log.join('\n'), label: 'Last log lines' } : null, + button ? { button: { label: 'Open the job', url: `${hubUrl()}/jobs/${job.id}` } } : { small: `Job ${job.id}: ${hubUrl()}/jobs/${job.id}` }, + ]; +} + +/** + * A release's What's New notes as email blocks: "- " lines (with their indented continuations) + * a list, other lines paragraphs; **bold** and `code` marks are dropped, as the Hub's page does. + */ +function notesBlocks(notes) { + const plain = t => t.replace(/\*\*(.+?)\*\*/g, '$1').replace(/`([^`]+)`/g, '$1').replace(/\s+/g, ' ').trim(); + const blocks = []; + let para = []; + let bullets = []; + const flushPara = () => { if (para.length) blocks.push({ p: plain(para.join(' ')) }); para = []; }; + const flushBullets = () => { if (bullets.length) blocks.push({ bullets: bullets.map(plain) }); bullets = []; }; + for (const line of String(notes || '').split(/\r?\n/)) { + if (/^\s*[-*] /.test(line)) { flushPara(); bullets.push(line.replace(/^\s*[-*] /, '')); } + else if (!line.trim()) { flushPara(); flushBullets(); } + else if (bullets.length && /^\s+/.test(line)) bullets[bullets.length - 1] += ` ${line.trim()}`; + else { flushBullets(); para.push(line.trim()); } + } + flushPara(); + flushBullets(); + return blocks; +} + +/** An email made of a job's report under a heading. */ +const jobReport = (job, heading, intro) => ({ heading, blocks: [intro ? { p: intro } : null, ...jobReportBlocks(job)] }); + function jobReportText(job) { const r = job.report || {}; const steps = (r.steps || []).map(s => ` ${s.outcome === 'ok' ? '✓' : s.outcome === 'failed' ? '✗' : '•'} ${s.name}${s.detail ? ` (${s.detail})` : ''}`).join('\n'); @@ -328,22 +464,50 @@ async function dnsPointsAtCentral(domain) { } } -/** The FastPanel email (§11): what Joshua sets up by hand; nothing is done automatically. */ -async function fastPanelText(d) { +/** + * The site's backend location for FastPanel's nginx. ^~ (2.10.0): FastPanel's static-file + * handling adds a regex location for file extensions that falls back to the site's main proxy + * (the frontend), and a regex wins over a plain "location /api", so /api/uploads/…/logo.png + * reached the frontend and 404'd (Events 3.6.1). No regex can override ^~. + */ +const fastPanelNginx = d => [ + 'location ^~ /api/ {', + ` proxy_pass http://127.0.0.1:${d.apiPort};`, + ' proxy_set_header Host $host;', + ' proxy_set_header X-Real-IP $remote_addr;', + ' proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;', + ' proxy_set_header X-Forwarded-Proto https;', + '}', + `location = /api { proxy_pass http://127.0.0.1:${d.apiPort}; }`, +].join('\n'); + +/** The FastPanel steps (§11): what Joshua sets up by hand; nothing is done automatically. */ +async function fastPanelSteps(d) { const dnsOk = await dnsPointsAtCentral(d.domain); const ip = await centralIp(); + return { + heading: `Set up in FastPanel: ${d.domain}`, + sub: `${d.customer?.name || d.shortName}, ${PRODUCT_NAMES[d.product]}`, + link: `${hubUrl()}/servers/installs/${d.id}`, + steps: [ + { text: `Add the site ${d.domain} as a proxy to http://127.0.0.1:${d.webPort} (the frontend). Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https, and allow uploads up to 25 MB.` }, + { text: 'Send /api to the backend: add this to the site\'s nginx configuration. Keep the ^~: without it FastPanel\'s static-file rule sends every /api path with a file extension (an uploaded logo, a PDF) to the frontend.', code: fastPanelNginx(d) }, + { text: 'Turn on Let\'s Encrypt for the site.' }, + { text: `DNS: ${d.domain} → ${ip || ''} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'}).` }, + { text: 'Click "Proxy done" in the Hub. It checks the site, its /api and a file under /api, then makes it live.' }, + ], + }; +} + +/** The FastPanel steps as text (the install's page shows them). */ +async function fastPanelText(d) { + const f = await fastPanelSteps(d); return [ - `Set up in FastPanel: ${d.domain} (${d.customer?.name || d.shortName}, ${PRODUCT_NAMES[d.product]})`, + `${f.heading} (${f.sub})`, '', - `1. Add the site ${d.domain}.`, - '2. Proxy:', - ` /api → http://127.0.0.1:${d.apiPort} (backend)`, - ` everything else → http://127.0.0.1:${d.webPort} (frontend)`, - ' Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https.', - ' Allow uploads up to 25 MB.', - '3. Turn on Let\'s Encrypt for the site.', - `4. DNS: ${d.domain} → ${ip || ''} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'})`, - `5. Then click "Proxy done" in the Hub: ${hubUrl()}/servers/installs/${d.id}`, + ...f.steps.map((s, i) => `${i + 1}. ${s.text}${s.code ? `\n\n${s.code.split('\n').map(l => ` ${l}`).join('\n')}\n` : ''}`), + '', + `Proxy done: ${f.link}`, ].join('\n'); } @@ -574,7 +738,17 @@ async function linkFromStatus(job, now = new Date()) { if (linked.length || unknown.length) { const text = [linked.length ? `Added: ${linked.join(', ')}.` : '', unknown.length ? `Not added (no registered site or other product of the church tells the customer, or no ports): ${unknown.join(', ')}.` : ''].filter(Boolean).join(' '); await prisma.job.update({ where: { id: job.id }, data: { message: [job.message, text].filter(Boolean).join(' ') } }); - if (linked.length) await emailJoshua(`Installs found on a server`, `${text}\n\n${hubUrl()}/jobs/${job.id}`); + if (linked.length) { + await emailJoshua('Installs found on a server', { + heading: 'Installs found on a server', + blocks: [ + { p: 'Added to the Hub:' }, + { bullets: linked }, + unknown.length ? { note: { kind: 'warning', title: 'Not added', text: `No registered site or other product of the church names the customer, or there are no ports: ${unknown.join(', ')}.` } } : null, + { button: { label: 'Open the job', url: `${hubUrl()}/jobs/${job.id}` } }, + ], + }); + } } return { linked, unknown }; } @@ -655,12 +829,24 @@ async function proxyDone(deploymentId, now = new Date(), fetcher = fetch) { try { reported = await health.json(); } catch { problems.push(`https://${d.domain}/api/health didn't answer with JSON (is /api sent to port ${d.apiPort}?).`); } if (reported && d.version && reported.version !== d.version) problems.push(`The backend reports version ${reported.version}, expected ${d.version}.`); } + // 2.10.0: a path under /api with a file extension must reach the backend too (FastPanel's + // static-file rule sent them to the frontend, which answers as Next.js). A 404 is fine. + const file = await get(`https://${d.domain}/api/proxy-check.png`); + if (file && /next\.js/i.test(file.headers?.get?.('x-powered-by') || '')) { + problems.push(`https://${d.domain}/api/… paths with a file extension (.png, .pdf) reach the frontend: in FastPanel use "location ^~ /api/" for the backend (step 2).`); + } if (problems.length) return { live: false, problems }; await prisma.deployment.update({ where: { id: d.id }, data: { status: 'live', liveAt: now } }); - await emailSiteAdmin(d, `Your ${PRODUCT_NAMES[d.product]} site is ready`, [ - `${d.customer?.name || 'Your church'}'s ${PRODUCT_NAMES[d.product]} site is ready at https://${d.domain}.`, - '', `To start, open https://${d.domain}/setup: it creates your admin account and walks you through the settings.`, - ].join('\n')); + const name = PRODUCT_NAMES[d.product]; + await emailSiteAdmin(d, `Your ${name} site is ready`, { + heading: `Your ${name} site is ready`, + sub: `https://${d.domain}`, + blocks: [ + { p: `${d.customer?.name || 'Your church'}'s ${name} site is ready.` }, + { p: 'To start, open the setup: it creates your admin account and walks you through the settings.' }, + { button: { label: 'Start the setup', url: `https://${d.domain}/setup` } }, + ], + }); return { live: true, problems: [] }; } @@ -821,8 +1007,16 @@ async function scheduleUpdate({ deploymentIds, product: wanted = null, version, ...next(), notBefore: when, noticeId, args: { church: d.shortName, products: [product], versions }, })); - const notes = release.notes ? `\n\nWhat's new in ${release.version}:\n${release.notes}` : ''; - await emailSiteAdmin(d, asap ? `Urgent: ${name} is being updated now` : `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, `${message}${notes}`); + await emailSiteAdmin(d, asap ? `Urgent: ${name} is being updated now` : `${emergency ? 'Urgent: ' : ''}${name} will be updated on ${sast(when)}`, { + heading: asap ? `${name} is being updated now` : emergency ? `An urgent ${name} update` : `A planned ${name} update`, + preheader: message, + blocks: [ + { rows: [['Site', d.domain], ['When', asap ? 'Now' : sast(when)], ['Version', release.version]] }, + { p: 'The site will be unavailable for a few minutes while it\'s updated.' }, + emergency && reason ? { note: { kind: 'warning', title: 'Why it can\'t wait', text: reason } } : null, + ...(release.notes ? [{ divider: true }, { h: `What's new in ${release.version}` }, ...notesBlocks(release.notes)] : []), + ], + }); } return { jobs, batchId, warnings: [...new Set(warnings)] }; } @@ -835,7 +1029,12 @@ async function cancelJob(jobId, admin, now = new Date()) { const updated = await prisma.job.update({ where: { id: job.id }, data: { status: 'cancelled', finishedAt: now, message: `Cancelled by ${admin?.name || 'an admin'}.` } }); if (job.noticeId) await endNotice(job.noticeId, now); if (job.scheduled && job.deployment && job.type === 'deploy') { - await emailSiteAdmin(job.deployment, `${PRODUCT_NAMES[job.deployment.product]} update cancelled`, `The update of ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} planned for ${sast(job.notBefore)} is cancelled. Your site keeps running as it is.`); + await emailSiteAdmin(job.deployment, `${PRODUCT_NAMES[job.deployment.product]} update cancelled`, { + heading: 'The update is cancelled', + blocks: [ + { note: { kind: 'info', title: 'Your site keeps running as it is', text: `The update of ${PRODUCT_NAMES[job.deployment.product]} at ${job.deployment.domain} planned for ${sast(job.notBefore)} is cancelled.` } }, + ], + }); } if (job.batchId) await advanceBatch(updated, now); if (job.type === 'uninstall' && job.deployment) await prisma.deployment.update({ where: { id: job.deployment.id }, data: { status: statusBeforeUninstall(job.deployment) } }); @@ -893,7 +1092,14 @@ async function scheduleUninstall({ deploymentId, at, totp, confirm }, admin, now const exportJob = await makeJob(prisma, { serverId: d.serverId, type: 'export', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 0, notBefore: when, args: { church: d.shortName, exportId } }); const uninstallJob = await makeJob(prisma, { serverId: d.serverId, type: 'uninstall', deploymentId: d.id, createdById: admin.id, scheduled: true, batchId, batchOrder: 1, status: 'scheduled', notBefore: when, noticeId, args: { church: d.shortName } }); await prisma.deployment.update({ where: { id: d.id }, data: { status: 'uninstalling' } }); - await emailSiteAdmin(d, `${PRODUCT_NAMES[d.product]} at ${d.domain} closes on ${sast(when)}`, `As agreed, ${PRODUCT_NAMES[d.product]} at ${d.domain} will be closed on ${sast(when)}. Shortly before, you'll get an email with a link to download all your data (events, people, registrations, payments and files). The link works for ${EXPORT_DAYS} days.`); + await emailSiteAdmin(d, `${PRODUCT_NAMES[d.product]} at ${d.domain} closes on ${sast(when)}`, { + heading: `${PRODUCT_NAMES[d.product]} is closing`, + blocks: [ + { p: `As agreed, ${PRODUCT_NAMES[d.product]} at ${d.domain} will be closed.` }, + { rows: [['Site', d.domain], ['Closes on', sast(when)]] }, + { note: { kind: 'info', title: 'Your data', text: `Shortly before, you'll get an email with a link to download all your data (events, people, registrations, payments and files). The link works for ${EXPORT_DAYS} days.` } }, + ], + }); return { exportJob, uninstallJob }; } @@ -944,7 +1150,13 @@ async function scheduleAdopt({ deploymentId, eventsDir, version, address, at }, const release = await releaseFor(d.product, version || null); const noticeId = await addNotice(d, { title: 'Planned maintenance', message: `${PRODUCT_NAMES[d.product]} will be moved to its new home on ${sast(when)}. The site will be unavailable for a minute or two.`, endsAt: new Date(when.getTime() + 2 * HOUR) }, now); const job = await makeJob(prisma, { serverId: d.serverId, type: 'adopt', deploymentId: d.id, createdById: admin?.id || null, scheduled: true, notBefore: when, noticeId, args: { church: d.shortName, eventsDir: String(eventsDir || ''), version: `${d.product}@${release.version}`, address: church } }); - await emailSiteAdmin(d, `Planned maintenance on ${sast(when)}`, `${PRODUCT_NAMES[d.product]} at ${d.domain} will be moved to its new home on ${sast(when)}. The site will be unavailable for a minute or two; nothing changes for your team.`); + await emailSiteAdmin(d, `Planned maintenance on ${sast(when)}`, { + heading: 'Planned maintenance', + blocks: [ + { rows: [['Site', d.domain], ['When', sast(when)]] }, + { p: `${PRODUCT_NAMES[d.product]} will be moved to its new home. The site will be unavailable for a minute or two; nothing changes for your team.` }, + ], + }); return job; } @@ -1060,5 +1272,5 @@ module.exports = { WINDOW_MIN, SCHEDULE_MIN_HOURS, EMERGENCY_MIN_MINUTES, setDemo, seedDemo, makeJob, signedJob, jobConfig, poll, receiveReport, finish, tick, advanceBatch, JOB_STATUSES, linkFromStatus, listWhere, lookForUnlinked, newInstall, proxyDone, scheduleUpdate, cancelJob, scheduleUninstall, neverInstalled, removeFailedInstall, receiveExport, linkDeployment, scheduleAdopt, queueCentralCheck, runNow, - fastPanelText, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail, + fastPanelText, fastPanelSteps, notesBlocks, jobReportText, scheduleWarnings, requireTotp, agentOnline, siteAdminEmail, }; diff --git a/backend/src/utils/mail.js b/backend/src/utils/mail.js index 25fedc2..98d3df9 100644 --- a/backend/src/utils/mail.js +++ b/backend/src/utils/mail.js @@ -1,5 +1,6 @@ const nodemailer = require('nodemailer'); const { smtpSettings } = require('./settings'); +const { render, logoAttachment } = require('./emailLayout'); // SMTP is set on the Settings page; the transporter is rebuilt when those settings change. let transporter = null; @@ -25,10 +26,18 @@ async function smtpConfigured() { return !!(await smtpSettings()).host; } +/** The logo goes with any HTML that shows it (cid:logo), unless it's attached already. */ +function withLogo(html, attachments) { + const list = attachments || []; + if (!html || !html.includes('cid:logo') || list.some(a => a.cid === 'logo')) return attachments; + const logo = logoAttachment(); + return logo ? [logo, ...list] : attachments; +} + /** - * Send an email; without SMTP it's logged instead (development). Billing emails (1.7.0) add - * `html`, `attachments` (nodemailer's: { filename, content, contentType, cid? }), `replyTo` and - * `fromName` (shown as the sender's name). + * Send an email; without SMTP it's logged instead (development). `html` (2.10.0: every email, + * from emailLayout.render; billing's own since 1.7.0), `attachments` (nodemailer's: { filename, + * content, contentType, cid? }), `replyTo` and `fromName` (shown as the sender's name). */ async function sendMail({ to, subject, text, html, attachments, replyTo, fromName }) { if (!to) return; @@ -45,7 +54,7 @@ async function sendMail({ to, subject, text, html, attachments, replyTo, fromNam } const address = fromAddress(smtp); const from = fromName ? { name: fromName, address: address.replace(/^.*<([^>]+)>.*$/, '$1') } : address; - await transporter.sendMail({ from, to, subject, text, html, attachments, replyTo }); + await transporter.sendMail({ from, to, subject, text, html, attachments: withLogo(html, attachments), replyTo }); } /** @@ -58,12 +67,16 @@ async function testSmtp(overrides, to) { const t = createTransport(smtp); try { await t.verify(); - await t.sendMail({ - from: fromAddress(smtp), - to, - subject: 'Cross Code Hub: test email', - text: `This is a test email from the Cross Code Hub.\n\nServer: ${smtp.host}:${smtp.port}\nUser: ${smtp.user || '(none)'}\n\nIf you got this, alert emails will arrive too.`, + const email = render({ + heading: 'Test email', + sub: 'Email from the Hub works.', + blocks: [ + { note: { kind: 'success', title: 'It arrived', text: 'If you got this, alerts and job reports will arrive too.' } }, + { rows: [['Server', `${smtp.host}:${smtp.port}`], ['User', smtp.user || '(none)']] }, + ], + footer: 'Sent from Settings in the Cross Code Hub.', }); + await t.sendMail({ from: fromAddress(smtp), to, subject: 'Cross Code Hub: test email', ...email, attachments: withLogo(email.html, []) }); } finally { t.close(); } diff --git a/backend/src/utils/notices.js b/backend/src/utils/notices.js index 20f511f..73c2074 100644 --- a/backend/src/utils/notices.js +++ b/backend/src/utils/notices.js @@ -6,6 +6,7 @@ const prisma = require('../config/db'); const { sendMail } = require('./mail'); +const { render } = require('./emailLayout'); function forInstall(notice, installId) { return notice.allInstalls || (notice.installIds || []).includes(installId); @@ -69,10 +70,23 @@ async function emailNotice(notice) { where: { releasedAt: null, ...(notice.allInstalls ? {} : { id: { in: notice.installIds } }) }, include: { customer: { select: { email: true } } }, }); + // 2.10.0: laid out as the Hub's other emails; the plain text stays emailText's. + const kind = notice.level === 'warning' ? 'warning' : notice.level === 'maintenance' ? 'info' : null; + const { html } = render({ + heading: notice.title, + label: 'Cross Events', + preheader: notice.message.trim().slice(0, 140), + blocks: [ + ...notice.message.trim().split(/\n{2,}/).map((p, i) => (kind && i === 0 ? { note: { kind, text: p } } : { p })), + { rows: [['From', notice.startsAt ? when(notice.startsAt) : null], ['Until', notice.endsAt ? when(notice.endsAt) : null]] }, + { p: 'Kind regards,\nThe Cross Code team' }, + ], + footer: 'You\'re getting this because your church uses Cross Events.', + }); let sent = 0; for (const to of recipients(installs)) { try { - await sendMail({ to, subject: `Cross Events: ${notice.title}`, text: emailText(notice) }); + await sendMail({ to, subject: `Cross Events: ${notice.title}`, text: emailText(notice), html }); sent++; } catch (e) { console.warn(`[notices] email to ${to} failed:`, e?.message); diff --git a/backend/src/utils/servers.js b/backend/src/utils/servers.js index 58a2ccc..dbe1ffb 100644 --- a/backend/src/utils/servers.js +++ b/backend/src/utils/servers.js @@ -13,6 +13,7 @@ const prisma = require('../config/db'); const { encrypt, decrypt } = require('./crypto'); const { getSettings } = require('./settings'); const { sendMail } = require('./mail'); +const { render } = require('./emailLayout'); const JOIN_TOKEN_MINUTES = 60; const POLL_SECONDS = 30; @@ -230,22 +231,27 @@ async function runServerAlerts(now = new Date()) { for (const p of current) { if (open.has(p.type)) continue; await prisma.serverAlert.create({ data: { serverId: server.id, type: p.type, level: p.level, message: p.message, createdAt: now } }); - opened.push(`• ${server.name}: ${p.message}`); + opened.push({ level: p.level, text: `${server.name}: ${p.message}` }); } const types = new Set(current.map(p => p.type)); for (const [type, a] of open) { if (types.has(type)) continue; await prisma.serverAlert.update({ where: { id: a.id }, data: { resolvedAt: now } }); - cleared.push(`• ${server.name}: cleared: ${a.message}`); + cleared.push(`${server.name}: ${a.message}`); } } - const lines = [...opened, ...cleared]; - if (lines.length && settings.alert_email) { - await sendMail({ - to: settings.alert_email, - subject: `Cross Code Hub: ${opened.length ? `${opened.length} server alert${opened.length === 1 ? '' : 's'}` : 'server alerts cleared'}`, - text: `${lines.join('\n')}\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/servers`, - }).catch(e => console.warn('[servers] alert email failed:', e?.message)); + if ((opened.length || cleared.length) && settings.alert_email) { + const subject = opened.length ? `${opened.length} server alert${opened.length === 1 ? '' : 's'}` : 'server alerts cleared'; + const email = render({ + heading: opened.length ? `${opened.length} server alert${opened.length === 1 ? '' : 's'}` : 'Server alerts cleared', + blocks: [ + ...opened.map(o => ({ note: { kind: o.level === 'critical' ? 'danger' : 'warning', text: o.text } })), + cleared.length ? { note: { kind: 'success', title: 'Cleared', text: cleared.join('\n') } } : null, + { button: { label: 'Open Servers', url: `${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/servers` } }, + ], + footer: 'Sent by the Cross Code Hub to the alert address in Settings.', + }); + await sendMail({ to: settings.alert_email, subject: `Cross Code Hub: ${subject}`, ...email }).catch(e => console.warn('[servers] alert email failed:', e?.message)); } return { opened: opened.length, cleared: cleared.length }; } diff --git a/backend/tests/emailLayout.test.js b/backend/tests/emailLayout.test.js new file mode 100644 index 0000000..67d9ec0 --- /dev/null +++ b/backend/tests/emailLayout.test.js @@ -0,0 +1,67 @@ +// The Hub's email layout (2.10.0): HTML and plain text from the same blocks, everything escaped. +const { render, logoAttachment } = require('../src/utils/emailLayout'); +const { notesBlocks } = require('../src/utils/jobs'); + +describe('render', () => { + test('makes the HTML and its plain-text twin from the same blocks', () => { + const { html, text } = render({ + heading: 'Installed', + sub: 'Now set it up', + blocks: [ + { hello: 'Jane' }, + { p: 'See https://hub.test/jobs/1 for more.' }, + { note: { kind: 'warning', title: 'Careful', text: 'Two lines\nhere' } }, + { rows: [['Site', 'events.hope.co.za'], ['Empty', null]] }, + { steps: [{ outcome: 'ok', name: 'Backup' }, { outcome: 'failed', name: 'Migrate', detail: 'P3009' }] }, + { numbered: [{ text: 'Add the site.' }, { text: 'Add this:', code: 'location ^~ /api/ {\n}' }] }, + { code: 'line 1\nline 2', label: 'Last log lines' }, + { button: { label: 'Open the job', url: 'https://hub.test/jobs/1' } }, + null, + ], + }); + expect(text).toBe([ + 'Installed', 'Now set it up', 'Hi Jane,', 'See https://hub.test/jobs/1 for more.', 'Careful\nTwo lines\nhere', + 'Site: events.hope.co.za', ' ✓ Backup\n ✗ Migrate (P3009)', + '1. Add the site.\n\n2. Add this:\n\n location ^~ /api/ {\n }', + 'Last log lines:\nline 1\nline 2', 'Open the job: https://hub.test/jobs/1', + ].join('\n\n')); + expect(html).toContain('https://hub.test/jobs/1 for more.'); + expect(html).toContain('Two lines
here'); + expect(html).not.toContain('Empty'); + expect(html).toContain('location ^~ /api/ {'); + expect(html).toContain('>Open the job'); + }); + + test('escapes everything and only links http(s)', () => { + const { html } = render({ + heading: '', + blocks: [{ p: 'Tom & "Jerry" ' }, { button: { label: 'Go', url: 'javascript:alert(1)' } }, { code: '' }], + }); + expect(html).not.toContain('