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
@@ -0,0 +1,150 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes, fmtDate, rand } from "@/lib/format";
import type { Health, InstallEvent, InstallSummary, Licence, Stats } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
type Detail = {
id: string; name: string; url: string; version: string | null; protocolVersion: number; timezone: string | null; notes: string | null;
adminContact: { name?: string; email?: string } | null; server: { node?: string; postgres?: string; os?: string } | null;
features: Record<string, unknown> | null; registeredAt: string; lastHeartbeatAt: string | null; releasedAt: string | null;
health: Health | null; stats: Stats | null;
customer: { id: string; name: string };
licence: (Licence & { tokenPreview: { status: string; validUntil: string; licenceExpiresAt: string | null } }) | null;
summary: InstallSummary;
events: InstallEvent[];
heartbeats: { receivedAt: string; version: string | null; stats: Stats | null }[];
};
const Row = ({ k, v }: { k: string; v: React.ReactNode }) => (
<div className="flex justify-between gap-4 border-b border-slate-100 py-1.5 text-sm last:border-0"><span className="text-slate-500">{k}</span><span className="text-right">{v}</span></div>
);
/** One install: health, usage, licence, history. */
export default function InstallPage() {
const { id } = useParams<{ id: string }>();
const [d, setD] = useState<Detail | null>(null);
const [notes, setNotes] = useState("");
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(() => api<Detail>(`/api/admin/installs/${id}`).then(x => { setD(x); setNotes(x.notes || ""); }).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => { load(); }, [load]);
if (!d) return msg ? <Message msg={msg} /> : <Loading />;
const h = d.health || {};
const s = d.stats || {};
const diskPct = h.disk && h.disk.totalBytes ? Math.round((h.disk.freeBytes / h.disk.totalBytes) * 100) : null;
// One point per day for the last 30 days: registrations in the last 30 days, as reported.
const daily = new Map<string, number>();
for (const b of d.heartbeats) daily.set(b.receivedAt.slice(0, 10), b.stats?.registrations?.last30d ?? 0);
const points = [...daily.entries()];
const max = Math.max(1, ...points.map(([, v]) => v));
const saveNotes = async () => {
try {
await api(`/api/admin/installs/${id}`, { method: "PUT", body: { notes } });
setMsg({ type: "ok", text: "Notes saved." });
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<>
<Link href="/" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Installs</Link>
<PageTitle
title={d.customer.name}
subtitle={<a href={d.url} target="_blank" rel="noopener noreferrer" className="text-indigo-600 hover:underline">{d.url}</a>}
actions={<Badge value={d.summary.status} />}
/>
{d.releasedAt && <div className="mb-4"><Message msg={{ type: "err", text: `Licence released ${fmtDate(d.releasedAt)} — this install's heartbeats are refused.` }} /></div>}
{d.summary.problems.length > 0 && (
<div className="card mb-6 space-y-1">
{d.summary.problems.map(p => <div key={p.type} className="flex items-center gap-2 text-sm"><Badge value={p.level} /> {p.message}</div>)}
</div>
)}
<div className="grid gap-6 md:grid-cols-2">
<div className="card">
<h2 className="mb-2 font-semibold">Health</h2>
<Row k="Last heartbeat" v={`${ago(d.lastHeartbeatAt)} (${fmtDate(d.lastHeartbeatAt)})`} />
<Row k="Version" v={`${d.version || "—"}${d.summary.behind ? " (behind)" : ""}`} />
<Row k="Database" v={h.db === false ? "Not OK" : h.db ? "OK" : "—"} />
<Row k="Background jobs" v={h.jobs ? `${h.jobs.mode || "?"}, ${h.jobs.failedLast24h ?? 0} failed (24 h)` : "—"} />
<Row k="Last backup" v={h.lastBackupAt ? `${ago(h.lastBackupAt)}` : "none reported"} />
<Row k="Disk free" v={h.disk ? `${bytes(h.disk.freeBytes)} of ${bytes(h.disk.totalBytes)} (${diskPct}%)` : "—"} />
<Row k="Errors (24 h)" v={h.errorsLast24h ?? "—"} />
<Row k="Pending migrations" v={h.pendingMigrations ?? "—"} />
<Row k="Uptime" v={h.uptimeSeconds != null ? `${Math.round(h.uptimeSeconds / 3600)} h` : "—"} />
</div>
<div className="card">
<h2 className="mb-2 font-semibold">Usage</h2>
<Row k="Users" v={s.users ?? "—"} />
<Row k="Events (active / upcoming / total)" v={s.events ? `${s.events.active ?? 0} / ${s.events.upcoming ?? 0} / ${s.events.total ?? 0}` : "—"} />
<Row k="Registrations (30 days / total)" v={s.registrations ? `${s.registrations.last30d ?? 0} / ${s.registrations.total ?? 0}` : "—"} />
<Row k="Tickets (30 days / total)" v={s.tickets ? `${s.tickets.last30d ?? 0} / ${s.tickets.total ?? 0}` : "—"} />
<Row k="Check-ins (30 days)" v={s.checkIns?.last30d ?? "—"} />
<Row k="Messages (30 days)" v={s.messages ? `${s.messages.email30d ?? 0} email, ${s.messages.whatsapp30d ?? 0} WhatsApp` : "—"} />
<Row k="Income (30 days / all time)" v={s.income ? `${s.income.last30d || "—"} / ${s.income.allTime || "—"}` : "—"} />
<Row k="Payment providers" v={s.paymentProviders?.join(", ") || "—"} />
{points.length > 1 && (
<div className="mt-3">
<div className="mb-1 text-xs text-slate-500">Registrations in the last 30 days, per day reported</div>
<div className="flex h-16 items-end gap-0.5">
{points.map(([day, v]) => <div key={day} title={`${day}: ${v}`} className="flex-1 rounded-t bg-indigo-300" style={{ height: `${(v / max) * 100}%` }} />)}
</div>
</div>
)}
</div>
<div className="card">
<h2 className="mb-2 font-semibold">Licence</h2>
{d.licence ? (
<>
<Row k="Key" v={<code className="text-xs">{d.licence.key}</code>} />
<Row k="Status" v={<Badge value={d.licence.status} />} />
<Row k="Expires" v={d.licence.expiresAt ? fmtDate(d.licence.expiresAt, false) : "no end date"} />
<Row k="Grace" v={`${d.licence.graceDays} days`} />
<Row k="AI cap (2.0)" v={d.licence.aiMonthlyCapCents ? `${rand(d.licence.aiMonthlyCapCents)} / month` : "off"} />
<Link href={`/customers/${d.customer.id}`} className="mt-3 inline-block text-sm text-indigo-600 hover:underline">Change the licence →</Link>
</>
) : <p className="text-sm text-slate-500">No licence (released).</p>}
</div>
<div className="card">
<h2 className="mb-2 font-semibold">About</h2>
<Row k="Admin contact" v={d.adminContact ? `${d.adminContact.name || ""} ${d.adminContact.email ? `<${d.adminContact.email}>` : ""}` : "—"} />
<Row k="Server" v={d.server ? `Node ${d.server.node || "?"}, Postgres ${d.server.postgres || "?"}, ${d.server.os || "?"}` : "—"} />
<Row k="Time zone" v={d.timezone || "—"} />
<Row k="Registered" v={fmtDate(d.registeredAt)} />
<Row k="Protocol" v={d.protocolVersion} />
<label className="label mt-3" htmlFor="notes">Notes</label>
<textarea id="notes" className="input" rows={3} value={notes} onChange={e => setNotes(e.target.value)} />
<button className="btn-secondary mt-2" onClick={saveNotes}>Save notes</button>
</div>
</div>
{msg && <div className="mt-4"><Message msg={msg} /></div>}
<div className="card mt-6">
<h2 className="mb-3 font-semibold">History</h2>
{d.events.length === 0 ? <p className="text-sm text-slate-500">Nothing yet.</p> : (
<ul className="space-y-2 text-sm">
{d.events.map(e => (
<li key={e.id} className="flex flex-wrap items-center gap-2">
<span className="w-40 shrink-0 text-xs text-slate-500">{fmtDate(e.createdAt)}</span>
<Badge value={e.level} />
<span>{e.message}</span>
{e.level !== "info" && <span className="text-xs text-slate-400">{e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"}</span>}
</li>
))}
</ul>
)}
</div>
</>
);
}