Merge branch 'feat/nicer-emails'

This commit is contained in:
2026-11-20 14:44:11 +02:00
16 changed files with 685 additions and 87 deletions
+26
View File
@@ -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
+2 -2
View File
@@ -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",
+1 -1
View File
@@ -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",
+26 -3
View File
@@ -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 });
+15 -6
View File
@@ -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 };
}
+12 -1
View File
@@ -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);
}
+188
View File
@@ -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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[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 : `<a href="${u}" style="color:${BUTTON};word-break:break-all">${u}</a>`))
.replace(/\n/g, '<br>');
}
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 ? `<p style="margin:0 0 6px 0;font-size:12px;font-weight:600;letter-spacing:0.4px;text-transform:uppercase;color:#64748b">${esc(label)}</p>` : ''}`
+ `<pre style="margin:0 0 20px 0;padding:14px 16px;background:#0f172a;color:#e2e8f0;border-radius:8px;font-family:${MONO};font-size:12.5px;line-height:1.55;white-space:pre-wrap;word-break:break-word">${esc(text)}</pre>`;
}
function blockHtml(b) {
if (b.hello !== undefined) return `<p style="margin:0 0 14px 0;color:#374151">Hi <strong>${esc(b.hello || 'there')}</strong>,</p>`;
if (b.h !== undefined) return `<p style="margin:8px 0 12px 0;font-size:16px;font-weight:700;color:#0f172a">${esc(b.h)}</p>`;
if (b.p !== undefined) return `<p style="margin:0 0 18px 0;color:#374151">${linkify(b.p)}</p>`;
if (b.button) {
const href = esc(safeUrl(b.button.url));
return `<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:26px auto 6px auto"><tr><td align="center" style="border-radius:8px;background:${BUTTON}">`
+ `<a href="${href}" target="_blank" style="display:inline-block;padding:13px 32px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;border-radius:8px;font-family:${FONT}">${esc(b.button.label)}</a></td></tr></table>`
+ `<p style="text-align:center;margin:4px 0 22px 0;font-size:12px;color:#94a3b8;word-break:break-all">Or open: <a href="${href}" style="color:${BUTTON}">${esc(b.button.url)}</a></p>`;
}
if (b.note) {
const [bg, bar, ink] = NOTE[b.note.kind] || NOTE.info;
return `<div style="background:${bg};border-left:4px solid ${bar};border-radius:0 6px 6px 0;padding:14px 18px;margin:0 0 22px 0;color:${ink};font-size:14px;line-height:1.6">`
+ `${b.note.title ? `<strong>${esc(b.note.title)}</strong>${b.note.text ? '<br>' : ''}` : ''}${b.note.text ? linkify(b.note.text) : ''}</div>`;
}
if (b.rows) {
const rows = b.rows.filter(r => r && r[1] !== undefined && r[1] !== null && r[1] !== '');
if (!rows.length) return '';
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 22px 0;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px">`
+ rows.map(([k, v], i) => `<tr><td style="padding:10px 16px;${i ? 'border-top:1px solid #e2e8f0;' : ''}font-size:13px;color:#64748b;white-space:nowrap;vertical-align:top">${esc(k)}</td>`
+ `<td style="padding:10px 16px;${i ? 'border-top:1px solid #e2e8f0;' : ''}font-size:14px;color:#0f172a;font-weight:600;word-break:break-word">${linkify(v)}</td></tr>`).join('')
+ '</table>';
}
if (b.bullets) {
if (!b.bullets.length) return '';
return `<ul style="margin:0 0 20px 0;padding:0 0 0 20px;color:#374151">${b.bullets.map(t => `<li style="margin:0 0 8px 0">${linkify(t)}</li>`).join('')}</ul>`;
}
if (b.steps) {
if (!b.steps.length) return '';
return `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 22px 0;border:1px solid #e2e8f0;border-radius:8px">`
+ b.steps.map((s, i) => {
const [mark, colour] = STEP[s.outcome] || ['•', '#94a3b8'];
return `<tr><td style="width:28px;padding:9px 0 9px 14px;${i ? 'border-top:1px solid #f1f5f9;' : ''}color:${colour};font-weight:700;font-size:15px;vertical-align:top">${mark}</td>`
+ `<td style="padding:9px 14px 9px 4px;${i ? 'border-top:1px solid #f1f5f9;' : ''}font-size:14px;color:#1e293b">${esc(s.name)}${s.detail ? `<span style="color:#64748b"> · ${esc(s.detail)}</span>` : ''}</td></tr>`;
}).join('')
+ '</table>';
}
if (b.numbered) {
return b.numbered.map((item, i) => `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 16px 0"><tr>`
+ `<td style="width:34px;vertical-align:top"><div style="width:24px;height:24px;line-height:24px;border-radius:12px;background:${INK};color:#ffffff;text-align:center;font-size:13px;font-weight:700">${i + 1}</div></td>`
+ `<td style="vertical-align:top;color:#374151;font-size:15px;line-height:1.6">${linkify(item.text)}${item.code ? `<div style="margin-top:10px">${codeHtml(item.code)}</div>` : ''}</td></tr></table>`).join('');
}
if (b.code !== undefined) return codeHtml(b.code, b.label);
if (b.small !== undefined) return `<p style="margin:0 0 12px 0;font-size:13px;color:#94a3b8">${linkify(b.small)}</p>`;
if (b.divider) return '<div style="border-top:1px solid #f1f5f9;margin:26px 0"></div>';
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()
? `<td style="padding-right:12px;vertical-align:middle"><img src="cid:logo" width="40" height="40" alt="" style="display:block;border:0"></td>`
: '';
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>${esc(heading)}</title>
</head>
<body style="margin:0;padding:0;background-color:#f1f5f9;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%">
<div style="display:none;font-size:1px;line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;mso-hide:all">${esc(preheader || sub || heading)}&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f1f5f9">
<tr><td align="center" style="padding:36px 16px">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px">
<tr><td style="background:${INK};background:linear-gradient(135deg,${INK} 0%,#1e2a4a 100%);border-radius:12px 12px 0 0;padding:28px 40px">
<table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
${logoCell}
<td style="vertical-align:middle;font-family:${FONT}">
<div style="font-size:15px;letter-spacing:4px;text-transform:uppercase;color:#ffffff"><span style="color:${SKY}">Cross</span> Code</div>
<div style="font-size:12px;color:#cbd5e1;margin-top:3px;letter-spacing:0.3px">${esc(label)}</div>
</td>
</tr></table>
</td></tr>
<tr><td style="height:4px;background:${SKY};line-height:4px;font-size:0">&nbsp;</td></tr>
<tr><td style="background:#ffffff;border-left:1px solid #e2e8f0;border-right:1px solid #e2e8f0;padding:36px 40px 18px 40px">
<div style="font-family:${FONT};color:#1e293b;font-size:15px;line-height:1.7">
<p style="font-size:22px;font-weight:800;color:#0f172a;margin:0 0 ${sub ? 6 : 20}px 0;letter-spacing:-0.3px;line-height:1.3">${esc(heading)}</p>
${sub ? `<p style="color:#64748b;font-size:14px;margin:0 0 24px 0">${esc(sub)}</p>` : ''}
${list.map(blockHtml).join('\n ')}
</div>
</td></tr>
<tr><td style="background:#f8fafc;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 12px 12px;padding:20px 40px;text-align:center">
<p style="color:#94a3b8;font-size:12px;margin:0 0 4px 0;font-family:${FONT}">Cross Code &bull; <a href="https://crosscode.co.za" style="color:#94a3b8;text-decoration:underline">crosscode.co.za</a></p>
<p style="color:#cbd5e1;font-size:11px;margin:6px 0 0 0;font-family:${FONT}">${esc(footer)}</p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>`;
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 };
+260 -48
View File
@@ -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 || '<central server 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 || '<central server 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,
};
+22 -9
View File
@@ -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();
}
+15 -1
View File
@@ -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);
+15 -9
View File
@@ -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 };
}
+67
View File
@@ -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('<a href="https://hub.test/jobs/1" style="color:#1d6a9c;word-break:break-all">https://hub.test/jobs/1</a> for more.');
expect(html).toContain('Two lines<br>here');
expect(html).not.toContain('Empty');
expect(html).toContain('location ^~ /api/ {');
expect(html).toContain('>Open the job</a>');
});
test('escapes everything and only links http(s)', () => {
const { html } = render({
heading: '<script>alert(1)</script>',
blocks: [{ p: 'Tom & "Jerry" <b>' }, { button: { label: 'Go', url: 'javascript:alert(1)' } }, { code: '</pre><img src=x>' }],
});
expect(html).not.toContain('<script>');
expect(html).toContain('&lt;script&gt;alert(1)&lt;/script&gt;');
expect(html).toContain('Tom &amp; &quot;Jerry&quot; &lt;b&gt;');
expect(html).not.toContain('href="javascript:');
expect(html).toContain('href="#"');
expect(html).toContain('&lt;/pre&gt;&lt;img src=x&gt;');
});
test('shows the logo when there is one, through cid:logo', () => {
const { html } = render({ heading: 'Hi', blocks: [] });
if (logoAttachment()) {
expect(html).toContain('src="cid:logo"');
expect(logoAttachment()).toMatchObject({ cid: 'logo', contentType: 'image/png' });
} else {
expect(html).not.toContain('cid:logo');
}
});
});
describe('notesBlocks (What\'s New in the update email)', () => {
test('lists, paragraphs, continuation lines, and no Markdown marks', () => {
expect(notesBlocks('Works with any Accounts.\n\n- **Fix:** logo uploads\n failed with `x`.\n- Faster.\nAfter the list.')).toEqual([
{ p: 'Works with any Accounts.' },
{ bullets: ['Fix: logo uploads failed with x.', 'Faster.'] },
{ p: 'After the list.' },
]);
});
});
+27 -2
View File
@@ -145,8 +145,33 @@ describe('jobs', () => {
expect(await db.deployment.findUnique({ where: { id: deployment.id } })).toMatchObject({ status: 'waiting_for_proxy', version: '2.4.0' });
expect(await db.job.findFirst({ where: { serverId: central.id, type: 'check-ports' } })).toMatchObject({ args: { ports: [20000, 20001] } });
const mail = mockMails.find(m => m.subject.includes('Installed: hope'));
expect(mail.text).toContain('/api → http://127.0.0.1:20001');
expect(mail.text).toContain('everything else → http://127.0.0.1:20000');
// 2.10.0: the backend location is ^~, so FastPanel's static-file rule can't take /api/…/logo.png.
expect(mail.text).toContain('location ^~ /api/ {');
expect(mail.text).toContain('proxy_pass http://127.0.0.1:20001;');
expect(mail.text).toContain('as a proxy to http://127.0.0.1:20000 (the frontend)');
expect(mail.html).toContain('location ^~ /api/ {');
expect(mail.html).toContain('href="https://hub.test/servers/installs/');
expect(await jobs.fastPanelText(await db.deployment.findUnique({ where: { id: deployment.id } }))).toContain(' location ^~ /api/ {');
});
test('Proxy done refuses a site whose /api paths with a file extension reach the frontend', async () => {
const { server } = await joinServer();
await servers.setServerConfig(server.id, { TRUST_PROXY: 'loopback' });
const { deployment } = await jobs.newInstall({ customerId: 'cust-1', serverId: server.id, shortName: 'hope', domain: 'events.hope.co.za', adminName: 'Jane', adminEmail: 'jane@hope.test' }, admin, NOW);
const answer = (status, poweredBy, json) => ({ status, headers: new Headers(poweredBy ? { 'x-powered-by': poweredBy } : {}), json: async () => json });
const site = frontendTakesFiles => async url => {
if (url.endsWith('/api/health')) return answer(200, 'Express', { version: null });
if (url.includes('/api/proxy-check.png')) return answer(404, frontendTakesFiles ? 'Next.js' : 'Express');
return answer(200, 'Next.js');
};
const refused = await jobs.proxyDone(deployment.id, NOW, site(true));
expect(refused.live).toBe(false);
expect(refused.problems.join(' ')).toContain('location ^~ /api/');
const ok = await jobs.proxyDone(deployment.id, NOW, site(false));
expect(ok).toEqual({ live: true, problems: [] });
const ready = mockMails.find(m => m.subject.includes('site is ready'));
expect(ready.html).toContain('href="https://events.hope.co.za/setup"');
expect(ready.text).toContain('Start the setup: https://events.hope.co.za/setup');
});
test('a failed install frees its ports again', async () => {
+6 -2
View File
@@ -215,10 +215,14 @@ in-process and would fire once per copy.
In FASTPANEL, open the site → **Configuration files** (the nginx config of the site). Inside the
`server { ... }` block that listens on 443, replace the default `location /` (the one serving
static files / PHP) with:
static files / PHP) with the two locations below. Keep the `^~` on `/api/`: FASTPANEL's
static-file handling adds a regex location for file extensions (`png|pdf|…`) that wins over a
plain `location /api/`, and would send `/api/…/statement.pdf` to the frontend (2.10.0; the same
happened to Cross Events' uploaded logos). Check with
`curl -sI https://events-hub.crosscode.co.za/api/x.pdf`: it must not say `X-Powered-By: Next.js`.
```nginx
location /api/ {
location ^~ /api/ {
proxy_pass http://127.0.0.1:5200;
proxy_http_version 1.1;
proxy_set_header Host $host;
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "events-hub-frontend",
"version": "2.9.0",
"version": "2.10.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "events-hub-frontend",
"version": "2.9.0",
"version": "2.10.0",
"dependencies": {
"lucide-react": "^0.536.0",
"next": "^15.5.24",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "events-hub-frontend",
"version": "2.9.0",
"version": "2.10.0",
"private": true,
"scripts": {
"dev": "next dev -p 3200",