UniFi: servers plugged into switches; server page in sections; My work; settings search and undo

UniFi: the controller's client list is matched to servers by IP address, so a
server is connected through a switch or access point (and port). That is a
dependency made by itself, shown on the server page, the Network devices page
and the Connections map. IP Addresses can sync the devices' addresses.

A server's page is split into Overview, Health, Network, History, Tasks and
Settings, by ?view=; alerts link to the section they are about.

My work lists what has your name on it: alerts you have, maintenance you
started (extend, end with undo) and update runs you started, with a badge.

Settings has a search box (and the command palette lists every setting).
Removing a dependency, admin link, runbook, hand-made IP address, port opening
or restore test is undone from the message instead of asked about first.

Two backup tests used a fixed date and failed as days passed; they follow the
real clock now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 19:35:45 +02:00
1 parent 396e074108
commit 5e26e77340
45 files changed
+6224 -194

No files matched your search

+2 -1
View File
@@ -27,7 +27,8 @@ const { buildDigest } = await import("../src/services/weeklyDigest.js");
await runMigrations();
const NOW = new Date("2026-10-17T12:00:00Z");
// The routes read the real clock, so the fixtures are laid out from it: a fixed date made these tests fail once enough days had passed.
const NOW = new Date(Math.floor(Date.now() / 1000) * 1000); // whole seconds, as snapshot times are
const HOUR = 3600_000;
const guest = (vmid: number, name: string, type: "qemu" | "lxc" = "qemu", node = "pve1") => ({ vmid, name, node, type, status: "running", cpu: null, maxmem: null, mem: null, uptime: null });
const allJob = { id: "j1", enabled: true, schedule: "02:00", storage: "pbs", node: null, allGuests: true, vmids: null, exclude: null };
+1 -1
View File
@@ -168,7 +168,7 @@ describe("through the report, the alerts, the figures and the page", () => {
const services = alerts.find((a) => a.id.startsWith("services:failed-units"));
assert.ok(services, JSON.stringify(alerts.map((a) => a.id)));
assert.equal(services.category, "services");
assert.equal(services.link, `/servers/${id}`);
assert.equal(services.link, `/servers/${id}?view=health`, "it opens the Health section of the server page");
assert.equal(services.silenced, false);
const disk = alerts.find((a) => a.id.startsWith("disk:smart"));
assert.ok(disk && disk.severity === "critical", "a failing disk is critical, in the disk category");
+143
View File
@@ -0,0 +1,143 @@
/**
* "My work": what has one person's name on it — alerts handed to them or acknowledged by them, their maintenance windows, their update runs — and which of those
* are about to run out.
*
* 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-mywork-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, updateRuns } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { setAck } = await import("../src/services/alertAcks.js");
const { startOrExtendWindow } = await import("../src/services/maintenance.js");
const { invalidateAlertsCache } = await import("../src/services/alerts.js");
const { buildMyWork, labelsOf } = await import("../src/services/myWork.js");
const { myWorkRouter } = await import("../src/routes/myWork.js");
await runMigrations();
const HOUR = 3600_000;
let app: Server;
let base = "";
let who = "olga";
const ids: Record<string, number> = {};
const olga = { id: 0, name: "Olga", email: "olga@example.lan", oidcSub: "olga" };
before(async () => {
const rows = await db
.insert(users)
.values([
{ oidcSub: "ada", name: "Ada", role: "admin" },
{ oidcSub: "olga", name: "Olga", email: "olga@example.lan", role: "operator" },
{ oidcSub: "vic", name: "Vic", role: "viewer" },
])
.returning({ id: users.id, oidcSub: users.oidcSub });
for (const r of rows) ids[r.oidcSub] = r.id;
olga.id = ids.olga;
// four servers that have stopped reporting: four standing alerts
for (const name of ["web", "db", "nas", "pi"]) {
ids[name] = (await db.insert(servers).values({ name, apiTokenHash: name, apiTokenPrefix: name, lastSeenAt: new Date(Date.now() - 6 * HOUR).toISOString() }).returning({ id: servers.id }))[0].id;
}
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
a.use("/api/my-work", myWorkRouter);
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/my-work`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows may still hold the database file
}
});
const alertOf = (name: string) => `offline:offline:server:${ids[name]}`;
describe("my work", () => {
test("the labels a person's actions are recorded under are their name, email and sign-in id", () => {
assert.deepEqual(labelsOf(olga).sort(), ["Olga", "olga", "olga@example.lan"].sort());
assert.deepEqual(labelsOf({ id: 1, name: null, email: null, oidcSub: "x" }), ["x"]);
});
test("nothing has their name on it: nothing is listed", async () => {
invalidateAlertsCache();
const mine = await buildMyWork(olga);
assert.deepEqual([mine.alerts.length, mine.windows.length, mine.updateRuns.length, mine.needsAttention], [0, 0, 0, 0]);
});
test("alerts handed to them, or acknowledged by them, and nobody else's; the one that runs out first is first", async () => {
await setAck({ alertId: alertOf("web"), note: "Looking at the PSU", assigneeId: ids.olga, hours: 72, actor: "Ada" });
await setAck({ alertId: alertOf("db"), note: "Waiting for the disk", assigneeId: null, hours: 4, actor: "Olga" });
await setAck({ alertId: alertOf("nas"), note: "Not mine", assigneeId: ids.ada, hours: 2, actor: "Ada" });
await setAck({ alertId: alertOf("pi"), note: "", assigneeId: ids.olga, hours: null, actor: "Olga" });
invalidateAlertsCache();
const mine = await buildMyWork(olga);
assert.deepEqual(
mine.alerts.map((a) => [a.alertId, a.role, a.endsSoon]),
[
[alertOf("db"), "acked", true],
[alertOf("web"), "handed", false],
[alertOf("pi"), "handed", false],
],
"ending in 4 hours, in 3 days, and never; the one for Ada is not here",
);
assert.equal(mine.alerts[0].note, "Waiting for the disk");
// handed to me (2) + one that runs out within a day (1, which is not also handed to me)
assert.equal(mine.needsAttention, 3);
});
test("a maintenance window they started, that ends soon; one that was started by somebody else is not theirs", async () => {
await startOrExtendWindow("server", ids.web, 45, "PSU swap", "Olga");
await startOrExtendWindow("server", ids.db, 600, "Disk replacement", "Olga");
await startOrExtendWindow("server", ids.nas, 30, "Somebody else's", "Ada");
invalidateAlertsCache();
const mine = await buildMyWork(olga);
assert.deepEqual(mine.windows.map((w) => [w.targetName, w.endsSoon, w.reason]), [["web", true, "PSU swap"], ["db", false, "Disk replacement"]], "the one that ends first first");
assert.equal(mine.needsAttention, 4);
});
test("update runs they started that are still going, or finished within a day; an older one, and somebody else's, are not listed", async () => {
const run = (serverId: number, startedBy: string, startedAt: Date, finishedAt: Date | null, status: string) =>
db.insert(updateRuns).values({ serverId, integrationId: 1, projectId: 1, templateId: 1, templateName: "Apply updates", hostLimit: "x", status, startedBy, startedAt: startedAt.toISOString(), finishedAt: finishedAt ? finishedAt.toISOString() : null, updatesBefore: 6, updatesAfter: finishedAt ? 0 : null });
const now = Date.now();
await run(ids.web, "Olga", new Date(now - 10 * 60_000), null, "running");
await run(ids.db, "Olga", new Date(now - 5 * HOUR), new Date(now - 4 * HOUR), "done");
await run(ids.nas, "Olga", new Date(now - 3 * 24 * HOUR), new Date(now - 3 * 24 * HOUR + HOUR), "done");
await run(ids.pi, "Ada", new Date(now - 10 * 60_000), null, "running");
const mine = await buildMyWork(olga);
assert.deepEqual(mine.updateRuns.map((r) => [r.serverName, r.running]), [["web", true], ["db", false]], "the running one first");
assert.equal(mine.needsAttention, 5);
});
test("over the route: only the signed-in person's own", async () => {
who = "olga";
const body = (await (await fetch(base)).json()) as any;
assert.equal(body.alerts.length, 3);
assert.equal(body.windows.length, 2);
who = "vic";
const vic = (await (await fetch(base)).json()) as any;
assert.deepEqual([vic.alerts.length, vic.windows.length, vic.updateRuns.length, vic.needsAttention], [0, 0, 0, 0]);
});
});
+1 -1
View File
@@ -42,7 +42,7 @@ const px = (guests: ReturnType<typeof guest>[]) => [{ integrationId: 1, integrat
const snapAgo = (now: number, vmid: number, hours: number) => ({ backupType: "vm", backupId: String(vmid), backupTime: Math.floor((now - hours * HOUR) / 1000), verification: "ok" as const });
describe("when a guest is stale", () => {
const NOW = new Date("2026-10-17T12:00:00Z");
const NOW = new Date(); // the real clock: the routes under test read it too
const now = NOW.getTime();
const input = (hoursAgo: number, extra: { servers?: Parameters<typeof buildCoverage>[0]["servers"]; staleHours?: number } = {}) => ({
proxmox: px([guest(100, "web")]),
+103 -5
View File
@@ -20,12 +20,14 @@ process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, integrations, integrationCredentials, networkDevices, networkSegments, dependencies, maintenanceWindows } = await import("../src/db/schema.js");
const { users, servers, integrations, integrationCredentials, networkDevices, networkSegments, networkServerLinks, ipamEntries, dependencies, maintenanceWindows } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { encryptSecret } = await import("../src/crypto.js");
const adapterModule = await import("../src/integrations/unifi/adapter.js");
const { createUnifiAdapter, normaliseMac, deviceKind, stateFromApi, stateFromLegacy, deviceFromApi, deviceFromLegacy, ssidFromLegacy } = adapterModule;
const { syncUnifiIntegration, trackOffline, isFresh, removeIntegrationData, syncStatuses } = await import("../src/services/unifiSync.js");
const { createUnifiAdapter, normaliseMac, deviceKind, stateFromApi, stateFromLegacy, deviceFromApi, deviceFromLegacy, ssidFromLegacy, clientFromApi, clientFromLegacy } = adapterModule;
const { syncUnifiIntegration, trackOffline, isFresh, removeIntegrationData, syncStatuses, matchClientsToServers } = await import("../src/services/unifiSync.js");
const { buildTopology } = await import("../src/services/topology.js");
const { ipamRouter } = await import("../src/routes/ipam.js");
const { evaluateHealth } = await import("../src/services/healthMonitor.js");
const { dependencyCover, uplinkEdges, loadGraph, alertIdOfNode } = await import("../src/services/dependencies.js");
const { subjectOfConditionKey, describeTarget } = await import("../src/services/maintenance.js");
@@ -69,6 +71,21 @@ const wifiList = {
],
};
const clientList = {
offset: 0,
limit: 200,
count: 3,
totalCount: 3,
data: [
{ id: "c1", type: "WIRED", name: "web", ipAddress: "192.168.1.50", macAddress: "aa:bb:cc:00:00:50", uplinkDeviceId: "d-sw" },
{ id: "c2", type: "WIRELESS", name: "phone", ipAddress: "192.168.1.60", macAddress: "aa:bb:cc:00:00:60", uplinkDeviceId: "d-ap" },
{ id: "c3", type: "WIRED", name: "stranger", ipAddress: "192.168.1.99", macAddress: "aa:bb:cc:00:00:99", uplinkDeviceId: "d-gone" },
],
};
const legacyClients = [
{ mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", hostname: "web", is_wired: true, sw_mac: "00:11:22:33:44:02", sw_port: 7 },
{ mac: "aa:bb:cc:00:00:60", ip: "192.168.1.60", name: "phone", is_wired: false, ap_mac: "00:11:22:33:44:03" },
];
const legacyDevices = [
{ _id: "x1", mac: "00:11:22:33:44:01", ip: "192.168.1.1", name: "Gateway", model: "UDMPRO", type: "udm", state: 1, uptime: 1000, version: "4.0.6", upgradable: false },
{ _id: "x2", mac: "00:11:22:33:44:02", ip: "192.168.1.2", name: "Rack switch", model: "US24PRO", type: "usw", state: 1, uptime: 500, version: "7.0.50", upgradable: true, uplink: { uplink_mac: "00:11:22:33:44:01", type: "wire" } },
@@ -93,6 +110,7 @@ function handleApi(url: URL, res: ServerResponse, strip: string) {
const path = url.pathname.slice(strip.length);
const m = /^\/sites\/site-1\/(devices|networks|wifi\/broadcasts)(?:\/([^/]+?)(\/statistics\/latest)?)?$/.exec(path);
if (path === "/sites") return reply(res, 200, siteList);
if (path === "/sites/site-1/clients") return reply(res, 200, clientList);
if (!m) return reply(res, 404, { message: "no such endpoint" });
if (m[1] === "devices") return reply(res, 200, m[2] ? (m[3] ? (stats[m[2]] ?? {}) : (detail[m[2]] ?? {})) : deviceList);
if (m[1] === "networks") return reply(res, 200, m[2] ? (networkDetail[m[2]] ?? {}) : networkList);
@@ -103,6 +121,7 @@ function handleLegacy(url: URL, res: ServerResponse, strip: string) {
const path = url.pathname.slice(strip.length);
if (path === "/api/self/sites") return reply(res, 200, { data: [{ name: "default", desc: "Default" }] });
if (path === "/api/s/default/stat/device") return reply(res, 200, { data: legacyDevices });
if (path === "/api/s/default/stat/sta") return reply(res, 200, { data: legacyClients });
if (path === "/api/s/default/rest/networkconf") return reply(res, 200, { data: legacyNetworks });
if (path === "/api/s/default/rest/wlanconf") return reply(res, 200, { data: legacyWlans });
return reply(res, 404, {});
@@ -206,6 +225,23 @@ describe("normalising what a controller says", () => {
});
});
describe("what is connected where", () => {
test("a client from either API: its address, whether it is wired, and the device it is on (and the port, on the classic one)", () => {
const macById = new Map([["d-sw", MAC.sw]]);
assert.deepEqual(clientFromApi(clientList.data[0], macById, "Default"), { mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", name: "web", wired: true, uplinkExternalId: MAC.sw, port: null, siteName: "Default" });
assert.equal(clientFromApi(clientList.data[2], macById, "Default")!.uplinkExternalId, null, "an unknown device is no uplink");
assert.deepEqual(clientFromLegacy(legacyClients[0], "Default"), { mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", name: "web", wired: true, uplinkExternalId: MAC.sw, port: 7, siteName: "Default" });
assert.deepEqual([clientFromLegacy(legacyClients[1], "Default")!.wired, clientFromLegacy(legacyClients[1], "Default")!.uplinkExternalId], [false, MAC.ap]);
});
test("a server is plugged into a device only by an exact, unambiguous address on a device that is known", () => {
const servers = [{ id: 1, ipAddresses: JSON.stringify(["10.0.0.1", "10.0.0.2"]) }, { id: 2, ipAddresses: JSON.stringify(["10.0.0.2", "10.0.0.3"]) }, { id: 3, ipAddresses: "not json" }, { id: 4, ipAddresses: null }];
const c = (mac: string, ip: string | null, up: string | null) => ({ mac, ip, name: null, wired: true, uplinkExternalId: up, port: 3, siteName: "Default" });
const links = matchClientsToServers([c("m1", "10.0.0.1", MAC.sw), c("m2", "10.0.0.2", MAC.sw), c("m3", "10.0.0.3", MAC.ap), c("m4", "10.0.0.1", "ff:ff:ff:ff:ff:ff"), c("m5", null, MAC.sw), c("m1", "10.0.0.1", MAC.sw)], servers, new Set([MAC.sw, MAC.ap]));
assert.deepEqual(links.map((l) => [l.serverId, l.deviceExternalId, l.clientMac]), [[1, MAC.sw, "m1"], [2, MAC.ap, "m3"]], "10.0.0.2 belongs to two servers, so to neither; an unknown device and no address count for nothing; a repeat is one link");
});
});
describe("reading a controller", () => {
const cfg = (extra: Record<string, unknown>) => ({ url: controllerUrl, ...extra }) as never;
@@ -321,7 +357,7 @@ describe("a controller in the database", () => {
const [cred] = await db.insert(integrationCredentials).values({ name: "unifi:Home", encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "good-key" })) }).returning();
const [row] = await db.insert(integrations).values({ type: "unifi", name: "Home UniFi", baseUrl: controllerUrl, credentialId: cred.id, config: JSON.stringify({ url: controllerUrl }) }).returning();
integrationId = row.id;
webId = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w", lastSeenAt: new Date().toISOString() }).returning({ id: servers.id }))[0].id;
webId = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w", lastSeenAt: new Date().toISOString(), ipAddresses: JSON.stringify(["192.168.1.50"]) }).returning({ id: servers.id }))[0].id;
});
test("the first read stores the devices, the networks and the Wi-Fi names, and says how it went", async () => {
@@ -361,6 +397,33 @@ describe("a controller in the database", () => {
assert.equal((await syncUnifiIntegration(integrationId)).ok, true);
});
test("the server whose address is on the controller's client list is plugged into the switch the controller says, and needs it", async () => {
const links = await db.select().from(networkServerLinks);
assert.equal(links.length, 1, "the phone and the stranger match no server");
assert.deepEqual([links[0].serverId, links[0].deviceExternalId, links[0].wired, links[0].clientMac], [webId, MAC.sw, true, "aa:bb:cc:00:00:50"]);
const graph = await loadGraph();
assert.ok(graph.edges.get(`server:${webId}`)?.includes(`device:${swId}`));
// the switch is down: the server (offline too) is explained by it, with nothing written by hand
const cover = await dependencyCover([webId], [], [swId]);
assert.equal(cover.cause.get(`server:${webId}`), `device:${swId}`);
});
test("a controller that lists no clients says nothing, so what was known stays", async () => {
const [row] = await db.select().from(integrations);
const before = (await db.select().from(networkServerLinks)).length;
const { storeInventory } = await import("../src/services/unifiSync.js");
await storeInventory(row.id, { mode: "api_key", sites: ["Default"], devices: [], networks: [], ssids: [], clients: [] });
assert.equal((await db.select().from(networkServerLinks)).length, before);
assert.equal((await db.select().from(networkDevices)).length, 0, "the devices, on the other hand, are gone from it");
assert.equal((await syncUnifiIntegration(row.id)).ok, true, "and come back on the next read");
// device ids are new now: look them up again
const rows = await db.select().from(networkDevices);
gwId = rows.find((r) => r.name === "Gateway")!.id;
swId = rows.find((r) => r.name === "Rack switch")!.id;
apId = rows.find((r) => r.name === "Hallway AP")!.id;
await db.delete(dependencies);
});
test("uplinks are dependencies nobody had to write: the access point needs the switch, which needs the gateway", async () => {
const graph = await loadGraph();
assert.deepEqual(graph.edges.get(`device:${apId}`), [`device:${swId}`]);
@@ -433,6 +496,15 @@ describe("a controller in the database", () => {
invalidateAlertsCache();
});
test("the Connections map draws a device that has a server on it, with its state", async () => {
const map = await buildTopology();
const sw = map.nodes.find((n) => n.kind === "device");
assert.ok(sw, "the switch is on the map");
assert.deepEqual([sw!.label, sw!.status, sw!.href], ["Rack switch", "ok", "/network/devices"]);
assert.ok(map.edges.some((e) => e.from === sw!.id && e.to === `server:${webId}`));
assert.equal(map.nodes.filter((n) => n.kind === "device").length, 1, "the access point and gateway have no server on them");
});
describe("the page's data", () => {
let app: Server;
let base = "";
@@ -459,7 +531,9 @@ describe("a controller in the database", () => {
const by = Object.fromEntries(body.devices.map((d: any) => [d.name, d]));
assert.deepEqual([by["Rack switch"].ip, by["Rack switch"].uptimeSeconds, by["Rack switch"].uplink.name, by["Rack switch"].firmwareUpdatable], ["192.168.1.2", 3600, "Gateway", true]);
assert.equal(by["Hallway AP"].state, "offline");
assert.equal(by["Gateway"].dependents, 3, "the switch, the access point and the server behind them");
assert.equal(by["Gateway"].dependents, 3, "the switch, the access point and the server behind it");
assert.deepEqual(by["Rack switch"].servers.map((x: any) => [x.serverName, x.port, x.wired]), [["web", null, true]]);
assert.deepEqual(body.serverLinks.map((l: any) => [l.serverName, l.deviceName]), [["web", "Rack switch"]]);
assert.equal(by["Hallway AP"].needs, 2);
assert.equal(by["Rack switch"].inMaintenance, true);
assert.deepEqual(body.networks.map((n: any) => [n.name, n.vlanId, n.subnet]), [["Default", 1, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]);
@@ -468,6 +542,29 @@ describe("a controller in the database", () => {
assert.ok(!JSON.stringify(body).includes(SECRET_PASSPHRASE));
});
test("the devices' addresses can be added to the IP addresses, and a hand-made entry is left alone", async () => {
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "operator" } };
next();
});
a.use("/api/ipam", ipamRouter);
const s = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
const ipam = `http://127.0.0.1:${(s.address() as AddressInfo).port}/api/ipam/sync-unifi`;
await db.insert(ipamEntries).values({ ipAddress: "192.168.1.3", label: "mine" });
const res = await fetch(ipam, { method: "POST" });
const body = (await res.json()) as any;
assert.deepEqual([body.added, body.skipped, body.skippedIps], [2, 1, ["192.168.1.3"]]);
const rows = await db.select().from(ipamEntries);
assert.deepEqual(rows.find((r) => r.ipAddress === "192.168.1.2")!.label, "Rack switch");
assert.equal(rows.find((r) => r.ipAddress === "192.168.1.3")!.label, "mine");
assert.equal(rows.find((r) => r.ipAddress === "192.168.1.1")!.source, "unifi");
s.close();
});
test("reading again needs an operator", async () => {
who = "viewer";
assert.equal((await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).status, 403);
@@ -484,6 +581,7 @@ describe("a controller in the database", () => {
await removeIntegrationData(integrationId);
assert.equal((await db.select().from(networkDevices)).length, 0);
assert.equal((await db.select().from(networkSegments)).length, 0);
assert.equal((await db.select().from(networkServerLinks)).length, 0);
assert.equal((await db.select().from(dependencies)).length, 0);
assert.equal((await syncStatuses())[integrationId], undefined);
});