/** * 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. */ const express = require('express'); const rateLimit = require('express-rate-limit'); const prisma = require('../config/db'); const { encrypt, decrypt, normaliseLicenceKey, randomSecret } = require('../utils/crypto'); 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 { releasesForInstall } = require('../utils/releases'); const { noticesForInstall } = require('../utils/notices'); const router = express.Router(); 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 }); function protocolOk(body) { const minSupported = Math.max(...PROTOCOL_VERSIONS) - 1; const v = body?.protocolVersion; return Number.isInteger(v) && v >= minSupported && v <= Math.max(...PROTOCOL_VERSIONS); } // Only small, known pieces of what an install says about itself are kept. const str = (v, max = 200) => (v == null ? null : String(v).slice(0, max)); function cleanUrl(url) { try { const u = new URL(String(url)); if (!/^https?:$/.test(u.protocol)) return null; return `${u.protocol}//${u.host}${u.pathname.replace(/\/$/, '')}`; } catch { return null; } } async function tokenFor(install) { const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true } } } }) : null; if (!licence) return null; 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 }); }); router.post('/installs/register', registerLimiter, async (req, res) => { try { const body = req.body || {}; if (!protocolOk(body)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${body.protocolVersion} is not supported; this Hub speaks ${PROTOCOL_VERSIONS.join(', ')}.`); const info = body.install || {}; const url = cleanUrl(info.url); if (!url) return fail(res, 400, 'BAD_URL', 'The install needs its public web address (https://…).'); const licence = await prisma.licence.findUnique({ where: { key: normaliseLicenceKey(body.licenceKey) }, include: { install: true, customer: true } }); if (!licence) return fail(res, 404, 'LICENCE_NOT_FOUND', 'That licence key was not found. Check it, or ask your provider for your key.'); if (licence.status === 'revoked') return fail(res, 403, 'LICENCE_REVOKED', 'This licence has been revoked.'); if (licence.install && licence.install.url !== url) { return fail(res, 409, 'LICENCE_IN_USE', 'This licence is already used by another site. Ask your provider to release it if you have moved.'); } const secret = randomSecret(); const data = { name: str(info.name) || licence.customer.name, url, secret: encrypt(secret), version: str(info.version, 40), protocolVersion: body.protocolVersion, adminContact: info.adminContact ? { name: str(info.adminContact.name), email: str(info.adminContact.email) } : undefined, server: info.server ? { node: str(info.server.node, 40), postgres: str(info.server.postgres, 40), os: str(info.server.os, 80) } : undefined, timezone: str(info.timezone, 60), features: info.features && typeof info.features === 'object' ? info.features : undefined, releasedAt: null, }; // Same licence, same site → re-register (new secret, same id). const install = licence.install ? await prisma.install.update({ where: { id: licence.install.id }, data }) : await prisma.install.create({ data: { ...data, customerId: licence.customerId, licenceId: licence.id } }); await prisma.installEvent.create({ data: { installId: install.id, type: 'registered', level: 'info', message: `${licence.install ? 'Re-registered' : 'Registered'} from ${url} (version ${install.version || '?'})`, resolvedAt: new Date() } }); const settings = await getSettings(); res.status(201).json({ installId: install.id, installSecret: secret, 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); fail(res, 500, 'SERVER_ERROR', 'The Hub could not register this install. Try again later.'); } }); router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => { try { const install = await signedInstall(req, res); if (!install) return; const body = req.body; const now = new Date(); const version = str(body.version, 40); const health = body.health && typeof body.health === 'object' ? body.health : null; const stats = body.stats && typeof body.stats === 'object' ? body.stats : null; await prisma.$transaction([ prisma.heartbeat.create({ data: { installId: install.id, receivedAt: now, version, health: health || undefined, stats: stats || undefined } }), prisma.install.update({ where: { id: install.id }, data: { lastHeartbeatAt: now, version, protocolVersion: body.protocolVersion, health: health || undefined, stats: stats || undefined } }), ]); 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(); 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.'); } }); // 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.'); } }); // 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;