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
+238
View File
@@ -0,0 +1,238 @@
/** The Hub dashboard's API (admin login required). */
const express = require('express');
const prisma = require('../config/db');
const { protect } = require('../middleware/auth');
const { licenceKey } = require('../utils/crypto');
const { audit } = require('../utils/audit');
const { getSettings, setSettings } = require('../utils/settings');
const { problems, compareVersions } = require('../utils/alerts');
const licenceToken = require('../utils/licenceToken');
const router = express.Router();
router.use(protect);
const wrap = fn => (req, res) => fn(req, res).catch(e => {
const status = e.status || 500;
if (status >= 500) console.error('[admin]', e);
res.status(status).json({ message: status >= 500 ? 'Something went wrong.' : e.message });
});
const bad = (message, status = 400) => Object.assign(new Error(message), { status });
const text = (v, max = 500) => (v == null || String(v).trim() === '' ? null : String(v).trim().slice(0, max));
function dateOrNull(v) {
if (v == null || v === '') return null;
const d = new Date(v);
if (Number.isNaN(d.getTime())) throw bad('Not a valid date.');
return d;
}
// The health of an install at a glance, for lists.
function summary(install, settings, now = new Date()) {
const current = problems(install, settings, now);
const worst = current.some(p => p.level === 'critical') ? 'critical' : current.some(p => p.level === 'warning') ? 'warning' : 'ok';
return {
id: install.id,
name: install.name,
url: install.url,
customer: install.customer ? { id: install.customer.id, name: install.customer.name } : null,
version: install.version,
behind: !!(settings.latest_version && install.version && compareVersions(install.version, settings.latest_version) < 0),
licence: install.licence ? { id: install.licence.id, status: install.licence.status, expiresAt: install.licence.expiresAt } : null,
lastHeartbeatAt: install.lastHeartbeatAt,
status: worst,
problems: current,
releasedAt: install.releasedAt,
};
}
// ─── Dashboard ────────────────────────────────────────────────────────────────
router.get('/dashboard', wrap(async (req, res) => {
const settings = await getSettings();
const installs = await prisma.install.findMany({ where: { releasedAt: null }, include: { licence: true, customer: true }, orderBy: { name: 'asc' } });
const rows = installs.map(i => summary(i, settings));
const [customers, licences, openAlerts] = await Promise.all([
prisma.customer.count(),
prisma.licence.groupBy({ by: ['status'], _count: { _all: true } }),
prisma.installEvent.count({ where: { resolvedAt: null, level: { not: 'info' } } }),
]);
res.json({
latestVersion: settings.latest_version || null,
counts: {
installs: rows.length,
healthy: rows.filter(r => r.status === 'ok').length,
warning: rows.filter(r => r.status === 'warning').length,
critical: rows.filter(r => r.status === 'critical').length,
behind: rows.filter(r => r.behind).length,
customers,
licences: Object.fromEntries(licences.map(l => [l.status, l._count._all])),
openAlerts,
},
installs: rows,
});
}));
// ─── Customers ────────────────────────────────────────────────────────────────
router.get('/customers', wrap(async (req, res) => {
const customers = await prisma.customer.findMany({
orderBy: { name: 'asc' },
include: { licences: { select: { id: true, status: true, expiresAt: true } }, installs: { where: { releasedAt: null }, select: { id: true, url: true, lastHeartbeatAt: true } } },
});
res.json(customers);
}));
function customerData(body, { partial = false } = {}) {
const data = {};
for (const f of ['name', 'contactName', 'email', 'phone', 'notes']) if (body?.[f] !== undefined) data[f] = text(body[f], f === 'notes' ? 5000 : 200);
if ((!partial || 'name' in data) && !data.name) throw bad('Give the customer a name.');
return data;
}
router.post('/customers', wrap(async (req, res) => {
const customer = await prisma.customer.create({ data: customerData(req.body) });
await audit(req, 'customer_created', customer.id, { name: customer.name });
res.status(201).json(customer);
}));
router.get('/customers/:id', wrap(async (req, res) => {
const customer = await prisma.customer.findUnique({
where: { id: req.params.id },
include: { licences: { orderBy: { createdAt: 'desc' }, include: { install: { select: { id: true, name: true, url: true, lastHeartbeatAt: true } } } }, installs: { orderBy: { registeredAt: 'desc' } } },
});
if (!customer) throw bad('Customer not found', 404);
res.json(customer);
}));
router.put('/customers/:id', wrap(async (req, res) => {
const customer = await prisma.customer.update({ where: { id: req.params.id }, data: customerData(req.body, { partial: true }) }).catch(() => { throw bad('Customer not found', 404); });
await audit(req, 'customer_updated', customer.id, { name: customer.name });
res.json(customer);
}));
// ─── Licences ─────────────────────────────────────────────────────────────────
function licenceData(body, { partial = false } = {}) {
const data = {};
if (body?.plan !== undefined) data.plan = text(body.plan, 50) || 'standard';
if (body?.expiresAt !== undefined) data.expiresAt = dateOrNull(body.expiresAt);
if (body?.graceDays !== undefined) {
const n = parseInt(body.graceDays, 10);
if (!Number.isInteger(n) || n < 0 || n > 90) throw bad('Grace period: 0–90 days.');
data.graceDays = n;
}
if (body?.aiMonthlyCapCents !== undefined) {
const n = parseInt(body.aiMonthlyCapCents, 10);
if (!Number.isInteger(n) || n < 0) throw bad('The AI cap must be 0 or more.');
data.aiMonthlyCapCents = n;
}
if (body?.status !== undefined) {
if (!['active', 'suspended', 'revoked'].includes(body.status)) throw bad('Status must be active, suspended or revoked.');
data.status = body.status;
}
if (body?.notes !== undefined) data.notes = text(body.notes, 5000);
if (!partial && data.status === undefined) data.status = 'active';
return data;
}
// "Generate": a new licence with a fresh key for a customer.
router.post('/customers/:id/licences', wrap(async (req, res) => {
const customer = await prisma.customer.findUnique({ where: { id: req.params.id } });
if (!customer) throw bad('Customer not found', 404);
let licence;
for (let attempt = 0; !licence && attempt < 5; attempt++) {
licence = await prisma.licence.create({ data: { ...licenceData(req.body), customerId: customer.id, key: licenceKey() } }).catch(e => (e.code === 'P2002' ? null : Promise.reject(e)));
}
await audit(req, 'licence_generated', licence.id, { customer: customer.name, expiresAt: licence.expiresAt });
res.status(201).json(licence);
}));
router.put('/licences/:id', wrap(async (req, res) => {
const existing = await prisma.licence.findUnique({ where: { id: req.params.id } });
if (!existing) throw bad('Licence not found', 404);
const data = licenceData(req.body, { partial: true });
const licence = await prisma.licence.update({ where: { id: existing.id }, data });
await audit(req, 'licence_updated', licence.id, { changed: Object.keys(data), status: licence.status, expiresAt: licence.expiresAt });
res.json(licence);
}));
// Free the licence from its install (e.g. the church moved to a new address): the old install's
// heartbeats are refused, and the licence can be registered again from the new site.
router.post('/licences/:id/release', wrap(async (req, res) => {
const licence = await prisma.licence.findUnique({ where: { id: req.params.id }, include: { install: true } });
if (!licence) throw bad('Licence not found', 404);
if (!licence.install) throw bad('This licence is not in use.');
await prisma.install.update({ where: { id: licence.install.id }, data: { licenceId: null, releasedAt: new Date() } });
await prisma.installEvent.create({ data: { installId: licence.install.id, type: 'released', level: 'info', message: 'Licence released from this install', resolvedAt: new Date() } });
await audit(req, 'licence_released', licence.id, { install: licence.install.url });
res.json({ message: 'Released.' });
}));
// ─── Installs ─────────────────────────────────────────────────────────────────
router.get('/installs', wrap(async (req, res) => {
const settings = await getSettings();
const installs = await prisma.install.findMany({ include: { licence: true, customer: true }, orderBy: { name: 'asc' } });
res.json(installs.map(i => summary(i, settings)));
}));
router.get('/installs/:id', wrap(async (req, res) => {
const settings = await getSettings();
const install = await prisma.install.findUnique({
where: { id: req.params.id },
include: { licence: true, customer: true, events: { orderBy: { createdAt: 'desc' }, take: 100 } },
});
if (!install) throw bad('Install not found', 404);
const since = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const heartbeats = await prisma.heartbeat.findMany({
where: { installId: install.id, receivedAt: { gte: since } },
orderBy: { receivedAt: 'asc' },
select: { receivedAt: true, version: true, health: true, stats: true },
});
const { secret, ...safe } = install;
let licence = null;
if (install.licence) {
// What the install would be told right now, for checking.
licence = { ...install.licence, tokenPreview: licenceToken.buildPayload(install.licence, install, install.customer.name) };
}
res.json({ ...safe, licence, summary: summary(install, settings), heartbeats });
}));
router.put('/installs/:id', wrap(async (req, res) => {
const install = await prisma.install.update({ where: { id: req.params.id }, data: { notes: text(req.body?.notes, 5000) } }).catch(() => { throw bad('Install not found', 404); });
await audit(req, 'install_notes_updated', install.id);
res.json({ id: install.id, notes: install.notes });
}));
// ─── Alerts and history ───────────────────────────────────────────────────────
router.get('/events', wrap(async (req, res) => {
const where = req.query.open === 'true' ? { resolvedAt: null, level: { not: 'info' } } : {};
const events = await prisma.installEvent.findMany({
where, orderBy: { createdAt: 'desc' }, take: 200,
include: { install: { select: { id: true, name: true, url: true } } },
});
res.json(events);
}));
router.get('/audit', wrap(async (req, res) => {
res.json(await prisma.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 300, include: { actor: { select: { name: true } } } }));
}));
// ─── Settings ─────────────────────────────────────────────────────────────────
router.get('/settings', wrap(async (req, res) => {
res.json({ settings: await getSettings(), publicKey: licenceToken.keyPair().publicKeyPem, smtp: !!process.env.SMTP_HOST });
}));
router.put('/settings', wrap(async (req, res) => {
const values = req.body?.settings || {};
if (values.latest_version && !/^\d+\.\d+\.\d+$/.test(String(values.latest_version))) throw bad('Latest version looks like 1.41.0.');
const settings = await setSettings(values);
await audit(req, 'settings_updated', null, values);
res.json({ settings });
}));
module.exports = router;
module.exports.summary = summary;