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
+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 };