Hub v1: install API, licences, health dashboard, alerts

- Protocol 1 (docs/hub-protocol.md): public key, register, signed heartbeats
- Ed25519 licence tokens (30-day validity, status, expiry, grace, limits)
- Dashboard: installs, install detail, customers and licences, alerts,
  settings and audit log; two-factor login required
- Alert checks every 5 minutes, emailed once; heartbeat roll-up after 30 days
- Unit tests for encryption, tokens, signatures, TOTP and alert rules

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:12:51 +02:00
co-authored by Claude Opus 5.5
commit e72330893a
56 changed files with 16952 additions and 0 deletions
+129
View File
@@ -0,0 +1,129 @@
/**
* Install alerts: which problems an install has right now (pure, testable), and the job
* that opens an InstallEvent (and emails Joshua) when a problem starts, and resolves it when
* it clears — so each problem is emailed once.
*/
const prisma = require('../config/db');
const { getSettings } = require('./settings');
const { sendMail } = require('./mail');
const MIN = 60 * 1000;
const HOUR = 60 * MIN;
const DAY = 24 * HOUR;
/** Compare "1.40.2" with "1.41.0": negative, 0 or positive. */
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;
}
/**
* The problems an install has now: [{ type, level, message }]. `install` needs
* lastHeartbeatAt, health, version, registeredAt, licence (status, expiresAt, graceDays).
*/
function problems(install, settings, now = new Date()) {
const out = [];
const s = {
offlineMin: parseInt(settings.offline_minutes, 10) || 60,
backupHours: parseInt(settings.backup_max_age_hours, 10) || 48,
diskPercent: parseFloat(settings.disk_min_free_percent) || 10,
errorsPerDay: parseInt(settings.errors_per_day, 10) || 50,
expiryDays: parseInt(settings.licence_expiry_warning_days, 10) || 14,
};
const health = install.health || {};
const lastSeen = install.lastHeartbeatAt ? new Date(install.lastHeartbeatAt) : null;
const since = lastSeen || new Date(install.registeredAt);
if (now - since > s.offlineMin * MIN) {
out.push({ type: 'offline', level: 'critical', message: lastSeen ? `No heartbeat since ${lastSeen.toISOString()}` : 'Never sent a heartbeat since registering' });
}
// Health from the last heartbeat (skipped when there is none yet).
if (lastSeen) {
if (health.db === false) out.push({ type: 'database', level: 'critical', message: 'The install reports its database is not OK' });
const backup = health.lastBackupAt ? new Date(health.lastBackupAt) : null;
if (!backup || now - backup > s.backupHours * HOUR) {
out.push({ type: 'backup_stale', level: 'warning', message: backup ? `Last backup ${backup.toISOString()}` : 'No backup reported' });
}
const disk = health.disk;
if (disk && disk.totalBytes > 0 && (disk.freeBytes / disk.totalBytes) * 100 < s.diskPercent) {
out.push({ type: 'disk_low', level: 'warning', message: `Disk ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free` });
}
if (Number.isFinite(health.errorsLast24h) && health.errorsLast24h > s.errorsPerDay) {
out.push({ type: 'errors_high', level: 'warning', message: `${health.errorsLast24h} errors in the last 24 hours` });
}
if (Number.isFinite(health.jobs?.failedLast24h) && health.jobs.failedLast24h > 0) {
out.push({ type: 'jobs_failing', level: 'warning', message: `${health.jobs.failedLast24h} background job run(s) failed in the last 24 hours` });
}
if (health.pendingMigrations > 0) {
out.push({ type: 'pending_migrations', level: 'warning', message: `${health.pendingMigrations} database migration(s) not applied` });
}
}
const lic = install.licence;
if (lic && lic.status === 'active' && lic.expiresAt) {
const left = new Date(lic.expiresAt) - now;
if (left <= 0) out.push({ type: 'licence_expired', level: 'critical', message: `Licence expired ${new Date(lic.expiresAt).toISOString().slice(0, 10)} (grace ${lic.graceDays} days)` });
else if (left <= s.expiryDays * DAY) out.push({ type: 'licence_expiring', level: 'warning', message: `Licence expires ${new Date(lic.expiresAt).toISOString().slice(0, 10)}` });
}
if (settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0) {
out.push({ type: 'behind', level: 'info', message: `Runs ${install.version}; latest is ${settings.latest_version}` });
}
return out;
}
/** Run the checks for every install: open new alerts (emailed unless info), resolve cleared ones. */
async function runAlerts(now = new Date()) {
const settings = await getSettings();
const installs = await prisma.install.findMany({
where: { releasedAt: null },
include: { licence: true, customer: { select: { name: true } }, events: { where: { resolvedAt: null } } },
});
let opened = 0;
let resolved = 0;
const newAlerts = [];
for (const install of installs) {
const current = problems(install, settings, now);
const openByType = new Map(install.events.filter(e => e.type !== 'registered' && e.type !== 'version').map(e => [e.type, e]));
for (const p of current) {
if (openByType.has(p.type)) continue;
await prisma.installEvent.create({ data: { installId: install.id, type: p.type, level: p.level, message: p.message, createdAt: now } });
opened++;
if (p.level !== 'info') newAlerts.push(`• ${install.customer?.name || install.name} (${install.url}): ${p.message}`);
}
const currentTypes = new Set(current.map(p => p.type));
for (const [type, event] of openByType) {
if (currentTypes.has(type)) continue;
await prisma.installEvent.update({ where: { id: event.id }, data: { resolvedAt: now } });
resolved++;
}
}
if (newAlerts.length && settings.alert_email) {
await sendMail({
to: settings.alert_email,
subject: `Hope Events Hub: ${newAlerts.length} new alert${newAlerts.length === 1 ? '' : 's'}`,
text: `${newAlerts.join('\n')}\n\n${(process.env.FRONTEND_URL || '').replace(/\/$/, '')}/`,
}).catch(e => console.warn('[alerts] email failed:', e?.message));
}
return { installs: installs.length, opened, resolved };
}
/** Keep every heartbeat for 30 days, then only the last one of each day per install. */
async function rollupHeartbeats(now = new Date(), db = prisma) {
const cutoff = new Date(now.getTime() - 30 * DAY);
const res = await db.$executeRawUnsafe(`
DELETE FROM "Heartbeat" h
WHERE h."receivedAt" < $1
AND h."id" NOT IN (
SELECT DISTINCT ON ("installId", date_trunc('day', "receivedAt")) "id"
FROM "Heartbeat" WHERE "receivedAt" < $1
ORDER BY "installId", date_trunc('day', "receivedAt"), "receivedAt" DESC
)`, cutoff);
return { deleted: res };
}
module.exports = { compareVersions, problems, runAlerts, rollupHeartbeats };
+16
View File
@@ -0,0 +1,16 @@
const prisma = require('../config/db');
function clientIp(req) {
return req?.ip || req?.socket?.remoteAddress || null;
}
/** Record an admin action. Never throws — logging must not break the action itself. */
async function audit(req, action, target = null, metadata = null) {
try {
await prisma.auditLog.create({ data: { actorId: req?.admin?.id || null, action, target, metadata: metadata || undefined, ip: clientIp(req) } });
} catch (e) {
console.error('[audit] failed:', e?.message);
}
}
module.exports = { audit, clientIp };
+54
View File
@@ -0,0 +1,54 @@
/**
* Secrets at rest (install secrets, two-factor secrets) and random identifiers.
*
* Encryption is AES-256-GCM with a key derived from HUB_ENCRYPTION_KEY, stored as
* "v1:<iv>:<tag>:<ciphertext>" (base64url). The key must not change once installs are
* registered — their secrets couldn't be decrypted any more.
*/
const crypto = require('crypto');
let cachedKey = null;
function key() {
if (cachedKey) return cachedKey;
const secret = process.env.HUB_ENCRYPTION_KEY || '';
if (secret.length < 32) throw new Error('HUB_ENCRYPTION_KEY must be at least 32 characters');
cachedKey = crypto.scryptSync(secret, 'events-hub-secrets-v1', 32);
return cachedKey;
}
function encrypt(plain) {
const iv = crypto.randomBytes(12);
const cipher = crypto.createCipheriv('aes-256-gcm', key(), iv);
const data = Buffer.concat([cipher.update(String(plain), 'utf8'), cipher.final()]);
return ['v1', iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), data.toString('base64url')].join(':');
}
function decrypt(stored) {
const [version, iv, tag, data] = String(stored || '').split(':');
if (version !== 'v1' || !iv || !tag || !data) throw new Error('Not an encrypted value');
const decipher = crypto.createDecipheriv('aes-256-gcm', key(), Buffer.from(iv, 'base64url'));
decipher.setAuthTag(Buffer.from(tag, 'base64url'));
return Buffer.concat([decipher.update(Buffer.from(data, 'base64url')), decipher.final()]).toString('utf8');
}
// No 0/O, 1/I/L, 5/S, 8/B — easy to read out over the phone.
const KEY_ALPHABET = 'ACDEFGHJKMNPQRTUVWXY234679';
/** A licence key: CEH-XXXX-XXXX-XXXX-XXXX (16 characters from 26, ~75 bits of randomness). */
function licenceKey() {
const bytes = crypto.randomBytes(20);
const chars = Array.from(bytes, b => KEY_ALPHABET[b % KEY_ALPHABET.length]).join('');
return `CEH-${chars.slice(0, 4)}-${chars.slice(4, 8)}-${chars.slice(8, 12)}-${chars.slice(12, 16)}`;
}
/** Tidy what someone typed: upper case, no spaces. */
function normaliseLicenceKey(input) {
return String(input || '').toUpperCase().replace(/\s+/g, '').trim();
}
function randomSecret(bytes = 32) {
return crypto.randomBytes(bytes).toString('base64url');
}
module.exports = { encrypt, decrypt, licenceKey, normaliseLicenceKey, randomSecret, KEY_ALPHABET, _resetKeyForTests: () => { cachedKey = null; } };
+65
View File
@@ -0,0 +1,65 @@
/**
* Licence tokens (docs/hub-protocol.md §4): `hel1.<payload>.<signature>`, where payload is
* base64url JSON and signature is Ed25519 over "hel1.<payload>". The Hub signs with its
* private key; installs verify offline with the public key.
*/
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const PREFIX = 'hel1';
const VALID_DAYS = 30;
const DAY = 24 * 60 * 60 * 1000;
let cached = null;
/** The Hub's signing key pair, from HUB_SIGNING_KEY (PEM) or HUB_SIGNING_KEY_FILE. */
function keyPair() {
if (cached) return cached;
let pem = (process.env.HUB_SIGNING_KEY || '').replace(/\\n/g, '\n').trim();
if (!pem && process.env.HUB_SIGNING_KEY_FILE) {
pem = fs.readFileSync(path.resolve(process.env.HUB_SIGNING_KEY_FILE), 'utf8');
}
if (!pem) throw new Error('No licence signing key: set HUB_SIGNING_KEY_FILE (run `npm run generate-keys`)');
const privateKey = crypto.createPrivateKey(pem);
if (privateKey.asymmetricKeyType !== 'ed25519') throw new Error('The licence signing key must be Ed25519');
const publicKey = crypto.createPublicKey(privateKey);
cached = { privateKey, publicKey, publicKeyPem: publicKey.export({ type: 'spki', format: 'pem' }).toString() };
return cached;
}
/** The payload for an install's licence, as of `now`. */
function buildPayload(licence, install, customerName, now = new Date()) {
return {
v: 1,
licenceId: licence.id,
installId: install.id,
customer: customerName,
plan: licence.plan,
status: licence.status,
licenceExpiresAt: licence.expiresAt ? new Date(licence.expiresAt).toISOString() : null,
graceDays: licence.graceDays,
issuedAt: now.toISOString(),
validUntil: new Date(now.getTime() + VALID_DAYS * DAY).toISOString(),
limits: { aiMonthlyCapCents: licence.aiMonthlyCapCents || 0 },
};
}
function sign(payload, privateKey = keyPair().privateKey) {
const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
const signed = `${PREFIX}.${body}`;
const signature = crypto.sign(null, Buffer.from(signed), privateKey).toString('base64url');
return `${signed}.${signature}`;
}
/** The payload if the token is genuine, else null. (The install does the same check.) */
function verify(token, publicKey = keyPair().publicKey) {
const parts = String(token || '').split('.');
if (parts.length !== 3 || parts[0] !== PREFIX) return null;
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), publicKey, Buffer.from(parts[2], 'base64url'));
if (!ok) return null;
try { return JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')); } catch { return null; }
}
module.exports = { PREFIX, VALID_DAYS, keyPair, buildPayload, sign, verify, _resetForTests: () => { cached = null; } };
+27
View File
@@ -0,0 +1,27 @@
const nodemailer = require('nodemailer');
let transporter = null;
function smtpConfigured() {
return !!process.env.SMTP_HOST;
}
/** Send an email; without SMTP it's logged instead (development). */
async function sendMail({ to, subject, text }) {
if (!to) return;
if (!smtpConfigured()) {
console.info(`[mail] (SMTP not set up) to=${to} subject="${subject}"\n${text}`);
return;
}
if (!transporter) {
transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: parseInt(process.env.SMTP_PORT || '587', 10),
secure: String(process.env.SMTP_PORT) === '465',
auth: process.env.SMTP_USER ? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS } : undefined,
});
}
await transporter.sendMail({ from: process.env.SMTP_FROM || 'hub@localhost', to, subject, text });
}
module.exports = { sendMail, smtpConfigured };
+29
View File
@@ -0,0 +1,29 @@
const prisma = require('../config/db');
// Hub settings Joshua edits on the Settings page, with their defaults.
const DEFAULTS = {
latest_version: '',
alert_email: '',
// Alert thresholds
offline_minutes: '60',
backup_max_age_hours: '48',
disk_min_free_percent: '10',
errors_per_day: '50',
licence_expiry_warning_days: '14',
};
async function getSettings() {
const rows = await prisma.setting.findMany();
const saved = Object.fromEntries(rows.map(r => [r.key, r.value]));
return { ...DEFAULTS, ...saved };
}
async function setSettings(values) {
const updates = Object.entries(values || {}).filter(([k]) => k in DEFAULTS);
for (const [key, value] of updates) {
await prisma.setting.upsert({ where: { key }, update: { value: String(value ?? '') }, create: { key, value: String(value ?? '') } });
}
return getSettings();
}
module.exports = { DEFAULTS, getSettings, setSettings };
+28
View File
@@ -0,0 +1,28 @@
/**
* Install → Hub request signing (docs/hub-protocol.md §3):
* X-Hub-Signature = hex HMAC-SHA256(installSecret, timestamp + "." + rawBody).
*/
const crypto = require('crypto');
const MAX_SKEW_MS = 5 * 60 * 1000;
function signature(secret, timestamp, rawBody) {
return crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex');
}
/**
* Check a signed request. Returns null when it's fine, or the error code
* (STALE_REQUEST | BAD_SIGNATURE).
*/
function checkSignature({ secret, timestamp, rawBody, given, now = Date.now() }) {
const at = Date.parse(timestamp || '');
if (!Number.isFinite(at) || Math.abs(now - at) > MAX_SKEW_MS) return 'STALE_REQUEST';
const expected = signature(secret, timestamp, rawBody);
const a = Buffer.from(String(given || ''), 'utf8');
const b = Buffer.from(expected, 'utf8');
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return 'BAD_SIGNATURE';
return null;
}
module.exports = { MAX_SKEW_MS, signature, checkSignature };
+74
View File
@@ -0,0 +1,74 @@
/**
* Two-factor codes from an authenticator app (RFC 6238 TOTP: SHA-1, 6 digits, 30 s), so
* logging in to the Hub doesn't depend on email being set up.
*/
const crypto = require('crypto');
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
const STEP = 30;
function base32Encode(buf) {
let bits = 0;
let value = 0;
let out = '';
for (const byte of buf) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
out += BASE32[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) out += BASE32[(value << (5 - bits)) & 31];
return out;
}
function base32Decode(str) {
let bits = 0;
let value = 0;
const out = [];
for (const ch of String(str).toUpperCase().replace(/=+$/, '')) {
const idx = BASE32.indexOf(ch);
if (idx === -1) continue;
value = (value << 5) | idx;
bits += 5;
if (bits >= 8) {
out.push((value >>> (bits - 8)) & 255);
bits -= 8;
}
}
return Buffer.from(out);
}
function generateSecret() {
return base32Encode(crypto.randomBytes(20));
}
function codeAt(secret, counter) {
const buf = Buffer.alloc(8);
buf.writeBigUInt64BE(BigInt(counter));
const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest();
const offset = hmac[hmac.length - 1] & 0xf;
const num = ((hmac[offset] & 0x7f) << 24) | (hmac[offset + 1] << 16) | (hmac[offset + 2] << 8) | hmac[offset + 3];
return String(num % 1_000_000).padStart(6, '0');
}
/** True if `code` is right for now, or one 30-second step either side (clock drift). */
function verifyCode(secret, code, now = Date.now()) {
const clean = String(code || '').replace(/\D/g, '');
if (clean.length !== 6) return false;
const counter = Math.floor(now / 1000 / STEP);
for (const c of [counter - 1, counter, counter + 1]) {
const expected = codeAt(secret, c);
if (crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(clean))) return true;
}
return false;
}
/** The otpauth:// link an authenticator app scans (as a QR code). */
function otpauthUrl(secret, account, issuer = 'Hope Events Hub') {
return `otpauth://totp/${encodeURIComponent(issuer)}:${encodeURIComponent(account)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
}
module.exports = { generateSecret, verifyCode, otpauthUrl, codeAt, base32Encode, base32Decode, STEP };