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
+48
View File
@@ -0,0 +1,48 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import type { InstallEvent } from "@/lib/types";
import { Badge, Loading, PageTitle } from "@/components/ui";
/** Open alerts, and the history of everything that happened to installs. */
export default function AlertsPage() {
const [openOnly, setOpenOnly] = useState(true);
const [events, setEvents] = useState<InstallEvent[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setEvents(null);
api<InstallEvent[]>(`/api/admin/events${openOnly ? "?open=true" : ""}`).then(setEvents).catch(e => setError(errorText(e)));
}, [openOnly]);
return (
<>
<PageTitle title="Alerts" subtitle="Checked every 5 minutes. New warnings and critical alerts are emailed once (Settings → Alert email)." />
<div className="mb-4 flex gap-2">
<button className={openOnly ? "btn-primary" : "btn-secondary"} onClick={() => setOpenOnly(true)}>Open</button>
<button className={!openOnly ? "btn-primary" : "btn-secondary"} onClick={() => setOpenOnly(false)}>Everything</button>
</div>
{error && <p className="text-sm text-red-700">{error}</p>}
{!events ? <Loading /> : events.length === 0 ? <p className="text-sm text-slate-500">{openOnly ? "No open alerts. 🎉" : "Nothing yet."}</p> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">When</th><th className="p-3">Install</th><th className="p-3">What</th><th className="p-3">State</th></tr></thead>
<tbody>
{events.map(e => (
<tr key={e.id} className="border-t align-top">
<td className="p-3 whitespace-nowrap text-xs text-slate-500">{fmtDate(e.createdAt)}</td>
<td className="p-3">{e.install ? <Link href={`/installs/${e.install.id}`} className="text-indigo-700 hover:underline">{e.install.name}</Link> : "—"}</td>
<td className="p-3"><Badge value={e.level} /> <span className="ml-1">{e.message}</span></td>
<td className="p-3 text-xs text-slate-500">{e.level === "info" ? "" : e.resolvedAt ? `resolved ${ago(e.resolvedAt)}` : "open"}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
);
}
@@ -0,0 +1,170 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ArrowLeft, Copy, KeyRound } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import type { Customer, Licence, LicenceStatus } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
type Msg = { type: "ok" | "err"; text: string } | null;
const dateInput = (d: string | null) => (d ? d.slice(0, 10) : "");
/** One licence: its key, and the settings that go into the next token the install receives. */
function LicenceCard({ licence, onSaved, setMsg }: { licence: Licence; onSaved: () => void; setMsg: (m: Msg) => void }) {
const [form, setForm] = useState({
status: licence.status,
expiresAt: dateInput(licence.expiresAt),
graceDays: String(licence.graceDays),
aiRand: String(licence.aiMonthlyCapCents / 100),
notes: licence.notes || "",
});
const [busy, setBusy] = useState(false);
const save = async () => {
if (form.status !== licence.status && form.status !== "active" && !confirm(`${form.status === "revoked" ? "Revoke" : "Suspend"} this licence? The site becomes read-only after its next heartbeat (tickets still scan, data can still be exported).`)) return;
setBusy(true);
try {
await api(`/api/admin/licences/${licence.id}`, {
method: "PUT",
body: {
status: form.status,
// End of the chosen day, South African time.
expiresAt: form.expiresAt ? `${form.expiresAt}T23:59:59+02:00` : null,
graceDays: form.graceDays,
aiMonthlyCapCents: Math.round((parseFloat(form.aiRand) || 0) * 100),
notes: form.notes,
},
});
setMsg({ type: "ok", text: "Licence saved. The site picks it up with its next heartbeat (within 15 minutes)." });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); } finally { setBusy(false); }
};
const release = async () => {
if (!confirm("Release this licence from its site? The site's heartbeats are refused from now on, and the key can be registered again from a new address.")) return;
try {
await api(`/api/admin/licences/${licence.id}/release`, { method: "POST" });
setMsg({ type: "ok", text: "Released." });
onSaved();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
return (
<div className="card space-y-3">
<div className="flex flex-wrap items-center gap-2">
<KeyRound className="h-4 w-4 text-slate-400" />
<code className="text-sm font-semibold tracking-wide">{licence.key}</code>
<button className="text-xs text-indigo-600 hover:underline" onClick={() => navigator.clipboard?.writeText(licence.key)} aria-label="Copy key"><Copy className="inline h-3.5 w-3.5" /> Copy</button>
<span className="ml-auto"><Badge value={licence.status} /></span>
</div>
<div className="text-sm text-slate-600">
{licence.install
? <>Used by <Link href={`/installs/${licence.install.id}`} className="text-indigo-600 hover:underline">{licence.install.url}</Link> · last heartbeat {ago(licence.install.lastHeartbeatAt)}</>
: "Not used yet — enter this key in the church's Hope Events setup (or Site settings → Licence)."}
</div>
<div className="grid gap-3 sm:grid-cols-4">
<div>
<label className="label">Status</label>
<select className="input" value={form.status} onChange={e => setForm({ ...form, status: e.target.value as LicenceStatus })}>
<option value="active">Active</option>
<option value="suspended">Suspended</option>
<option value="revoked">Revoked</option>
</select>
</div>
<div>
<label className="label">Expires</label>
<input type="date" className="input" value={form.expiresAt} onChange={e => setForm({ ...form, expiresAt: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{form.expiresAt ? "" : "No end date"}</p>
</div>
<div>
<label className="label">Grace (days)</label>
<input type="number" min={0} max={90} className="input" value={form.graceDays} onChange={e => setForm({ ...form, graceDays: e.target.value })} />
</div>
<div>
<label className="label">AI cap (R / month)</label>
<input type="number" min={0} step="1" className="input" value={form.aiRand} onChange={e => setForm({ ...form, aiRand: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">0 = off. Used from 2.0.</p>
</div>
</div>
<div>
<label className="label">Notes</label>
<input className="input" value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="e.g. paid annually, invoice #123" />
</div>
<div className="flex flex-wrap gap-2">
<button className="btn-primary" onClick={save} disabled={busy}>{busy ? "Saving…" : "Save licence"}</button>
{licence.install && <button className="btn-danger" onClick={release}>Release from site</button>}
<span className="self-center text-xs text-slate-400">Created {fmtDate(licence.createdAt, false)}</span>
</div>
</div>
);
}
export default function CustomerPage() {
const { id } = useParams<{ id: string }>();
const [c, setC] = useState<Customer | null>(null);
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "", notes: "" });
const [newLicence, setNewLicence] = useState({ expiresAt: "", graceDays: "14" });
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => api<Customer>(`/api/admin/customers/${id}`).then(x => {
setC(x);
setForm({ name: x.name, contactName: x.contactName || "", email: x.email || "", phone: x.phone || "", notes: x.notes || "" });
}).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => { load(); }, [load]);
if (!c) return msg ? <Message msg={msg} /> : <Loading />;
const saveDetails = async (e: React.FormEvent) => {
e.preventDefault();
try {
await api(`/api/admin/customers/${id}`, { method: "PUT", body: form });
setMsg({ type: "ok", text: "Saved." });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const generate = async (e: React.FormEvent) => {
e.preventDefault();
try {
const l = await api<Licence>(`/api/admin/customers/${id}/licences`, {
method: "POST",
body: { expiresAt: newLicence.expiresAt ? `${newLicence.expiresAt}T23:59:59+02:00` : null, graceDays: newLicence.graceDays },
});
setMsg({ type: "ok", text: `Licence ${l.key} created. Send it to the church for their setup.` });
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<Link href="/customers" className="mb-2 inline-flex items-center gap-1 text-sm text-slate-500 hover:underline"><ArrowLeft className="h-4 w-4" /> Customers</Link>
<PageTitle title={c.name} subtitle={`Customer since ${fmtDate(c.createdAt, false)}`} />
<div className="mb-4"><Message msg={msg} /></div>
<div className="grid gap-6 lg:grid-cols-[1fr_2fr]">
<form onSubmit={saveDetails} className="card space-y-3 self-start">
<h2 className="font-semibold">Details</h2>
<div><label className="label">Name</label><input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required /></div>
<div><label className="label">Contact person</label><input className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<div><label className="label">Email</label><input type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
<div><label className="label">Phone</label><input className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div><label className="label">Notes</label><textarea className="input" rows={4} value={form.notes} onChange={e => setForm({ ...form, notes: e.target.value })} placeholder="Plan, billing, anything worth remembering" /></div>
<button className="btn-secondary">Save details</button>
</form>
<div className="space-y-4">
<h2 className="font-semibold">Licences</h2>
{c.licences.map(l => <LicenceCard key={`${l.id}-${l.status}-${l.expiresAt}`} licence={l} onSaved={load} setMsg={setMsg} />)}
<form onSubmit={generate} className="card flex flex-wrap items-end gap-3">
<div><label className="label">Expires (optional)</label><input type="date" className="input" value={newLicence.expiresAt} onChange={e => setNewLicence({ ...newLicence, expiresAt: e.target.value })} /></div>
<div><label className="label">Grace (days)</label><input type="number" min={0} max={90} className="input w-24" value={newLicence.graceDays} onChange={e => setNewLicence({ ...newLicence, graceDays: e.target.value })} /></div>
<button className="btn-primary"><KeyRound className="h-4 w-4" /> Generate licence</button>
</form>
</div>
</div>
</>
);
}
+61
View File
@@ -0,0 +1,61 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago } from "@/lib/format";
import type { Customer } from "@/lib/types";
import { Badge, Loading, Message, PageTitle } from "@/components/ui";
export default function CustomersPage() {
const router = useRouter();
const [list, setList] = useState<Customer[] | null>(null);
const [adding, setAdding] = useState(false);
const [form, setForm] = useState({ name: "", contactName: "", email: "", phone: "" });
const [msg, setMsg] = useState<{ type: "ok" | "err"; text: string } | null>(null);
const load = useCallback(() => api<Customer[]>("/api/admin/customers").then(setList).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
useEffect(() => { load(); }, [load]);
const add = async (e: React.FormEvent) => {
e.preventDefault();
try {
const c = await api<Customer>("/api/admin/customers", { method: "POST", body: form });
router.push(`/customers/${c.id}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<>
<PageTitle title="Customers" subtitle="Churches and organisations with a licence." actions={!adding && <button className="btn-primary" onClick={() => setAdding(true)}><Plus className="h-4 w-4" /> Add customer</button>} />
{adding && (
<form onSubmit={add} className="card mb-6 grid gap-3 md:grid-cols-2">
<div className="md:col-span-2"><label className="label" htmlFor="name">Name</label><input id="name" className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required placeholder="Hope Family Church" /></div>
<div><label className="label" htmlFor="contact">Contact person</label><input id="contact" className="input" value={form.contactName} onChange={e => setForm({ ...form, contactName: e.target.value })} /></div>
<div><label className="label" htmlFor="email">Email</label><input id="email" type="email" className="input" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} /></div>
<div><label className="label" htmlFor="phone">Phone</label><input id="phone" className="input" value={form.phone} onChange={e => setForm({ ...form, phone: e.target.value })} /></div>
<div className="flex items-end gap-2"><button className="btn-primary">Save</button><button type="button" className="btn-secondary" onClick={() => setAdding(false)}>Cancel</button></div>
</form>
)}
<Message msg={msg} />
{!list ? <Loading /> : list.length === 0 ? <p className="text-sm text-slate-500">No customers yet.</p> : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500"><tr><th className="p-3">Customer</th><th className="p-3">Licences</th><th className="p-3">Site</th></tr></thead>
<tbody>
{list.map(c => (
<tr key={c.id} className="border-t hover:bg-slate-50">
<td className="p-3"><Link href={`/customers/${c.id}`} className="font-medium text-indigo-700 hover:underline">{c.name}</Link><div className="text-xs text-slate-500">{[c.contactName, c.email].filter(Boolean).join(" · ")}</div></td>
<td className="p-3">{c.licences.length ? c.licences.map(l => <span key={l.id} className="mr-1"><Badge value={l.status} /></span>) : <span className="text-xs text-slate-400">none</span>}</td>
<td className="p-3">{c.installs.length ? c.installs.map(i => <div key={i.id} className="text-xs">{i.url} <span className="text-slate-400">· {ago(i.lastHeartbeatAt)}</span></div>) : <span className="text-xs text-slate-400">not connected</span>}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
);
}
@@ -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>
</>
);
}
+64
View File
@@ -0,0 +1,64 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut } from "lucide-react";
import { api, getToken, setToken } from "@/lib/api";
type Me = { id: string; name: string; email: string };
const NAV = [
{ href: "/", label: "Installs", icon: LayoutDashboard },
{ href: "/customers", label: "Customers", icon: Building2 },
{ href: "/alerts", label: "Alerts", icon: BellRing },
{ href: "/settings", label: "Settings", icon: Settings },
];
/** Everything except /login: requires a session, with the side navigation. */
export default function HubLayout({ children }: { children: React.ReactNode }) {
const router = useRouter();
const pathname = usePathname();
const [me, setMe] = useState<Me | null>(null);
useEffect(() => {
if (!getToken()) { router.replace("/login"); return; }
api<Me>("/api/auth/me").then(setMe).catch(() => router.replace("/login"));
}, [router]);
if (!me) return <div className="flex min-h-screen items-center justify-center text-sm text-slate-400">Loading…</div>;
const active = (href: string) => (href === "/" ? pathname === "/" || pathname.startsWith("/installs") : pathname.startsWith(href));
return (
<div className="flex min-h-screen">
<aside className="hidden w-56 shrink-0 border-r border-slate-200 bg-white p-4 md:flex md:flex-col">
<div className="mb-6 px-2">
<div className="text-base font-semibold">Hope Events Hub</div>
<div className="text-xs text-slate-500">{me.name}</div>
</div>
<nav className="space-y-1">
{NAV.map(n => {
const Icon = n.icon;
return (
<Link key={n.href} href={n.href} className={`flex items-center gap-2 rounded-lg px-3 py-2 text-sm ${active(n.href) ? "bg-indigo-50 font-medium text-indigo-700" : "text-slate-600 hover:bg-slate-50"}`}>
<Icon className="h-4 w-4" /> {n.label}
</Link>
);
})}
</nav>
<button onClick={() => { setToken(null); router.replace("/login"); }} className="mt-auto flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-slate-600 hover:bg-slate-50">
<LogOut className="h-4 w-4" /> Sign out
</button>
</aside>
<div className="flex-1 min-w-0">
<nav className="flex gap-1 overflow-x-auto border-b border-slate-200 bg-white px-3 py-2 md:hidden">
{NAV.map(n => (
<Link key={n.href} href={n.href} className={`whitespace-nowrap rounded-lg px-3 py-1.5 text-sm ${active(n.href) ? "bg-indigo-50 font-medium text-indigo-700" : "text-slate-600"}`}>{n.label}</Link>
))}
</nav>
<main className="mx-auto max-w-6xl p-4 md:p-8">{children}</main>
</div>
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { ago, fmtDate } from "@/lib/format";
import type { InstallSummary } from "@/lib/types";
import { Badge, Loading, PageTitle, Stat } from "@/components/ui";
type Dashboard = {
latestVersion: string | null;
counts: { installs: number; healthy: number; warning: number; critical: number; behind: number; customers: number; openAlerts: number; licences: Record<string, number> };
installs: InstallSummary[];
};
/** Every install at a glance: health, version, licence, last heartbeat. */
export default function OverviewPage() {
const [data, setData] = useState<Dashboard | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const load = () => api<Dashboard>("/api/admin/dashboard").then(d => { setData(d); setError(null); }).catch(e => setError(errorText(e)));
load();
const t = setInterval(load, 60_000);
return () => clearInterval(t);
}, []);
if (error) return <p className="text-sm text-red-700">{error}</p>;
if (!data) return <Loading />;
const c = data.counts;
return (
<>
<PageTitle title="Installs" subtitle={data.latestVersion ? `Latest release: ${data.latestVersion}` : "Set the latest release in Settings to see who is behind."} />
<div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-5">
<Stat label="Installs" value={c.installs} />
<Stat label="Healthy" value={c.healthy} tone="green" />
<Stat label="Warnings" value={c.warning} tone={c.warning ? "amber" : undefined} />
<Stat label="Critical" value={c.critical} tone={c.critical ? "red" : undefined} />
<Stat label="Behind latest" value={c.behind} tone={c.behind ? "amber" : undefined} />
</div>
{data.installs.length === 0 ? (
<div className="card text-sm text-slate-600">
No installs yet. Add a <Link href="/customers" className="text-indigo-600 hover:underline">customer</Link>, generate a licence, and enter its key in the church&apos;s Hope Events setup.
</div>
) : (
<div className="card overflow-x-auto p-0">
<table className="w-full text-sm">
<thead className="bg-slate-50 text-left text-xs text-slate-500">
<tr><th className="p-3">Install</th><th className="p-3">Health</th><th className="p-3">Version</th><th className="p-3">Licence</th><th className="p-3">Last heartbeat</th></tr>
</thead>
<tbody>
{data.installs.map(i => (
<tr key={i.id} className="border-t align-top hover:bg-slate-50">
<td className="p-3">
<Link href={`/installs/${i.id}`} className="font-medium text-indigo-700 hover:underline">{i.customer?.name || i.name}</Link>
<div className="text-xs text-slate-500">{i.url}</div>
</td>
<td className="p-3">
<Badge value={i.status} />
{i.problems.filter(p => p.level !== "info").map(p => <div key={p.type} className="mt-1 text-xs text-slate-600">{p.message}</div>)}
</td>
<td className="p-3 whitespace-nowrap">{i.version || "—"}{i.behind && <span className="ml-1 text-xs text-amber-700">(behind)</span>}</td>
<td className="p-3 whitespace-nowrap">
{i.licence ? <><Badge value={i.licence.status} />{i.licence.expiresAt && <div className="mt-1 text-xs text-slate-500">to {fmtDate(i.licence.expiresAt, false)}</div>}</> : <span className="text-xs text-slate-400">none</span>}
</td>
<td className="p-3 whitespace-nowrap" title={fmtDate(i.lastHeartbeatAt)}>{ago(i.lastHeartbeatAt)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</>
);
}
+117
View File
@@ -0,0 +1,117 @@
"use client";
import React, { useEffect, useState } from "react";
import { api, errorText, setToken } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
type Settings = Record<string, string>;
type AuditRow = { id: string; action: string; target: string | null; metadata: unknown; createdAt: string; actor: { name: string } | null };
type Msg = { type: "ok" | "err"; text: string } | null;
const FIELDS: { key: string; label: string; hint: string; type?: string }[] = [
{ key: "latest_version", label: "Latest Hope Events release", hint: "e.g. 1.41.0 — installs on an older version show as behind, and see \"Update available\"." },
{ key: "alert_email", label: "Alert email", hint: "Where new alerts are sent.", type: "email" },
{ key: "offline_minutes", label: "Offline after (minutes without a heartbeat)", hint: "Default 60.", type: "number" },
{ key: "backup_max_age_hours", label: "Backup too old after (hours)", hint: "Default 48.", type: "number" },
{ key: "disk_min_free_percent", label: "Disk low below (% free)", hint: "Default 10.", type: "number" },
{ key: "errors_per_day", label: "Errors spiking above (per 24 h)", hint: "Default 50.", type: "number" },
{ key: "licence_expiry_warning_days", label: "Warn about licence expiry (days before)", hint: "Default 14.", type: "number" },
];
export default function SettingsPage() {
const [settings, setSettings] = useState<Settings | null>(null);
const [publicKey, setPublicKey] = useState("");
const [smtp, setSmtp] = useState(false);
const [audit, setAudit] = useState<AuditRow[]>([]);
const [pw, setPw] = useState({ currentPassword: "", newPassword: "" });
const [msg, setMsg] = useState<Msg>(null);
useEffect(() => {
api<{ settings: Settings; publicKey: string; smtp: boolean }>("/api/admin/settings").then(r => { setSettings(r.settings); setPublicKey(r.publicKey); setSmtp(r.smtp); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<AuditRow[]>("/api/admin/audit").then(setAudit).catch(() => {});
}, []);
if (!settings) return msg ? <Message msg={msg} /> : <Loading />;
const save = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ settings: Settings }>("/api/admin/settings", { method: "PUT", body: { settings } });
setSettings(r.settings);
setMsg({ type: "ok", text: "Settings saved." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const changePassword = async (e: React.FormEvent) => {
e.preventDefault();
try {
const r = await api<{ token: string }>("/api/auth/password", { method: "POST", body: pw });
setToken(r.token);
setPw({ currentPassword: "", newPassword: "" });
setMsg({ type: "ok", text: "Password changed. Other devices are signed out." });
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const signOutEverywhere = async () => {
if (!confirm("Sign out on every device, including this one?")) return;
await api("/api/auth/logout-everywhere", { method: "POST" }).catch(() => {});
setToken(null);
window.location.href = "/login";
};
return (
<>
<PageTitle title="Settings" />
<div className="mb-4"><Message msg={msg} /></div>
<div className="grid gap-6 lg:grid-cols-2">
<form onSubmit={save} className="card space-y-4">
<h2 className="font-semibold">Releases and alerts</h2>
{!smtp && <p className="rounded-lg bg-amber-50 p-3 text-sm text-amber-900">Email isn&apos;t set up on this server (SMTP_* in .env), so alerts are only logged.</p>}
{FIELDS.map(f => (
<div key={f.key}>
<label className="label" htmlFor={f.key}>{f.label}</label>
<input id={f.key} className="input" type={f.type || "text"} value={settings[f.key] ?? ""} onChange={e => setSettings({ ...settings, [f.key]: e.target.value })} />
<p className="mt-1 text-xs text-slate-500">{f.hint}</p>
</div>
))}
<button className="btn-primary">Save settings</button>
</form>
<div className="space-y-6">
<div className="card space-y-2">
<h2 className="font-semibold">Licence signing key</h2>
<p className="text-sm text-slate-600">Installs check licences with this public key (built into Hope Events: <code>backend/src/hub/publicKey.js</code>). The private key stays on this server only — keep a backup.</p>
<pre className="overflow-x-auto rounded-lg bg-slate-50 p-3 text-xs">{publicKey}</pre>
</div>
<form onSubmit={changePassword} className="card space-y-3">
<h2 className="font-semibold">Your login</h2>
<div><label className="label">Current password</label><input type="password" className="input" autoComplete="current-password" value={pw.currentPassword} onChange={e => setPw({ ...pw, currentPassword: e.target.value })} required /></div>
<div><label className="label">New password (12+ characters)</label><input type="password" className="input" autoComplete="new-password" minLength={12} value={pw.newPassword} onChange={e => setPw({ ...pw, newPassword: e.target.value })} required /></div>
<div className="flex flex-wrap gap-2">
<button className="btn-secondary">Change password</button>
<button type="button" className="btn-danger" onClick={signOutEverywhere}>Sign out everywhere</button>
</div>
</form>
</div>
</div>
<div className="card mt-6">
<h2 className="mb-3 font-semibold">Audit log</h2>
{audit.length === 0 ? <p className="text-sm text-slate-500">Nothing yet.</p> : (
<ul className="space-y-1 text-sm">
{audit.map(a => (
<li key={a.id} className="flex flex-wrap gap-2">
<span className="w-40 shrink-0 text-xs text-slate-500">{fmtDate(a.createdAt)}</span>
<span className="font-medium">{a.actor?.name || "—"}</span>
<span>{a.action.replace(/_/g, " ")}</span>
{a.metadata ? <span className="text-xs text-slate-400 break-all">{JSON.stringify(a.metadata)}</span> : null}
</li>
))}
</ul>
)}
</div>
</>
);
}
+17
View File
@@ -0,0 +1,17 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
@apply bg-slate-50 text-slate-900 antialiased;
}
@layer components {
.input { @apply w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500; }
.btn { @apply inline-flex items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-sm font-medium disabled:opacity-50; }
.btn-primary { @apply btn bg-indigo-600 text-white hover:bg-indigo-700; }
.btn-secondary { @apply btn border border-slate-300 bg-white text-slate-700 hover:bg-slate-50; }
.btn-danger { @apply btn border border-red-300 bg-white text-red-700 hover:bg-red-50; }
.card { @apply rounded-xl border border-slate-200 bg-white p-5 shadow-sm; }
.label { @apply mb-1 block text-sm font-medium text-slate-700; }
}
+16
View File
@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "Hope Events Hub",
description: "Installs, licences and health for Hope Events",
robots: { index: false, follow: false },
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}
+96
View File
@@ -0,0 +1,96 @@
"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { api, errorText, setToken } from "@/lib/api";
type LoginResponse = { token?: string; twoFactorRequired?: boolean; challengeToken?: string; setupRequired?: boolean; setupToken?: string };
type SetupResponse = { secret: string; otpauthUrl: string; qrDataUrl: string };
/** Email + password, then the authenticator code — or, the first time, setting up the app. */
export default function LoginPage() {
const router = useRouter();
const [step, setStep] = useState<"password" | "code" | "setup">("password");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [code, setCode] = useState("");
const [stepToken, setStepToken] = useState("");
const [setup, setSetup] = useState<SetupResponse | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const run = async (fn: () => Promise<void>) => {
setBusy(true);
setError(null);
try { await fn(); } catch (e) { setError(errorText(e)); } finally { setBusy(false); }
};
const done = (token: string) => { setToken(token); router.replace("/"); };
const submitPassword = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const r = await api<LoginResponse>("/api/auth/login", { method: "POST", body: { email, password }, auth: false });
if (r.setupRequired && r.setupToken) {
setStepToken(r.setupToken);
setSetup(await api<SetupResponse>("/api/auth/2fa/setup", { method: "POST", body: { setupToken: r.setupToken }, auth: false }));
setStep("setup");
} else if (r.challengeToken) {
setStepToken(r.challengeToken);
setStep("code");
}
});
};
const submitCode = (e: React.FormEvent) => {
e.preventDefault();
run(async () => {
const path = step === "setup" ? "/api/auth/2fa/confirm" : "/api/auth/2fa";
const body = step === "setup" ? { setupToken: stepToken, code } : { challengeToken: stepToken, code };
const r = await api<{ token: string }>(path, { method: "POST", body, auth: false });
done(r.token);
});
};
return (
<div className="flex min-h-screen items-center justify-center p-4">
<div className="card w-full max-w-sm">
<h1 className="text-xl font-semibold">Hope Events Hub</h1>
{step === "password" && (
<form onSubmit={submitPassword} className="mt-5 space-y-4">
<div>
<label className="label" htmlFor="email">Email</label>
<input id="email" className="input" type="email" autoComplete="username" value={email} onChange={e => setEmail(e.target.value)} required />
</div>
<div>
<label className="label" htmlFor="password">Password</label>
<input id="password" className="input" type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} required />
</div>
<button className="btn-primary w-full" disabled={busy}>{busy ? "Checking…" : "Continue"}</button>
</form>
)}
{step !== "password" && (
<form onSubmit={submitCode} className="mt-5 space-y-4">
{step === "setup" && setup && (
<div className="space-y-2 text-sm text-slate-600">
<p>Two-factor is required. Scan this with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password…), then enter the code it shows.</p>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={setup.qrDataUrl} alt="QR code for your authenticator app" className="mx-auto h-44 w-44" />
<p className="break-all text-xs text-slate-500">Or type this key: <code>{setup.secret}</code></p>
</div>
)}
{step === "code" && <p className="text-sm text-slate-600">Enter the 6-digit code from your authenticator app.</p>}
<div>
<label className="label" htmlFor="code">Code</label>
<input id="code" className="input tracking-widest" inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={code} onChange={e => setCode(e.target.value.replace(/\D/g, ""))} required autoFocus />
</div>
<button className="btn-primary w-full" disabled={busy || code.length !== 6}>{busy ? "Checking…" : step === "setup" ? "Turn on and log in" : "Log in"}</button>
<button type="button" className="w-full text-sm text-slate-500 hover:underline" onClick={() => { setStep("password"); setCode(""); setError(null); }}>Start again</button>
</form>
)}
{error && <p className="mt-4 text-sm text-red-700">{error}</p>}
</div>
</div>
);
}