Releases with what's new, notices to churches, withdrawn update requests
- Releases page: each Cross Events version with notes and an urgent flag; the newest is the latest version (moved off Settings; the old setting becomes the first release). Installs get the notes for every newer version. - Notices page: a banner for site admins and supervisors (with a time window), an email to the customer and admin contact, or both; for every install or chosen ones. - POST /api/installs/update-request/cancel resolves the request and emails Joshua. - Protocol doc: releases and notices in the heartbeat/register replies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+129
-2
@@ -10,6 +10,8 @@ const { getSettings, setSettings } = require('../utils/settings');
|
||||
const { problems, compareVersions } = require('../utils/alerts');
|
||||
const licenceToken = require('../utils/licenceToken');
|
||||
const { smtpConfigured, testSmtp } = require('../utils/mail');
|
||||
const { VERSION_RE, sortReleases, syncLatestVersion } = require('../utils/releases');
|
||||
const { emailNotice } = require('../utils/notices');
|
||||
|
||||
const router = express.Router();
|
||||
router.use(protect);
|
||||
@@ -224,6 +226,130 @@ router.get('/audit', wrap(async (req, res) => {
|
||||
res.json(await prisma.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 300, include: { actor: { select: { name: true } } } }));
|
||||
}));
|
||||
|
||||
// ─── Releases ─────────────────────────────────────────────────────────────────
|
||||
// What's new in each Cross Events version. Installs on an older version see the notes; the highest
|
||||
// version is the latest (latest_version), so adding one tells installs an update is out.
|
||||
|
||||
router.get('/releases', wrap(async (req, res) => {
|
||||
const [releases, installs] = await Promise.all([
|
||||
prisma.release.findMany(),
|
||||
prisma.install.findMany({ where: { releasedAt: null }, select: { version: true } }),
|
||||
]);
|
||||
const onVersion = {};
|
||||
for (const i of installs) if (i.version) onVersion[i.version] = (onVersion[i.version] || 0) + 1;
|
||||
res.json(sortReleases(releases).map(r => ({ ...r, installs: onVersion[r.version] || 0 })));
|
||||
}));
|
||||
|
||||
function releaseData(body, { partial = false } = {}) {
|
||||
const data = {};
|
||||
if (body?.version !== undefined) {
|
||||
const v = String(body.version || '').trim().replace(/^v/i, '');
|
||||
if (!VERSION_RE.test(v)) throw bad('The version looks like 1.47.0.');
|
||||
data.version = v;
|
||||
} else if (!partial) throw bad('The version looks like 1.47.0.');
|
||||
if (body?.notes !== undefined) data.notes = String(body.notes || '').trim().slice(0, 20000);
|
||||
if (body?.urgent !== undefined) data.urgent = !!body.urgent;
|
||||
if (body?.releasedAt !== undefined) data.releasedAt = dateOrNull(body.releasedAt) || new Date();
|
||||
return data;
|
||||
}
|
||||
|
||||
const releaseError = e => {
|
||||
if (e.code === 'P2002') throw bad('There is already a release with that version.', 409);
|
||||
if (e.code === 'P2025') throw bad('Release not found', 404);
|
||||
throw e;
|
||||
};
|
||||
|
||||
router.post('/releases', wrap(async (req, res) => {
|
||||
const release = await prisma.release.create({ data: releaseData(req.body) }).catch(releaseError);
|
||||
const latest = await syncLatestVersion();
|
||||
await audit(req, 'release_added', release.id, { version: release.version, urgent: release.urgent });
|
||||
res.status(201).json({ release, latestVersion: latest || null });
|
||||
}));
|
||||
|
||||
router.put('/releases/:id', wrap(async (req, res) => {
|
||||
const data = releaseData(req.body, { partial: true });
|
||||
const release = await prisma.release.update({ where: { id: req.params.id }, data }).catch(releaseError);
|
||||
const latest = await syncLatestVersion();
|
||||
await audit(req, 'release_updated', release.id, { version: release.version, changed: Object.keys(data) });
|
||||
res.json({ release, latestVersion: latest || null });
|
||||
}));
|
||||
|
||||
router.delete('/releases/:id', wrap(async (req, res) => {
|
||||
const release = await prisma.release.delete({ where: { id: req.params.id } }).catch(releaseError);
|
||||
const latest = await syncLatestVersion();
|
||||
await audit(req, 'release_deleted', release.id, { version: release.version });
|
||||
res.json({ latestVersion: latest || null });
|
||||
}));
|
||||
|
||||
// ─── Notices ──────────────────────────────────────────────────────────────────
|
||||
// Messages to churches: a banner on their site (site admins and supervisors) and/or one email.
|
||||
|
||||
router.get('/notices', wrap(async (req, res) => {
|
||||
res.json(await prisma.notice.findMany({ orderBy: { createdAt: 'desc' }, take: 200 }));
|
||||
}));
|
||||
|
||||
const NOTICE_LEVELS = ['info', 'maintenance', 'warning'];
|
||||
|
||||
async function noticeData(body, { partial = false } = {}) {
|
||||
const data = {};
|
||||
if (body?.title !== undefined) data.title = text(body.title, 120);
|
||||
if (body?.message !== undefined) data.message = text(body.message, 2000);
|
||||
if ((!partial || 'title' in data) && !data.title) throw bad('Give the notice a title.');
|
||||
if ((!partial || 'message' in data) && !data.message) throw bad('Write the message.');
|
||||
if (body?.level !== undefined) {
|
||||
if (!NOTICE_LEVELS.includes(body.level)) throw bad('Level must be info, maintenance or warning.');
|
||||
data.level = body.level;
|
||||
}
|
||||
if (body?.allInstalls !== undefined) data.allInstalls = !!body.allInstalls;
|
||||
if (body?.installIds !== undefined) {
|
||||
const ids = [...new Set((Array.isArray(body.installIds) ? body.installIds : []).map(String))];
|
||||
const found = ids.length ? await prisma.install.count({ where: { id: { in: ids } } }) : 0;
|
||||
if (found !== ids.length) throw bad('One of the chosen installs no longer exists.');
|
||||
data.installIds = ids;
|
||||
}
|
||||
if (body?.showBanner !== undefined) data.showBanner = !!body.showBanner;
|
||||
if (body?.startsAt !== undefined) data.startsAt = dateOrNull(body.startsAt);
|
||||
if (body?.endsAt !== undefined) data.endsAt = dateOrNull(body.endsAt);
|
||||
return data;
|
||||
}
|
||||
|
||||
function checkNotice(notice) {
|
||||
if (notice.allInstalls === false && !(notice.installIds || []).length) throw bad('Choose at least one install, or send it to every install.');
|
||||
if (notice.startsAt && notice.endsAt && new Date(notice.endsAt) <= new Date(notice.startsAt)) throw bad('The end has to be after the start.');
|
||||
}
|
||||
|
||||
// Create, and email it straight away when asked. Email only (no banner) is fine too.
|
||||
router.post('/notices', wrap(async (req, res) => {
|
||||
const data = await noticeData(req.body);
|
||||
const sendEmail = !!req.body?.sendEmail;
|
||||
if (data.showBanner === false && !sendEmail) throw bad('Show it as a banner, email it, or both.');
|
||||
checkNotice(data);
|
||||
let notice = await prisma.notice.create({ data });
|
||||
if (sendEmail) {
|
||||
const sent = await emailNotice(notice);
|
||||
notice = await prisma.notice.update({ where: { id: notice.id }, data: { emailedAt: new Date(), emailedTo: sent } });
|
||||
}
|
||||
await audit(req, 'notice_created', notice.id, { title: notice.title, allInstalls: notice.allInstalls, installs: notice.installIds.length, banner: notice.showBanner, emailedTo: sendEmail ? notice.emailedTo : null });
|
||||
res.status(201).json(notice);
|
||||
}));
|
||||
|
||||
// Edit the banner (the email isn't sent again). "End now" is { endsAt: now }.
|
||||
router.put('/notices/:id', wrap(async (req, res) => {
|
||||
const existing = await prisma.notice.findUnique({ where: { id: req.params.id } });
|
||||
if (!existing) throw bad('Notice not found', 404);
|
||||
const data = await noticeData(req.body, { partial: true });
|
||||
checkNotice({ ...existing, ...data });
|
||||
const notice = await prisma.notice.update({ where: { id: existing.id }, data });
|
||||
await audit(req, 'notice_updated', notice.id, { title: notice.title, changed: Object.keys(data) });
|
||||
res.json(notice);
|
||||
}));
|
||||
|
||||
router.delete('/notices/:id', wrap(async (req, res) => {
|
||||
const notice = await prisma.notice.delete({ where: { id: req.params.id } }).catch(() => { throw bad('Notice not found', 404); });
|
||||
await audit(req, 'notice_deleted', notice.id, { title: notice.title });
|
||||
res.json({ message: 'Deleted.' });
|
||||
}));
|
||||
|
||||
// ─── Settings ─────────────────────────────────────────────────────────────────
|
||||
|
||||
router.get('/settings', wrap(async (req, res) => {
|
||||
@@ -246,8 +372,9 @@ function auditValues(values) {
|
||||
}
|
||||
|
||||
router.put('/settings', wrap(async (req, res) => {
|
||||
const values = req.body?.settings || {};
|
||||
if (values.latest_version && !/^\d+\.\d+\.\d+$/.test(String(values.latest_version))) throw bad('Latest version looks like 1.41.0.');
|
||||
// The latest version follows the Releases page.
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
const { latest_version, ...values } = req.body?.settings || {};
|
||||
checkSmtp(values);
|
||||
const settings = await setSettings(values);
|
||||
await audit(req, 'settings_updated', null, auditValues(values));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request.
|
||||
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request
|
||||
* (and withdrawing it).
|
||||
* Install → Hub only; these are the only endpoints that aren't behind an admin login.
|
||||
*/
|
||||
|
||||
@@ -12,6 +13,8 @@ const { checkSignature } = require('../utils/signing');
|
||||
const { getSettings } = require('../utils/settings');
|
||||
const { compareVersions } = require('../utils/alerts');
|
||||
const { sendMail } = require('../utils/mail');
|
||||
const { releasesForInstall } = require('../utils/releases');
|
||||
const { noticesForInstall } = require('../utils/notices');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
@@ -114,6 +117,8 @@ router.post('/installs/register', registerLimiter, async (req, res) => {
|
||||
licence: await tokenFor(install),
|
||||
heartbeatIntervalMinutes: HEARTBEAT_MINUTES,
|
||||
latestVersion: settings.latest_version || null,
|
||||
releases: await releasesForInstall(install.version),
|
||||
notices: await noticesForInstall(install.id),
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[register]', e);
|
||||
@@ -144,7 +149,13 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
|
||||
}
|
||||
|
||||
const settings = await getSettings();
|
||||
res.json({ licence: await tokenFor(install), latestVersion: settings.latest_version || null, serverTime: now.toISOString() });
|
||||
res.json({
|
||||
licence: await tokenFor(install),
|
||||
latestVersion: settings.latest_version || null,
|
||||
releases: await releasesForInstall(version || install.version),
|
||||
notices: await noticesForInstall(install.id, now),
|
||||
serverTime: now.toISOString(),
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[heartbeat]', e);
|
||||
fail(res, 500, 'SERVER_ERROR', 'The Hub could not record this heartbeat.');
|
||||
@@ -184,5 +195,34 @@ router.post('/installs/update-request', updateRequestLimiter, async (req, res) =
|
||||
}
|
||||
});
|
||||
|
||||
// A site admin withdrew their update request: resolve the open request, and tell Joshua if he was
|
||||
// emailed about it, so he doesn't update the site after all.
|
||||
router.post('/installs/update-request/cancel', updateRequestLimiter, async (req, res) => {
|
||||
try {
|
||||
const install = await signedInstall(req, res);
|
||||
if (!install) return;
|
||||
|
||||
const now = new Date();
|
||||
const open = await prisma.installEvent.findMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null } });
|
||||
if (!open.length) return res.json({ cancelled: false });
|
||||
await prisma.installEvent.updateMany({ where: { id: { in: open.map(e => e.id) } }, data: { resolvedAt: now } });
|
||||
await prisma.installEvent.create({ data: { installId: install.id, type: 'update_request_withdrawn', level: 'info', message: 'Update request withdrawn by the site', resolvedAt: now } });
|
||||
|
||||
const settings = await getSettings();
|
||||
if (settings.alert_email) {
|
||||
const customer = await prisma.customer.findUnique({ where: { id: install.customerId }, select: { name: true } });
|
||||
await sendMail({
|
||||
to: settings.alert_email,
|
||||
subject: `Cross Events 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}`,
|
||||
}).catch(e => console.warn('[update-request] email failed:', e?.message));
|
||||
}
|
||||
res.json({ cancelled: true });
|
||||
} catch (e) {
|
||||
console.error('[update-request/cancel]', e);
|
||||
fail(res, 500, 'SERVER_ERROR', 'The Hub could not withdraw the update request. Try again later.');
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
module.exports.PROTOCOL_VERSIONS = PROTOCOL_VERSIONS;
|
||||
|
||||
Reference in New Issue
Block a user