/** * Talking to the Cross Events Hub (docs/hub-protocol.md): register with a licence key, then a * signed heartbeat every 15 minutes, and a signed update request (or withdrawal) when an admin * asks. Install → Hub only. Stored in AppSetting: * hub_install_id, hub_install_secret (encrypted), hub_licence (signed token), * hub_last_heartbeat_at, hub_last_error, hub_latest_version, * hub_releases, hub_notices (JSON from the last heartbeat: what's new, provider's notices), * hub_update_requested_at, hub_update_requested_version, * hub_update_snoozed_version ("Not now" for that version; set here, not by the Hub). * These keys are kept out of the generic settings endpoints (settingsController). */ const crypto = require('crypto'); const prisma = require('../config/db'); const { encrypt, decrypt } = require('../utils/encryption'); const { verifyToken, clearLicenceCache } = require('./licence'); const report = require('./report'); const PROTOCOL_VERSION = 1; const TIMEOUT_MS = 15000; const HUB_KEYS = ['hub_install_id', 'hub_install_secret', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version', 'hub_update_requested_at', 'hub_update_requested_version', 'hub_releases', 'hub_notices', 'hub_update_snoozed_version']; function hubUrl() { return String(process.env.HUB_URL || 'https://events-hub.crosscode.co.za').replace(/\/$/, ''); } class HubError extends Error { constructor(message, code, status) { super(message); this.code = code; this.statusCode = status; } } async function save(values) { for (const [key, value] of Object.entries(values)) { if (value === null) await prisma.appSetting.deleteMany({ where: { key } }); else await prisma.appSetting.upsert({ where: { key }, update: { value: String(value) }, create: { key, value: String(value) } }); } clearLicenceCache(); } /** What's new and the provider's notices from a register/heartbeat reply (a Hub before 1.4.0 sends neither). */ function fromHub(data) { return { hub_releases: Array.isArray(data.releases) ? JSON.stringify(data.releases.slice(0, 20)) : null, hub_notices: Array.isArray(data.notices) ? JSON.stringify(data.notices.slice(0, 20)) : null, }; } async function read(keys) { const rows = await prisma.appSetting.findMany({ where: { key: { in: keys } } }); return Object.fromEntries(rows.map(r => [r.key, r.value])); } async function post(path, body, headers = {}) { const raw = JSON.stringify(body); let res; try { res = await fetch(`${hubUrl()}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json', ...(typeof headers === 'function' ? headers(raw) : headers) }, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS), }); } catch (e) { throw new HubError(`The Hub (${hubUrl()}) could not be reached: ${e?.message || e}`, 'HUB_UNREACHABLE', 502); } const data = await res.json().catch(() => ({})); if (!res.ok) throw new HubError(data.message || `The Hub answered ${res.status}`, data.code || 'HUB_ERROR', res.status); return data; } /** POST signed with the install secret (§3). Throws NOT_CONNECTED when there is no connection. */ async function signedPost(path, body) { const s = await read(['hub_install_id', 'hub_install_secret']); if (!s.hub_install_id || !s.hub_install_secret) throw new HubError('This site isn\'t connected to the Hub yet.', 'NOT_CONNECTED', 400); const secret = decrypt(s.hub_install_secret); return post(path, body, raw => { const timestamp = new Date().toISOString(); return { 'X-Hub-Install': s.hub_install_id, 'X-Hub-Timestamp': timestamp, 'X-Hub-Signature': crypto.createHmac('sha256', secret).update(`${timestamp}.${raw}`).digest('hex'), }; }); } /** Register this install with a licence key. Returns the licence claims. */ async function connect(licenceKey, adminContact) { if (!require('./publicKey').hubPublicKey()) { throw new HubError('This version of Cross Events has no Hub key built in, so it can\'t check licences yet.', 'NO_PUBLIC_KEY', 500); } const install = await report.installInfo(); if (!/^https?:\/\//.test(install.url)) { throw new HubError('Set the site\'s web address first (FRONTEND_URL on the server, or Site settings → Organisation).', 'NO_SITE_URL', 400); } const data = await post('/api/installs/register', { protocolVersion: PROTOCOL_VERSION, licenceKey: String(licenceKey || '').trim(), install: { ...install, adminContact: adminContact ? { name: adminContact.name || null, email: adminContact.email || null } : null }, }); const claims = verifyToken(data.licence); if (!claims || claims.installId !== data.installId) { throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL pointing at the right Hub?', 'BAD_LICENCE', 502); } await save({ hub_install_id: data.installId, hub_install_secret: encrypt(data.installSecret), hub_licence: data.licence, hub_last_heartbeat_at: new Date().toISOString(), hub_last_error: null, hub_latest_version: data.latestVersion || null, ...fromHub(data), }); return claims; } /** Send a heartbeat (the `hub-heartbeat` job). Skips quietly when not connected. */ async function heartbeat() { const s = await read(['hub_install_id', 'hub_install_secret']); if (!s.hub_install_id || !s.hub_install_secret) return { skipped: 'not connected' }; const body = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health: await report.health(), stats: await report.stats() }; try { const data = await signedPost('/api/installs/heartbeat', body); const claims = verifyToken(data.licence); await save({ // Keep the old token if the new one doesn't check out (never accept an unverified one). ...(claims && claims.installId === s.hub_install_id ? { hub_licence: data.licence } : {}), hub_last_heartbeat_at: new Date().toISOString(), hub_last_error: null, hub_latest_version: data.latestVersion || null, ...fromHub(data), }); return { ok: true, status: claims?.status || null }; } catch (e) { await save({ hub_last_error: `${new Date().toISOString()} ${e.code || ''} ${e.message}`.slice(0, 500) }); // The Hub doesn't know this install any more (licence released): drop the connection and the // licence, so the site is unlicensed (read-only) and shows "Connect" until a key is entered. if (e.code === 'INSTALL_NOT_FOUND') { await save({ hub_install_id: null, hub_install_secret: null, hub_licence: null }); return { ok: false, reconnect: true }; } throw e; } } /** a < b as x.y.z versions. */ function olderThan(a, b) { const pa = String(a || '').split('.').map(n => parseInt(n, 10) || 0); const pb = String(b || '').split('.').map(n => parseInt(n, 10) || 0); for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] < pb[i]; return false; } /** * Ask the Hub for this site to be updated (§3a). Joshua is told; the site never updates itself. * Asking again after a newer version came out moves the request on to it (`changed`). A Hub before * 1.5.0 can't do that (it doesn't send `changed`), so the old request is withdrawn and made again. * Returns { requestedAt, version, alreadyRequested, changed, previousVersion }. */ async function requestUpdate() { const ask = async () => { try { return await signedPost('/api/installs/update-request', { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION }); } catch (e) { if (e.code === 'NOT_FOUND') throw new HubError('The Hub doesn\'t take update requests yet. Please contact your provider.', 'NOT_SUPPORTED', 502); throw e; } }; let data = await ask(); if (data.alreadyRequested && data.changed === undefined) { const asked = (await read(['hub_update_requested_version'])).hub_update_requested_version || null; if (!asked || olderThan(asked, data.version)) { await cancelUpdateRequest(); data = { ...(await ask()), changed: true, previousVersion: asked }; } } await save({ hub_update_requested_at: data.requestedAt, hub_update_requested_version: data.version || null }); return data; } /** Withdraw the update request (§3a): the provider is told not to update after all. */ async function cancelUpdateRequest() { try { await signedPost('/api/installs/update-request/cancel', { protocolVersion: PROTOCOL_VERSION }); } catch (e) { if (e.code === 'NOT_FOUND') throw new HubError('The Hub can\'t withdraw update requests yet. Please contact your provider.', 'NOT_SUPPORTED', 502); throw e; } await save({ hub_update_requested_at: null, hub_update_requested_version: null }); } /** "Not now": no update reminders until a newer version than `version` is out. Null turns them back on. */ async function snoozeUpdate(version) { await save({ hub_update_snoozed_version: version || null }); } /** * A heartbeat soon (on startup, and after connecting), so a licence change on the Hub shows * without waiting for the next 15-minute run. Never throws; skipped when the job is switched off. */ let soonTimer = null; function heartbeatSoon(delayMs = 30 * 1000) { if (String(process.env.JOBS_ENABLED || 'true').toLowerCase() === 'false') return; if (String(process.env.HUB_HEARTBEAT_ENABLED || 'true').toLowerCase() === 'false') return; clearTimeout(soonTimer); soonTimer = setTimeout(() => { heartbeat().catch(e => console.warn('[hub] Heartbeat failed:', e?.message || e)); }, delayMs); soonTimer.unref?.(); } module.exports = { PROTOCOL_VERSION, HUB_KEYS, hubUrl, HubError, connect, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };