From 1449e5046e3a6de7ff75d2fb12d7062237ec8a6f Mon Sep 17 00:00:00 2001 From: joshua Date: Wed, 28 Oct 2026 08:54:35 +0200 Subject: [PATCH] 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 --- CHANGELOG.md | 20 ++ .../migration.sql | 45 ++++ backend/prisma/schema.prisma | 43 ++++ backend/src/routes/admin.js | 131 ++++++++++- backend/src/routes/installApi.js | 44 +++- backend/src/utils/alerts.js | 2 +- backend/src/utils/notices.js | 84 +++++++ backend/src/utils/releases.js | 41 ++++ backend/tests/releases-notices.test.js | 72 ++++++ docs/hub-protocol.md | 42 +++- frontend/src/app/(hub)/alerts/page.tsx | 2 +- frontend/src/app/(hub)/layout.tsx | 4 +- frontend/src/app/(hub)/notices/page.tsx | 215 ++++++++++++++++++ frontend/src/app/(hub)/page.tsx | 2 +- frontend/src/app/(hub)/releases/page.tsx | 119 ++++++++++ frontend/src/app/(hub)/settings/page.tsx | 5 +- frontend/src/components/ui.tsx | 23 ++ frontend/src/lib/types.ts | 18 ++ 18 files changed, 900 insertions(+), 12 deletions(-) create mode 100644 backend/prisma/migrations/20261028064313_releases_notices/migration.sql create mode 100644 backend/src/utils/notices.js create mode 100644 backend/src/utils/releases.js create mode 100644 backend/tests/releases-notices.test.js create mode 100644 frontend/src/app/(hub)/notices/page.tsx create mode 100644 frontend/src/app/(hub)/releases/page.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bca458..776af06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added + +- **Releases page** — each Cross Events version with what's new in it, and whether it's **urgent** + (a security or serious bug fix). Installs on an older version get the notes for every version + they'd get, so the church can decide whether to ask for the update; urgent ones can't be put off. + The newest release is the latest version (it used to be set on the Settings page; the version + that was set there becomes the first release, without notes). +- **Notices page** — write a message for every install or chosen ones: a **banner** on their site for + site admins and supervisors (from and until a time, e.g. planned maintenance), an **email** to the + customer and the site's admin contact, or both. Banners can be edited or ended early. +- **Withdrawn update requests** — when a church withdraws its update request, the alert is resolved + and you're emailed, so you don't update the site after all. + +### Changed + +- Settings → "Releases and alerts" is now "Alerts"; the latest version follows the Releases page. + +Needs Cross Events 1.4x with the matching changes to show the notes and notices; older installs keep +working and ignore them. + ## [1.3.0] - 2026-10-28 ### Added diff --git a/backend/prisma/migrations/20261028064313_releases_notices/migration.sql b/backend/prisma/migrations/20261028064313_releases_notices/migration.sql new file mode 100644 index 0000000..60285c2 --- /dev/null +++ b/backend/prisma/migrations/20261028064313_releases_notices/migration.sql @@ -0,0 +1,45 @@ +-- CreateEnum +CREATE TYPE "NoticeLevel" AS ENUM ('info', 'maintenance', 'warning'); + +-- CreateTable +CREATE TABLE "Release" ( + "id" TEXT NOT NULL, + "version" TEXT NOT NULL, + "notes" TEXT NOT NULL DEFAULT '', + "urgent" BOOLEAN NOT NULL DEFAULT false, + "releasedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Release_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Notice" ( + "id" TEXT NOT NULL, + "title" TEXT NOT NULL, + "message" TEXT NOT NULL, + "level" "NoticeLevel" NOT NULL DEFAULT 'info', + "allInstalls" BOOLEAN NOT NULL DEFAULT true, + "installIds" TEXT[] DEFAULT ARRAY[]::TEXT[], + "showBanner" BOOLEAN NOT NULL DEFAULT true, + "startsAt" TIMESTAMP(3), + "endsAt" TIMESTAMP(3), + "emailedAt" TIMESTAMP(3), + "emailedTo" INTEGER NOT NULL DEFAULT 0, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Notice_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Release_version_key" ON "Release"("version"); + +-- CreateIndex +CREATE INDEX "Notice_endsAt_idx" ON "Notice"("endsAt"); + +-- The latest version set on the Settings page becomes the first release (no notes yet). +INSERT INTO "Release" ("id", "version", "notes", "urgent", "releasedAt", "createdAt", "updatedAt") +SELECT gen_random_uuid()::text, "value", '', false, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP +FROM "Setting" WHERE "key" = 'latest_version' AND "value" <> ''; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 539560c..9f9cb20 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -147,3 +147,46 @@ model Setting { key String @id value String } + +// A Cross Events version and what's new in it, shown to installs on an older version so the church +// can decide whether to ask for the update. The highest version is the latest (kept in the +// latest_version setting). Urgent releases (security or serious bug fixes) can't be put off. +model Release { + id String @id @default(uuid()) + version String @unique + // Plain text; lines starting with "- " show as a list. + notes String @default("") + urgent Boolean @default(false) + releasedAt DateTime @default(now()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt +} + +enum NoticeLevel { + info + maintenance + warning +} + +// A message from Joshua to churches: a banner on their site for site admins and supervisors +// (between startsAt and endsAt), an email to the customer and the install's admin contact, or both. +model Notice { + id String @id @default(uuid()) + title String + message String + level NoticeLevel @default(info) + // Every install, or only the ones listed. + allInstalls Boolean @default(true) + installIds String[] @default([]) + showBanner Boolean @default(true) + // Null = straight away / until ended. + startsAt DateTime? + endsAt DateTime? + // Set when the email went out (sent once, when the notice is created). + emailedAt DateTime? + emailedTo Int @default(0) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + @@index([endsAt]) +} diff --git a/backend/src/routes/admin.js b/backend/src/routes/admin.js index fb861c5..24ecc20 100644 --- a/backend/src/routes/admin.js +++ b/backend/src/routes/admin.js @@ -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)); diff --git a/backend/src/routes/installApi.js b/backend/src/routes/installApi.js index 08d5fa2..f041cce 100644 --- a/backend/src/routes/installApi.js +++ b/backend/src/routes/installApi.js @@ -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; diff --git a/backend/src/utils/alerts.js b/backend/src/utils/alerts.js index 2a6b6da..879c548 100644 --- a/backend/src/utils/alerts.js +++ b/backend/src/utils/alerts.js @@ -89,7 +89,7 @@ async function runAlerts(now = new Date()) { for (const install of installs) { const current = problems(install, settings, now); // Update requests are opened by the install and resolved by its heartbeat, not by these checks. - const openByType = new Map(install.events.filter(e => !['registered', 'version', 'update_requested'].includes(e.type)).map(e => [e.type, e])); + const openByType = new Map(install.events.filter(e => !['registered', 'version', 'update_requested', 'update_request_withdrawn'].includes(e.type)).map(e => [e.type, e])); for (const p of current) { 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 } }); diff --git a/backend/src/utils/notices.js b/backend/src/utils/notices.js new file mode 100644 index 0000000..20f511f --- /dev/null +++ b/backend/src/utils/notices.js @@ -0,0 +1,84 @@ +/** + * Notices from Joshua to churches (Notices page): a banner on the site for site admins and + * supervisors, sent with every heartbeat until it ends, and/or one email to the customer and the + * install's admin contact. + */ + +const prisma = require('../config/db'); +const { sendMail } = require('./mail'); + +function forInstall(notice, installId) { + return notice.allInstalls || (notice.installIds || []).includes(installId); +} + +/** + * The banners an install is sent (§3): for it, banner on, and not ended. Ones that start later are + * included so the site shows them on time without waiting for a heartbeat; the site checks the dates. + */ +function noticesFor(notices, installId, now = new Date()) { + return notices + .filter(n => n.showBanner && forInstall(n, installId) && (!n.endsAt || new Date(n.endsAt) > now)) + .map(n => ({ + id: n.id, + level: n.level, + title: n.title, + message: n.message, + startsAt: n.startsAt ? new Date(n.startsAt).toISOString() : null, + endsAt: n.endsAt ? new Date(n.endsAt).toISOString() : null, + updatedAt: new Date(n.updatedAt).toISOString(), + })); +} + +async function noticesForInstall(installId, now = new Date()) { + const notices = await prisma.notice.findMany({ + where: { showBanner: true, OR: [{ endsAt: null }, { endsAt: { gt: now } }] }, + orderBy: { createdAt: 'desc' }, + }); + return noticesFor(notices, installId, now); +} + +/** Who a notice is emailed to: each install's customer email and admin contact, once each. */ +function recipients(installs) { + const seen = new Map(); + for (const install of installs) { + for (const email of [install.customer?.email, install.adminContact?.email]) { + const e = String(email || '').trim(); + if (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e) && !seen.has(e.toLowerCase())) seen.set(e.toLowerCase(), e); + } + } + return [...seen.values()]; +} + +const when = d => new Date(d).toLocaleString('en-ZA', { timeZone: 'Africa/Johannesburg', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' }); + +function emailText(notice) { + const lines = [notice.message.trim()]; + if (notice.startsAt || notice.endsAt) { + lines.push('', [notice.startsAt && `From: ${when(notice.startsAt)}`, notice.endsAt && `Until: ${when(notice.endsAt)}`].filter(Boolean).join('\n')); + } + lines.push('', '— Cross Events'); + return lines.join('\n'); +} + +/** + * Email a notice to the installs it's for (one email per address, so churches don't see each + * other). Returns how many were sent. + */ +async function emailNotice(notice) { + const installs = await prisma.install.findMany({ + where: { releasedAt: null, ...(notice.allInstalls ? {} : { id: { in: notice.installIds } }) }, + include: { customer: { select: { email: true } } }, + }); + let sent = 0; + for (const to of recipients(installs)) { + try { + await sendMail({ to, subject: `Cross Events: ${notice.title}`, text: emailText(notice) }); + sent++; + } catch (e) { + console.warn(`[notices] email to ${to} failed:`, e?.message); + } + } + return sent; +} + +module.exports = { noticesFor, noticesForInstall, recipients, emailText, emailNotice }; diff --git a/backend/src/utils/releases.js b/backend/src/utils/releases.js new file mode 100644 index 0000000..e7b79b8 --- /dev/null +++ b/backend/src/utils/releases.js @@ -0,0 +1,41 @@ +/** + * Cross Events releases and their notes (Releases page). The highest version is the latest one, + * kept in the latest_version setting so alerts and the install API read it as before. + */ + +const prisma = require('../config/db'); +const { compareVersions } = require('./alerts'); +const { setSettings } = require('./settings'); + +const VERSION_RE = /^\d+\.\d+\.\d+$/; +const MAX_SENT = 20; + +/** Newest first. */ +function sortReleases(releases) { + return [...releases].sort((a, b) => compareVersions(b.version, a.version)); +} + +/** + * What an install on `version` is told (§3): every release newer than it, newest first — at most + * 20, so a long-neglected install still gets a reply of sensible size. + */ +function releasesFor(releases, version) { + return sortReleases(releases) + .filter(r => !version || compareVersions(r.version, version) > 0) + .slice(0, MAX_SENT) + .map(r => ({ version: r.version, releasedAt: new Date(r.releasedAt).toISOString(), urgent: !!r.urgent, notes: r.notes || '' })); +} + +/** Point latest_version at the highest release (blank when there are none). */ +async function syncLatestVersion() { + const releases = await prisma.release.findMany({ select: { version: true } }); + const latest = sortReleases(releases)[0]?.version || ''; + await setSettings({ latest_version: latest }); + return latest; +} + +async function releasesForInstall(version) { + return releasesFor(await prisma.release.findMany(), version); +} + +module.exports = { VERSION_RE, sortReleases, releasesFor, releasesForInstall, syncLatestVersion }; diff --git a/backend/tests/releases-notices.test.js b/backend/tests/releases-notices.test.js new file mode 100644 index 0000000..ddf1b48 --- /dev/null +++ b/backend/tests/releases-notices.test.js @@ -0,0 +1,72 @@ +// What installs are told about releases and notices (docs/hub-protocol.md §3). +jest.mock('../src/config/db', () => ({})); + +const { releasesFor } = require('../src/utils/releases'); +const { noticesFor, recipients, emailText } = require('../src/utils/notices'); + +const NOW = new Date('2026-10-28T10:00:00Z'); +const at = '2026-10-20T08:00:00.000Z'; + +describe('releases for an install', () => { + const releases = [ + { version: '1.9.0', notes: 'Old', urgent: false, releasedAt: at }, + { version: '1.10.1', notes: '- Security fix', urgent: true, releasedAt: at }, + { version: '1.10.0', notes: '- Rosters', urgent: false, releasedAt: at }, + ]; + + test('only newer versions, newest first, compared as numbers (1.10 > 1.9)', () => { + expect(releasesFor(releases, '1.9.0').map(r => r.version)).toEqual(['1.10.1', '1.10.0']); + expect(releasesFor(releases, '1.10.1')).toEqual([]); + }); + + test('sends the notes and the urgent flag, nothing else', () => { + expect(releasesFor(releases, '1.10.0')).toEqual([{ version: '1.10.1', releasedAt: at, urgent: true, notes: '- Security fix' }]); + }); + + test('at most 20', () => { + const many = Array.from({ length: 30 }, (_, i) => ({ version: `1.${i + 1}.0`, notes: '', urgent: false, releasedAt: at })); + const sent = releasesFor(many, '1.0.0'); + expect(sent).toHaveLength(20); + expect(sent[0].version).toBe('1.30.0'); + }); +}); + +describe('notices for an install', () => { + const base = { level: 'info', title: 'T', message: 'M', showBanner: true, allInstalls: true, installIds: [], startsAt: null, endsAt: null, updatedAt: at }; + + test('every install, or only the chosen ones', () => { + const notices = [{ ...base, id: 'all' }, { ...base, id: 'some', allInstalls: false, installIds: ['inst_2'] }]; + expect(noticesFor(notices, 'inst_1', NOW).map(n => n.id)).toEqual(['all']); + expect(noticesFor(notices, 'inst_2', NOW).map(n => n.id)).toEqual(['all', 'some']); + }); + + test('ended and email-only notices are not sent; ones starting later are', () => { + const notices = [ + { ...base, id: 'ended', endsAt: '2026-10-28T09:00:00Z' }, + { ...base, id: 'email-only', showBanner: false }, + { ...base, id: 'later', startsAt: '2026-11-01T18:00:00Z', endsAt: '2026-11-01T20:00:00Z' }, + ]; + expect(noticesFor(notices, 'inst_1', NOW)).toEqual([ + { id: 'later', level: 'info', title: 'T', message: 'M', startsAt: '2026-11-01T18:00:00.000Z', endsAt: '2026-11-01T20:00:00.000Z', updatedAt: at }, + ]); + }); +}); + +describe('notice emails', () => { + test('to each customer email and admin contact once, skipping blanks and nonsense', () => { + const installs = [ + { customer: { email: 'office@hope.org' }, adminContact: { email: 'Jane@hope.org' } }, + { customer: { email: 'OFFICE@hope.org' }, adminContact: { email: 'jane@hope.org' } }, + { customer: { email: null }, adminContact: { email: 'not an email' } }, + { customer: { email: 'grace@grace.org' }, adminContact: null }, + ]; + expect(recipients(installs)).toEqual(['office@hope.org', 'Jane@hope.org', 'grace@grace.org']); + }); + + test('the message, with the dates when there are any', () => { + expect(emailText({ message: 'Hello ' })).toBe('Hello\n\n— Cross Events'); + const text = emailText({ message: 'Down for maintenance.', startsAt: '2026-11-01T18:00:00Z', endsAt: '2026-11-01T20:00:00Z' }); + expect(text).toContain('From: 1 November 2026'); + expect(text).toContain('Until: 1 November 2026'); + }); +}); diff --git a/docs/hub-protocol.md b/docs/hub-protocol.md index a3ef0e5..eac96af 100644 --- a/docs/hub-protocol.md +++ b/docs/hub-protocol.md @@ -55,7 +55,9 @@ POST /api/installs/register "installSecret": "…", // shown once; the install stores it encrypted "licence": "", "heartbeatIntervalMinutes": 15, - "latestVersion": "1.41.0" + "latestVersion": "1.41.0", + "releases": [ … ], // as in the heartbeat reply (§3); Hub 1.4.0+ + "notices": [ … ] } ``` @@ -101,9 +103,29 @@ X-Hub-Signature: "income": { "last30d": "R5 001–R20 000", "allTime": "over R100 000" } } } -→ 200 { "licence": "", "latestVersion": "1.42.0", "serverTime": "…" } +→ 200 { + "licence": "", + "latestVersion": "1.42.0", + "releases": [ // Hub 1.4.0+: newer than the version sent, newest first, at most 20 + { "version": "1.42.0", "releasedAt": "2026-10-27T10:00:00.000Z", "urgent": false, "notes": "- Event series\n- Fixed: …" } + ], + "notices": [ // Hub 1.4.0+: the provider's banners for this install + { "id": "…", "level": "maintenance", "title": "Planned maintenance", "message": "…", + "startsAt": "2026-11-01T16:00:00.000Z", "endsAt": "2026-11-01T16:30:00.000Z", "updatedAt": "…" } + ], + "serverTime": "…" +} ``` +- **`releases`** — what's new in each version, written by Joshua on the Hub's Releases page, so the + church can decide whether to ask for the update. `notes` is plain text; lines starting with `- ` are + a list. `urgent` marks security or serious bug fixes: the install shows those in red and doesn't let + admins put them off. The highest release is `latestVersion`. +- **`notices`** — banners Joshua posts on the Hub's Notices page (`level`: `info`, `maintenance` or + `warning`). Sent until `endsAt`, including ones that haven't started, so the install shows each one + from `startsAt` without waiting for a heartbeat. The install shows them to site admins and + supervisors. Notices can also be emailed; that happens on the Hub, not through the install. +- A Hub older than 1.4.0 sends neither field; the install then shows no notes and no notices. - The signature covers the exact bytes sent. Requests more than **5 minutes** off the Hub's clock are refused (`401 STALE_REQUEST`); a bad signature is `401 BAD_SIGNATURE`; an unknown or released install is `404 INSTALL_NOT_FOUND` (the install should show "Reconnect to Hub"). @@ -132,6 +154,22 @@ X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) hour per IP). A Hub older than this section answers `404 NOT_FOUND`. - No personal information: not who pressed the button (the Hub already has the admin contact). +### Withdrawing it + +Sent when a site admin presses **Withdraw request**. Signed like the heartbeat. + +``` +POST /api/installs/update-request/cancel +X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) +{ "protocolVersion": 1 } +→ 200 { "cancelled": true } // the open request was resolved, and Joshua is emailed +→ 200 { "cancelled": false } // there was no open request +``` + +- The Hub resolves the `update_requested` alert and records `update_request_withdrawn` in the install's + history. Rate-limited with update requests. A Hub older than 1.4.0 answers `404 NOT_FOUND`. +- **"Not now"** (no reminders until the next version) stays on the install; the Hub isn't told. + ## 4. Licence token `hel1..` — `payload` is base64url JSON, `signature` is the base64url diff --git a/frontend/src/app/(hub)/alerts/page.tsx b/frontend/src/app/(hub)/alerts/page.tsx index dc43027..d62bb1f 100644 --- a/frontend/src/app/(hub)/alerts/page.tsx +++ b/frontend/src/app/(hub)/alerts/page.tsx @@ -25,7 +25,7 @@ export default function AlertsPage() { return ( <> - +
diff --git a/frontend/src/app/(hub)/layout.tsx b/frontend/src/app/(hub)/layout.tsx index 9592f63..16fc05f 100644 --- a/frontend/src/app/(hub)/layout.tsx +++ b/frontend/src/app/(hub)/layout.tsx @@ -3,7 +3,7 @@ import React, { useEffect, useState } from "react"; import Link from "next/link"; import { usePathname, useRouter } from "next/navigation"; -import { LayoutDashboard, Building2, BellRing, Settings, LogOut } from "lucide-react"; +import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone } from "lucide-react"; import { api, getToken, setToken } from "@/lib/api"; import { Logo } from "@/components/ui"; @@ -13,6 +13,8 @@ const NAV = [ { href: "/", label: "Installs", icon: LayoutDashboard }, { href: "/customers", label: "Customers", icon: Building2 }, { href: "/alerts", label: "Alerts", icon: BellRing }, + { href: "/releases", label: "Releases", icon: Rocket }, + { href: "/notices", label: "Notices", icon: Megaphone }, { href: "/settings", label: "Settings", icon: Settings }, ]; diff --git a/frontend/src/app/(hub)/notices/page.tsx b/frontend/src/app/(hub)/notices/page.tsx new file mode 100644 index 0000000..0983064 --- /dev/null +++ b/frontend/src/app/(hub)/notices/page.tsx @@ -0,0 +1,215 @@ +"use client"; + +import React, { useCallback, useEffect, useMemo, useState } from "react"; +import { Mail, Megaphone } from "lucide-react"; +import { api, errorText } from "@/lib/api"; +import { fmtDate } from "@/lib/format"; +import { matches } from "@/lib/paging"; +import type { InstallSummary, Notice, NoticeLevel } from "@/lib/types"; +import { Badge, Loading, Message, PageTitle, SearchInput } from "@/components/ui"; + +type Msg = { type: "ok" | "err"; text: string } | null; + +const LEVELS: { key: NoticeLevel; label: string; hint: string }[] = [ + { key: "info", label: "Information", hint: "Blue banner" }, + { key: "maintenance", label: "Planned maintenance", hint: "Amber banner" }, + { key: "warning", label: "Important", hint: "Red banner" }, +]; +const LEVEL_LABEL = Object.fromEntries(LEVELS.map(l => [l.key, l.label])) as Record; + +// works in the browser's time; the API takes ISO. +const toInput = (d: string | null) => { + if (!d) return ""; + const x = new Date(d); + return new Date(x.getTime() - x.getTimezoneOffset() * 60000).toISOString().slice(0, 16); +}; +const fromInput = (v: string) => (v ? new Date(v).toISOString() : null); + +type Form = { title: string; message: string; level: NoticeLevel; allInstalls: boolean; installIds: string[]; showBanner: boolean; sendEmail: boolean; startsAt: string; endsAt: string }; +const empty = (): Form => ({ title: "", message: "", level: "info", allInstalls: true, installIds: [], showBanner: true, sendEmail: false, startsAt: "", endsAt: "" }); + +function state(n: Notice, now = Date.now()) { + if (!n.showBanner) return { label: "Email only", value: "info" as const }; + if (n.endsAt && new Date(n.endsAt).getTime() <= now) return { label: "Ended", value: "info" as const }; + if (n.startsAt && new Date(n.startsAt).getTime() > now) return { label: "Scheduled", value: "warning" as const }; + return { label: "Showing", value: "ok" as const }; +} + +/** Pick every install or some of them. */ +function Audience({ installs, form, setForm }: { installs: InstallSummary[]; form: Form; setForm: (f: Form) => void }) { + const [query, setQuery] = useState(""); + const shown = useMemo(() => installs.filter(i => matches(query, i.name, i.url, i.customer?.name)), [installs, query]); + const toggle = (id: string) => setForm({ ...form, installIds: form.installIds.includes(id) ? form.installIds.filter(x => x !== id) : [...form.installIds, id] }); + return ( +
+ Who gets it +
+ + +
+ {!form.allInstalls && ( +
+ +
+ {shown.length === 0 &&

No installs match.

} + {shown.map(i => ( + + ))} +
+
+ )} +
+ ); +} + +function NoticeForm({ initial, installs, editing, busy, onSave, onCancel }: { initial: Form; installs: InstallSummary[]; editing: boolean; busy: boolean; onSave: (f: Form) => void; onCancel: () => void }) { + const [form, setForm] = useState(initial); + return ( +
{ e.preventDefault(); onSave(form); }} className="space-y-4"> +
+
+ + setForm({ ...form, title: e.target.value })} required /> +
+
+ + +
+
+
+ +