Hub client: licence, heartbeat, read-only mode, /health, install script

- Connect with a licence key (/setup last screen, Site settings -> Licence)
- hub-heartbeat job every 15 min: version, health, totals (income as a band)
- Licence tokens verified with the Hub's public key; states active / grace
  (banner for site admins only) / suspended / revoked (read-only) /
  unlicensed; Hub keys kept out of the generic settings endpoints
- /health; "update available" for admins; scripts/install.sh
- docs/hub-protocol.md shared with the events-hub repo
- Unit tests (hub.test.js); docs

The production Hub public key (backend/src/hub/publicKey.js) must be set
before this is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
This commit is contained in:
2026-10-26 12:25:52 +02:00
co-authored by Claude Opus 5.5
parent 9960c4e938
commit b67f40c2df
30 changed files with 1419 additions and 6 deletions
@@ -0,0 +1,86 @@
const prisma = require('../config/db');
const { safeErrorMessage } = require('../utils/errorUtils');
const { getClientIp } = require('../utils/requestUtils');
const { logAdminAction } = require('../utils/adminAudit');
const { licenceStatus } = require('../hub/licence');
const hub = require('../hub/client');
const { APP_VERSION } = require('../hub/report');
function compareVersions(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] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
return 0;
}
/** What the admin pages show: licence state, Hub connection, version and update. */
async function statusPayload({ fresh = false } = {}) {
const s = await licenceStatus({ fresh });
return {
state: s.state,
readOnly: s.readOnly,
daysLeft: s.daysLeft,
endsAt: s.endsAt,
graceEndsAt: s.graceEndsAt,
licence: s.claims ? {
customer: s.claims.customer,
plan: s.claims.plan,
status: s.claims.status,
licenceExpiresAt: s.claims.licenceExpiresAt,
graceDays: s.claims.graceDays,
issuedAt: s.claims.issuedAt,
validUntil: s.claims.validUntil,
limits: s.claims.limits || {},
} : null,
connected: s.connected,
keyConfigured: s.keyConfigured,
hubUrl: hub.hubUrl(),
lastHeartbeatAt: s.lastHeartbeatAt,
lastError: s.lastError,
version: APP_VERSION,
latestVersion: s.latestVersion,
updateAvailable: !!(s.latestVersion && compareVersions(APP_VERSION, s.latestVersion) < 0),
};
}
// @desc Licence and Hub status (for the admin banner and Site settings → Licence)
// @route GET /api/hub/status
// @access Private/Admin
const getStatus = async (req, res) => {
try {
res.json(await statusPayload());
} catch (e) {
res.status(500).json({ message: safeErrorMessage(e) });
}
};
// @desc Connect this install to the Hub with a licence key (also the /setup licence step)
// @route POST /api/hub/connect body: { licenceKey }
// @access Private/Admin
const connect = async (req, res) => {
try {
const licenceKey = String(req.body?.licenceKey || '').trim();
if (!licenceKey) { res.status(400); throw new Error('Enter your licence key.'); }
const me = await prisma.user.findUnique({ where: { id: req.user.id }, select: { name: true, email: true } });
const claims = await hub.connect(licenceKey, me);
logAdminAction({ actorId: req.user.id, actorRole: req.user.role, action: 'hub_connected', targetType: 'hub', metadata: { customer: claims.customer, hubUrl: hub.hubUrl() }, ip: getClientIp(req) });
res.json(await statusPayload({ fresh: true }));
} catch (e) {
const status = e.statusCode || (res.statusCode === 200 ? 400 : res.statusCode);
res.status(status >= 500 && e.code ? 502 : status).json({ message: e.message || safeErrorMessage(e), code: e.code });
}
};
// @desc Send a heartbeat now (checks the connection and picks up licence changes)
// @route POST /api/hub/heartbeat
// @access Private/Admin
const heartbeatNow = async (req, res) => {
try {
await hub.heartbeat();
res.json(await statusPayload({ fresh: true }));
} catch (e) {
res.status(502).json({ message: e.message || safeErrorMessage(e), code: e.code, status: await statusPayload({ fresh: true }).catch(() => null) });
}
};
module.exports = { getStatus, connect, heartbeatNow, statusPayload, compareVersions };
@@ -15,6 +15,11 @@ const PAYMENT_PRIVATE_KEYS = new Set([
'payfast_merchant_id', 'payfast_merchant_key', 'payfast_passphrase', 'payfast_mode',
]);
// The Hub connection (install id and secret, licence token) is only written by src/hub —
// an admin editing it here could borrow another install's licence.
const HUB_PRIVATE_KEYS = new Set(require('../hub/client').HUB_KEYS);
const PRIVATE_KEYS = new Set([...PAYMENT_PRIVATE_KEYS, ...HUB_PRIVATE_KEYS]);
const PUBLIC_KEYS = [
'org_name', 'org_tagline', 'org_email', 'org_phone', 'org_address',
// Branding — primary_color/secondary_color/accent_color are the 3-color brand
@@ -53,7 +58,7 @@ const getAllSettings = async (req, res) => {
const rows = await prisma.appSetting.findMany();
const settings = {};
for (const r of rows) {
if (PAYMENT_PRIVATE_KEYS.has(r.key)) continue;
if (PRIVATE_KEYS.has(r.key)) continue;
if (ENCRYPTED_KEYS.has(r.key)) {
// Return a sentinel so the UI knows the value is set, without exposing it.
// smtp_user (email address) we can safely return as-is after decryption so
@@ -89,7 +94,7 @@ const updateSettings = async (req, res) => {
}
const ops = Object.entries(updates)
.filter(([k, v]) => v !== undefined && v !== null && !PAYMENT_PRIVATE_KEYS.has(k))
.filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k))
.map(([key, value]) => {
let storedValue = String(value);
@@ -128,7 +133,7 @@ const updateSettings = async (req, res) => {
actorRole: req.user.role,
action: 'settings_updated',
targetType: 'AppSetting',
metadata: { changedKeys: Object.keys(updates).filter(k => updates[k] !== undefined && updates[k] !== null && !PAYMENT_PRIVATE_KEYS.has(k)) },
metadata: { changedKeys: Object.keys(updates).filter(k => updates[k] !== undefined && updates[k] !== null && !PRIVATE_KEYS.has(k)) },
ip: getClientIp(req),
});
}
@@ -205,7 +210,7 @@ const runSetup = async (req, res) => {
const toSave = { ...settings, setup_complete: 'true' };
const ops = Object.entries(toSave)
.filter(([k, v]) => v !== undefined && v !== null && String(v).trim() !== '' && !PAYMENT_PRIVATE_KEYS.has(k))
.filter(([k, v]) => v !== undefined && v !== null && String(v).trim() !== '' && !PRIVATE_KEYS.has(k))
.map(([key, value]) => {
let storedValue = String(value);
if (ENCRYPTED_KEYS.has(key)) storedValue = encrypt(storedValue);
+123
View File
@@ -0,0 +1,123 @@
/**
* 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): show "Reconnect".
if (e.code === 'INSTALL_NOT_FOUND') return { ok: false, reconnect: true };
throw e;
}
}
module.exports = { PROTOCOL_VERSION, HUB_KEYS, hubUrl, HubError, connect, heartbeat };
+93
View File
@@ -0,0 +1,93 @@
/**
* Licence checks (docs/hub-protocol.md §4). The Hub signs a licence token with its private
* key; this install checks it with the public key and works out its state, offline:
*
* active — everything works
* grace — past the end date for up to graceDays: works, site admins see a banner
* suspended — suspended by the Hub, or grace ran out: read-only (no new events,
* registrations or payments); tickets still scan, data can be exported
* revoked — like suspended, with a permanent banner
* unlicensed — never connected to the Hub: works, admins see "Connect to Hub"
*/
const crypto = require('crypto');
const prisma = require('../config/db');
const { hubPublicKey } = require('./publicKey');
const DAY = 24 * 60 * 60 * 1000;
const READ_ONLY_STATES = new Set(['suspended', 'revoked']);
const CACHE_MS = 30 * 1000;
let publicKeyObject = null;
let publicKeyPem = null;
function publicKey() {
const pem = hubPublicKey();
if (!pem) return null;
if (pem !== publicKeyPem) {
publicKeyObject = crypto.createPublicKey(pem);
publicKeyPem = pem;
}
return publicKeyObject;
}
/** The token's claims if the Hub signed it, else null. */
function verifyToken(token, key = publicKey()) {
if (!key) return null;
const parts = String(token || '').split('.');
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
try {
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), key, Buffer.from(parts[2], 'base64url'));
return ok ? JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) : null;
} catch {
return null;
}
}
/**
* The state for verified claims (or null = never connected). Pure, for tests.
* Returns { state, readOnly, endsAt, graceEndsAt, daysLeft }.
*/
function stateFor(claims, installId, now = new Date()) {
if (!claims || (installId && claims.installId !== installId)) {
return { state: 'unlicensed', readOnly: false, endsAt: null, graceEndsAt: null, daysLeft: null };
}
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map(d => new Date(d));
const endsAt = ends.length ? new Date(Math.min(...ends)) : null;
const graceEndsAt = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
let state;
if (claims.status === 'revoked') state = 'revoked';
else if (claims.status === 'suspended') state = 'suspended';
else if (!endsAt || now < endsAt) state = 'active';
else if (now < graceEndsAt) state = 'grace';
else state = 'suspended';
const daysLeft = state === 'grace' ? Math.max(0, Math.ceil((graceEndsAt - now) / DAY)) : null;
return { state, readOnly: READ_ONLY_STATES.has(state), endsAt, graceEndsAt, daysLeft, expired: state === 'suspended' && claims.status === 'active' };
}
let cache = null;
/** This install's licence: claims, state and Hub connection details. Cached for 30 s. */
async function licenceStatus({ fresh = false } = {}) {
if (!fresh && cache && Date.now() - cache.at < CACHE_MS) return cache.value;
const rows = await prisma.appSetting.findMany({ where: { key: { in: ['hub_install_id', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version'] } } });
const s = Object.fromEntries(rows.map(r => [r.key, r.value]));
const claims = verifyToken(s.hub_licence);
const value = {
keyConfigured: !!publicKey(),
connected: !!s.hub_install_id,
installId: s.hub_install_id || null,
claims: claims && claims.installId === s.hub_install_id ? claims : null,
...stateFor(claims, s.hub_install_id || null),
lastHeartbeatAt: s.hub_last_heartbeat_at || null,
lastError: s.hub_last_error || null,
latestVersion: s.hub_latest_version || null,
};
cache = { at: Date.now(), value };
return value;
}
function clearLicenceCache() {
cache = null;
}
module.exports = { verifyToken, stateFor, licenceStatus, clearLicenceCache, READ_ONLY_STATES };
+17
View File
@@ -0,0 +1,17 @@
/**
* The Hope Events Hub's public licence key (Ed25519). Installs check every licence token with
* it, so a licence can't be faked by editing the database. The matching private key exists
* only on the Hub server (events-hub repo, `npm run generate-keys`).
*
* Set PRODUCTION_PUBLIC_KEY to the key the production Hub prints, before the release that ships
* the Hub connection. HUB_PUBLIC_KEY (env) overrides it — for a local Hub while developing.
*/
const PRODUCTION_PUBLIC_KEY = null;
function hubPublicKey() {
const fromEnv = (process.env.HUB_PUBLIC_KEY || '').replace(/\\n/g, '\n').trim();
return fromEnv || PRODUCTION_PUBLIC_KEY;
}
module.exports = { hubPublicKey, PRODUCTION_PUBLIC_KEY };
+48
View File
@@ -0,0 +1,48 @@
/**
* Read-only mode while the licence is suspended or revoked: no *new* activity — new events,
* registrations, tickets added, payments started or recorded, waitlist places, coupons or bundles.
* Everything else keeps working on purpose: scanning tickets for events people already paid for,
* viewing and exporting data, refunds and cancellations, privacy requests, logging in, and the
* settings needed to renew the licence. Payment webhooks for payments already started also still
* arrive (they're mounted before this middleware).
*/
const { licenceStatus } = require('./licence');
const BLOCKED = [
['POST', /^\/api\/events\/?$/],
['POST', /^\/api\/events\/[^/]+\/options\/?$/],
['POST', /^\/api\/events\/options\/[^/]+\/variants\/?$/],
['POST', /^\/api\/registrations\/?$/],
['POST', /^\/api\/registrations\/manual\/?$/],
['PUT', /^\/api\/registrations\/[^/]+\/options\/?$/],
['POST', /^\/api\/payments\/?$/],
['POST', /^\/api\/payments\/(checkout|yoco-checkout)(\/send)?\/?$/],
['POST', /^\/api\/payments\/pay\/[^/]+\/?$/],
['POST', /^\/api\/waitlist\/?$/],
['POST', /^\/api\/coupons\/?$/],
['POST', /^\/api\/bundles\/event\/[^/]+\/?$/],
];
function isBlocked(method, path) {
return BLOCKED.some(([m, re]) => m === method && re.test(path));
}
async function licenceReadOnly(req, res, next) {
if (!isBlocked(req.method, req.path)) return next();
try {
const status = await licenceStatus();
if (!status.readOnly) return next();
return res.status(403).json({
code: 'LICENCE_READ_ONLY',
message: status.state === 'revoked'
? "This site's licence has been revoked, so nothing new can be added. Tickets still scan and all data can still be viewed and exported."
: "This site's licence is suspended, so nothing new can be added for now. Tickets still scan and all data can still be viewed and exported. Please contact the site's administrator.",
});
} catch {
// Never let a licence check failure take the site down.
return next();
}
}
module.exports = { licenceReadOnly, isBlocked, BLOCKED };
+148
View File
@@ -0,0 +1,148 @@
/**
* What this install tells the Hub (docs/hub-protocol.md §3): health, and aggregate counts —
* no personal information. Income goes as a range, never an amount.
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const prisma = require('../config/db');
const errorCounter = require('../utils/errorCounter');
const DAY = 24 * 60 * 60 * 1000;
const APP_VERSION = require('../../package.json').version;
const STARTED_AT = Date.now();
const INCOME_BANDS = [
[1000, 'R0–R1 000'],
[5000, 'R1 001–R5 000'],
[20000, 'R5 001–R20 000'],
[50000, 'R20 001–R50 000'],
[100000, 'R50 001–R100 000'],
];
/** The range an amount falls in: "R5 001–R20 000", or "over R100 000". */
function incomeBand(amount) {
const rand = Math.max(0, Math.round(Number(amount) || 0));
for (const [max, label] of INCOME_BANDS) if (rand <= max) return label;
return 'over R100 000';
}
async function postgresVersion() {
try {
const rows = await prisma.$queryRawUnsafe('SHOW server_version');
return String(rows[0]?.server_version || '').split(' ')[0] || null;
} catch {
return null;
}
}
/** Migrations in the repo that the database hasn't applied. */
async function pendingMigrations() {
try {
const dir = path.join(__dirname, '..', '..', 'prisma', 'migrations');
const folders = fs.readdirSync(dir, { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name);
const rows = await prisma.$queryRawUnsafe('SELECT migration_name FROM "_prisma_migrations" WHERE finished_at IS NOT NULL AND rolled_back_at IS NULL');
const applied = new Set(rows.map(r => r.migration_name));
return folders.filter(f => !applied.has(f)).length;
} catch {
return null;
}
}
async function disk() {
try {
const s = await fs.promises.statfs(path.join(__dirname, '..', '..'));
return { freeBytes: s.bavail * s.bsize, totalBytes: s.blocks * s.bsize };
} catch {
return null;
}
}
async function jobsHealth() {
try {
const { jobStatus } = require('../jobs');
const status = await jobStatus(prisma);
const since = Date.now() - DAY;
const failed = status.jobs.flatMap(j => j.recent).filter(r => r.state === 'failed' && new Date(r.completedOn || r.startedOn || 0).getTime() > since).length;
return { mode: status.mode, failedLast24h: failed };
} catch {
return null;
}
}
async function lastBackupAt() {
try {
const backups = await require('../utils/backupUtils').listBackups();
return backups[0]?.createdAt ? new Date(backups[0].createdAt).toISOString() : null;
} catch {
return null;
}
}
async function health() {
let db = true;
try { await prisma.$queryRawUnsafe('SELECT 1'); } catch { db = false; }
const [jobs, backupAt, diskInfo, pending] = await Promise.all([jobsHealth(), lastBackupAt(), disk(), pendingMigrations()]);
return {
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
db,
jobs,
lastBackupAt: backupAt,
disk: diskInfo,
errorsLast24h: errorCounter.countLast24h(),
pendingMigrations: pending,
};
}
async function stats(now = new Date()) {
const since = new Date(now.getTime() - 30 * DAY);
const realUser = { isActive: true, NOT: [{ email: { endsWith: '@deleted.invalid' } }, { email: { endsWith: '@guest.local' } }] };
const [users, activeEvents, upcomingEvents, totalEvents, regs30, regsTotal, tickets30, ticketsTotal, checkIns30, income30, incomeAll, providers] = await Promise.all([
prisma.user.count({ where: realUser }),
prisma.event.count({ where: { isActive: true, startDate: { lte: now }, endDate: { gte: now } } }),
prisma.event.count({ where: { isActive: true, startDate: { gt: now } } }),
prisma.event.count(),
prisma.registration.count({ where: { createdAt: { gte: since } } }),
prisma.registration.count(),
prisma.ticket.count({ where: { createdAt: { gte: since } } }),
prisma.ticket.count(),
prisma.ticketUsage.count({ where: { scannedAt: { gte: since } } }),
prisma.payment.aggregate({ where: { createdAt: { gte: since } }, _sum: { amount: true } }),
prisma.payment.aggregate({ _sum: { amount: true } }),
require('../payments').availableProviders().then(list => list.map(p => p.id)).catch(() => []),
]);
return {
users,
events: { active: activeEvents, upcoming: upcomingEvents, total: totalEvents },
registrations: { last30d: regs30, total: regsTotal },
tickets: { last30d: tickets30, total: ticketsTotal },
checkIns: { last30d: checkIns30 },
// Messages aren't logged one by one, so there's nothing to count yet.
messages: null,
paymentProviders: providers,
campuses: false,
income: { last30d: incomeBand(income30._sum.amount), allTime: incomeBand(incomeAll._sum.amount) },
};
}
/** What the install says about itself when registering. */
async function installInfo() {
const { getSetting } = require('../utils/settingsCache');
const [name, url, waConfigured, providers] = await Promise.all([
getSetting('org_name', ''),
getSetting('app_base_url', process.env.FRONTEND_URL || ''),
require('../utils/whatsapp').isConfigured().catch(() => false),
require('../payments').availableProviders().then(list => list.map(p => p.id)).catch(() => []),
]);
return {
name: name || 'Hope Events',
url: String(url || process.env.FRONTEND_URL || '').split(',')[0].trim().replace(/\/$/, ''),
version: APP_VERSION,
timezone: process.env.APP_TIMEZONE || 'Africa/Johannesburg',
server: { node: process.versions.node, postgres: await postgresVersion(), os: `${os.platform()} ${os.release()}` },
features: { whatsapp: !!waConfigured, paymentProviders: providers, campuses: false },
};
}
module.exports = { APP_VERSION, incomeBand, health, stats, installInfo };
+37
View File
@@ -156,7 +156,32 @@ app.use('/api/webhooks', webhookRoutes);
// Apply JSON body parser for all non-webhook routes
app.use(express.json());
// Count server errors (any 5xx response) for the Hub heartbeat.
app.use((req, res, next) => {
res.on('finish', () => { if (res.statusCode >= 500) require('./utils/errorCounter').recordError(); });
next();
});
// Licence suspended or revoked: no new events, registrations or payments (src/hub/readOnly.js).
app.use(require('./hub/readOnly').licenceReadOnly);
// Health for monitoring (and the Hub): no secrets, no personal information.
app.get('/health', async (req, res) => {
const report = require('./hub/report');
let db = true;
try { await prisma.$queryRaw`SELECT 1`; } catch { db = false; }
const health = db ? await report.health().catch(() => null) : null;
res.status(db ? 200 : 503).json({
status: db ? 'ok' : 'error',
version: report.APP_VERSION,
db,
jobs: health?.jobs || null,
lastBackupAt: health?.lastBackupAt || null,
});
});
// Use routes
app.use('/api/hub', require('./routes/hubRoutes'));
app.use('/api/users', userRoutes);
app.use('/api/events', eventRoutes);
app.use('/api/registrations', registrationRoutes);
@@ -886,6 +911,18 @@ app.get('/docs', async (req, res) => {
responses:[{ status:200, desc:'Success', body:[{ eventId:'ev-uuid-...', title:'Camp 2025', totalTickets:50, scanned:38, remaining:12 }]}]},
]},
{ title: 'Hub and licence', base: '/api/hub', endpoints: [
{ method:'GET', path:'/health', auth:'public', desc:'Status, version, database, background jobs and last backup (503 if the database is down)',
responses:[{ status:200, desc:'Healthy', body:{ status:'ok', version:'1.41.0', db:true, jobs:{ mode:'queue', failedLast24h:0 }, lastBackupAt:'2026-10-26T00:00:12.000Z' }}]},
{ method:'GET', path:'/api/hub/status', auth:'admin', desc:'Licence state (active, grace, suspended, revoked, unlicensed), Hub connection, version and update',
responses:[{ status:200, desc:'Success', body:{ state:'grace', readOnly:false, daysLeft:9, connected:true, version:'1.41.0', latestVersion:'1.42.0', updateAvailable:true }}]},
{ method:'POST', path:'/api/hub/connect', auth:'admin', desc:'Connect to the Hope Events Hub with a licence key (also the /setup licence step)',
request:{ body:{ licenceKey:'CEH-7K2M-9QXA-P4RT-WD8C' } },
responses:[{ status:200, desc:'Connected (status as above)' }, { status:404, desc:'Unknown key', body:{ code:'LICENCE_NOT_FOUND', message:'That licence key was not found.' }}]},
{ method:'POST', path:'/api/hub/heartbeat', auth:'admin', desc:'Check in with the Hub now (picks up licence changes)',
responses:[{ status:200, desc:'Status' }, { status:502, desc:'Hub unreachable' }]},
]},
{ title: 'Privacy (POPIA)', base: '/api/privacy', endpoints: [
{ method:'GET', path:'/api/privacy/me', auth:'user', desc:'My news opt-in, its history, and my privacy requests',
responses:[{ status:200, desc:'Success', body:{ news:{ email:true, whatsapp:false }, newsAskedAt:'2026-10-23T08:00:00.000Z', canWhatsApp:false, notificationPreference:'email', history:[{ channel:'email', granted:true, source:'signup', createdAt:'2026-10-23T08:00:00.000Z' }], requests:[] }}]},
+4
View File
@@ -56,6 +56,10 @@ const JOBS = [
name: 'privacy', label: 'Privacy requests: remind admins of requests due soon', cron: '0 8 * * *', env: 'PRIVACY_JOBS_ENABLED',
run: () => require('../utils/privacy').remindDueRequests(new Date()),
},
{
name: 'hub-heartbeat', label: 'Hope Events Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED',
run: () => require('../hub/client').heartbeat(),
},
{
name: 'retention', label: 'Retention: delete or anonymise personal information past its retention period', cron: '30 3 * * *', env: 'RETENTION_JOBS_ENABLED',
run: () => require('../utils/retention').runRetention(new Date()),
@@ -0,0 +1,12 @@
const express = require('express');
const router = express.Router();
const { getStatus, connect, heartbeatNow } = require('../controllers/hubController');
const { protect, admin } = require('../middleware/authMiddleware');
// Licence and the Hope Events Hub (docs/hub-protocol.md). Admins only; the setup wizard's
// admin token counts, so the licence step can run during /setup.
router.get('/status', protect, admin, getStatus);
router.post('/connect', protect, admin, connect);
router.post('/heartbeat', protect, admin, heartbeatNow);
module.exports = router;
@@ -0,0 +1,17 @@
// Server errors (5xx responses) in the last 24 hours, for the Hub heartbeat. In memory per
// process: a restart starts again from zero, which is fine for spotting a spike.
const WINDOW_MS = 24 * 60 * 60 * 1000;
const MAX_KEPT = 10000;
let times = [];
function recordError(now = Date.now()) {
times.push(now);
if (times.length > MAX_KEPT) times = times.slice(-MAX_KEPT);
}
function countLast24h(now = Date.now()) {
times = times.filter(t => now - t < WINDOW_MS);
return times.length;
}
module.exports = { recordError, countLast24h };