diff --git a/DATABASE.md b/DATABASE.md index a12ec77..eda918c 100644 --- a/DATABASE.md +++ b/DATABASE.md @@ -97,7 +97,7 @@ Who changed what. Written by the app on every change (see | `id` | integer PK | | | `actor_user_id` | integer → `users.id`, **set null** on delete | Null for automatic actions, and for entries whose user was deleted. | | `actor_label` | text | The user's name/email as it was at the time (or `system`), so an entry still reads correctly after the account is gone. | -| `category` | text NOT NULL | Free text. In use: `server`, `integration`, `dns`, `settings`, `ipam`, `secret`, `domain`, `tag`, `task`, `session`, `network`, `maintenance`, `consistency`, `user`, `privacy`, `diag_log`, `alert_ticket`. | +| `category` | text NOT NULL | Free text. In use: `server` (including the health check's own `went_offline`, `back_online`, `disk_full` and `disk_ok`, written as `system` and shown on a server's Activity card), `integration`, `dns`, `settings`, `ipam`, `secret`, `domain`, `tag`, `task`, `session`, `network`, `maintenance`, `consistency`, `user`, `privacy`, `diag_log`, `alert_ticket`. | | `action` | text NOT NULL | `create`, `update`, `delete`, `start`, `stop`, … — free text. | | `target_type`, `target_id` | text | What it happened to. `target_id` is text so it can hold any kind of ID; there's no foreign key. | | `detail` | text | JSON, free-form context (what changed, names, counts). Secrets are never put here. | diff --git a/README.md b/README.md index 7274e80..58762f5 100644 --- a/README.md +++ b/README.md @@ -355,6 +355,48 @@ schedule needs a login on the Uptime Kuma integration (see INTEGRATIONS.md). "Import now" is the older, simpler route: it only looks at what is in maintenance this moment and starts a window for a duration you choose. +**Getting around.** Ctrl/Cmd+K opens a search that also runs actions: go to any +page, switch light/dark or the density, start (or end) a maintenance window on +a server, integration or DNS provider ("silence elsa"), open the wall display, +sign out. "g" then a letter goes to a page (`g d` dashboard, `g a` alerts, +`g s` servers, `g m` maintenance, `g i` integrations, `g k` secrets, `g p` map, +`g w` wall display), "/" jumps to the page's table search, and "?" lists them +all. Shortcuts for pages your role can't open are ignored, and none fire while +you are typing. On a table of Proxmox guests, Docker containers, Tailscale +devices, Uptime Kuma monitors, Gitea repositories or Semaphore templates, a +click (or Enter) on a row opens a panel with everything known about it, without +leaving the table. + +**Map** (Infrastructure → Map) draws how things connect: which Proxmox host each +linked server runs on, which DNS names point at it (an A or AAAA record holding +one of the server's own addresses — nothing is guessed from names), and which +Uptime Kuma monitors watch it. Hover or tab to a box to light up its +connections; each box links to its page. A monitor Uptime Kuma can't be read for +leaves a note rather than a silent gap. + +**Wall display** (`/wall`, also on the dashboard and the user menu) is a +full-screen status board for a spare monitor or tablet: the overall state in +large type, servers online, alerts, maintenance windows and failing integrations, +the problems themselves, and each integration's status, refreshing every 30 +seconds with the screen kept awake where the browser allows. Esc returns to the +app. + +**Activity.** Operators and admins see an Activity card on each server's page: +what changed on it and who changed it, the moments the health check saw it stop +reporting (and report again) or a disk fill (and recover) — now written to the +audit log as they happen — and its maintenance windows, including ones set up by +the Uptime Kuma sync. **Getting started**: until the basics are in place, an +admin's dashboard shows a checklist (an integration, a server and agent, DNS, a +secret, notifications, a second user) whose ticks come from what actually +exists; it can be hidden, and brought back from the search box. + +**Accessibility.** There is a skip-to-content link, labelled landmarks, visible +keyboard focus, and page changes are announced to screen readers; sortable table +headings are real buttons; every form field is tied to its label; status is +never colour alone; the search box and dialogs are proper dialogs (keyboard +trapped and restored); and the text colours were checked against the contrast +minimum in both themes. Motion is turned down for those who ask the system to. + **Ports** — each server's detail page has a Ports card for finding free ports and remembering what each one is for. "Scan…" runs a TCP scan of a port range from the app against the server's address (private addresses only, up to diff --git a/server/src/app.ts b/server/src/app.ts index 3861dfd..9a1ba3c 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -28,6 +28,7 @@ import { privacyRouter } from "./routes/privacy.js"; import { tagsRouter } from "./routes/tags.js"; import { portsRouter } from "./routes/ports.js"; import { alertsRouter } from "./routes/alerts.js"; +import { mapRouter } from "./routes/map.js"; import { generatorRouter } from "./routes/generator.js"; import { alertTicketsRouter } from "./routes/alertTickets.js"; import { apiErrorHandler } from "./utils/apiErrorHandler.js"; @@ -105,6 +106,7 @@ export function createApp() { app.use("/api/tags", tagsRouter); app.use("/api/ports", portsRouter); app.use("/api/alerts", alertsRouter); + app.use("/api/map", mapRouter); app.use("/api/generator", generatorRouter); app.use("/api/alert-tickets", alertTicketsRouter); diff --git a/server/src/routes/map.ts b/server/src/routes/map.ts new file mode 100644 index 0000000..38d94f4 --- /dev/null +++ b/server/src/routes/map.ts @@ -0,0 +1,14 @@ +import { Router } from "express"; +import { requireAuth } from "../auth/middleware.js"; +import { buildTopology } from "../services/topology.js"; +import { asyncHandler } from "../utils/asyncHandler.js"; + +export const mapRouter = Router(); + +mapRouter.use(requireAuth); + +// How servers, Proxmox hosts, DNS names and monitors connect. Everyone signed in can see it: it is the same information the pages +// it links to already show. +mapRouter.get("/", asyncHandler(async (_req, res) => { + res.json(await buildTopology()); +})); diff --git a/server/src/routes/servers.ts b/server/src/routes/servers.ts index d30a432..6fedbfb 100644 --- a/server/src/routes/servers.ts +++ b/server/src/routes/servers.ts @@ -7,6 +7,7 @@ import { requireAuth, requireRole } from "../auth/middleware.js"; import { generateApiToken } from "../services/tokens.js"; import { recordAudit } from "../services/audit.js"; import { getServerMetrics, RETENTION_DAYS } from "../services/serverMetrics.js"; +import { getServerActivity } from "../services/serverActivity.js"; import { asyncHandler } from "../utils/asyncHandler.js"; import { ID_PATTERNS } from "../utils/pathSegment.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; @@ -201,6 +202,16 @@ serversRouter.get("/:id/metrics", asyncHandler(async (req, res) => { res.json({ days, series: await getServerMetrics(id, days) }); })); +// What has happened to a server: changes to it, the health check seeing it stop reporting or a disk fill, and its maintenance +// windows. Operators and above — the audit log it draws on is theirs to read. +serversRouter.get("/:id/activity", requireRole("operator"), asyncHandler(async (req, res) => { + const id = Number(req.params.id); + if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" }); + const [server] = await db.select({ id: servers.id }).from(servers).where(eq(servers.id, id)).limit(1); + if (!server) return res.status(404).json({ error: "not_found" }); + res.json({ events: await getServerActivity(id) }); +})); + serversRouter.get("/:id/detail", asyncHandler(async (req, res) => { const id = Number(req.params.id); if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" }); diff --git a/server/src/services/healthMonitor.ts b/server/src/services/healthMonitor.ts index 55bec76..452c8c8 100644 --- a/server/src/services/healthMonitor.ts +++ b/server/src/services/healthMonitor.ts @@ -5,6 +5,7 @@ import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { createProxmoxAdapter, type ProxmoxNodeStats } from "../integrations/proxmox/adapter.js"; import { createSynologyAdapter, type SynologyStorageInfo } from "../integrations/synology/adapter.js"; import { notifyHealthIssues, notifyHealthRecovered } from "./notify.js"; +import { recordAudit } from "./audit.js"; import { getInternalFlag, getSettings, setInternalFlag } from "./settingsStore.js"; import { activeSubjects, subjectOfConditionKey } from "./maintenance.js"; @@ -318,6 +319,33 @@ async function loadState(): Promise { } } +/** + * Writes down, in the audit log, the moments a server stopped reporting or a disk filled up — and when they ended — so a server's + * page can tell the story afterwards. Only for problems that are about a server; never allowed to hold up the check itself. + */ +export async function recordServerTransitions(added: { key: string; message: string }[], resolved: { key: string; message: string }[]): Promise { + const about = (key: string) => /^(offline|disk):server:(\d+)(?::(.*))?$/.exec(key); + const write = async (items: { key: string; message: string }[], names: { offline: string; disk: string }, withMessage: boolean) => { + for (const item of items) { + const m = about(item.key); + if (!m) continue; + try { + await recordAudit({ + category: "server", + action: m[1] === "offline" ? names.offline : names.disk, + targetType: "server", + targetId: m[2], + detail: withMessage ? { message: item.message, ...(m[3] ? { mount: m[3] } : {}) } : m[3] ? { mount: m[3] } : undefined, + }); + } catch (err) { + console.error("[health] couldn't record a server event:", err); + } + } + }; + await write(added, { offline: "went_offline", disk: "disk_full" }, true); + await write(resolved, { offline: "back_online", disk: "disk_ok" }, false); +} + export async function runHealthCheck(now: number = Date.now()): Promise<{ added: number; resolved: number }> { const { healthChecks } = await getSettings(); const { snapshot, held } = await collectSnapshot(); @@ -331,6 +359,7 @@ export async function runHealthCheck(now: number = Date.now()): Promise<{ added: // State is tracked even when the alert toggle is off (the notify functions check it), // so turning alerts back on doesn't dump every long-standing condition at once. + await recordServerTransitions(added, resolved); if (added.length > 0) await notifyHealthIssues(added); if (resolved.length > 0) await notifyHealthRecovered(resolved); return { added: added.length, resolved: resolved.length }; diff --git a/server/src/services/serverActivity.ts b/server/src/services/serverActivity.ts new file mode 100644 index 0000000..6cda09a --- /dev/null +++ b/server/src/services/serverActivity.ts @@ -0,0 +1,117 @@ +/** + * What has happened to one server, newest first: changes people made to it, the moments the health check saw it stop reporting or + * a disk fill (and recover), and its maintenance windows. Built from the audit log and the maintenance windows, so it needs + * nothing of its own — except that the health check now writes down those moments when they happen. + */ +import { and, desc, eq } from "drizzle-orm"; +import { db } from "../db/client.js"; +import { auditLog, maintenanceWindows } from "../db/schema.js"; + +export type ActivityTone = "good" | "bad" | "neutral" | "info"; + +export interface ActivityEvent { + /** ISO. */ + at: string; + kind: "change" | "health" | "maintenance"; + tone: ActivityTone; + title: string; + detail: string | null; + /** Who did it; "system" for the app's own checks. Null when it isn't a person's doing. */ + actor: string | null; +} + +/** The audit log stores SQLite's "2026-10-03 14:05:09" (UTC); the rest of the app speaks ISO. */ +export function auditTimeToIso(value: string): string { + return /T|Z$/.test(value) ? new Date(value).toISOString() : new Date(`${value.replace(" ", "T")}Z`).toISOString(); +} + +const humanize = (s: string) => { + const t = s.replace(/[_-]+/g, " "); + return t.charAt(0).toUpperCase() + t.slice(1); +}; + +function parseDetail(detail: string | null): Record { + if (!detail) return {}; + try { + const v = JSON.parse(detail); + return v && typeof v === "object" ? (v as Record) : {}; + } catch { + return {}; + } +} + +/** A readable line for one audit entry about a server. */ +export function describeAudit(category: string, action: string, detail: Record): { title: string; tone: ActivityTone; kind: ActivityEvent["kind"]; detail: string | null } { + const message = typeof detail.message === "string" ? detail.message : null; + const label = typeof detail.label === "string" ? detail.label : null; + if (category === "server") { + switch (action) { + case "went_offline": + return { title: "Stopped reporting — marked offline", tone: "bad", kind: "health", detail: message }; + case "back_online": + return { title: "Reporting again", tone: "good", kind: "health", detail: null }; + case "disk_full": + return { title: "A disk got nearly full", tone: "bad", kind: "health", detail: message }; + case "disk_ok": + return { title: "A disk is no longer nearly full", tone: "good", kind: "health", detail: null }; + case "create": + return { title: "Server added", tone: "neutral", kind: "change", detail: null }; + case "update": + return { title: "Details changed", tone: "neutral", kind: "change", detail: null }; + case "rotate_token": + return { title: "Agent token replaced", tone: "neutral", kind: "change", detail: null }; + case "set_tags": + return { title: "Tags changed", tone: "neutral", kind: "change", detail: null }; + case "add_link": + return { title: "Admin link added", tone: "neutral", kind: "change", detail: label }; + case "update_link": + return { title: "Admin link changed", tone: "neutral", kind: "change", detail: label }; + case "remove_link": + return { title: "Admin link removed", tone: "neutral", kind: "change", detail: label }; + } + } + return { title: `${humanize(category)}: ${action.replace(/_/g, " ")}`, tone: "neutral", kind: "change", detail: message ?? label }; +} + +export async function getServerActivity(serverId: number, now: Date = new Date(), limit = 60): Promise { + const events: ActivityEvent[] = []; + + const audits = await db + .select() + .from(auditLog) + .where(and(eq(auditLog.targetType, "server"), eq(auditLog.targetId, String(serverId)))) + .orderBy(desc(auditLog.createdAt)) + .limit(limit); + for (const a of audits) { + // Maintenance is shown from the windows themselves below, which also cover the ones nobody started by hand. + if (a.category === "maintenance") continue; + const d = describeAudit(a.category, a.action, parseDetail(a.detail)); + events.push({ at: auditTimeToIso(a.createdAt), kind: d.kind, tone: d.tone, title: d.title, detail: d.detail, actor: a.actorLabel }); + } + + const windows = await db + .select() + .from(maintenanceWindows) + .where(and(eq(maintenanceWindows.targetType, "server"), eq(maintenanceWindows.targetId, serverId))) + .orderBy(desc(maintenanceWindows.startedAt)) + .limit(20); + const nowIso = now.toISOString(); + for (const w of windows) { + const cancelled = w.endsAt <= w.startedAt; + if (cancelled) continue; // set up and withdrawn before it began: nothing happened + const until = `until ${w.endsAt.slice(0, 16).replace("T", " ")} UTC`; + events.push({ + at: w.startedAt, + kind: "maintenance", + tone: "info", + title: w.startedAt > nowIso ? "Maintenance scheduled" : "Maintenance started — alerts silenced", + detail: [w.reason, until].filter(Boolean).join(" · "), + actor: w.createdBy, + }); + if (w.endsAt <= nowIso) { + events.push({ at: w.endsAt, kind: "maintenance", tone: "info", title: "Maintenance ended", detail: null, actor: null }); + } + } + + return events.sort((a, b) => b.at.localeCompare(a.at)).slice(0, limit); +} diff --git a/server/src/services/topology.ts b/server/src/services/topology.ts new file mode 100644 index 0000000..0a4b2af --- /dev/null +++ b/server/src/services/topology.ts @@ -0,0 +1,136 @@ +/** + * How the things in the app connect, as a graph for the Map page: which Proxmox host each server runs on, which DNS names point + * at it, and which Uptime Kuma monitors watch it. Everything here is already known elsewhere in the app; this only puts it side + * by side. Nothing is guessed: a DNS name is a server's only when an A or AAAA record holds one of the server's own addresses, + * and a monitor only when its target is the server's (the same matching the Uptime Kuma page uses). + */ +import { and, eq, inArray } from "drizzle-orm"; +import { db } from "../db/client.js"; +import { dnsRecordsCache, dnsZonesCache, integrations, servers } from "../db/schema.js"; +import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; +import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js"; +import { getSettings } from "./settingsStore.js"; +import { attachMatchedServers, toMatchableServers } from "./uptimeKumaMatch.js"; + +export type MapStatus = "ok" | "bad" | "warn" | "unknown"; + +export interface MapNode { + id: string; + kind: "host" | "server" | "dns" | "monitor"; + label: string; + sub: string | null; + status: MapStatus; + /** Where in the app to find out more. */ + href: string | null; +} + +export interface MapEdge { + from: string; + to: string; +} + +export interface MapData { + nodes: MapNode[]; + edges: MapEdge[]; + /** Things that couldn't be read, so the picture is incomplete. */ + notes: string[]; +} + +/** More than this many DNS names on the map and it stops being a map. */ +const MAX_DNS_NAMES = 60; +const KUMA_TIMEOUT_MS = 8_000; + +function withTimeout(work: Promise, ms: number): Promise { + let timer: ReturnType; + const limit = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`timed out after ${ms / 1000}s`)), ms); + }); + return Promise.race([work, limit]).finally(() => clearTimeout(timer)); +} + +function parseIps(stored: string | null): string[] { + if (!stored) return []; + try { + const v = JSON.parse(stored); + return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; + } catch { + return []; + } +} + +export async function buildTopology(now: Date = new Date()): Promise { + const nodes: MapNode[] = []; + const edges: MapEdge[] = []; + const notes: string[] = []; + + const { healthChecks } = await getSettings(); + const offlineAfterMs = healthChecks.serverOfflineMinutes * 60_000; + const serverRows = await db.select().from(servers); + const integrationRows = await db.select({ id: integrations.id, name: integrations.name, type: integrations.type, enabled: integrations.enabled }).from(integrations); + const integrationName = new Map(integrationRows.map((i) => [i.id, i.name])); + + // Servers, and the Proxmox hosts they run on. + const hostIds = new Set(); + for (const s of serverRows) { + const lastSeen = s.lastSeenAt ? Date.parse(s.lastSeenAt) : null; + const status: MapStatus = lastSeen === null ? "unknown" : now.getTime() - lastSeen > offlineAfterMs ? "bad" : "ok"; + nodes.push({ id: `server:${s.id}`, kind: "server", label: s.name, sub: s.hostname, status, href: `/servers/${s.id}` }); + if (s.proxmoxIntegrationId && s.proxmoxNode) { + const hostId = `host:${s.proxmoxIntegrationId}:${s.proxmoxNode}`; + if (!hostIds.has(hostId)) { + hostIds.add(hostId); + nodes.push({ id: hostId, kind: "host", label: s.proxmoxNode, sub: integrationName.get(s.proxmoxIntegrationId) ?? "Proxmox", status: "unknown", href: "/proxmox" }); + } + edges.push({ from: hostId, to: `server:${s.id}` }); + } + } + + // DNS names that point at a server's own address. + const serversByIp = new Map(); + for (const s of serverRows) for (const ip of parseIps(s.ipAddresses)) serversByIp.set(ip, [...(serversByIp.get(ip) ?? []), s.id]); + if (serversByIp.size > 0) { + const records = await db + .select({ name: dnsRecordsCache.name, content: dnsRecordsCache.content, zoneName: dnsZonesCache.zoneName }) + .from(dnsRecordsCache) + .leftJoin(dnsZonesCache, and(eq(dnsZonesCache.providerId, dnsRecordsCache.providerId), eq(dnsZonesCache.zoneId, dnsRecordsCache.zoneId))) + .where(and(inArray(dnsRecordsCache.type, ["A", "AAAA"]), inArray(dnsRecordsCache.content, [...serversByIp.keys()]))); + const seen = new Set(); + for (const r of records) { + const zone = r.zoneName?.replace(/\.$/, "") ?? ""; + const name = r.name === "@" ? zone : zone && !r.name.replace(/\.$/, "").endsWith(zone) ? `${r.name}.${zone}` : r.name.replace(/\.$/, ""); + const id = `dns:${name}`; + if (!seen.has(id)) { + if (seen.size >= MAX_DNS_NAMES) { + if (!notes.some((n) => n.startsWith("Only the first"))) notes.push(`Only the first ${MAX_DNS_NAMES} DNS names are shown.`); + continue; + } + seen.add(id); + nodes.push({ id, kind: "dns", label: name, sub: null, status: "unknown", href: "/dns" }); + } + for (const serverId of serversByIp.get(r.content) ?? []) { + if (!edges.some((e) => e.from === `server:${serverId}` && e.to === id)) edges.push({ from: `server:${serverId}`, to: id }); + } + } + } + + // Uptime Kuma monitors watching a server. + const matchable = toMatchableServers(serverRows.map((s) => ({ id: s.id, name: s.name, hostname: s.hostname, ips: s.ipAddresses }))); + for (const row of integrationRows.filter((i) => i.type === "uptimekuma" && i.enabled)) { + try { + const loaded = await loadIntegrationConfig(row.id); + if (!loaded) continue; + const monitors = await withTimeout(createUptimeKumaAdapter(loaded.config as never).listMonitors(), KUMA_TIMEOUT_MS); + for (const m of attachMatchedServers(monitors, matchable)) { + if (!m.matchedServer) continue; + const id = `monitor:${row.id}:${m.id}`; + const status: MapStatus = m.status === "up" ? "ok" : m.status === "down" ? "bad" : m.status === "unknown" ? "unknown" : "warn"; + nodes.push({ id, kind: "monitor", label: m.name, sub: row.name, status, href: "/uptime-kuma" }); + edges.push({ from: `server:${m.matchedServer.id}`, to: id }); + } + } catch (err) { + notes.push(`Couldn't read Uptime Kuma “${row.name}” (${err instanceof Error ? err.message : String(err)}), so its monitors are missing.`); + } + } + + return { nodes, edges, notes }; +} diff --git a/server/test/serverActivity.test.ts b/server/test/serverActivity.test.ts new file mode 100644 index 0000000..ce8844d --- /dev/null +++ b/server/test/serverActivity.test.ts @@ -0,0 +1,163 @@ +/** + * A server's activity timeline: what the health check wrote down, what people changed, and its maintenance windows. + * + * Run with: npm test --workspace server + */ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { AddressInfo } from "node:net"; +import type { Server } from "node:http"; + +const dir = mkdtempSync(join(tmpdir(), "hm-activity-")); +process.env.DATABASE_PATH = join(dir, "test.sqlite"); +process.env.SESSION_DIR = join(dir, "sessions"); +process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); + +const express = (await import("express")).default; +const { db } = await import("../src/db/client.js"); +const { users, servers, maintenanceWindows, auditLog } = await import("../src/db/schema.js"); +const { runMigrations } = await import("../src/db/migrate.js"); +const { recordAudit } = await import("../src/services/audit.js"); +const { recordServerTransitions } = await import("../src/services/healthMonitor.js"); +const { getServerActivity, describeAudit, auditTimeToIso } = await import("../src/services/serverActivity.js"); +const { serversRouter } = await import("../src/routes/servers.js"); + +await runMigrations(); + +describe("reading audit entries", () => { + test("SQLite's UTC timestamp becomes ISO", () => { + assert.equal(auditTimeToIso("2026-10-03 14:05:09"), "2026-10-03T14:05:09.000Z"); + assert.equal(auditTimeToIso("2026-10-03T14:05:09.123Z"), "2026-10-03T14:05:09.123Z"); + }); + + test("known actions read as sentences, unknown ones still say something", () => { + assert.equal(describeAudit("server", "went_offline", { message: "x" }).tone, "bad"); + assert.equal(describeAudit("server", "back_online", {}).tone, "good"); + assert.equal(describeAudit("server", "rotate_token", {}).title, "Agent token replaced"); + assert.equal(describeAudit("server", "add_link", { label: "Cockpit" }).detail, "Cockpit"); + assert.equal(describeAudit("task", "run_now", {}).title, "Task: run now"); + }); +}); + +describe("the timeline", () => { + let serverId = 0; + let otherId = 0; + + before(async () => { + serverId = (await db.insert(servers).values({ name: "elsa", apiTokenHash: "a", apiTokenPrefix: "a" }).returning())[0].id; + otherId = (await db.insert(servers).values({ name: "other", apiTokenHash: "b", apiTokenPrefix: "b" }).returning())[0].id; + }); + + test("the health check's moments are written down for the server they are about, and only server ones", async () => { + await recordServerTransitions( + [ + { key: `offline:server:${serverId}`, message: "elsa hasn't reported for 2 hours" }, + { key: `disk:server:${serverId}:/data`, message: "/data is 93% full" }, + { key: "disk:proxmox:4:local", message: "not a server" }, + { key: `offline:server:${otherId}`, message: "other is quiet" }, + ], + [], + ); + await recordServerTransitions([], [{ key: `offline:server:${serverId}`, message: "back" }]); + + const events = await getServerActivity(serverId); + const titles = events.map((e) => e.title); + assert.ok(titles.includes("Stopped reporting — marked offline")); + assert.ok(titles.includes("A disk got nearly full")); + assert.ok(titles.includes("Reporting again")); + assert.equal(events.find((e) => e.title === "A disk got nearly full")!.detail, "/data is 93% full"); + assert.equal(events.find((e) => e.title === "Reporting again")!.tone, "good"); + assert.equal(events.every((e) => e.actor === "system"), true, "the app's own doing is marked as such"); + assert.equal((await getServerActivity(otherId)).length, 1, "the other server has only its own"); + }); + + test("changes people made appear with who made them", async () => { + const [tobias] = await db.insert(users).values({ oidcSub: "tobias", name: "Tobias", role: "admin" }).returning(); + await recordAudit({ category: "server", action: "rotate_token", targetType: "server", targetId: serverId, actor: tobias }); + const found = (await getServerActivity(serverId)).find((e) => e.title === "Agent token replaced")!; + assert.equal(found.actor, "Tobias"); + assert.equal(found.kind, "change"); + }); + + test("maintenance windows appear as a start and, once over, an end; maintenance audit entries are not doubled", async () => { + const now = new Date(); + const H = 3600_000; + await db.insert(maintenanceWindows).values([ + { targetType: "server", targetId: serverId, reason: "patching", startedAt: new Date(now.getTime() - 5 * H).toISOString(), endsAt: new Date(now.getTime() - 4 * H).toISOString(), createdBy: "Tobias" }, + { targetType: "server", targetId: serverId, reason: "tonight", startedAt: new Date(now.getTime() + 5 * H).toISOString(), endsAt: new Date(now.getTime() + 6 * H).toISOString(), createdBy: "Uptime Kuma sync" }, + // Set up, then cancelled before it began. + { targetType: "server", targetId: serverId, reason: "cancelled", startedAt: new Date(now.getTime() + 9 * H).toISOString(), endsAt: new Date(now.getTime() + 9 * H).toISOString() }, + ]); + await recordAudit({ category: "maintenance", action: "start", targetType: "server", targetId: serverId, detail: { minutes: 60 } }); + + const events = await getServerActivity(serverId); + const maint = events.filter((e) => e.kind === "maintenance"); + assert.deepEqual(maint.map((e) => e.title).sort(), ["Maintenance ended", "Maintenance scheduled", "Maintenance started — alerts silenced"]); + assert.ok(!events.some((e) => e.detail?.includes("cancelled")), "a cancelled window is not an event"); + assert.equal(events.filter((e) => e.title.toLowerCase().includes("maintenance")).length, 3, "the audit entry did not add a fourth"); + }); + + test("newest first", async () => { + const events = await getServerActivity(serverId); + const sorted = [...events].sort((a, b) => b.at.localeCompare(a.at)); + assert.deepEqual(events.map((e) => e.at), sorted.map((e) => e.at)); + // the scheduled window is in the future, so it leads + assert.equal(events[0].title, "Maintenance scheduled"); + }); +}); + +describe("GET /api/servers/:id/activity", () => { + let app: Server; + let base = ""; + let serverId = 0; + let role: "viewer" | "operator" = "viewer"; + + before(async () => { + await db.insert(users).values([ + { oidcSub: "viewer", name: "Viewer", role: "viewer" }, + { oidcSub: "operator", name: "Operator", role: "operator" }, + ]); + serverId = (await db.insert(servers).values({ name: "route", apiTokenHash: "r", apiTokenPrefix: "r" }).returning())[0].id; + await db.insert(auditLog).values({ category: "server", action: "create", targetType: "server", targetId: String(serverId), actorLabel: "Someone" }); + const a = express(); + a.use(express.json()); + a.use((req, _res, next) => { + (req as unknown as { session: unknown }).session = { user: { sub: role } }; + next(); + }); + a.use("/api/servers", serversRouter); + app = await new Promise((resolve) => { + const s = a.listen(0, "127.0.0.1", () => resolve(s)); + }); + base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/servers`; + }); + + after(() => { + app.close(); + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows keeps the database file locked until the process exits. + } + }); + + test("a viewer is refused; an operator gets the timeline", async () => { + role = "viewer"; + assert.equal((await fetch(`${base}/${serverId}/activity`)).status, 403); + role = "operator"; + const res = await fetch(`${base}/${serverId}/activity`); + assert.equal(res.status, 200); + const body = await res.json(); + assert.equal(body.events[0].title, "Server added"); + assert.equal(body.events[0].actor, "Someone"); + }); + + test("an unknown server is a 404 and a bad id a 400", async () => { + role = "operator"; + assert.equal((await fetch(`${base}/99999/activity`)).status, 404); + assert.equal((await fetch(`${base}/abc/activity`)).status, 400); + }); +}); diff --git a/server/test/topology.test.ts b/server/test/topology.test.ts new file mode 100644 index 0000000..3afe546 --- /dev/null +++ b/server/test/topology.test.ts @@ -0,0 +1,114 @@ +/** + * The Map page's graph: Proxmox hosts → servers → DNS names and monitors, with nothing guessed. + * + * Run with: npm test --workspace server + */ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; + +const dir = mkdtempSync(join(tmpdir(), "hm-topology-")); +process.env.DATABASE_PATH = join(dir, "test.sqlite"); +process.env.SESSION_DIR = join(dir, "sessions"); +process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); + +const { db } = await import("../src/db/client.js"); +const { servers, integrations, dnsProviders, dnsZonesCache, dnsRecordsCache } = await import("../src/db/schema.js"); +const { runMigrations } = await import("../src/db/migrate.js"); +const { buildTopology } = await import("../src/services/topology.js"); + +await runMigrations(); + +const metric = (id: number, host: string, status: number) => + `monitor_status{monitor_id="${id}",monitor_name="m${id}",monitor_type="ping",monitor_url="",monitor_hostname="${host}",monitor_port=""} ${status}`; + +describe("buildTopology", () => { + let kuma: http.Server; + let kumaStatus = 200; + + before(async () => { + kuma = await new Promise((resolve) => { + const s = http.createServer((req, res) => { + res.statusCode = kumaStatus; + res.end(req.url === "/metrics" ? [metric(1, "elsa.lab.example", 1), metric(2, "elsa.lab.example", 0), metric(3, "unknown.example", 1)].join("\n") : ""); + }); + s.listen(0, "127.0.0.1", () => resolve(s)); + }); + const kumaUrl = `http://127.0.0.1:${(kuma.address() as AddressInfo).port}`; + + const [pve] = await db.insert(integrations).values({ type: "proxmox", name: "Felicia", baseUrl: "https://pve.lab", config: "{}" }).returning(); + await db.insert(integrations).values({ type: "uptimekuma", name: "Kuma", baseUrl: kumaUrl, config: JSON.stringify({ url: kumaUrl, password: "k" }) }); + + const recent = new Date().toISOString(); + await db.insert(servers).values([ + { name: "elsa", hostname: "elsa.lab.example", apiTokenHash: "a", apiTokenPrefix: "a", lastSeenAt: recent, ipAddresses: JSON.stringify(["10.0.0.5"]), proxmoxIntegrationId: pve.id, proxmoxNode: "pve1", proxmoxGuestType: "qemu", proxmoxVmid: 100 }, + { name: "anna", hostname: null, apiTokenHash: "b", apiTokenPrefix: "b", lastSeenAt: new Date(Date.now() - 5 * 24 * 3600_000).toISOString(), ipAddresses: JSON.stringify(["10.0.0.6"]) }, + { name: "never", hostname: null, apiTokenHash: "c", apiTokenPrefix: "c" }, + ]); + + const [provider] = await db.insert(dnsProviders).values({ providerType: "technitium", name: "Ginny", config: "{}" }).returning(); + await db.insert(dnsZonesCache).values({ providerId: provider.id, zoneId: "z1", zoneName: "lab.example" }); + await db.insert(dnsRecordsCache).values([ + { providerId: provider.id, zoneId: "z1", recordId: "1", type: "A", name: "elsa", content: "10.0.0.5" }, + { providerId: provider.id, zoneId: "z1", recordId: "2", type: "A", name: "www.lab.example", content: "10.0.0.5" }, + { providerId: provider.id, zoneId: "z1", recordId: "3", type: "A", name: "@", content: "10.0.0.6" }, + { providerId: provider.id, zoneId: "z1", recordId: "4", type: "A", name: "stranger", content: "10.9.9.9" }, + { providerId: provider.id, zoneId: "z1", recordId: "5", type: "TXT", name: "txt", content: "10.0.0.5" }, + ]); + }); + + after(() => { + kuma.close(); + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows keeps the database file locked until the process exits. + } + }); + + const has = (map: { edges: { from: string; to: string }[] }, from: string, to: string) => map.edges.some((e) => e.from === from && e.to === to); + + test("every server is a node, with its state; a Proxmox link adds the host above it", async () => { + const map = await buildTopology(); + const status = (label: string) => map.nodes.find((n) => n.kind === "server" && n.label === label)!.status; + assert.equal(status("elsa"), "ok"); + assert.equal(status("anna"), "bad", "last heard from five days ago"); + assert.equal(status("never"), "unknown", "never reported"); + const host = map.nodes.find((n) => n.kind === "host")!; + assert.equal(host.label, "pve1"); + assert.equal(host.sub, "Felicia"); + const elsa = map.nodes.find((n) => n.label === "elsa" && n.kind === "server")!; + assert.ok(has(map, host.id, elsa.id)); + }); + + test("a DNS name is shown only where an A or AAAA record holds the server's own address, written out in full", async () => { + const map = await buildTopology(); + const dns = map.nodes.filter((n) => n.kind === "dns").map((n) => n.label).sort(); + assert.deepEqual(dns, ["elsa.lab.example", "lab.example", "www.lab.example"]); + const elsa = map.nodes.find((n) => n.kind === "server" && n.label === "elsa")!; + assert.ok(has(map, elsa.id, "dns:elsa.lab.example")); + assert.ok(has(map, elsa.id, "dns:www.lab.example")); + assert.ok(has(map, map.nodes.find((n) => n.kind === "server" && n.label === "anna")!.id, "dns:lab.example"), "an apex record is the zone's own name"); + assert.ok(!map.nodes.some((n) => n.label.includes("stranger")), "an address no server has is left out"); + }); + + test("monitors watching a server hang off it, with their status; ones watching nothing known are left out", async () => { + const map = await buildTopology(); + const monitors = map.nodes.filter((n) => n.kind === "monitor"); + assert.deepEqual(monitors.map((m) => [m.label, m.status]).sort(), [["m1", "ok"], ["m2", "bad"]]); + for (const m of monitors) assert.ok(map.edges.some((e) => e.to === m.id && e.from.startsWith("server:"))); + }); + + test("when Uptime Kuma can't be read the rest of the map is still there, with a note", async () => { + kumaStatus = 500; + const map = await buildTopology(); + assert.equal(map.nodes.filter((n) => n.kind === "monitor").length, 0); + assert.ok(map.nodes.filter((n) => n.kind === "server").length === 3); + assert.match(map.notes.join(" "), /Couldn't read Uptime Kuma “Kuma”/); + kumaStatus = 200; + }); +}); diff --git a/web/src/App.tsx b/web/src/App.tsx index d8bd871..aca4ca5 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -42,6 +42,8 @@ import NameSettings from "./pages/settings/NameSettings"; import AlertTicketSettings from "./pages/settings/AlertTicketSettings"; import AppShell from "./layout/AppShell"; import DialogHost from "./components/DialogHost"; +import Wall from "./pages/Wall"; +import MapPage from "./pages/Map"; import { setDateTimeSettings } from "./utils/date"; import { setPageSize } from "./utils/pageSize"; import ToastHost from "./components/ToastHost"; @@ -92,10 +94,21 @@ export default function App() { return ; } + // The wall display is a screen of its own, with none of the app's menu around it; everything else sits inside the shell. + return ( + + } /> + } /> + + ); +} + +function Shelled({ user }: { user: CurrentUser }) { return ( } /> + } /> } /> } /> } /> diff --git a/web/src/api/client.ts b/web/src/api/client.ts index f3e72fb..2e34956 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -126,6 +126,33 @@ export interface SecretInput { checkPort?: number | null; } +export interface MapNode { + id: string; + kind: "host" | "server" | "dns" | "monitor"; + label: string; + sub: string | null; + status: "ok" | "bad" | "warn" | "unknown"; + href: string | null; +} + +export interface MapData { + nodes: MapNode[]; + edges: { from: string; to: string }[]; + /** Things that couldn't be read, so the picture is incomplete. */ + notes: string[]; +} + +export interface ServerActivityEvent { + /** ISO. */ + at: string; + kind: "change" | "health" | "maintenance"; + tone: "good" | "bad" | "neutral" | "info"; + title: string; + detail: string | null; + /** Who did it; "system" for the app's own checks. */ + actor: string | null; +} + export interface ServerMetricSeries { metric: string; kind: "cpu" | "mem" | "disk"; @@ -1154,6 +1181,9 @@ export const api = { importNames: (sex: "girls" | "boys", years: number, count: number) => request("/api/generator/themes/import", { method: "POST", body: JSON.stringify({ sex, years, count }) }), }, + map: { + get: () => request("/api/map"), + }, alerts: { list: (refresh = false) => request(`/api/alerts${refresh ? "?refresh=1" : ""}`), }, @@ -1251,6 +1281,7 @@ export const api = { request<{ server: ServerRecord }>(`/api/servers/${id}`, { method: "PATCH", body: JSON.stringify(data) }), summary: () => request("/api/servers/summary"), detail: (id: number) => request(`/api/servers/${id}/detail`), + activity: (id: number) => request<{ events: ServerActivityEvent[] }>(`/api/servers/${id}/activity`), metrics: (id: number, days: number) => request<{ days: number; series: ServerMetricSeries[] }>(`/api/servers/${id}/metrics?days=${days}`), remove: (id: number) => request(`/api/servers/${id}`, { method: "DELETE" }), setTags: (id: number, tags: string[]) => diff --git a/web/src/components/CommandPalette.tsx b/web/src/components/CommandPalette.tsx index cd77b5d..c73af4a 100644 --- a/web/src/components/CommandPalette.tsx +++ b/web/src/components/CommandPalette.tsx @@ -1,7 +1,23 @@ -import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react"; +import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react"; import { useNavigate } from "react-router-dom"; import { IconSearch } from "@tabler/icons-react"; -import { api, type SearchResponse, type IntegrationType, type DnsProviderType, type SecretType } from "../api/client"; +import { + api, + type CurrentUser, + type DnsProviderType, + type IntegrationType, + type MaintenanceTargetType, + type MaintenanceTargets, + type MaintenanceWindow, + type SearchResponse, + type SecretType, +} from "../api/client"; +import { isGroup, visibleNav } from "../layout/nav"; +import { SHOW_SHORTCUTS_EVENT, shortcutHintFor } from "../layout/shortcuts"; +import { DENSITIES, type Density } from "../utils/density"; +import { readableError } from "../utils/errors"; +import { toast } from "../utils/toast"; +import { SHOW_SETUP_EVENT } from "./SetupGuide"; const SECRET_TYPE_LABELS: Record = { api_token: "API Token", @@ -37,10 +53,17 @@ interface PaletteItem { category: string; title: string; subtitle: string; - path: string; + /** A shortcut to show beside it, e.g. "g s". */ + hint?: string; + /** Go to a page… */ + path?: string; + /** …or do something. */ + run?: () => void | Promise; + /** Extra words it can be found by. */ + keywords?: string; } -function buildItems(res: SearchResponse): PaletteItem[] { +function buildSearchItems(res: SearchResponse): PaletteItem[] { const items: PaletteItem[] = []; for (const s of res.servers) { items.push({ key: `server-${s.id}`, category: "Servers", title: s.name, subtitle: s.hostname ?? "", path: `/servers/${s.id}` }); @@ -109,21 +132,45 @@ function buildItems(res: SearchResponse): PaletteItem[] { return items; } -export default function CommandPalette() { +/** Every word typed must appear somewhere in the item's title, subtitle or keywords. */ +function matches(item: PaletteItem, terms: string[]): boolean { + if (terms.length === 0) return true; + const hay = `${item.title} ${item.subtitle} ${item.keywords ?? ""}`.toLowerCase(); + return terms.every((t) => hay.includes(t)); +} + +const SUGGESTED_LIMIT = 9; + +export default function CommandPalette({ + user, + onToggleTheme, + onSetDensity, +}: { + user: CurrentUser; + onToggleTheme: () => void; + onSetDensity: (density: Density) => void; +}) { const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); - const [items, setItems] = useState([]); - const [loading, setLoading] = useState(false); + const [found, setFound] = useState([]); + const [searching, setSearching] = useState(false); const [activeIndex, setActiveIndex] = useState(0); + const [targets, setTargets] = useState(null); + const [windows, setWindows] = useState([]); const inputRef = useRef(null); + const opener = useRef(null); const navigate = useNavigate(); + const canAct = user.role === "admin" || user.role === "operator"; - // Global Ctrl/Cmd+K opens the palette from anywhere in the app; Escape closes it. + // Ctrl/Cmd+K opens it from anywhere in the app; Escape closes it. useEffect(() => { function onKeyDown(e: KeyboardEvent) { if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") { e.preventDefault(); - setOpen((o) => !o); + setOpen((o) => { + if (!o) opener.current = document.activeElement as HTMLElement | null; + return !o; + }); } else if (e.key === "Escape") { setOpen(false); } @@ -132,37 +179,158 @@ export default function CommandPalette() { return () => window.removeEventListener("keydown", onKeyDown); }, []); + // On open: start clean, focus the box, and fetch what the maintenance actions need; on close: hand the focus back. useEffect(() => { - if (open) { - setQuery(""); - setItems([]); - setActiveIndex(0); - setTimeout(() => inputRef.current?.focus(), 0); - } - }, [open]); - - useEffect(() => { - if (!open || query.trim().length < 2) { - setItems([]); + if (!open) { + opener.current?.focus?.(); return; } - setLoading(true); + setQuery(""); + setFound([]); + setActiveIndex(0); + setTimeout(() => inputRef.current?.focus(), 0); + api.maintenance + .list() + .then((res) => { + setTargets(res.targets); + setWindows(res.windows); + }) + .catch(() => {}); + }, [open]); + + // The commands: pages to go to, and things to do. + const commands = useMemo(() => { + const items: PaletteItem[] = []; + const pages: { to: string; label: string; group: string }[] = []; + for (const entry of visibleNav(user.role)) { + if (isGroup(entry)) entry.items.forEach((i) => pages.push({ to: i.to, label: i.label, group: entry.label })); + else pages.push({ to: entry.to, label: entry.label, group: "" }); + } + pages.push({ to: "/wall", label: "Wall display", group: "" }); + for (const p of pages) { + items.push({ key: `page-${p.to}`, category: "Go to", title: p.label, subtitle: p.group, hint: shortcutHintFor(p.to) ?? undefined, path: p.to, keywords: "go open page" }); + } + + items.push({ key: "act-theme", category: "Actions", title: "Switch between light and dark mode", subtitle: "", run: onToggleTheme, keywords: "theme dark light mode appearance" }); + for (const d of DENSITIES) { + items.push({ key: `act-density-${d.value}`, category: "Actions", title: `Density: ${d.label}`, subtitle: "How tightly pages are packed", run: () => onSetDensity(d.value), keywords: "density compact roomy spacing size" }); + } + items.push({ + key: "act-refresh-alerts", + category: "Actions", + title: "Check alerts again", + subtitle: "", + run: () => { + window.dispatchEvent(new Event("maintenance-changed")); + toast.info("Checking alerts again…"); + }, + keywords: "refresh reload alerts", + }); + items.push({ key: "act-shortcuts", category: "Actions", title: "Show keyboard shortcuts", subtitle: "", hint: "?", run: () => void window.dispatchEvent(new Event(SHOW_SHORTCUTS_EVENT)), keywords: "keys help" }); + if (user.role === "admin") { + items.push({ + key: "act-setup", + category: "Actions", + title: "Show the getting started guide", + subtitle: "on the dashboard", + run: () => { + window.dispatchEvent(new Event(SHOW_SETUP_EVENT)); + navigate("/"); + }, + keywords: "setup onboarding checklist first run", + }); + } + items.push({ key: "act-signout", category: "Actions", title: "Sign out", subtitle: "", run: () => void (window.location.href = "/auth/logout"), keywords: "log out logout" }); + + if (canAct && targets) { + const start = (type: MaintenanceTargetType, id: number, name: string, minutes: number, words: string) => async () => { + try { + await api.maintenance.start({ targetType: type, targetId: id, minutes, reason: "Started from the command palette" }); + toast.success(`${name} is silenced for ${words}. End it early under Maintenance.`); + window.dispatchEvent(new Event("maintenance-changed")); + } catch (err) { + toast.error(readableError(err)); + } + }; + const targetList: { type: MaintenanceTargetType; id: number; name: string; kind: string }[] = [ + ...targets.servers.map((s) => ({ type: "server" as const, id: s.id, name: s.name, kind: "server" })), + ...targets.integrations.map((i) => ({ type: "integration" as const, id: i.id, name: i.name, kind: i.type })), + ...targets.dnsProviders.map((p) => ({ type: "dns_provider" as const, id: p.id, name: p.name, kind: "DNS provider" })), + ]; + for (const t of targetList) { + for (const [minutes, words] of [ + [60, "1 hour"], + [240, "4 hours"], + ] as const) { + items.push({ + key: `maint-${t.type}-${t.id}-${minutes}`, + category: "Maintenance", + title: `Silence ${t.name} for ${words}`, + subtitle: `${t.kind} · starts a maintenance window`, + run: start(t.type, t.id, t.name, minutes, words), + keywords: "maintenance silence mute window", + }); + } + } + for (const w of windows) { + items.push({ + key: `maint-end-${w.id}`, + category: "Maintenance", + title: `End maintenance on ${w.targetName}`, + subtitle: "alerts about it become active again", + run: async () => { + try { + await api.maintenance.end(w.id); + toast.success(`Maintenance on ${w.targetName} ended.`); + window.dispatchEvent(new Event("maintenance-changed")); + } catch (err) { + toast.error(readableError(err)); + } + }, + keywords: "maintenance end stop silence window", + }); + } + } + return items; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [user.role, canAct, targets, windows, onToggleTheme, onSetDensity]); + + const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean); + + // Data search, for two characters or more. + useEffect(() => { + if (!open || query.trim().length < 2) { + setFound([]); + setSearching(false); + return; + } + setSearching(true); const handle = setTimeout(() => { api.search .query(query.trim()) - .then((res) => { - setItems(buildItems(res)); - setActiveIndex(0); - }) - .catch(() => setItems([])) - .finally(() => setLoading(false)); + .then((res) => setFound(buildSearchItems(res))) + .catch(() => setFound([])) + .finally(() => setSearching(false)); }, 200); return () => clearTimeout(handle); }, [query, open]); + // What is listed: with nothing typed, a few suggestions; otherwise every command that matches, then the data search results. + const items = useMemo(() => { + if (terms.length === 0) { + const wanted = ["page-/", "page-/alerts", "page-/servers", "page-/maintenance", "page-/wall", "act-theme", "act-shortcuts"]; + return wanted.map((k) => commands.find((c) => c.key === k)).filter((c): c is PaletteItem => !!c).slice(0, SUGGESTED_LIMIT); + } + return [...commands.filter((c) => matches(c, terms)).slice(0, 14), ...found]; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [commands, found, query]); + + useEffect(() => setActiveIndex(0), [items.length, query]); + function go(item: PaletteItem) { setOpen(false); - navigate(item.path); + if (item.run) void item.run(); + else if (item.path) navigate(item.path); } function handleInputKeyDown(e: ReactKeyboardEvent) { @@ -175,16 +343,28 @@ export default function CommandPalette() { } else if (e.key === "Enter") { e.preventDefault(); if (items[activeIndex]) go(items[activeIndex]); + } else if (e.key === "Tab") { + // Nothing else in here is worth tabbing to: the list is driven from the box. + e.preventDefault(); } } + // Keep the highlighted row in view as the arrows move it. + useEffect(() => { + document.getElementById(`palette-opt-${activeIndex}`)?.scrollIntoView({ block: "nearest" }); + }, [activeIndex]); + if (!open) { return ( + +
{children}
+ + , + document.body, + ); +} + +// ─── Showing every field of a record ──────────────────────────────────────── + +/** "environmentName" → "Environment name". */ +function humanize(key: string): string { + const spaced = key + .replace(/([a-z])([A-Z])/g, "$1 $2") + .replace(/([a-zA-Z])(\d)/g, "$1 $2") + .replace(/[_-]+/g, " ") + .toLowerCase() + // A trailing unit reads better in brackets: "Response time (ms)". + .replace(/ (ms|kb|mb|gb|tb)$/, " ($1)"); + return spaced.charAt(0).toUpperCase() + spaced.slice(1); +} + +function formatBytes(bytes: number): string { + const units = ["B", "KB", "MB", "GB", "TB", "PB"]; + let value = bytes; + let unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; + } + return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`; +} + +const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/; + +function formatValue(key: string, value: unknown): ReactNode { + if (value === null || value === undefined || value === "") return —; + if (typeof value === "boolean") return value ? "Yes" : "No"; + if (typeof value === "number") return /bytes?$/i.test(key) ? `${formatBytes(value)} (${value.toLocaleString()} bytes)` : value.toLocaleString(); + if (typeof value === "string") { + if (ISO_DATE.test(value) && !Number.isNaN(Date.parse(value))) return formatDateTime(new Date(value)); + return value; + } + return null; +} + +/** Every field of a record as a labelled list: dates and sizes made readable, lists joined, nested records indented. */ +export function ObjectDetails({ data, omit = [], labels = {}, depth = 0 }: { data: object; omit?: string[]; labels?: Record; depth?: number }) { + const entries = Object.entries(data).filter(([k]) => !omit.includes(k)); + return ( +
0 ? "detail-list-nested" : ""}`}> + {entries.map(([key, value]) => { + const label = labels[key] ?? humanize(key); + let shown: ReactNode = formatValue(key, value); + if (shown === null) { + if (Array.isArray(value)) { + if (value.length === 0) shown = —; + else if (value.every((v) => v === null || typeof v !== "object")) shown = value.map((v) => String(v)).join(", "); + else if (depth < 2) shown = value.map((v, i) => ); + else shown = `${value.length} items`; + } else if (typeof value === "object" && depth < 2) { + shown = ; + } else { + shown = String(value); + } + } + return ( +
+
{label}
+
{shown}
+
+ ); + })} +
+ ); +} diff --git a/web/src/components/ServerActivity.tsx b/web/src/components/ServerActivity.tsx new file mode 100644 index 0000000..665c3a2 --- /dev/null +++ b/web/src/components/ServerActivity.tsx @@ -0,0 +1,72 @@ +import { useEffect, useState } from "react"; +import { IconAlertTriangle, IconCircleCheck, IconEdit, IconTool } from "@tabler/icons-react"; +import { api, type ServerActivityEvent } from "../api/client"; +import { formatDateTime } from "../utils/date"; +import { formatAgo } from "../utils/duration"; +import { BlockSkeleton } from "./Skeleton"; + +const TONE_CLASS: Record = { + good: "text-green", + bad: "text-red", + info: "text-blue", + neutral: "text-secondary", +}; + +function EventIcon({ event }: { event: ServerActivityEvent }) { + const cls = TONE_CLASS[event.tone]; + if (event.kind === "maintenance") return