diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b73534..375bdf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,23 @@ versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [1.1.0] - 2026-10-27 + +### Added + +- **Update requests** (`docs/hub-protocol.md` §3a): `POST /api/installs/update-request`, signed + like the heartbeat. When a church's site admin presses "Request update", the Hub opens an + `update_requested` alert on the install (shown under Alerts and in its history) and emails the + alert address once; asking again while it's open doesn't email again. The alert resolves itself + when the install's heartbeat reports a newer version. `409 UP_TO_DATE` if it's already on the + latest release. Installs no longer show the deploy command. + +### Changed + +- The signature check for install requests is shared by the heartbeat and update requests. +- `docs/hub-protocol.md` brought in line with the install's copy (licence states from Cross Events + 1.41.1). + ## [1.0.1] - 2026-10-27 ### Changed diff --git a/backend/package-lock.json b/backend/package-lock.json index 8da620a..14bcf60 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-backend", - "version": "1.0.1", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-backend", - "version": "1.0.1", + "version": "1.1.0", "hasInstallScript": true, "dependencies": { "@prisma/adapter-pg": "^7.10.1", diff --git a/backend/package.json b/backend/package.json index ed0e089..ea4579f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-backend", - "version": "1.0.1", + "version": "1.1.0", "private": true, "description": "Cross Events Hub — API for managing Cross Events installs, licences and heartbeats", "main": "src/index.js", diff --git a/backend/src/routes/installApi.js b/backend/src/routes/installApi.js index 0505ed1..08d5fa2 100644 --- a/backend/src/routes/installApi.js +++ b/backend/src/routes/installApi.js @@ -1,5 +1,5 @@ /** - * The API installs call (docs/hub-protocol.md): public key, register, heartbeat. + * The API installs call (docs/hub-protocol.md): public key, register, heartbeat, update request. * Install → Hub only; these are the only endpoints that aren't behind an admin login. */ @@ -10,6 +10,8 @@ const { encrypt, decrypt, normaliseLicenceKey, randomSecret } = require('../util const licenceToken = require('../utils/licenceToken'); const { checkSignature } = require('../utils/signing'); const { getSettings } = require('../utils/settings'); +const { compareVersions } = require('../utils/alerts'); +const { sendMail } = require('../utils/mail'); const router = express.Router(); @@ -17,6 +19,7 @@ const PROTOCOL_VERSIONS = [1]; const HEARTBEAT_MINUTES = 15; const registerLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts.', code: 'RATE_LIMITED' } }); const heartbeatLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } }); +const updateRequestLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 10, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } }); const fail = (res, status, code, message) => res.status(status).json({ code, message }); @@ -44,6 +47,28 @@ async function tokenFor(install) { return licenceToken.sign(licenceToken.buildPayload(licence, install, licence.customer.name)); } +/** + * The install a signed request comes from (§3), or null once the error has been sent: + * unknown/released install, stale timestamp, bad signature or unsupported protocol. + */ +async function signedInstall(req, res) { + const installId = String(req.headers['x-hub-install'] || ''); + const install = installId ? await prisma.install.findUnique({ where: { id: installId } }) : null; + if (!install || install.releasedAt) { fail(res, 404, 'INSTALL_NOT_FOUND', 'This install is not registered with the Hub. Reconnect it in Site settings.'); return null; } + + const problem = checkSignature({ + secret: decrypt(install.secret), + timestamp: String(req.headers['x-hub-timestamp'] || ''), + rawBody: req.rawBody || '', + given: String(req.headers['x-hub-signature'] || ''), + }); + if (problem === 'STALE_REQUEST') { fail(res, 401, problem, "The request's time is too far from the Hub's — check the server clock."); return null; } + if (problem) { fail(res, 401, problem, 'The request signature is not valid.'); return null; } + + if (!protocolOk(req.body)) { fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${req.body?.protocolVersion} is not supported.`); return null; } + return install; +} + router.get('/public-key', (req, res) => { res.json({ protocolVersions: PROTOCOL_VERSIONS, keyId: 'k1', algorithm: 'Ed25519', publicKey: licenceToken.keyPair().publicKeyPem }); }); @@ -98,21 +123,9 @@ router.post('/installs/register', registerLimiter, async (req, res) => { router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => { try { - const installId = String(req.headers['x-hub-install'] || ''); - const install = installId ? await prisma.install.findUnique({ where: { id: installId } }) : null; - if (!install || install.releasedAt) return fail(res, 404, 'INSTALL_NOT_FOUND', 'This install is not registered with the Hub. Reconnect it in Site settings.'); - - const problem = checkSignature({ - secret: decrypt(install.secret), - timestamp: String(req.headers['x-hub-timestamp'] || ''), - rawBody: req.rawBody || '', - given: String(req.headers['x-hub-signature'] || ''), - }); - if (problem === 'STALE_REQUEST') return fail(res, 401, problem, "The request's time is too far from the Hub's — check the server clock."); - if (problem) return fail(res, 401, problem, 'The request signature is not valid.'); - - const body = req.body || {}; - if (!protocolOk(body)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${body.protocolVersion} is not supported.`); + const install = await signedInstall(req, res); + if (!install) return; + const body = req.body; const now = new Date(); const version = str(body.version, 40); @@ -124,6 +137,10 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => { ]); if (version && install.version && version !== install.version) { await prisma.installEvent.create({ data: { installId: install.id, type: 'version', level: 'info', message: `Updated from ${install.version} to ${version}`, resolvedAt: now } }); + // An update the church asked for is done once the install runs a newer version. + if (compareVersions(version, install.version) > 0) { + await prisma.installEvent.updateMany({ where: { installId: install.id, type: 'update_requested', resolvedAt: null }, data: { resolvedAt: now } }); + } } const settings = await getSettings(); @@ -134,5 +151,38 @@ router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => { } }); +// A site admin pressed "Request update": open an alert (emailed once) until the install reports a +// newer version. Asking again while a request is open doesn't email again. +router.post('/installs/update-request', updateRequestLimiter, async (req, res) => { + try { + const install = await signedInstall(req, res); + if (!install) return; + + const settings = await getSettings(); + const latest = settings.latest_version || null; + const current = str(req.body.version, 40) || install.version; + if (!latest || compareVersions(current, latest) >= 0) { + return fail(res, 409, 'UP_TO_DATE', 'This site already runs the latest version.'); + } + + const open = await prisma.installEvent.findFirst({ where: { installId: install.id, type: 'update_requested', resolvedAt: null }, orderBy: { createdAt: 'desc' } }); + if (open) return res.json({ requestedAt: open.createdAt.toISOString(), version: latest, alreadyRequested: true }); + + const event = await prisma.installEvent.create({ data: { installId: install.id, type: 'update_requested', level: 'warning', message: `Update requested: runs ${current}, latest is ${latest}` } }); + 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 requested by ${customer?.name || install.name}`, + text: `${customer?.name || install.name} (${install.url}) would like to be updated from ${current} to ${latest}.\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/installs/${install.id}`, + }).catch(e => console.warn('[update-request] email failed:', e?.message)); + } + res.status(201).json({ requestedAt: event.createdAt.toISOString(), version: latest, alreadyRequested: false }); + } catch (e) { + console.error('[update-request]', e); + fail(res, 500, 'SERVER_ERROR', 'The Hub could not record 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 42fc3cf..2a6b6da 100644 --- a/backend/src/utils/alerts.js +++ b/backend/src/utils/alerts.js @@ -88,7 +88,8 @@ async function runAlerts(now = new Date()) { const newAlerts = []; for (const install of installs) { const current = problems(install, settings, now); - const openByType = new Map(install.events.filter(e => e.type !== 'registered' && e.type !== 'version').map(e => [e.type, e])); + // 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])); 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/docs/hub-protocol.md b/docs/hub-protocol.md index 6e8f462..c47b9bf 100644 --- a/docs/hub-protocol.md +++ b/docs/hub-protocol.md @@ -110,6 +110,27 @@ X-Hub-Signature: `R1 001–R5 000`, `R5 001–R20 000`, `R20 001–R50 000`, `R50 001–R100 000`, `over R100 000`. - The Hub keeps every heartbeat for 30 days, then one per install per day. +## 3a. Update request + +Sent when a site admin presses **Request update** (Site settings → Licence). Installs never update +themselves and never show the deploy command; the request tells Joshua, who updates the server. +Signed exactly like the heartbeat. + +``` +POST /api/installs/update-request +X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3) +{ "protocolVersion": 1, "version": "1.41.2" } +→ 201 { "requestedAt": "2026-10-27T09:00:00.000Z", "version": "1.42.0", "alreadyRequested": false } +→ 200 { …, "alreadyRequested": true } // a request is already open: not emailed again +``` + +- The Hub opens an `update_requested` alert on the install (shown under Alerts) and emails the + alert address once. It is resolved when a heartbeat reports a newer version than before. +- `409 UP_TO_DATE` — the install already runs the Hub's latest version (or none is set). +- Errors as in §3 (`INSTALL_NOT_FOUND`, `STALE_REQUEST`, `BAD_SIGNATURE`). Rate-limited (10 an + 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). + ## 4. Licence token `hel1..` — `payload` is base64url JSON, `signature` is the base64url @@ -140,9 +161,9 @@ out its state: |-------|------|--------------| | **active** | `status` is active and now is before `min(licenceExpiresAt, validUntil)` | Everything works | | **grace** | after that date, for up to `graceDays` | Everything works; **only site admins** see a banner "Licence needs renewing — X days left" | -| **suspended** | `status` is suspended, or grace has run out | Read-only: no new events, registrations or payments. Tickets still scan; admins can view and export all data; privacy requests still work | +| **suspended** | `status` is suspended, or grace has run out | Read-only: events can't be created or edited; no new registrations or payments. Tickets still scan; admins can view and export all data; privacy requests still work | | **revoked** | `status` is revoked | Same as suspended, with a permanent banner | -| **unlicensed** | never connected | Works; admins see "Connect to Hub" | +| **unlicensed** | never connected, or the Hub answered `INSTALL_NOT_FOUND` (the install drops its token) | Same as suspended (events can't be created or edited either); admins see "Connect to Hub" | `validUntil` is refreshed by every heartbeat, so a Hub outage only matters after 30 days (then grace starts). Blocking the Hub can't keep a suspended licence active for more than 30 days. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index fa6d14e..45d1c6a 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "events-hub-frontend", - "version": "1.0.1", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "events-hub-frontend", - "version": "1.0.1", + "version": "1.1.0", "dependencies": { "lucide-react": "^0.536.0", "next": "^15.5.24", diff --git a/frontend/package.json b/frontend/package.json index 4347843..a852732 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "events-hub-frontend", - "version": "1.0.1", + "version": "1.1.0", "private": true, "scripts": { "dev": "next dev -p 3200",