Servers and the agent, dashboard (2.1.0): servers, installs, updates, jobs, ports, download page

- Servers: add with a one-time join command, each server's CPU / RAM
  charts (24 h, 7 days, 90 days, spikes over 85% marked, table view),
  configuration, PM2 processes, sites, jobs and alerts.
- Installs: New install (server chooser with free RAM, CPU and sites),
  Link existing, FastPanel steps and Proxy done, schedule / emergency
  update, adopt, uninstall (2FA and the short name).
- Updates: one release to many installs (a batch), planned jobs.
- Jobs with their reports; Ports & defaults; the public download page
  that decrypts an export in the browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 13:18:20 +02:00
co-authored by Claude Opus 5.5
parent 041461f2b5
commit c8359c77e9
13 changed files with 1075 additions and 4 deletions
+1 -1
View File
@@ -91,7 +91,7 @@ router.get('/servers/:id', wrap(async (req, res) => {
server: serverSummary(s),
config: masked(servers.serverConfig(s)),
processes: s.lastStats?.processes || [],
stats: stats.map(x => ({ at: x.at, cpu: x.cpuPercent, cpuPeak: x.cpuPeak, ram: x.ramUsedPercent, ramPeak: x.ramPeak, disk: x.diskUsedPercent })),
stats: stats.map(x => ({ at: x.at, cpuPercent: x.cpuPercent, cpuPeak: x.cpuPeak, ramUsedPercent: x.ramUsedPercent, ramPeak: x.ramPeak, diskUsedPercent: x.diskUsedPercent })),
deployments: s.deployments,
jobs: recentJobs,
alerts: s.alerts,
+1 -1
View File
@@ -317,7 +317,7 @@ async function fastPanelText(d) {
' Allow uploads up to 25 MB.',
'3. Turn on Let\'s Encrypt for the site.',
`4. DNS: ${d.domain} → ${ip || '<central server IP>'} (${dnsOk === true ? 'checked: points there' : dnsOk === false ? 'not yet' : 'not checked: set the central server IP in Settings'})`,
`5. Then click "Proxy done" in the Hub: ${hubUrl()}/servers/deployments/${d.id}`,
`5. Then click "Proxy done" in the Hub: ${hubUrl()}/servers/installs/${d.id}`,
].join('\n');
}
+67
View File
@@ -0,0 +1,67 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { ServersNav, StatusPill, type Job } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
const OUTCOME: Record<string, string> = { ok: "✓", failed: "✗", skipped: "–", "rolled-back": "↺" };
/** One job and its full report: steps, result and the last log lines (§11). */
export default function JobPage() {
const { id } = useParams<{ id: string }>();
const [job, setJob] = useState<Job | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => api<{ job: Job }>(`/api/admin/jobs/${id}`).then(r => setJob(r.job)).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => {
load();
const t = setInterval(() => { if (!job || ["queued", "delivered", "scheduled"].includes(job.status)) load(); }, 10000);
return () => clearInterval(t);
}, [load, job]);
const post = async (path: string, ok: string) => {
try { await api(path, { method: "POST", body: {} }); setMsg({ type: "ok", text: ok }); load(); } catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
if (!job) return <div><ServersNav active="/jobs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const r = job.report;
return (
<div className="space-y-6">
<div>
<PageTitle title={`${job.type}${job.deployment ? `: ${job.deployment.shortName}` : ""}`} subtitle={<>on <Link className="text-indigo-700 hover:underline" href={`/servers/${job.serverId}`}>{job.server?.name}</Link> · {job.id} <StatusPill status={job.status} /></>}
actions={<div className="flex gap-2">
{["queued", "scheduled"].includes(job.status) && <button className="btn-secondary" onClick={() => post(`/api/admin/jobs/${job.id}/cancel`, "Cancelled.")}>Cancel</button>}
{job.type === "purge" && job.status === "queued" && job.message !== "extended" && <button className="btn-secondary" onClick={() => post(`/api/admin/jobs/${job.id}/extend`, "Put off by 30 days.")}>Keep 30 days longer</button>}
</div>} />
<ServersNav active="/jobs" />
<Message msg={msg} />
</div>
<div className="card grid gap-2 text-sm md:grid-cols-2">
<div><span className="text-slate-500">Window:</span> {fmtDate(job.notBefore)} – {fmtDate(job.expiresAt)}</div>
<div><span className="text-slate-500">Handed to the agent:</span> {fmtDate(job.deliveredAt)}</div>
<div><span className="text-slate-500">Finished:</span> {fmtDate(job.finishedAt)}</div>
{job.reason && <div><span className="text-slate-500">Reason:</span> {job.reason}</div>}
{job.message && <div className="md:col-span-2"><span className="text-slate-500">Result:</span> {job.message}</div>}
<div className="md:col-span-2"><span className="text-slate-500">Arguments:</span> <code className="text-xs">{JSON.stringify(job.args)}</code></div>
</div>
{r && (
<>
<div className="card">
<h2 className="font-medium">Steps</h2>
<ol className="mt-3 space-y-1 text-sm">
{r.steps.map((s, i) => <li key={i} className={s.outcome === "failed" ? "text-red-700" : ""}><span className="inline-block w-5" aria-label={s.outcome}>{OUTCOME[s.outcome] || "•"}</span>{s.name}{s.detail && <span className="text-xs text-slate-500"> ({s.detail})</span>}</li>)}
{!r.steps.length && <li className="text-slate-500">No steps reported.</li>}
</ol>
</div>
{Object.keys(r.result || {}).length > 0 && <div className="card"><h2 className="font-medium">Result</h2><pre className="mt-3 overflow-x-auto text-xs">{JSON.stringify(r.result, null, 2)}</pre></div>}
<div className="card"><h2 className="font-medium">Last log lines</h2><pre className="mt-3 max-h-96 overflow-auto rounded-lg bg-slate-900 p-3 text-xs text-slate-100">{(r.log || []).join("\n") || "(none)"}</pre></div>
</>
)}
</div>
);
}
+52
View File
@@ -0,0 +1,52 @@
"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { ServersNav, StatusPill, type Job } from "@/components/servers";
const FILTERS = [
{ key: "", label: "All" },
{ key: "upcoming", label: "Planned and running" },
{ key: "failed", label: "Failed" },
{ key: "rolled_back", label: "Rolled back" },
{ key: "missed", label: "Missed" },
{ key: "refused", label: "Refused" },
];
/** Every job sent to a server's agent, newest first (§11: the full report is on each job). */
export default function JobsPage() {
const [filter, setFilter] = useState("");
const [jobs, setJobs] = useState<Job[] | null>(null);
const [err, setErr] = useState<string | null>(null);
useEffect(() => {
const q = filter === "upcoming" ? "?upcoming=true" : filter ? `?status=${filter}` : "";
setJobs(null);
api<{ jobs: Job[] }>(`/api/admin/jobs${q}`).then(r => setJobs(r.jobs)).catch(e => setErr(errorText(e)));
}, [filter]);
return (
<div>
<PageTitle title="Jobs" subtitle="Installs, updates, adopts, exports, uninstalls and checks run by the agents." />
<ServersNav active="/jobs" />
{err && <Message msg={{ type: "err", text: err }} />}
<div className="mb-4 flex flex-wrap gap-2">{FILTERS.map(f => <button key={f.key} className={filter === f.key ? "btn-primary" : "btn-secondary"} onClick={() => setFilter(f.key)}>{f.label}</button>)}</div>
{!jobs ? <Loading /> : (
<div className="card overflow-x-auto">
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>Server</th><th>Install</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
<tbody>{jobs.map(j => (
<tr key={j.id} className="border-t">
<td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td>{j.server?.name}</td><td>{j.deployment?.shortName || String(j.args?.church || "–")}</td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td>
<td className="max-w-sm truncate text-xs text-slate-500">{j.message}</td>
</tr>
))}</tbody>
</table>
{!jobs.length && <p className="mt-2 text-sm text-slate-500">No jobs.</p>}
</div>
)}
</div>
);
}
+3 -2
View File
@@ -3,7 +3,7 @@
import React, { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone, Receipt } from "lucide-react";
import { LayoutDashboard, Building2, BellRing, Settings, LogOut, Rocket, Megaphone, Receipt, Server } from "lucide-react";
import { api, getToken, setToken } from "@/lib/api";
import { Logo } from "@/components/ui";
@@ -13,6 +13,7 @@ const NAV = [
{ href: "/", label: "Installs", icon: LayoutDashboard },
{ href: "/customers", label: "Customers", icon: Building2 },
{ href: "/billing", label: "Billing", icon: Receipt },
{ href: "/servers", label: "Servers", icon: Server },
{ href: "/alerts", label: "Alerts", icon: BellRing },
{ href: "/releases", label: "Releases", icon: Rocket },
{ href: "/notices", label: "Notices", icon: Megaphone },
@@ -32,7 +33,7 @@ export default function HubLayout({ children }: { children: React.ReactNode }) {
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));
const active = (href: string) => (href === "/" ? pathname === "/" || pathname.startsWith("/installs") : href === "/servers" ? pathname.startsWith("/servers") || pathname.startsWith("/jobs") : pathname.startsWith(href));
return (
<div className="flex min-h-screen">
@@ -0,0 +1,169 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { Plus, Trash2 } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes, fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { PercentChart, ServersNav, StatusPill, pct, type Deployment, type Job, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = {
server: ServerSummary;
config: Record<string, string>;
processes: { name: string; church: string | null; product: string | null; status: string; memoryBytes: number; cpuPercent: number; restarts: number; uptimeSeconds: number }[];
stats: { at: string; cpuPercent: number; cpuPeak: number; ramUsedPercent: number; ramPeak: number; diskUsedPercent: number }[];
deployments: (Deployment & { customer: { id: string; name: string } })[];
jobs: Job[];
alerts: { id: string; type: string; level: string; message: string; createdAt: string; resolvedAt: string | null }[];
ports: { port: number; role: string; note: string | null; releasedAt: string | null }[];
};
/** The settings a church server's jobs need (§5); others can be added. */
const SUGGESTED: { key: string; hint: string }[] = [
{ key: "TRUST_PROXY", hint: "Behind frp: loopback" },
{ key: "DB_HOST", hint: "The PostgreSQL server the sites use (default localhost)" },
{ key: "DB_PORT", hint: "Default 5432" },
{ key: "DB_ADMIN_URL", hint: "postgresql://admin:…@host/postgres: may create databases and roles. Blank: the local PostgreSQL via sudo -u postgres" },
];
function ConfigEditor({ id, config, onSaved }: { id: string; config: Record<string, string>; onSaved: (m: Msg) => void }) {
const [rows, setRows] = useState<[string, string][]>(() => {
const keys = [...new Set([...SUGGESTED.map(s => s.key), ...Object.keys(config)])];
return keys.map(k => [k, config[k] ?? (k === "TRUST_PROXY" ? "loopback" : "")]);
});
const set = (i: number, j: 0 | 1, v: string) => setRows(rows.map((r, n) => (n === i ? (j === 0 ? [v.toUpperCase(), r[1]] : [r[0], v]) : r)));
const save = async () => {
try {
await api(`/api/admin/servers/${id}/config`, { method: "PUT", body: { values: Object.fromEntries(rows.filter(r => r[0].trim())) } });
onSaved({ type: "ok", text: "Configuration saved. Jobs from now on carry it, sealed to this server's key." });
} catch (e) { onSaved({ type: "err", text: errorText(e) }); }
};
return (
<div className="card">
<h2 className="font-medium">Configuration</h2>
<p className="mt-1 text-sm text-slate-500">The server layer of every install&apos;s .env here. Stored encrypted; sent only inside jobs, sealed to this server. Values ending in _URL, KEY, SECRET or PASSWORD show as dots: leave them to keep them.</p>
<div className="mt-3 space-y-2">
{rows.map(([k, v], i) => (
<div key={i} className="grid gap-2 md:grid-cols-[14rem_1fr_auto]">
<input className="input font-mono" value={k} onChange={e => set(i, 0, e.target.value)} placeholder="NAME" aria-label="Name" />
<input className="input font-mono" value={v} onChange={e => set(i, 1, e.target.value)} placeholder={SUGGESTED.find(s => s.key === k)?.hint || "value"} aria-label={`${k} value`} />
<button type="button" className="btn-secondary" onClick={() => setRows(rows.filter((_, n) => n !== i))} aria-label={`Remove ${k}`}><Trash2 className="h-4 w-4" /></button>
</div>
))}
</div>
<div className="mt-3 flex gap-2">
<button type="button" className="btn-secondary" onClick={() => setRows([...rows, ["", ""]])}><Plus className="h-4 w-4" /> Add a setting</button>
<button type="button" className="btn-primary" onClick={save}>Save</button>
</div>
</div>
);
}
export default function ServerPage() {
const { id } = useParams<{ id: string }>();
const router = useRouter();
const [d, setD] = useState<Detail | null>(null);
const [range, setRange] = useState<"24h" | "7d" | "90d">("24h");
const [msg, setMsg] = useState<Msg>(null);
const [agentVersion, setAgentVersion] = useState("");
const load = useCallback(() => api<Detail>(`/api/admin/servers/${id}?range=${range}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id, range]);
useEffect(() => { load(); }, [load]);
const job = async (type: string, args: Record<string, unknown> = {}) => {
setMsg(null);
try {
const r = await api<{ job: Job }>(`/api/admin/servers/${id}/jobs`, { method: "POST", body: { type, args } });
setMsg({ type: "ok", text: `Queued: the agent picks it up within 30 seconds.` });
router.push(`/jobs/${r.job.id}`);
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const remove = async () => {
if (!d || !window.confirm(`Remove ${d.server.name} from the Hub? Its agent stops getting jobs. (Uninstall the agent on the server too.)`)) return;
try { await api(`/api/admin/servers/${id}`, { method: "DELETE" }); router.push("/servers"); } catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
if (!d) return <div><ServersNav active="/servers" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const s = d.server;
return (
<div className="space-y-6">
<div>
<PageTitle title={s.name} subtitle={<>{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname} · agent {s.agentVersion} · last heard {ago(s.lastSeenAt)} <StatusPill status={s.online ? "online" : "offline"} /></>} />
<ServersNav active="/servers" />
<Message msg={msg} />
</div>
{!!d.alerts.filter(a => !a.resolvedAt).length && (
<div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">
{d.alerts.filter(a => !a.resolvedAt).map(a => <div key={a.id}>⚠ {a.message} <span className="text-xs">(since {fmtDate(a.createdAt)})</span></div>)}
</div>
)}
<div className="flex flex-wrap items-center gap-2">
{(["24h", "7d", "90d"] as const).map(r => <button key={r} className={range === r ? "btn-primary" : "btn-secondary"} onClick={() => setRange(r)}>{r === "24h" ? "24 hours" : r === "7d" ? "7 days" : "90 days"}</button>)}
</div>
<div className="grid gap-4 lg:grid-cols-2">
<PercentChart title="CPU" points={d.stats.map(p => ({ at: p.at, value: p.cpuPercent, peak: p.cpuPeak }))} />
<PercentChart title="RAM used" points={d.stats.map(p => ({ at: p.at, value: p.ramUsedPercent, peak: p.ramPeak }))} />
</div>
<div className="grid gap-4 md:grid-cols-3">
<div className="card text-sm">
<h2 className="font-medium">Resources now</h2>
<p className="mt-2">RAM {pct(s.ram?.usedPercent)} used, {bytes(s.ram?.availableBytes)} free of {bytes(s.ram?.totalBytes)}</p>
<p>CPU {pct(s.cpu?.percent)} · load {s.cpu?.load1?.toFixed(2)} on {s.cpu?.cores} cores</p>
{s.disk.map(x => <p key={x.mount}>Disk {x.mount}: {pct((x.usedBytes / Math.max(1, x.totalBytes)) * 100)} used, {bytes(x.freeBytes)} free</p>)}
</div>
<div className="card text-sm">
<h2 className="font-medium">Versions</h2>
<p className="mt-2">{s.versions?.os}</p>
<p>Node {s.versions?.node} · PostgreSQL {s.versions?.postgres || "–"} · frpc {s.versions?.frpc || "–"}</p>
{s.mode === "church" && <p>frpc {s.frpcRunning === null ? "unknown" : s.frpcRunning ? "running" : <b className="text-red-700">not running</b>}</p>}
{s.central && <p>frps.ini: proxy_bind_addr {s.central.proxyBindAddr || <b className="text-red-700">not set</b>}, allow_ports {s.central.allowPorts || "any"}</p>}
</div>
<div className="card space-y-2 text-sm">
<h2 className="font-medium">Actions</h2>
<button className="btn-secondary w-full" onClick={() => job("status")}>Check status now</button>
<div className="flex gap-2"><input className="input" placeholder="agent@1.0.1" value={agentVersion} onChange={e => setAgentVersion(e.target.value)} aria-label="Agent version" /><button className="btn-secondary" disabled={!agentVersion} onClick={() => job("update-agent", { version: agentVersion })}>Update agent</button></div>
<button className="btn-danger w-full" onClick={remove}><Trash2 className="h-4 w-4" /> Remove server</button>
</div>
</div>
{s.mode === "church" && <ConfigEditor key={JSON.stringify(d.config)} id={s.id} config={d.config} onSaved={m => { setMsg(m); load(); }} />}
{s.mode === "church" && (
<div className="card overflow-x-auto">
<h2 className="font-medium">Sites on this server</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Church</th><th>Domain</th><th>Version</th><th>Ports (web, api)</th><th>Status</th></tr></thead>
<tbody>{d.deployments.map(x => (
<tr key={x.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${x.id}`}>{x.customer?.name} ({x.shortName})</Link></td><td>{x.domain}</td><td>{x.version || "–"}</td><td className="tabular-nums">{x.webPort}, {x.apiPort}</td><td><StatusPill status={x.status} /></td></tr>
))}</tbody>
</table>
{!d.deployments.length && <p className="mt-2 text-sm text-slate-500">None yet. <Link className="text-indigo-700 hover:underline" href="/servers/installs">New install</Link></p>}
</div>
)}
{s.mode === "church" && (
<div className="card overflow-x-auto">
<h2 className="font-medium">Processes (PM2)</h2>
<table className="mt-3 w-full text-sm tabular-nums">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Name</th><th>Church</th><th>Status</th><th className="text-right">Memory</th><th className="text-right">CPU</th><th className="text-right">Restarts</th></tr></thead>
<tbody>{d.processes.map(p => <tr key={p.name} className="border-t"><td className="py-1.5">{p.name}</td><td>{p.church || "–"}</td><td>{p.status}</td><td className="text-right">{bytes(p.memoryBytes)}</td><td className="text-right">{Math.round(p.cpuPercent)}%</td><td className="text-right">{p.restarts}</td></tr>)}</tbody>
</table>
</div>
)}
<div className="card overflow-x-auto">
<h2 className="font-medium">Recent jobs</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>When</th><th>Status</th><th>Result</th></tr></thead>
<tbody>{d.jobs.map(j => <tr key={j.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link> <span className="text-xs text-slate-500">{String(j.args?.church || "")}</span></td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td></tr>)}</tbody>
</table>
</div>
</div>
);
}
@@ -0,0 +1,130 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
import { api, errorText } from "@/lib/api";
import { bytes, fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Detail = {
deployment: Deployment & { server: ServerSummary; jobs: Job[]; exports: { id: string; bytes: number; expiresAt: string; downloadedAt: string | null; deletedAt: string | null }[]; install: { version: string | null; url: string } | null };
fastPanel: string;
};
const H = 60 * 60 * 1000;
/** One install on a server: proxy, updates, adopt, uninstall (§7–9). */
export default function DeploymentPage() {
const { id } = useParams<{ id: string }>();
const warn = useSearchParams().get("warn");
const [d, setD] = useState<Detail | null>(null);
const [msg, setMsg] = useState<Msg>(warn ? { type: "err", text: warn } : null);
const [problems, setProblems] = useState<string[]>([]);
const [upd, setUpd] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" });
const [adopt, setAdopt] = useState({ eventsDir: "", version: "", at: toInput(new Date(Date.now() + 5 * H)) });
const [un, setUn] = useState({ at: toInput(new Date(Date.now() + 7 * 24 * H)), totp: "", confirm: "" });
const load = useCallback(() => api<Detail>(`/api/admin/deployments/${id}`).then(setD).catch(e => setMsg({ type: "err", text: errorText(e) })), [id]);
useEffect(() => { load(); }, [load]);
const act = async (path: string, body: unknown, ok: string) => {
setMsg(null);
try {
const r = await api<{ warnings?: string[] }>(path, { method: "POST", body });
setMsg({ type: "ok", text: `${ok}${r?.warnings?.length ? ` Note: ${r.warnings.join(" ")}` : ""}` });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const proxyDone = async () => {
setMsg(null);
try {
const r = await api<{ live: boolean; problems: string[] }>(`/api/admin/deployments/${id}/proxy-done`, { method: "POST" });
setProblems(r.problems);
setMsg(r.live ? { type: "ok", text: "Live. The site admin got the welcome email." } : { type: "err", text: "The site isn't answering as expected yet:" });
load();
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
if (!d) return <div><ServersNav active="/servers/installs" />{msg ? <Message msg={msg} /> : <Loading />}</div>;
const x = d.deployment;
const minAt = upd.emergency ? 15 * 60 * 1000 : 4 * H;
return (
<div className="space-y-6">
<div>
<PageTitle title={`${x.customer?.name} (${x.shortName})`} subtitle={<>{x.domain} · on <Link className="text-indigo-700 hover:underline" href={`/servers/${x.serverId}`}>{x.server.name}</Link> · ports web {x.webPort}, api {x.apiPort} · version {x.install?.version || x.version || "–"} <StatusPill status={x.status} /></>} />
<ServersNav active="/servers/installs" />
<Message msg={msg} />
{!!problems.length && <ul className="mt-2 list-disc pl-6 text-sm text-red-800">{problems.map(p => <li key={p}>{p}</li>)}</ul>}
</div>
{(x.status === "waiting_for_proxy" || x.status === "installing") && (
<div className="card">
<h2 className="font-medium">Set up the site in FastPanel</h2>
<pre className="mt-3 overflow-x-auto whitespace-pre-wrap rounded-lg bg-slate-50 p-3 text-xs">{d.fastPanel}</pre>
<button className="btn-primary mt-3" disabled={x.status !== "waiting_for_proxy"} onClick={proxyDone}>Proxy done</button>
{x.status === "installing" && <p className="mt-2 text-xs text-slate-500">Waiting for the install to finish (see its job below).</p>}
</div>
)}
{x.status === "live" && (
<form className="card grid gap-3 md:grid-cols-2" onSubmit={e => { e.preventDefault(); act("/api/admin/updates", { deploymentIds: [x.id], version: upd.version || undefined, at: fromInput(upd.at), emergency: upd.emergency, reason: upd.reason || null, totp: upd.totp || null }, "Planned. The site admin was emailed and sees a banner."); }}>
<h2 className="font-medium md:col-span-2">Schedule an update</h2>
<div><label className="label" htmlFor="u-v">Release</label><input id="u-v" className="input" placeholder="latest" value={upd.version} onChange={e => setUpd({ ...upd, version: e.target.value })} /></div>
<div><label className="label" htmlFor="u-at">When</label><input id="u-at" type="datetime-local" className="input" value={upd.at} min={toInput(new Date(Date.now() + minAt))} onChange={e => setUpd({ ...upd, at: e.target.value })} /><p className="mt-1 text-xs text-slate-500">At least {upd.emergency ? "15 minutes" : "4 hours"} away, so the church gets notice.</p></div>
<label className="flex items-center gap-2 text-sm md:col-span-2"><input type="checkbox" checked={upd.emergency} onChange={e => setUpd({ ...upd, emergency: e.target.checked })} /> Emergency (security fix or broken release): 15 minutes&apos; notice, a reason and your two-factor code</label>
{upd.emergency && <>
<div><label className="label" htmlFor="u-r">Reason (shown to the church)</label><input id="u-r" className="input" required value={upd.reason} onChange={e => setUpd({ ...upd, reason: e.target.value })} /></div>
<div><label className="label" htmlFor="u-t">Two-factor code</label><input id="u-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={upd.totp} onChange={e => setUpd({ ...upd, totp: e.target.value })} /></div>
</>}
<div className="md:col-span-2"><button className="btn-primary">Schedule</button></div>
</form>
)}
{x.status === "live" && x.install?.version?.startsWith("2.1.") && (
<form className="card grid gap-3 md:grid-cols-3" onSubmit={e => { e.preventDefault(); act(`/api/admin/deployments/${x.id}/adopt`, { eventsDir: adopt.eventsDir, version: adopt.version || undefined, at: fromInput(adopt.at) }, "Adopt planned. The site admin was emailed."); }}>
<h2 className="font-medium md:col-span-3">Move onto the monorepo (crosscode adopt)</h2>
<div><label className="label" htmlFor="a-d">The old install&apos;s folder</label><input id="a-d" className="input font-mono" required placeholder="/var/www/hope-events" value={adopt.eventsDir} onChange={e => setAdopt({ ...adopt, eventsDir: e.target.value })} /></div>
<div><label className="label" htmlFor="a-v">Release</label><input id="a-v" className="input" placeholder="latest" value={adopt.version} onChange={e => setAdopt({ ...adopt, version: e.target.value })} /></div>
<div><label className="label" htmlFor="a-at">When</label><input id="a-at" type="datetime-local" className="input" value={adopt.at} onChange={e => setAdopt({ ...adopt, at: e.target.value })} /></div>
<div className="md:col-span-3"><button className="btn-primary">Plan the move</button></div>
</form>
)}
<div className="card overflow-x-auto">
<h2 className="font-medium">Jobs</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>When</th><th>Status</th><th>Result</th><th /></tr></thead>
<tbody>{x.jobs.map(j => (
<tr key={j.id} className="border-t">
<td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td>
<td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td><td className="max-w-md truncate text-xs text-slate-500">{j.message}</td>
<td>{["queued", "scheduled"].includes(j.status) && <button className="btn-secondary px-2 py-1 text-xs" onClick={() => act(`/api/admin/jobs/${j.id}/cancel`, {}, "Cancelled; the church was told.")}>Cancel</button>}</td>
</tr>
))}</tbody>
</table>
</div>
{!!x.exports.length && (
<div className="card text-sm">
<h2 className="font-medium">Exports</h2>
{x.exports.map(e => <p key={e.id} className="mt-2">{e.id}: {bytes(e.bytes)}, {e.deletedAt ? `deleted ${fmtDate(e.deletedAt)}` : `until ${fmtDate(e.expiresAt)}`}{e.downloadedAt ? `, downloaded ${fmtDate(e.downloadedAt)}` : ", not downloaded yet"}</p>)}
</div>
)}
{x.status !== "removed" && x.status !== "uninstalling" && (
<form className="card grid gap-3 border-red-200 md:grid-cols-3" onSubmit={e => { e.preventDefault(); if (window.confirm(`Uninstall ${x.shortName} on ${un.at.replace("T", " ")}? The church gets its data first.`)) act(`/api/admin/deployments/${x.id}/uninstall`, { at: fromInput(un.at), totp: un.totp, confirm: un.confirm }, "Uninstall planned: the site admin was emailed and sees a banner. The export runs first."); }}>
<h2 className="font-medium text-red-800 md:col-span-3">Uninstall</h2>
<p className="text-sm text-slate-500 md:col-span-3">At the time: the church&apos;s data is exported (encrypted; the link goes to the site admin), then the site, its tunnels and database are removed. The final backup stays on the server for 30 days.</p>
<div><label className="label" htmlFor="x-at">When</label><input id="x-at" type="datetime-local" className="input" value={un.at} onChange={e => setUn({ ...un, at: e.target.value })} /></div>
<div><label className="label" htmlFor="x-c">Type {x.shortName}</label><input id="x-c" className="input" required value={un.confirm} onChange={e => setUn({ ...un, confirm: e.target.value })} /></div>
<div><label className="label" htmlFor="x-t">Two-factor code</label><input id="x-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={un.totp} onChange={e => setUn({ ...un, totp: e.target.value })} /></div>
<div className="md:col-span-3"><button className="btn-danger" disabled={un.confirm !== x.shortName}>Plan the uninstall</button></div>
</form>
)}
</div>
);
}
@@ -0,0 +1,136 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Link2, Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { ServersNav, StatusPill, pct, type Deployment, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Customer = { id: string; name: string; domain?: string | null };
type InstallRow = { id: string; name: string; url: string; customer: { id: string; name: string } | null; version: string | null };
const emptyNew = { customerId: "", serverId: "", shortName: "", domain: "", timezone: "", adminName: "", adminEmail: "", version: "" };
const emptyLink = { installId: "", serverId: "", shortName: "", webPort: "", apiPort: "" };
/** Installs on servers: New install (§7) and linking existing installs (§14). */
export default function InstallsPage() {
const router = useRouter();
const [list, setList] = useState<Deployment[] | null>(null);
const [srv, setSrv] = useState<ServerSummary[]>([]);
const [customers, setCustomers] = useState<Customer[]>([]);
const [installs, setInstalls] = useState<InstallRow[]>([]);
const [mode, setMode] = useState<"none" | "new" | "link">("none");
const [form, setForm] = useState(emptyNew);
const [link, setLink] = useState(emptyLink);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(() => {
api<{ deployments: Deployment[] }>("/api/admin/deployments").then(r => setList(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setSrv(r.servers.filter(s => s.mode === "church"))).catch(() => {});
}, []);
useEffect(() => { load(); }, [load]);
useEffect(() => {
if (mode === "new" && !customers.length) api<Customer[]>("/api/admin/customers").then(setCustomers).catch(() => {});
if (mode === "link" && !installs.length) api<InstallRow[]>("/api/admin/installs").then(setInstalls).catch(() => {});
}, [mode, customers.length, installs.length]);
const submitNew = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setMsg(null);
try {
const r = await api<{ deployment: Deployment; warnings: string[] }>("/api/admin/deployments", { method: "POST", body: { ...form, product: "events", version: form.version || undefined } });
router.push(`/servers/installs/${r.deployment.id}${r.warnings.length ? `?warn=${encodeURIComponent(r.warnings.join(" "))}` : ""}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setBusy(false);
};
const submitLink = async (e: React.FormEvent) => {
e.preventDefault();
setBusy(true);
setMsg(null);
try {
const r = await api<{ deployment: Deployment }>("/api/admin/deployments/link", { method: "POST", body: link });
router.push(`/servers/installs/${r.deployment.id}`);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
setBusy(false);
};
const f = (k: keyof typeof emptyNew) => ({ value: form[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setForm({ ...form, [k]: e.target.value }) });
const l = (k: keyof typeof emptyLink) => ({ value: link[k], onChange: (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setLink({ ...link, [k]: e.target.value }) });
return (
<div>
<PageTitle title="Installs on servers" subtitle="Sites the Hub installs, updates and uninstalls through each server's agent."
actions={<div className="flex gap-2"><button className="btn-secondary" onClick={() => setMode("link")}><Link2 className="h-4 w-4" /> Link existing</button><button className="btn-primary" onClick={() => setMode("new")}><Plus className="h-4 w-4" /> New install</button></div>} />
<ServersNav active="/servers/installs" />
<Message msg={msg} />
{mode === "new" && (
<form onSubmit={submitNew} className="card mb-6 grid gap-3 md:grid-cols-2">
<h2 className="font-medium md:col-span-2">New Cross Events install</h2>
<div><label className="label" htmlFor="n-cust">Customer</label><select id="n-cust" className="input" required {...f("customerId")}><option value="">Choose…</option>{customers.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}</select></div>
<div><label className="label" htmlFor="n-short">Short name</label><input id="n-short" className="input" required pattern="[a-z][a-z0-9-]{1,30}" placeholder="hope" {...f("shortName")} /><p className="mt-1 text-xs text-slate-500">Folders, database and tunnels: a-z, 0-9 and -.</p></div>
<div><label className="label" htmlFor="n-domain">Domain</label><input id="n-domain" className="input" required placeholder="events.hope.co.za" {...f("domain")} /></div>
<div><label className="label" htmlFor="n-tz">Time zone</label><input id="n-tz" className="input" placeholder="Africa/Johannesburg" {...f("timezone")} /></div>
<div><label className="label" htmlFor="n-an">Site admin name</label><input id="n-an" className="input" {...f("adminName")} /></div>
<div><label className="label" htmlFor="n-ae">Site admin email</label><input id="n-ae" type="email" className="input" {...f("adminEmail")} /><p className="mt-1 text-xs text-slate-500">Gets the welcome email and update notices.</p></div>
<div className="md:col-span-2">
<span className="label">Server</span>
<div className="grid gap-2 md:grid-cols-2">
{srv.map(s => {
const low = (s.ram?.availableBytes ?? 0) < 1.5 * 1024 ** 3;
return (
<label key={s.id} className={`flex cursor-pointer gap-2 rounded-lg border p-3 text-sm ${form.serverId === s.id ? "border-indigo-500 bg-indigo-50" : "border-slate-200"}`}>
<input type="radio" name="server" value={s.id} checked={form.serverId === s.id} onChange={() => setForm({ ...form, serverId: s.id })} disabled={!s.online} />
<span>
<span className="font-medium">{s.name}</span> <StatusPill status={s.online ? "online" : "offline"} />
<span className="block text-xs text-slate-500">RAM free {s.ram ? `${(s.ram.availableBytes / 1024 ** 3).toFixed(1)} GB` : "?"} · CPU day avg {pct(s.lastDay?.cpuAvg)} · disk {pct(s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0))} · {s.deployments ?? 0} site(s)</span>
{low && <span className="block text-xs font-medium text-amber-800">Not recommended: under 1.5 GB RAM free</span>}
</span>
</label>
);
})}
</div>
</div>
<div><label className="label" htmlFor="n-ver">Release</label><input id="n-ver" className="input" placeholder="latest" {...f("version")} /></div>
<div className="flex items-end gap-2 md:col-span-2">
<button className="btn-primary" disabled={busy || !form.serverId}>{busy ? "Starting…" : "Install"}</button>
<button type="button" className="btn-secondary" onClick={() => setMode("none")}>Cancel</button>
<p className="text-xs text-slate-500">The Hub makes the licence, picks two ports, and the agent installs within a minute. You get the report and the FastPanel steps by email.</p>
</div>
</form>
)}
{mode === "link" && (
<form onSubmit={submitLink} className="card mb-6 grid gap-3 md:grid-cols-2">
<h2 className="font-medium md:col-span-2">Link an install that&apos;s already on a server</h2>
<p className="text-sm text-slate-500 md:col-span-2">For sites installed by hand or moved with <code>crosscode adopt</code>. Nothing on the server changes; the Hub records the server, folder name and ports (see the server&apos;s church.env and frpc.ini).</p>
<div><label className="label" htmlFor="l-inst">Install</label><select id="l-inst" className="input" required {...l("installId")}><option value="">Choose…</option>{installs.map(i => <option key={i.id} value={i.id}>{i.customer?.name || i.name} ({i.url})</option>)}</select></div>
<div><label className="label" htmlFor="l-srv">Server</label><select id="l-srv" className="input" required {...l("serverId")}><option value="">Choose…</option>{srv.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}</select></div>
<div><label className="label" htmlFor="l-short">Short name (its folder in /var/www/sites)</label><input id="l-short" className="input" required {...l("shortName")} /></div>
<div className="grid grid-cols-2 gap-2">
<div><label className="label" htmlFor="l-web">Web port</label><input id="l-web" className="input" required inputMode="numeric" {...l("webPort")} /></div>
<div><label className="label" htmlFor="l-api">API port</label><input id="l-api" className="input" required inputMode="numeric" {...l("apiPort")} /></div>
</div>
<div className="flex gap-2 md:col-span-2"><button className="btn-primary" disabled={busy}>Link</button><button type="button" className="btn-secondary" onClick={() => setMode("none")}>Cancel</button></div>
</form>
)}
{!list ? <Loading /> : (
<div className="card overflow-x-auto">
<table className="w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Church</th><th>Domain</th><th>Server</th><th>Version</th><th>Last heartbeat</th><th>Status</th></tr></thead>
<tbody>{list.map(d => (
<tr key={d.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/servers/installs/${d.id}`}>{d.customer?.name} ({d.shortName})</Link></td><td>{d.domain}</td><td>{d.server?.name}</td><td>{d.install?.version || d.version || "–"}</td><td>{ago(d.install?.lastHeartbeatAt)}</td><td><StatusPill status={d.status} /></td></tr>
))}</tbody>
</table>
{!list.length && <p className="mt-2 text-sm text-slate-500">No installs on servers yet.</p>}
</div>
)}
</div>
);
}
+104
View File
@@ -0,0 +1,104 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { Copy, Plus } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { ago, bytes } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { ServersNav, StatusPill, pct, type ServerSummary } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
/** Hub → Servers: every server with its agent, resources and sites; Add server (§3, §10). */
export default function ServersPage() {
const [list, setList] = useState<ServerSummary[] | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [adding, setAdding] = useState(false);
const [name, setName] = useState("");
const [mode, setMode] = useState<"church" | "central">("church");
const [joined, setJoined] = useState<{ command: string; expiresAt: string } | null>(null);
const load = useCallback(() => api<{ servers: ServerSummary[] }>("/api/admin/servers").then(r => setList(r.servers)).catch(e => setMsg({ type: "err", text: errorText(e) })), []);
useEffect(() => { load(); const t = setInterval(load, 30000); return () => clearInterval(t); }, [load]);
const add = async (e: React.FormEvent) => {
e.preventDefault();
setMsg(null);
try {
const r = await api<{ command: string; expiresAt: string }>("/api/admin/servers/join-token", { method: "POST", body: { name, mode } });
setJoined(r);
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<div>
<PageTitle title="Servers" subtitle="Each server runs the Cross Code agent, which polls the Hub for jobs and reports its health every minute." actions={<button className="btn-primary" onClick={() => { setAdding(true); setJoined(null); setName(""); }}><Plus className="h-4 w-4" /> Add server</button>} />
<ServersNav active="/servers" />
<Message msg={msg} />
{adding && (
<div className="card mb-6">
{!joined ? (
<form onSubmit={add} className="flex flex-wrap items-end gap-3">
<div className="min-w-[14rem] flex-1"><label className="label" htmlFor="srv-name">Name</label><input id="srv-name" className="input" value={name} onChange={e => setName(e.target.value)} placeholder="church-server-2" required /></div>
<div><label className="label" htmlFor="srv-mode">Kind</label>
<select id="srv-mode" className="input" value={mode} onChange={e => setMode(e.target.value as "church" | "central")}>
<option value="church">Church server (runs sites)</option>
<option value="central">Central server (FastPanel, read-only checks)</option>
</select>
</div>
<button className="btn-primary">Make the join command</button>
<button type="button" className="btn-secondary" onClick={() => setAdding(false)}>Cancel</button>
</form>
) : (
<div className="space-y-2">
<p className="text-sm">Run this on the new server as root. The token works once, until {new Date(joined.expiresAt).toLocaleTimeString()}:</p>
<pre className="overflow-x-auto rounded-lg bg-slate-900 p-3 text-xs text-slate-100">{joined.command}</pre>
<div className="flex gap-2">
<button className="btn-secondary" onClick={() => navigator.clipboard?.writeText(joined.command)}><Copy className="h-4 w-4" /> Copy</button>
<button className="btn-secondary" onClick={() => { setAdding(false); load(); }}>Done</button>
</div>
<p className="text-xs text-slate-500">The server shows here within a minute of joining. Then set its configuration (database, TRUST_PROXY) on its page.</p>
</div>
)}
</div>
)}
{!list ? <Loading /> : list.length === 0 ? <p className="text-sm text-slate-500">No servers yet. Add one to install churches from the Hub.</p> : (
<div className="grid gap-4 md:grid-cols-2">
{list.map(s => {
const disk = s.disk.reduce((m, d) => Math.max(m, d.totalBytes ? (d.usedBytes / d.totalBytes) * 100 : 0), 0);
return (
<Link key={s.id} href={`/servers/${s.id}`} className="card block hover:border-indigo-300">
<div className="flex items-start justify-between gap-2">
<div>
<div className="font-medium">{s.name}</div>
<div className="text-xs text-slate-500">{s.mode === "central" ? "Central server" : "Church server"} · {s.hostname || "?"} · agent {s.agentVersion || "?"}</div>
</div>
<StatusPill status={s.online ? "online" : "offline"} />
</div>
<dl className="mt-4 grid grid-cols-3 gap-2 text-sm">
<div><dt className="text-xs text-slate-500">RAM used</dt><dd className="tabular-nums">{pct(s.ram?.usedPercent)} <span className="text-xs text-slate-500">of {bytes(s.ram?.totalBytes)}</span></dd></div>
<div><dt className="text-xs text-slate-500">CPU now · day avg</dt><dd className="tabular-nums">{pct(s.cpu?.percent)} · {pct(s.lastDay?.cpuAvg)}</dd></div>
<div><dt className="text-xs text-slate-500">Fullest disk</dt><dd className="tabular-nums">{pct(disk)}</dd></div>
</dl>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-500">
{s.mode === "church" && <span>{s.deployments ?? 0} site(s)</span>}
<span>Last heard {ago(s.lastSeenAt)}</span>
{s.mode === "church" && s.frpcRunning === false && <span className="font-medium text-red-700">frpc not running</span>}
{s.central && !s.central.proxyBindAddr && <span className="font-medium text-red-700">proxy_bind_addr not set</span>}
</div>
{!!s.alerts?.length && (
<ul className="mt-3 space-y-1 text-xs">
{s.alerts.map(a => <li key={a.type} className={a.level === "critical" ? "text-red-700" : "text-amber-800"}>⚠ {a.message}</li>)}
</ul>
)}
</Link>
);
})}
</div>
)}
</div>
);
}
@@ -0,0 +1,89 @@
"use client";
import React, { useCallback, useEffect, useState } from "react";
import { Plus, Trash2 } from "lucide-react";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { ServersNav } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
type Port = { port: number; role: string; note: string | null; releasedAt: string | null; deploymentId: string | null; server: { id: string; name: string } | null };
/** The port list (§6) and the install defaults (§5): the same for every install. */
export default function ServerSettingsPage() {
const [ports, setPorts] = useState<Port[] | null>(null);
const [range, setRange] = useState({ from: "20000", to: "29999" });
const [defaults, setDefaults] = useState<[string, string][]>([]);
const [ip, setIp] = useState("");
const [newPort, setNewPort] = useState({ port: "", note: "" });
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => {
api<{ ports: Port[]; range: { from: number; to: number } }>("/api/admin/ports").then(r => { setPorts(r.ports); setRange({ from: String(r.range.from), to: String(r.range.to) }); }).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ defaults: Record<string, string>; centralServerIp: string }>("/api/admin/install-defaults").then(r => { setDefaults(Object.entries(r.defaults)); setIp(r.centralServerIp); }).catch(() => {});
}, []);
useEffect(() => { load(); }, [load]);
const saveDefaults = async () => {
try {
await api("/api/admin/install-defaults", { method: "PUT", body: { defaults: Object.fromEntries(defaults.filter(d => d[0].trim())), portRange: { from: range.from, to: range.to }, centralServerIp: ip } });
setMsg({ type: "ok", text: "Saved." });
} catch (e) { setMsg({ type: "err", text: errorText(e) }); }
};
const take = async (e: React.FormEvent) => {
e.preventDefault();
try { await api("/api/admin/ports", { method: "POST", body: { port: newPort.port, note: newPort.note } }); setNewPort({ port: "", note: "" }); load(); } catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
const free = async (port: number) => {
try { await api(`/api/admin/ports/${port}`, { method: "DELETE" }); load(); } catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<div className="space-y-6">
<div>
<PageTitle title="Ports & defaults" />
<ServersNav active="/servers/settings" />
<Message msg={msg} />
</div>
<div className="card space-y-3">
<h2 className="font-medium">Install defaults</h2>
<p className="text-sm text-slate-500">The defaults layer of every install&apos;s .env (HUB_URL, APP_TIMEZONE, job switches, SENTRY_DSN…). A server&apos;s own configuration is on its page.</p>
{defaults.map(([k, v], i) => (
<div key={i} className="grid gap-2 md:grid-cols-[14rem_1fr_auto]">
<input className="input font-mono" value={k} aria-label="Name" onChange={e => setDefaults(defaults.map((d, n) => (n === i ? [e.target.value.toUpperCase(), d[1]] : d)))} />
<input className="input font-mono" value={v} aria-label={`${k} value`} onChange={e => setDefaults(defaults.map((d, n) => (n === i ? [d[0], e.target.value] : d)))} />
<button type="button" className="btn-secondary" aria-label={`Remove ${k}`} onClick={() => setDefaults(defaults.filter((_, n) => n !== i))}><Trash2 className="h-4 w-4" /></button>
</div>
))}
<button type="button" className="btn-secondary" onClick={() => setDefaults([...defaults, ["", ""]])}><Plus className="h-4 w-4" /> Add a default</button>
<div className="grid gap-3 border-t pt-3 md:grid-cols-3">
<div><label className="label" htmlFor="pr-from">Port range from</label><input id="pr-from" className="input" inputMode="numeric" value={range.from} onChange={e => setRange({ ...range, from: e.target.value })} /></div>
<div><label className="label" htmlFor="pr-to">to</label><input id="pr-to" className="input" inputMode="numeric" value={range.to} onChange={e => setRange({ ...range, to: e.target.value })} /><p className="mt-1 text-xs text-slate-500">Match allow_ports in frps.ini.</p></div>
<div><label className="label" htmlFor="c-ip">Central server IP</label><input id="c-ip" className="input" placeholder="203.0.113.10" value={ip} onChange={e => setIp(e.target.value)} /><p className="mt-1 text-xs text-slate-500">To check a new install&apos;s DNS.</p></div>
</div>
<button className="btn-primary" onClick={saveDefaults}>Save</button>
</div>
<div className="card overflow-x-auto">
<h2 className="font-medium">Port list</h2>
<p className="mt-1 text-sm text-slate-500">Every port frps opens on the central server must be unique across servers. Mark ports used by anything else (today&apos;s tunnels written by hand) as taken.</p>
<form onSubmit={take} className="mt-3 flex flex-wrap gap-2">
<input className="input w-32" placeholder="Port" inputMode="numeric" required value={newPort.port} onChange={e => setNewPort({ ...newPort, port: e.target.value })} aria-label="Port" />
<input className="input w-72" placeholder="What uses it" value={newPort.note} onChange={e => setNewPort({ ...newPort, note: e.target.value })} aria-label="Note" />
<button className="btn-secondary">Mark as taken</button>
</form>
{!ports ? <Loading /> : (
<table className="mt-3 w-full text-sm tabular-nums">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Port</th><th>Use</th><th>Server</th><th>Note</th><th /></tr></thead>
<tbody>{ports.map(p => (
<tr key={p.port} className="border-t"><td className="py-1.5">{p.port}</td><td>{p.releasedAt ? `free from ${fmtDate(new Date(new Date(p.releasedAt).getTime() + 30 * 24 * 3600 * 1000), false)}` : p.role}</td><td>{p.server?.name || "–"}</td><td className="text-xs text-slate-500">{p.note}</td>
<td>{(p.role === "taken" || p.releasedAt) && <button className="btn-secondary px-2 py-1 text-xs" onClick={() => free(p.port)}>Remove</button>}</td></tr>
))}</tbody>
</table>
)}
</div>
</div>
);
}
@@ -0,0 +1,90 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { api, errorText } from "@/lib/api";
import { fmtDate } from "@/lib/format";
import { Loading, Message, PageTitle } from "@/components/ui";
import { ServersNav, StatusPill, toInput, fromInput, type Deployment, type Job } from "@/components/servers";
type Msg = { type: "ok" | "err"; text: string } | null;
const H = 60 * 60 * 1000;
/**
* Updates (§8): one release to several installs at one time with one notice. They run one at a
* time, and the batch stops at the first failure (the rest are told it's postponed).
*/
export default function UpdatesPage() {
const [deployments, setDeployments] = useState<Deployment[] | null>(null);
const [upcoming, setUpcoming] = useState<Job[]>([]);
const [chosen, setChosen] = useState<string[]>([]);
const [form, setForm] = useState({ version: "", at: toInput(new Date(Date.now() + 5 * H)), emergency: false, reason: "", totp: "" });
const [msg, setMsg] = useState<Msg>(null);
const load = useCallback(() => {
api<{ deployments: Deployment[] }>("/api/admin/deployments?status=live").then(r => setDeployments(r.deployments)).catch(e => setMsg({ type: "err", text: errorText(e) }));
api<{ jobs: Job[] }>("/api/admin/jobs?upcoming=true").then(r => setUpcoming(r.jobs)).catch(() => {});
}, []);
useEffect(() => { load(); }, [load]);
const byVersion = useMemo(() => [...new Set((deployments || []).map(d => d.install?.version || d.version || "?"))].sort(), [deployments]);
const submit = async (e: React.FormEvent) => {
e.preventDefault();
setMsg(null);
try {
const r = await api<{ jobs: Job[]; warnings: string[] }>("/api/admin/updates", { method: "POST", body: { deploymentIds: chosen, version: form.version || undefined, at: fromInput(form.at), emergency: form.emergency, reason: form.reason || null, totp: form.totp || null } });
setMsg({ type: "ok", text: `Planned for ${r.jobs.length} install(s); each church was emailed and sees a banner.${r.warnings.length ? ` Note: ${r.warnings.join(" ")}` : ""}` });
setChosen([]);
load();
} catch (err) { setMsg({ type: "err", text: errorText(err) }); }
};
return (
<div className="space-y-6">
<div>
<PageTitle title="Updates" subtitle="Plan a release for one or more installs. Churches get an email and a banner now, and a reminder an hour before." />
<ServersNav active="/servers/updates" />
<Message msg={msg} />
</div>
{!deployments ? <Loading /> : (
<form className="card space-y-4" onSubmit={submit}>
<div className="flex flex-wrap items-center gap-2 text-sm">
<span className="text-slate-500">Select:</span>
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.map(d => d.id))}>All live ({deployments.length})</button>
{byVersion.map(v => <button key={v} type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen(deployments.filter(d => (d.install?.version || d.version || "?") === v).map(d => d.id))}>On {v}</button>)}
<button type="button" className="btn-secondary px-2 py-1 text-xs" onClick={() => setChosen([])}>None</button>
</div>
<div className="max-h-72 space-y-1 overflow-y-auto rounded-lg border border-slate-200 p-3">
{deployments.map(d => (
<label key={d.id} className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={chosen.includes(d.id)} onChange={() => setChosen(chosen.includes(d.id) ? chosen.filter(x => x !== d.id) : [...chosen, d.id])} />
<span className="font-medium">{d.customer?.name}</span><span className="text-slate-500">{d.domain} · {d.install?.version || d.version || "?"} · {d.server?.name}</span>
</label>
))}
{!deployments.length && <p className="text-sm text-slate-500">No live installs on servers.</p>}
</div>
<div className="grid gap-3 md:grid-cols-2">
<div><label className="label" htmlFor="b-v">Release</label><input id="b-v" className="input" placeholder="latest" value={form.version} onChange={e => setForm({ ...form, version: e.target.value })} /></div>
<div><label className="label" htmlFor="b-at">When</label><input id="b-at" type="datetime-local" className="input" value={form.at} onChange={e => setForm({ ...form, at: e.target.value })} /><p className="mt-1 text-xs text-slate-500">At least {form.emergency ? "15 minutes" : "4 hours"} away. They run one at a time from then.</p></div>
<label className="flex items-center gap-2 text-sm md:col-span-2"><input type="checkbox" checked={form.emergency} onChange={e => setForm({ ...form, emergency: e.target.checked })} /> Emergency: 15 minutes&apos; notice, with a reason and your two-factor code</label>
{form.emergency && <>
<div><label className="label" htmlFor="b-r">Reason (shown to the churches)</label><input id="b-r" className="input" required value={form.reason} onChange={e => setForm({ ...form, reason: e.target.value })} /></div>
<div><label className="label" htmlFor="b-t">Two-factor code</label><input id="b-t" className="input" inputMode="numeric" autoComplete="one-time-code" required value={form.totp} onChange={e => setForm({ ...form, totp: e.target.value })} /></div>
</>}
</div>
<button className="btn-primary" disabled={!chosen.length}>Plan the update for {chosen.length} install(s)</button>
</form>
)}
<div className="card overflow-x-auto">
<h2 className="font-medium">Planned and running</h2>
<table className="mt-3 w-full text-sm">
<thead><tr className="text-left text-xs text-slate-500"><th className="py-1">Job</th><th>Install</th><th>When</th><th>Status</th></tr></thead>
<tbody>{upcoming.map(j => <tr key={j.id} className="border-t"><td className="py-1.5"><Link className="text-indigo-700 hover:underline" href={`/jobs/${j.id}`}>{j.type}</Link>{j.batchId && <span className="ml-1 text-xs text-slate-500">batch</span>}{j.emergency && <span className="ml-1 text-xs text-red-700">emergency</span>}</td><td>{j.deployment?.shortName || "–"}</td><td>{fmtDate(j.notBefore)}</td><td><StatusPill status={j.status} /></td></tr>)}</tbody>
</table>
{!upcoming.length && <p className="mt-2 text-sm text-slate-500">Nothing planned.</p>}
</div>
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
"use client";
import React, { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Download, Lock } from "lucide-react";
import { API_URL } from "@/lib/api";
import { bytes, fmtDate } from "@/lib/format";
import { Logo } from "@/components/ui";
/**
* A church's export (crosscode-platform AGENT-1.0-PLAN §9). The file on the Hub is encrypted; the
* key is the part of the link after #, which browsers never send to a server. This page fetches
* the encrypted bytes and decrypts them here (AES-256-GCM: 12-byte IV ‖ ciphertext ‖ tag).
*/
const fromB64u = (s: string) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((s.length + 3) % 4)), c => c.charCodeAt(0));
export default function DownloadPage() {
const { id } = useParams<{ id: string }>();
const [meta, setMeta] = useState<{ bytes: number; expiresAt: string } | null>(null);
const [state, setState] = useState<"loading" | "ready" | "working" | "done" | "error">("loading");
const [error, setError] = useState("");
useEffect(() => {
if (!window.location.hash.slice(1)) { setState("error"); setError("This link is missing its key (the part after #). Use the whole link from the email."); return; }
fetch(`${API_URL}/api/exports/${encodeURIComponent(id)}`).then(async r => {
if (!r.ok) throw new Error((await r.json().catch(() => null))?.message || "This download has expired or doesn't exist.");
setMeta(await r.json());
setState("ready");
}).catch(e => { setState("error"); setError(e.message); });
}, [id]);
const download = async () => {
setState("working");
try {
const key = fromB64u(window.location.hash.slice(1));
if (key.length !== 32) throw new Error("This link's key isn't complete. Copy the whole link from the email.");
const res = await fetch(`${API_URL}/api/exports/${encodeURIComponent(id)}/file`);
if (!res.ok) throw new Error("The file couldn't be downloaded. It may have expired.");
const data = new Uint8Array(await res.arrayBuffer());
const cryptoKey = await crypto.subtle.importKey("raw", key, "AES-GCM", false, ["decrypt"]);
let zip: ArrayBuffer;
try {
zip = await crypto.subtle.decrypt({ name: "AES-GCM", iv: data.slice(0, 12) }, cryptoKey, data.slice(12));
} catch {
throw new Error("The file couldn't be opened with this link's key. Check you used the whole link.");
}
const url = URL.createObjectURL(new Blob([zip], { type: "application/zip" }));
const a = document.createElement("a");
a.href = url;
a.download = "church-data.zip";
a.click();
setTimeout(() => URL.revokeObjectURL(url), 60000);
setState("done");
} catch (e) {
setState("error");
setError(e instanceof Error ? e.message : "Something went wrong.");
}
};
return (
<main className="mx-auto flex min-h-screen max-w-lg flex-col justify-center p-6">
<Logo />
<div className="card mt-6 space-y-4">
<h1 className="text-xl font-semibold">Your church&apos;s data</h1>
<p className="text-sm text-slate-600">One ZIP file with your events, people, registrations, payments, check-ins and rosters (export.json, explained in README.txt) and the uploaded files.</p>
<p className="flex items-start gap-2 text-xs text-slate-500"><Lock className="mt-0.5 h-3.5 w-3.5 shrink-0" /> The file is encrypted. It&apos;s opened here in your browser with the key in your link; we can&apos;t read it.</p>
{state === "loading" && <p className="text-sm text-slate-400">Checking the link…</p>}
{meta && state !== "error" && <p className="text-sm">{bytes(meta.bytes)} · available until {fmtDate(meta.expiresAt)}</p>}
{(state === "ready" || state === "working" || state === "done") && (
<button className="btn-primary" onClick={download} disabled={state === "working"}><Download className="h-4 w-4" /> {state === "working" ? "Downloading and opening…" : state === "done" ? "Download again" : "Download"}</button>
)}
{state === "done" && <p className="text-sm text-green-700">Saved as church-data.zip.</p>}
{state === "error" && <p className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-800">{error}</p>}
</div>
</main>
);
}
+156
View File
@@ -0,0 +1,156 @@
"use client";
import React, { useMemo, useRef, useState } from "react";
import { fmtDate } from "@/lib/format";
/** Shared pieces for the servers pages (2.1.0). */
export type ServerSummary = {
id: string; name: string; mode: "church" | "central"; hostname: string | null; agentVersion: string | null;
lastSeenAt: string | null; joinedAt: string; removedAt: string | null; notes: string | null; online: boolean;
ram: { totalBytes: number; availableBytes: number; usedPercent: number } | null;
cpu: { percent: number; load1: number; cores: number } | null;
disk: { mount: string; totalBytes: number; usedBytes: number; freeBytes: number }[];
versions: { os: string; node: string; postgres: string | null; frpc: string | null; agent: string } | null;
frpcRunning: boolean | null;
central: { proxyBindAddr: string | null; allowPorts: string | null; frpsRunning: boolean | null } | null;
deployments?: number;
alerts?: { type: string; level: string; message: string; createdAt: string }[];
lastDay?: { cpuAvg: number | null; ramAvg: number | null; cpuPeak: number | null; ramPeak: number | null } | null;
};
export type Deployment = {
id: string; serverId: string; customerId: string; installId: string | null; product: string; shortName: string; domain: string;
webPort: number; apiPort: number; status: string; version: string | null; adminName: string | null; adminEmail: string | null;
liveAt: string | null; createdAt: string;
server?: { id: string; name: string }; customer?: { id: string; name: string };
install?: { id: string; version: string | null; lastHeartbeatAt: string | null; url: string } | null;
};
export type Job = {
id: string; serverId: string; type: string; args: Record<string, unknown>; status: string; notBefore: string; expiresAt: string;
scheduled: boolean; emergency: boolean; reason: string | null; batchId: string | null; deliveredAt: string | null; finishedAt: string | null;
message: string | null; createdAt: string; deploymentId: string | null;
server?: { id: string; name: string }; deployment?: { id: string; shortName: string; domain: string } | null;
report?: { status: string; steps: { name: string; startedAt: string; finishedAt: string | null; outcome: string; detail?: string }[]; result: Record<string, unknown>; log: string[]; message?: string } | null;
};
const TONE: Record<string, string> = {
green: "bg-green-50 text-green-700 ring-green-600/20",
amber: "bg-amber-50 text-amber-800 ring-amber-600/20",
red: "bg-red-50 text-red-700 ring-red-600/20",
blue: "bg-indigo-50 text-indigo-700 ring-indigo-600/20",
grey: "bg-slate-100 text-slate-600 ring-slate-500/20",
};
const STATUS: Record<string, [string, string]> = {
// deployments
installing: ["Installing", "blue"], waiting_for_proxy: ["Waiting for proxy", "amber"], live: ["Live", "green"], failed: ["Failed", "red"],
uninstalling: ["Uninstalling", "amber"], removed: ["Removed", "grey"],
// jobs
scheduled: ["Waiting its turn", "grey"], queued: ["Due", "blue"], delivered: ["Running", "blue"], succeeded: ["Succeeded", "green"],
rolled_back: ["Rolled back", "amber"], refused: ["Refused", "red"], expired: ["Expired", "red"], missed: ["Missed", "red"], cancelled: ["Cancelled", "grey"],
// servers
online: ["Online", "green"], offline: ["Offline", "red"],
};
/** A status as a label (never colour alone). */
export function StatusPill({ status }: { status: string }) {
const [label, tone] = STATUS[status] || [status, "grey"];
return <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset ${TONE[tone]}`}>{label}</span>;
}
export const pct = (n: number | null | undefined) => (n == null ? "–" : `${Math.round(n)}%`);
// <input type="datetime-local"> works in the browser's time; the API takes ISO.
export const toInput = (d: Date) => new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
export const fromInput = (v: string) => (v ? new Date(v).toISOString() : "");
/**
* A single-series line chart of a percentage (0–100) over time, with spikes over `spike`%
* marked, a crosshair tooltip and a table view. One axis; the title names the series.
*/
export function PercentChart({ title, points, spike = 85 }: { title: string; points: { at: string; value: number; peak: number }[]; spike?: number }) {
const W = 640, H = 160, L = 34, R = 8, T = 10, B = 22;
const [hover, setHover] = useState<number | null>(null);
const svgRef = useRef<SVGSVGElement>(null);
const times = useMemo(() => points.map(p => new Date(p.at).getTime()), [points]);
if (points.length < 2) return <div className="card"><h3 className="text-sm font-medium">{title}</h3><p className="mt-2 text-sm text-slate-500">Not enough data yet.</p></div>;
const t0 = times[0], t1 = times[times.length - 1] || t0 + 1;
const x = (t: number) => L + ((t - t0) / Math.max(1, t1 - t0)) * (W - L - R);
const y = (v: number) => T + (1 - Math.min(100, Math.max(0, v)) / 100) * (H - T - B);
const path = points.map((p, i) => `${i ? "L" : "M"}${x(times[i]).toFixed(1)},${y(p.value).toFixed(1)}`).join("");
const spikes = points.map((p, i) => ({ p, i })).filter(({ p }) => p.peak > spike);
const onMove = (e: React.MouseEvent<SVGSVGElement>) => {
const r = svgRef.current?.getBoundingClientRect();
if (!r) return;
const t = t0 + ((((e.clientX - r.left) / r.width) * W - L) / (W - L - R)) * (t1 - t0);
let best = 0;
for (let i = 1; i < times.length; i++) if (Math.abs(times[i] - t) < Math.abs(times[best] - t)) best = i;
setHover(best);
};
const h = hover != null ? points[hover] : null;
return (
<div className="card">
<div className="flex items-baseline justify-between gap-2">
<h3 className="text-sm font-medium">{title}</h3>
<span className="text-xs text-slate-500">{spikes.length ? `${spikes.length} spike${spikes.length === 1 ? "" : "s"} over ${spike}%` : `No spikes over ${spike}%`}</span>
</div>
<div className="relative mt-2">
<svg ref={svgRef} viewBox={`0 0 ${W} ${H}`} className="h-40 w-full" role="img" aria-label={`${title}, ${points.length} points`} onMouseMove={onMove} onMouseLeave={() => setHover(null)}>
{[0, 50, 100].map(v => (
<g key={v}>
<line x1={L} x2={W - R} y1={y(v)} y2={y(v)} stroke="#e2e8f0" strokeWidth="1" />
<text x={L - 6} y={y(v) + 4} textAnchor="end" className="fill-slate-400 text-[10px]">{v}%</text>
</g>
))}
<line x1={L} x2={W - R} y1={y(spike)} y2={y(spike)} stroke="#f59e0b" strokeWidth="1" strokeDasharray="3 3" />
<text x={L} y={H - 6} className="fill-slate-400 text-[10px]">{fmtDate(points[0].at)}</text>
<text x={W - R} y={H - 6} textAnchor="end" className="fill-slate-400 text-[10px]">{fmtDate(points[points.length - 1].at)}</text>
<path d={path} fill="none" stroke="#4f46e5" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
{spikes.map(({ p, i }) => <circle key={i} cx={x(times[i])} cy={y(p.peak)} r="4" fill="#f59e0b" stroke="#fff" strokeWidth="2"><title>{`Spike ${Math.round(p.peak)}% at ${fmtDate(p.at)}`}</title></circle>)}
{h && hover != null && (
<g>
<line x1={x(times[hover])} x2={x(times[hover])} y1={T} y2={H - B} stroke="#94a3b8" strokeWidth="1" />
<circle cx={x(times[hover])} cy={y(h.value)} r="4" fill="#4f46e5" stroke="#fff" strokeWidth="2" />
</g>
)}
</svg>
{h && hover != null && (
<div className="pointer-events-none absolute top-0 rounded-md border border-slate-200 bg-white px-2 py-1 text-xs shadow-sm" style={{ left: `${Math.min(80, (x(times[hover]) / W) * 100)}%` }}>
<div className="text-slate-500">{fmtDate(h.at)}</div>
<div className="font-medium tabular-nums">{Math.round(h.value)}% (peak {Math.round(h.peak)}%)</div>
</div>
)}
</div>
<details className="mt-2 text-xs text-slate-500">
<summary className="cursor-pointer">Show as a table</summary>
<div className="mt-2 max-h-48 overflow-y-auto">
<table className="w-full tabular-nums">
<thead><tr className="text-left"><th>Time</th><th className="text-right">Average</th><th className="text-right">Peak</th></tr></thead>
<tbody>{points.slice(-200).reverse().map(p => <tr key={p.at}><td>{fmtDate(p.at)}</td><td className="text-right">{Math.round(p.value)}%</td><td className="text-right">{Math.round(p.peak)}%</td></tr>)}</tbody>
</table>
</div>
</details>
</div>
);
}
const SUBNAV = [
{ href: "/servers", label: "Servers" },
{ href: "/servers/installs", label: "Installs" },
{ href: "/servers/updates", label: "Updates" },
{ href: "/jobs", label: "Jobs" },
{ href: "/servers/settings", label: "Ports & defaults" },
];
/** The links between the servers pages. */
export function ServersNav({ active }: { active: string }) {
return (
<nav className="mb-6 flex flex-wrap gap-1 border-b border-slate-200">
{SUBNAV.map(n => (
<a key={n.href} href={n.href} className={`-mb-px border-b-2 px-3 py-2 text-sm ${active === n.href ? "border-indigo-600 font-medium text-indigo-700" : "border-transparent text-slate-600 hover:text-slate-900"}`}>{n.label}</a>
))}
</nav>
);
}