/** * 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), * hub_v1_until (the Hub refused protocol v2: speak v1 until then; 2.4.0), * and this site's key pair and the Hub's list of the church's other products (links/store.ts). * These keys are kept out of the generic settings endpoints (settingsController). * * Protocol (2.4.0, docs/EVENTS-2.4-PLAN.md §1): register and heartbeat speak **v2** * (`product: "events"`, this site's public key, the church's other products in the reply). An * install that registered with v1 moves over by sending its key on the heartbeat (Hub 2.2.0 * saves it), so nobody needs the licence key again. If the Hub refuses a v2 body (a Hub before * 2.0, or a body the Hub's contract doesn't accept), the same heartbeat goes again as v1 and v1 * is used for a day: the licence must keep refreshing whatever happens. Update requests and AI * calls stay v1, which every Hub accepts. */ 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 { hub } = require('@crosscode/contracts'); const store = require('../links/store'); /** Update requests and AI calls (as in v1; the Hub answers both versions). */ const PROTOCOL_VERSION = 1; /** Register and heartbeat (2.4.0). */ const HEARTBEAT_PROTOCOL = 2; const V1_FALLBACK_MS = 24 * 60 * 60 * 1000; 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', 'hub_v1_until', ...store.KEY_SETTINGS]; function hubUrl() { return String(process.env.HUB_URL || 'https://events-hub.crosscode.co.za').replace(/\/$/, ''); } class HubError extends Error { constructor(message, code, status, data = null) { super(message); this.code = code; this.statusCode = status; // The Hub's whole error body (AI errors carry the new AI status, protocol §3b). this.data = data; } } 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 = {}, timeoutMs = TIMEOUT_MS) { 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(timeoutMs), }); } 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, data); return data; } /** * POST signed with the install secret (§3). Throws NOT_CONNECTED when there is no connection. * AI calls wait longer than the default (Claude can take a while to write). */ async function signedPost(path, body, { timeoutMs = TIMEOUT_MS } = {}) { 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'), }; }, timeoutMs); } /** 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 v1Body = { protocolVersion: PROTOCOL_VERSION, licenceKey: String(licenceKey || '').trim(), install: { ...install, adminContact: adminContact ? { name: adminContact.name || null, email: adminContact.email || null } : null }, }; // v2 (2.4.0): the product and this site's public key, so the church's other products can link. // Anything wrong with the key (or a Hub that only speaks v1) registers with v1 instead. const publicKeyPem = await ownPublicKey(); const v2Body = { ...v1Body, protocolVersion: HEARTBEAT_PROTOCOL, licenceKey: v1Body.licenceKey.toUpperCase(), product: 'events', install: { ...v1Body.install, publicKey: publicKeyPem } }; const v2 = !!publicKeyPem && !(await v1Only()) && hub.registerRequestSchema.safeParse(v2Body).success; let data; let sentV2 = v2; try { data = await post('/api/installs/register', v2 ? v2Body : v1Body); } catch (e) { if (!v2 || !refusedV2(e)) throw e; await useV1ForADay(); sentV2 = false; data = await post('/api/installs/register', v1Body); } 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), }); if (sentV2) { try { await store.saveLinkedProducts(data.linkedProducts); // Registered with the key, so the Hub has it. await store.setPublicKeyStatus('matches'); } catch (e) { console.warn('[hub] Could not save the linked products:', e?.message || e); } } return claims; } /** This site's public key, or null when it can't be made or read (then v1 is used). */ async function ownPublicKey() { try { return (await store.keyPair()).publicKeyPem; } catch (e) { console.warn('[hub] No key pair for protocol v2, using v1:', e?.message || e); return null; } } /** Whether the Hub refused a v2 body (too old for v2, or a contract it doesn't accept): retry as v1. */ function refusedV2(e) { return e instanceof HubError && e.statusCode === 400 && ['UNSUPPORTED_PROTOCOL', 'INVALID_REQUEST'].includes(e.code); } async function v1Only() { const until = (await read(['hub_v1_until'])).hub_v1_until; return !!until && new Date(until).getTime() > Date.now(); } async function useV1ForADay() { await save({ hub_v1_until: new Date(Date.now() + V1_FALLBACK_MS).toISOString() }); } /** * The health as protocol v2 wants it: every field there (a part that couldn't be read is * reported as nothing wrong rather than left out). */ function v2Health(h) { return { ...h, jobs: h.jobs || { mode: 'unknown', failedLast24h: 0 }, pendingMigrations: Number.isInteger(h.pendingMigrations) ? h.pendingMigrations : 0, }; } /** * The heartbeat body: v2 when it fits the contract (with the public key until the Hub has it), * otherwise v1. Returns { body, v2 }. */ async function heartbeatBody() { const health = await report.health(); const stats = await report.stats(); const v1 = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health, stats }; if (await v1Only()) return { body: v1, v2: false }; const publicKeyPem = await ownPublicKey(); if (!publicKeyPem) return { body: v1, v2: false }; const status = await store.publicKeyStatus().catch(() => null); const v2 = { protocolVersion: HEARTBEAT_PROTOCOL, product: 'events', version: report.APP_VERSION, health: v2Health(health), stats, ...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }), }; const check = hub.heartbeatRequestSchema.safeParse(v2); if (!check.success) { console.warn('[hub] The v2 heartbeat doesn\'t fit the contract, sending v1:', check.error.issues.slice(0, 3).map(i => `${i.path.join('.')} ${i.message}`).join('; ')); return { body: v1, v2: false }; } return { body: v2, v2: true }; } /** 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' }; let { body, v2 } = await heartbeatBody(); try { let data; try { data = await signedPost('/api/installs/heartbeat', body); } catch (e) { if (!v2 || !refusedV2(e)) throw e; console.warn(`[hub] The Hub refused a v2 heartbeat (${e.code}: ${e.message}); using v1 for a day.`); await useV1ForADay(); ({ body, v2 } = await heartbeatBody()); data = await signedPost('/api/installs/heartbeat', body); } if (v2) { try { await store.saveLinkedProducts(data.linkedProducts); if (typeof data.publicKeyStatus === 'string') await store.setPublicKeyStatus(data.publicKeyStatus); // 3.0.0: connect to the church's Accounts once the Hub lists it (accounts/autoConnect.ts). require('../accounts/autoConnect').connectAccountsIfListed().catch((e) => console.warn('[accounts] Could not connect to Accounts yet:', e?.message || e)); } catch (e) { console.warn('[hub] Could not save the linked products:', e?.message || e); } } 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, protocol: v2 ? 2 : 1 }; } 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?.(); } /** * Installs made from the Hub (crosscode install, docs/AGENT-1.0-PLAN.md §7) have the licence key in * HUB_LICENCE_KEY: the site registers by itself on its first start, instead of in /setup. Does * nothing once registered, or without the key. Retries a few times (the Hub may be briefly * unreachable); a refused key is logged and left for /setup. Never throws. */ async function connectFromEnv({ attempts = 5, delayMs = 60 * 1000, sleep = ms => new Promise(r => setTimeout(r, ms).unref?.()) } = {}) { const key = String(process.env.HUB_LICENCE_KEY || '').trim(); if (!key) return { connected: false, reason: 'no_key' }; for (let i = 1; i <= attempts; i++) { try { const stored = await read(['hub_install_id']); if (stored.hub_install_id) return { connected: false, reason: 'already' }; const name = String(process.env.HUB_ADMIN_NAME || '').trim() || null; const email = String(process.env.HUB_ADMIN_EMAIL || '').trim() || null; await connect(key, name || email ? { name, email } : null); console.log('[hub] Registered with the Hub using HUB_LICENCE_KEY.'); return { connected: true }; } catch (e) { const status = e?.statusCode || 0; console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, e?.message || e); // The Hub said no (unknown, revoked or in-use key): retrying won't help. if (status >= 400 && status < 500) return { connected: false, reason: e?.code || 'refused' }; if (i < attempts) await sleep(delayMs); } } return { connected: false, reason: 'unreachable' }; } module.exports = { PROTOCOL_VERSION, HEARTBEAT_PROTOCOL, HUB_KEYS, heartbeatBody, hubUrl, HubError, signedPost, connect, connectFromEnv, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };