Accessibility pass, command palette actions, row detail panel, server activity, map, wall display and setup guide
Accessibility: skip link, labelled landmarks, visible focus, page-change announcements, sortable headings as real buttons, every label tied to its field, named row checkboxes, and text contrast raised to 4.5:1 in both themes. Command palette: also runs actions (silence/end maintenance, theme, density, wall display, sign out) and is a proper dialog; g-then-letter shortcuts, "/" and "?". Row detail panel for six tables. Server Activity card, with the health check now recording offline/back-online and disk events in the audit log. Map page of hosts, servers, DNS names and monitors. Full-screen wall display. A getting-started checklist on the admin dashboard. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f7f5e1cd41
commit
57fd4f8c52
36 files changed
+2790
-210
No files matched your search
@@ -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);
|
||||
|
||||
|
||||
@@ -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());
|
||||
}));
|
||||
@@ -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" });
|
||||
|
||||
@@ -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<ActiveState> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<void> {
|
||||
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 };
|
||||
|
||||
@@ -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<string, unknown> {
|
||||
if (!detail) return {};
|
||||
try {
|
||||
const v = JSON.parse(detail);
|
||||
return v && typeof v === "object" ? (v as Record<string, unknown>) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** A readable line for one audit entry about a server. */
|
||||
export function describeAudit(category: string, action: string, detail: Record<string, unknown>): { 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<ActivityEvent[]> {
|
||||
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);
|
||||
}
|
||||
@@ -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<T>(work: Promise<T>, ms: number): Promise<T> {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const limit = new Promise<never>((_, 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<MapData> {
|
||||
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<string>();
|
||||
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<string, number[]>();
|
||||
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<string>();
|
||||
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 };
|
||||
}
|
||||
@@ -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<Server>((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);
|
||||
});
|
||||
});
|
||||
@@ -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<http.Server>((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;
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user