/** * 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 when an admin asks for one. * 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_update_requested_at, hub_update_requested_version. * 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']; 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(); } 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, }); 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, }); 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; } } /** * Ask the Hub for this site to be updated (§3a). Joshua is told; the site never updates itself. * Returns { requestedAt, version, alreadyRequested }. */ async function requestUpdate() { let data; try { data = 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; } await save({ hub_update_requested_at: data.requestedAt, hub_update_requested_version: data.version || null }); return data; } /** * 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 };