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
+138
View File
@@ -0,0 +1,138 @@
/**
* The API installs call (docs/hub-protocol.md): public key, register, heartbeat.
* Install → Hub only; these are the only endpoints that aren't behind an admin login.
*/
const express = require('express');
const rateLimit = require('express-rate-limit');
const prisma = require('../config/db');
const { encrypt, decrypt, normaliseLicenceKey, randomSecret } = require('../utils/crypto');
const licenceToken = require('../utils/licenceToken');
const { checkSignature } = require('../utils/signing');
const { getSettings } = require('../utils/settings');
const router = express.Router();
const PROTOCOL_VERSIONS = [1];
const HEARTBEAT_MINUTES = 15;
const registerLimiter = rateLimit({ windowMs: 60 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts.', code: 'RATE_LIMITED' } });
const heartbeatLimiter = rateLimit({ windowMs: 60 * 1000, max: 30, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests.', code: 'RATE_LIMITED' } });
const fail = (res, status, code, message) => res.status(status).json({ code, message });
function protocolOk(body) {
const minSupported = Math.max(...PROTOCOL_VERSIONS) - 1;
const v = body?.protocolVersion;
return Number.isInteger(v) && v >= minSupported && v <= Math.max(...PROTOCOL_VERSIONS);
}
// Only small, known pieces of what an install says about itself are kept.
const str = (v, max = 200) => (v == null ? null : String(v).slice(0, max));
function cleanUrl(url) {
try {
const u = new URL(String(url));
if (!/^https?:$/.test(u.protocol)) return null;
return `${u.protocol}//${u.host}${u.pathname.replace(/\/$/, '')}`;
} catch {
return null;
}
}
async function tokenFor(install) {
const licence = install.licenceId ? await prisma.licence.findUnique({ where: { id: install.licenceId }, include: { customer: { select: { name: true } } } }) : null;
if (!licence) return null;
return licenceToken.sign(licenceToken.buildPayload(licence, install, licence.customer.name));
}
router.get('/public-key', (req, res) => {
res.json({ protocolVersions: PROTOCOL_VERSIONS, keyId: 'k1', algorithm: 'Ed25519', publicKey: licenceToken.keyPair().publicKeyPem });
});
router.post('/installs/register', registerLimiter, async (req, res) => {
try {
const body = req.body || {};
if (!protocolOk(body)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${body.protocolVersion} is not supported; this Hub speaks ${PROTOCOL_VERSIONS.join(', ')}.`);
const info = body.install || {};
const url = cleanUrl(info.url);
if (!url) return fail(res, 400, 'BAD_URL', 'The install needs its public web address (https://…).');
const licence = await prisma.licence.findUnique({ where: { key: normaliseLicenceKey(body.licenceKey) }, include: { install: true, customer: true } });
if (!licence) return fail(res, 404, 'LICENCE_NOT_FOUND', 'That licence key was not found. Check it, or ask your provider for your key.');
if (licence.status === 'revoked') return fail(res, 403, 'LICENCE_REVOKED', 'This licence has been revoked.');
if (licence.install && licence.install.url !== url) {
return fail(res, 409, 'LICENCE_IN_USE', 'This licence is already used by another site. Ask your provider to release it if you have moved.');
}
const secret = randomSecret();
const data = {
name: str(info.name) || licence.customer.name,
url,
secret: encrypt(secret),
version: str(info.version, 40),
protocolVersion: body.protocolVersion,
adminContact: info.adminContact ? { name: str(info.adminContact.name), email: str(info.adminContact.email) } : undefined,
server: info.server ? { node: str(info.server.node, 40), postgres: str(info.server.postgres, 40), os: str(info.server.os, 80) } : undefined,
timezone: str(info.timezone, 60),
features: info.features && typeof info.features === 'object' ? info.features : undefined,
releasedAt: null,
};
// Same licence, same site → re-register (new secret, same id).
const install = licence.install
? await prisma.install.update({ where: { id: licence.install.id }, data })
: await prisma.install.create({ data: { ...data, customerId: licence.customerId, licenceId: licence.id } });
await prisma.installEvent.create({ data: { installId: install.id, type: 'registered', level: 'info', message: `${licence.install ? 'Re-registered' : 'Registered'} from ${url} (version ${install.version || '?'})`, resolvedAt: new Date() } });
const settings = await getSettings();
res.status(201).json({
installId: install.id,
installSecret: secret,
licence: await tokenFor(install),
heartbeatIntervalMinutes: HEARTBEAT_MINUTES,
latestVersion: settings.latest_version || null,
});
} catch (e) {
console.error('[register]', e);
fail(res, 500, 'SERVER_ERROR', 'The Hub could not register this install. Try again later.');
}
});
router.post('/installs/heartbeat', heartbeatLimiter, async (req, res) => {
try {
const installId = String(req.headers['x-hub-install'] || '');
const install = installId ? await prisma.install.findUnique({ where: { id: installId } }) : null;
if (!install || install.releasedAt) return fail(res, 404, 'INSTALL_NOT_FOUND', 'This install is not registered with the Hub. Reconnect it in Site settings.');
const problem = checkSignature({
secret: decrypt(install.secret),
timestamp: String(req.headers['x-hub-timestamp'] || ''),
rawBody: req.rawBody || '',
given: String(req.headers['x-hub-signature'] || ''),
});
if (problem === 'STALE_REQUEST') return fail(res, 401, problem, "The request's time is too far from the Hub's — check the server clock.");
if (problem) return fail(res, 401, problem, 'The request signature is not valid.');
const body = req.body || {};
if (!protocolOk(body)) return fail(res, 400, 'UNSUPPORTED_PROTOCOL', `Protocol ${body.protocolVersion} is not supported.`);
const now = new Date();
const version = str(body.version, 40);
const health = body.health && typeof body.health === 'object' ? body.health : null;
const stats = body.stats && typeof body.stats === 'object' ? body.stats : null;
await prisma.$transaction([
prisma.heartbeat.create({ data: { installId: install.id, receivedAt: now, version, health: health || undefined, stats: stats || undefined } }),
prisma.install.update({ where: { id: install.id }, data: { lastHeartbeatAt: now, version, protocolVersion: body.protocolVersion, health: health || undefined, stats: stats || undefined } }),
]);
if (version && install.version && version !== install.version) {
await prisma.installEvent.create({ data: { installId: install.id, type: 'version', level: 'info', message: `Updated from ${install.version} to ${version}`, resolvedAt: now } });
}
const settings = await getSettings();
res.json({ licence: await tokenFor(install), latestVersion: settings.latest_version || null, serverTime: now.toISOString() });
} catch (e) {
console.error('[heartbeat]', e);
fail(res, 500, 'SERVER_ERROR', 'The Hub could not record this heartbeat.');
}
});
module.exports = router;
module.exports.PROTOCOL_VERSIONS = PROTOCOL_VERSIONS;