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:
@@ -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 };
|
||||
Reference in New Issue
Block a user