- A site the Hub answers INSTALL_NOT_FOUND for drops its install and licence, so it no longer shows "Active" on the old token. - Unlicensed is read-only like suspended; read-only also blocks editing events, options and variants. LICENCE_CHECK_DISABLED (ignored in production) for e2e. - Heartbeat 30 s after the server starts and after a licence key is connected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
143 lines
6.1 KiB
JavaScript
143 lines
6.1 KiB
JavaScript
/**
|
|
* Talking to the Hope Events Hub (docs/hub-protocol.md): register with a licence key, then a
|
|
* signed heartbeat every 15 minutes. 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.
|
|
* 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'];
|
|
|
|
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;
|
|
}
|
|
|
|
/** 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 Hope 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 secret = decrypt(s.hub_install_secret);
|
|
const body = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health: await report.health(), stats: await report.stats() };
|
|
try {
|
|
const data = await post('/api/installs/heartbeat', 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'),
|
|
};
|
|
});
|
|
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;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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 };
|