Racks, notes and to-do, OS support, suggested dependencies, Nginx Proxy Manager and Home Assistant

- Racks page and a network diagram (UniFi tree with servers, printable)
- Notes on servers and devices; To do list shown in Coming up and My work
- Agents report the operating system (Linux 7, Windows 6); end-of-life badge and alert
- Suggested dependencies from where a service is reached
- Nginx Proxy Manager integration: proxy hosts page, certificate and host alerts, suggested checks
- Home Assistant integration: watch chosen entities, history chart, limit and unavailable alerts
- TimeChart gets a "value" scale that fits negatives; docs updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 21:47:56 +02:00
1 parent 68b41b5586
commit 18ceed62e8
77 files changed
+20432 -35

No files matched your search

+2 -2
View File
@@ -129,7 +129,7 @@ describe("through a report, the page, the alerts and the figures", () => {
before(async () => {
await db.insert(users).values([{ oidcSub: "admin", name: "Ada", role: "admin" }]);
const [s] = await db.insert(servers).values({ name: "elsa", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t", lastSeenAt: new Date().toISOString(), agentVersion: 6 }).returning();
const [s] = await db.insert(servers).values({ name: "elsa", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t", lastSeenAt: new Date().toISOString(), agentVersion: 7 }).returning();
id = s.id;
const a = express();
a.use("/api/agent/report", agentReportRouter);
@@ -155,7 +155,7 @@ describe("through a report, the page, the alerts and the figures", () => {
});
const report = (system: unknown) =>
fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ hostname: "h", os_type: "linux", agent_version: 6, tasks: [], system }) });
fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ hostname: "h", os_type: "linux", agent_version: 7, tasks: [], system }) });
const detail = async () => await (await fetch(`${base}/servers/${id}/detail`)).json();
const patch = (body: unknown) => fetch(`${base}/servers/${id}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+137
View File
@@ -0,0 +1,137 @@
/**
* Suggested dependencies: an integration reached at a server's own address is offered as needing that server; what is already so, would make a loop, or was
* said no to is left out; and adding one writes an ordinary dependency.
*
* 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-depsug-"));
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, integrations, dependencies, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { suggestDependencies, hostOfIntegration } = await import("../src/services/dependencySuggestions.js");
const { dependenciesRouter } = await import("../src/routes/dependencies.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
describe("what is offered", () => {
const servers = [
{ id: 1, name: "nas", hostname: "nas.lan", ips: ["10.0.0.5"] },
{ id: 2, name: "elsa", hostname: null, ips: ["10.0.0.9"] },
];
const integ = (id: number, name: string, type: string, host: string | null, enabled = true) => ({ id, name, type, enabled, host });
const none = new Map<string, string[]>();
test("an integration at a server's own address (its IP, hostname or short name) needs that server", () => {
const { suggestions } = suggestDependencies({
integrations: [integ(1, "Gitea", "gitea", "10.0.0.5"), integ(2, "Kuma", "uptimekuma", "nas.lan"), integ(3, "IPAM", "phpipam", "elsa"), integ(4, "Cloud", "tailscale", "api.tailscale.com")],
servers,
edges: none,
dismissed: new Set(),
});
assert.deepEqual(suggestions.map((x) => x.key), ["integration:1>server:1", "integration:3>server:2", "integration:2>server:1"], "by name (Gitea, IPAM, Kuma); the one in the cloud matches nothing");
assert.ok(suggestions.every((x) => x.reason.includes("most likely runs there")));
});
test("a disabled integration, one with no address, and one with an unknown host are not offered", () => {
const { suggestions } = suggestDependencies({ integrations: [integ(1, "Off", "gitea", "10.0.0.5", false), integ(2, "None", "gitea", null), integ(3, "Elsewhere", "gitea", "10.9.9.9")], servers, edges: none, dismissed: new Set() });
assert.equal(suggestions.length, 0);
});
test("what is already so, and what would make a loop, is left out", () => {
const already = new Map([["integration:1", ["server:1"]]]);
assert.equal(suggestDependencies({ integrations: [integ(1, "Gitea", "gitea", "10.0.0.5")], servers, edges: already, dismissed: new Set() }).suggestions.length, 0);
// the server needs the integration already: the other way round would make them wait for each other
const loop = new Map([["server:1", ["integration:1"]]]);
assert.equal(suggestDependencies({ integrations: [integ(1, "Gitea", "gitea", "10.0.0.5")], servers, edges: loop, dismissed: new Set() }).suggestions.length, 0);
});
test("what somebody said no to is kept apart, and can come back", () => {
const r = suggestDependencies({ integrations: [integ(1, "Gitea", "gitea", "10.0.0.5")], servers, edges: none, dismissed: new Set(["integration:1>server:1"]) });
assert.deepEqual([r.suggestions.length, r.dismissed.length], [0, 1]);
});
test("where an integration is reached: a URL's host, or osTicket's database host", () => {
assert.equal(hostOfIntegration("https://git.example.lan:3000/", "{}"), "git.example.lan");
assert.equal(hostOfIntegration("", JSON.stringify({ host: "osticket-db.lan" })), "osticket-db.lan");
assert.equal(hostOfIntegration("not a url", null), null);
assert.equal(hostOfIntegration(null, "not json"), null);
});
});
describe("over the routes", () => {
let app: Server;
let base = "";
let who = "viewer";
before(async () => {
await db.insert(users).values([
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
{ oidcSub: "operator", name: "Olga", role: "operator" },
]);
await db.insert(servers).values({ name: "nas", hostname: "nas.lan", apiTokenHash: "n", apiTokenPrefix: "n", ipAddresses: JSON.stringify(["10.0.0.5"]) });
await db.insert(integrations).values({ type: "gitea", name: "Gitea", baseUrl: "http://10.0.0.5:3000", config: JSON.stringify({ url: "http://10.0.0.5:3000" }) });
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/dependencies", dependenciesRouter);
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/dependencies`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows may still hold the database file
}
});
const post = (path: string, body: unknown = {}) => fetch(`${base}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
test("anyone signed in sees them; only an operator adds or dismisses", async () => {
who = "viewer";
const body = (await (await fetch(`${base}/suggestions`)).json()) as any;
assert.deepEqual(body.suggestions.map((s: any) => s.key), ["integration:1>server:1"]);
assert.equal((await post("/suggestions/add", { keys: ["integration:1>server:1"] })).status, 403);
assert.equal((await post("/suggestions/dismiss", { keys: ["integration:1>server:1"] })).status, 403);
});
test("dismissing hides it, restoring brings it back, and a bad body is refused", async () => {
who = "operator";
const hidden = (await (await post("/suggestions/dismiss", { keys: ["integration:1>server:1"] })).json()) as any;
assert.deepEqual([hidden.suggestions.length, hidden.dismissed.length], [0, 1]);
const back = (await (await post("/suggestions/restore")).json()) as any;
assert.equal(back.suggestions.length, 1);
assert.equal((await post("/suggestions/add", { keys: [] })).status, 400);
});
test("adding writes an ordinary dependency, written down, and it is no longer offered", async () => {
who = "operator";
const res = (await (await post("/suggestions/add", { keys: ["integration:1>server:1", "integration:9>server:9"] })).json()) as any;
assert.deepEqual(res.added.map((a: any) => [a.from, a.to]), [["Gitea", "nas"]], "a key that is not offered adds nothing");
assert.equal(res.suggestions.length, 0);
const rows = await db.select().from(dependencies);
assert.deepEqual(rows.map((r) => [r.fromType, r.fromId, r.toType, r.toId]), [["integration", 1, "server", 1]]);
const written = (await db.select().from(auditLog).where(eq(auditLog.category, "dependency")))[0];
assert.equal(written.action, "create");
const list = (await (await fetch(base)).json()) as any;
assert.equal(list.dependencies.length, 1, "and the page lists it with the rest");
});
});
+415
View File
@@ -0,0 +1,415 @@
/**
* Nginx Proxy Manager and Home Assistant: reading each (against pretend ones), what is kept, what makes an alert, and the suggestions NPM feeds.
*
* 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 { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
const dir = mkdtempSync(join(tmpdir(), "hm-npmha-"));
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, integrations, integrationCredentials, haEntities, haReadings, haWatched } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { encryptSecret } = await import("../src/crypto.js");
const { createNpmAdapter, isoOf, hostFrom } = await import("../src/integrations/npm/adapter.js");
const { createHomeAssistantAdapter, entityFrom } = await import("../src/integrations/homeassistant/adapter.js");
const { npmProblems, readNpm, clearNpmCacheForTests } = await import("../src/services/npmReader.js");
const { haProblems, trackUnavailable, syncHomeAssistant, removeHomeAssistantData, isHaFresh, haSyncStatuses } = await import("../src/services/homeAssistantSync.js");
const { suggestChecks, loadSuggestions } = await import("../src/services/endpointSuggestions.js");
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
const { npmRouter } = await import("../src/routes/npm.js");
const { homeAssistantRouter } = await import("../src/routes/homeAssistant.js");
const { validateIntegrationConfig } = await import("../src/integrations/fieldSchemas.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
const DAY = 86_400_000;
const inDays = (n: number) => new Date(Date.now() + n * DAY).toISOString();
const npmTime = (n: number) => inDays(n).replace("T", " ").slice(0, 19);
// ─── A pretend Nginx Proxy Manager ──────────────────────────────────────────
let npmPassword = "pw";
const npmCertificates = [
{ id: 1, nice_name: "wiki.example.com", provider: "letsencrypt", domain_names: ["wiki.example.com"], expires_on: npmTime(40) },
{ id: 2, nice_name: "git.example.com", provider: "letsencrypt", domain_names: ["git.example.com"], expires_on: npmTime(2) },
{ id: 3, nice_name: "old.example.com", provider: "letsencrypt", domain_names: ["old.example.com"], expires_on: npmTime(-5) },
];
const npmHosts = [
{ id: 10, domain_names: ["wiki.example.com"], forward_scheme: "http", forward_host: "10.0.0.5", forward_port: 8080, enabled: 1, ssl_forced: 1, certificate: npmCertificates[0], meta: { nginx_online: true } },
{ id: 11, domain_names: ["git.example.com"], forward_scheme: "http", forward_host: "10.0.0.6", forward_port: 3000, enabled: 1, ssl_forced: 1, certificate: npmCertificates[1], meta: { nginx_online: true } },
// A certificate that ran out, but on a host that is switched off: nobody is served it, so it is not a problem.
{ id: 12, domain_names: ["old.example.com"], forward_scheme: "http", forward_host: "10.0.0.7", forward_port: 80, enabled: 0, ssl_forced: 0, certificate: npmCertificates[2], meta: {} },
{ id: 13, domain_names: ["broken.example.com"], forward_scheme: "http", forward_host: "10.0.0.8", forward_port: 80, enabled: 1, ssl_forced: 0, certificate: null, meta: { nginx_online: false, nginx_err: "host not found in upstream" } },
];
let npmRequests: string[] = [];
function reply(res: ServerResponse, status: number, body: unknown) {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(body));
}
function npmRoute(req: IncomingMessage, res: ServerResponse) {
const url = req.url ?? "";
npmRequests.push(`${req.method} ${url.split("?")[0]}`);
if (url === "/api/tokens" && req.method === "POST") {
let raw = "";
req.on("data", (c) => (raw += c));
req.on("end", () => {
const b = JSON.parse(raw || "{}");
if (b.identity === "viewer@example.com" && b.secret === npmPassword) return reply(res, 200, { token: "npm-token", expires: inDays(1) });
return reply(res, 400, { error: { message: "Invalid email or password" } });
});
return;
}
if (req.headers.authorization !== "Bearer npm-token") return reply(res, 401, {});
if (url.startsWith("/api/nginx/proxy-hosts")) return reply(res, 200, npmHosts);
if (url.startsWith("/api/nginx/certificates")) return reply(res, 200, npmCertificates);
if (url === "/api/") return reply(res, 200, { status: "OK", version: { major: 2, minor: 11, revision: 3 } });
return reply(res, 404, {});
}
// ─── A pretend Home Assistant ───────────────────────────────────────────────
let haToken = "good-token";
let haStates: Record<string, unknown>[] = [];
const state = (entity_id: string, s: string, attributes: Record<string, unknown> = {}) => ({ entity_id, state: s, attributes, last_changed: "2026-10-20T08:00:00+00:00" });
function haRoute(req: IncomingMessage, res: ServerResponse) {
if (req.headers.authorization !== `Bearer ${haToken}`) return reply(res, 401, { message: "401: Unauthorized" });
if (req.url === "/api/") return reply(res, 200, { message: "API running." });
if (req.url === "/api/states") return reply(res, 200, haStates);
return reply(res, 404, {});
}
let npmServer: Server;
let haServer: Server;
let npmUrl = "";
let haUrl = "";
let npmId = 0;
let haId = 0;
before(async () => {
npmServer = await new Promise<Server>((resolve) => {
const s = createServer(npmRoute).listen(0, "127.0.0.1", () => resolve(s));
});
haServer = await new Promise<Server>((resolve) => {
const s = createServer(haRoute).listen(0, "127.0.0.1", () => resolve(s));
});
npmUrl = `http://127.0.0.1:${(npmServer.address() as AddressInfo).port}`;
haUrl = `http://127.0.0.1:${(haServer.address() as AddressInfo).port}`;
});
after(() => {
npmServer.close();
haServer.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows may still hold the database file
}
});
describe("normalising what they say", () => {
test("NPM writes its times without a zone, and they are UTC", () => {
assert.equal(isoOf("2026-12-31 23:59:59"), "2026-12-31T23:59:59.000Z");
assert.equal(isoOf("2026-12-31T23:59:59+01:00"), "2026-12-31T22:59:59.000Z");
assert.equal(isoOf("nonsense"), null);
assert.equal(isoOf(null), null);
});
test("a proxy host: where it goes, whether it is on, and that NPM's own error makes it not working; a host with no id is nothing", () => {
const h = hostFrom(npmHosts[3])!;
assert.deepEqual([h.domains, h.forwardHost, h.forwardPort, h.enabled, h.online, h.error], [["broken.example.com"], "10.0.0.8", 80, true, false, "host not found in upstream"]);
const ok = hostFrom(npmHosts[0])!;
assert.deepEqual([ok.sslForced, ok.online, ok.certificate?.id], [true, true, 1]);
assert.equal(hostFrom({ domain_names: ["x"] }), null);
assert.equal(hostFrom(npmHosts[2])!.enabled, false);
});
test("a Home Assistant entity: a number when its state is one, unavailable when it says nothing, its friendly name or else its id", () => {
const e = entityFrom(state("sensor.ups_battery", "87.5", { friendly_name: "UPS battery", unit_of_measurement: "%", device_class: "battery" }))!;
assert.deepEqual([e.name, e.value, e.unit, e.deviceClass, e.unavailable], ["UPS battery", 87.5, "%", "battery", false]);
const off = entityFrom(state("switch.pump", "unavailable"))!;
assert.deepEqual([off.name, off.value, off.unavailable], ["switch.pump", null, true]);
assert.equal(entityFrom(state("light.x", "on"))!.value, null, "on/off is not a number");
assert.equal(entityFrom(state("sensor.blank", ""))!.value, null);
assert.equal(entityFrom({ state: "1" }), null);
});
});
describe("Nginx Proxy Manager", () => {
const cfg = (extra: Record<string, unknown> = {}) => ({ url: npmUrl, email: "viewer@example.com", password: npmPassword, ...extra }) as never;
test("signs in, then only reads: hosts with their certificate, the certificates, the version", async () => {
npmRequests = [];
const snap = await createNpmAdapter(cfg()).fetchSnapshot();
assert.equal(snap.version, "2.11.3");
assert.equal(snap.hosts.length, 4);
assert.equal(snap.certificates.length, 3);
assert.ok(npmRequests.every((r) => r.startsWith("GET") || r === "POST /api/tokens"), "nothing but the sign-in and reads");
});
test("a wrong password is said plainly, and the login check works as a ping", async () => {
await assert.rejects(createNpmAdapter(cfg({ password: "wrong" })).fetchSnapshot(), /did not accept the email and password/);
assert.equal((await createNpmAdapter(cfg()).ping()).ok, true);
assert.equal((await createNpmAdapter(cfg({ password: "wrong" })).ping()).ok, false);
});
test("certificates in use that run out soon are a problem — critical in the last days, and an expired one too — but not on a host that is off", async () => {
const snap = await createNpmAdapter(cfg()).fetchSnapshot();
const problems = npmProblems(1, "Edge NPM", snap, new Date());
const by = Object.fromEntries(problems.map((p) => [p.key, p]));
assert.deepEqual(Object.keys(by).sort(), ["npm-cert:1:2", "npm-host:1:13"], "wiki is fine (40 days), old is on a host that is off");
assert.equal(by["npm-cert:1:2"].severity, "critical");
assert.match(by["npm-cert:1:2"].message, /git\.example\.com.*expires in [12] days?/);
assert.match(by["npm-host:1:13"].message, /broken\.example\.com is not working.*host not found in upstream/);
const later = npmProblems(1, "Edge NPM", snap, new Date(Date.now() + 30 * DAY));
assert.ok(later.some((p) => p.key === "npm-cert:1:1"), "and the wiki one in time");
assert.match(later.find((p) => p.key === "npm-cert:1:2")!.message, /expired 2[89] days ago/);
});
});
describe("Home Assistant", () => {
const cfg = (extra: Record<string, unknown> = {}) => ({ url: haUrl, token: haToken, ...extra }) as never;
test("lists every entity with the token; a refused token and a wrong address are said plainly", async () => {
haStates = [state("sensor.ups_battery", "87", { friendly_name: "UPS battery", unit_of_measurement: "%" }), state("light.hall", "on")];
assert.equal((await createHomeAssistantAdapter(cfg()).listEntities()).length, 2);
await assert.rejects(createHomeAssistantAdapter(cfg({ token: "nope" })).listEntities(), /did not accept the token/);
const ping = await createHomeAssistantAdapter(cfg()).ping();
assert.equal(ping.ok, true);
});
test("an entity that says nothing is only a problem after a while, and a number only past a limit that was set", () => {
const now = new Date("2026-10-20T12:00:00Z");
const watched = [
{ entityId: "sensor.ups", name: "UPS", above: null, below: 30 },
{ entityId: "sensor.freezer", name: null, above: -10, below: null },
{ entityId: "switch.pump", name: "Pump", above: null, below: null },
{ entityId: "sensor.fine", name: null, above: 50, below: 10 },
];
const rows = new Map<string, { friendlyName: string | null; state: string; value: number | null; unit: string | null; unavailableSince: string | null }>([
["sensor.ups", { friendlyName: "UPS battery", state: "22", value: 22, unit: "%", unavailableSince: null }],
["sensor.freezer", { friendlyName: "Freezer", state: "-18", value: -18, unit: "°C", unavailableSince: null }],
["switch.pump", { friendlyName: null, state: "unavailable", value: null, unit: null, unavailableSince: "2026-10-20T11:30:00Z" }],
["sensor.fine", { friendlyName: null, state: "20", value: 20, unit: null, unavailableSince: null }],
]);
const problems = haProblems(3, "Home", watched, rows, now);
assert.deepEqual(problems.map((p) => p.key), ["ha-limit:3:sensor.ups", "ha-unavailable:3:switch.pump"]);
assert.match(problems[0].message, /UPS is 22 %, below its limit of 30 %/);
assert.match(problems[1].message, /Pump has been unavailable in Home Assistant for 30 min/);
rows.get("switch.pump")!.unavailableSince = "2026-10-20T11:55:00Z";
assert.equal(haProblems(3, "Home", watched, rows, now).length, 1, "five minutes of silence is nothing");
});
test("when an entity first went quiet is kept until it speaks again", () => {
assert.equal(trackUnavailable(null, true, "T1"), "T1");
assert.equal(trackUnavailable("T0", true, "T1"), "T0");
assert.equal(trackUnavailable("T0", false, "T1"), null);
});
});
describe("kept in the app", () => {
before(async () => {
await db.insert(users).values([
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
{ oidcSub: "operator", name: "Olga", role: "operator" },
]);
const [npmCred] = await db.insert(integrationCredentials).values({ name: "npm:Edge", encryptedSecret: encryptSecret(JSON.stringify({ password: "pw" })) }).returning();
const [npmRow] = await db.insert(integrations).values({ type: "npm", name: "Edge NPM", baseUrl: npmUrl, credentialId: npmCred.id, config: JSON.stringify({ url: npmUrl, email: "viewer@example.com" }) }).returning();
npmId = npmRow.id;
const [haCred] = await db.insert(integrationCredentials).values({ name: "ha:Home", encryptedSecret: encryptSecret(JSON.stringify({ token: "good-token" })) }).returning();
const [haRow] = await db.insert(integrations).values({ type: "homeassistant", name: "Home", baseUrl: haUrl, credentialId: haCred.id, config: JSON.stringify({ url: haUrl }) }).returning();
haId = haRow.id;
await db.insert(servers).values({ name: "wiki-host", hostname: "wiki-host.example.lan", ipAddresses: JSON.stringify(["10.0.0.5"]), osType: "linux", apiTokenHash: "x", apiTokenPrefix: "x" } as never);
});
test("the field forms need what each one needs", () => {
assert.deepEqual(validateIntegrationConfig("npm", { url: "https://npm", email: "a@b" }), ["password"]);
assert.deepEqual(validateIntegrationConfig("homeassistant", { url: "https://ha" }), ["token"]);
assert.deepEqual(validateIntegrationConfig("homeassistant", { url: "https://ha", token: "t" }), []);
});
test("NPM is read once a minute at most, and a failed read is kept just as briefly", async () => {
clearNpmCacheForTests();
npmRequests = [];
const a = await readNpm(npmId);
const b = await readNpm(npmId);
assert.ok(a.snapshot && b.snapshot);
assert.equal(npmRequests.filter((r) => r === "POST /api/tokens").length, 1);
await readNpm(npmId, true);
assert.equal(npmRequests.filter((r) => r === "POST /api/tokens").length, 2, "asking again is possible");
});
test("on the Alerts page: the certificate in its last days and the host NPM can't set up, from the right place", async () => {
clearNpmCacheForTests();
invalidateAlertsCache();
const report = await getAlerts(true);
const cert = report.alerts.find((a) => a.id === `expiry:npm-cert:${npmId}:2`)!;
assert.ok(cert, "the certificate that runs out");
assert.deepEqual([cert.severity, cert.source, cert.link, cert.target?.type], ["critical", "Nginx Proxy Manager", "/proxy-hosts", "integration"]);
const host = report.alerts.find((a) => a.id === `monitoring:npm-host:${npmId}:13`)!;
assert.ok(host);
assert.equal(report.alerts.some((a) => a.id === `expiry:npm-cert:${npmId}:3`), false, "the one on the host that is off is left alone");
});
test("an NPM that can't be read says so rather than being quiet", async () => {
npmPassword = "changed";
clearNpmCacheForTests();
invalidateAlertsCache();
const report = await getAlerts(true);
assert.ok(report.couldntCheck.some((c) => /Nginx Proxy Manager/.test(c.name)));
assert.equal(report.alerts.some((a) => a.id.startsWith("expiry:npm-cert")), false, "and raises nothing from what it could not read");
npmPassword = "pw";
clearNpmCacheForTests();
});
test("hosts NPM serves are offered as checks on the name people use, linked to the server it forwards to — and not when a check already covers it", async () => {
invalidateAlertsCache();
const { suggestions } = await loadSuggestions();
const wiki = suggestions.find((s) => s.target === "https://wiki.example.com/")!;
assert.ok(wiki);
assert.deepEqual([wiki.kind, wiki.serverName], ["http", "wiki-host"]);
assert.match(wiki.reason, /Edge NPM serves wiki\.example\.com, forwarding to wiki-host/);
assert.ok(suggestions.some((s) => s.target === "http://broken.example.com/"), "a host with no certificate is a plain web check");
assert.ok(!suggestions.some((s) => /old\.example\.com/.test(s.target)), "a host that is off is not offered");
const none = suggestChecks({ servers: [], dns: [], secrets: [], dismissed: new Set(), existing: [{ kind: "http", target: "https://wiki.example.com/", port: null }], proxied: [{ domain: "wiki.example.com", secure: true, serverId: null, serverName: null, integrationName: "x" }, { domain: "*.example.com", secure: true, serverId: null, serverName: null, integrationName: "x" }, { domain: "10.0.0.1", secure: false, serverId: null, serverName: null, integrationName: "x" }] });
assert.deepEqual(none.suggestions, []);
});
test("the NPM page: each host with the server it forwards to, its certificate, and the problems; anyone signed in may see it", async () => {
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "viewer" } };
next();
});
a.use("/api/npm", npmRouter);
const s = await new Promise<Server>((resolve) => {
const x = a.listen(0, "127.0.0.1", () => resolve(x));
});
const res = await fetch(`http://127.0.0.1:${(s.address() as AddressInfo).port}/api/npm?refresh=1`);
assert.equal(res.status, 200);
const body = (await res.json()) as any;
const npm = body.integrations[0];
assert.equal(npm.version, "2.11.3");
const wiki = npm.hosts.find((h: any) => h.id === 10);
assert.deepEqual([wiki.server?.name, wiki.certificate.name], ["wiki-host", "wiki.example.com"]);
assert.equal(npm.hosts.find((h: any) => h.id === 11).server, null, "an address no server has is left unmatched");
assert.equal(npm.problems.length, 2);
s.close();
});
describe("Home Assistant stored", () => {
let app: Server;
let base = "";
let who = "viewer";
before(async () => {
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/home-assistant", homeAssistantRouter);
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/home-assistant`;
});
after(() => app.close());
const put = (body: unknown) => fetch(`${base}/${haId}/watched`, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
test("choosing what to watch needs an operator; only entities that exist and sensible limits are accepted", async () => {
haStates = [state("sensor.ups_battery", "87", { friendly_name: "UPS battery", unit_of_measurement: "%" }), state("switch.pump", "on", { friendly_name: "Pump" }), state("light.hall", "on")];
who = "viewer";
assert.equal((await put({ entityId: "sensor.ups_battery" })).status, 403);
assert.equal((await fetch(`${base}/${haId}/entities`)).status, 403);
who = "operator";
assert.equal((await put({ entityId: "not an entity" })).status, 400);
assert.equal((await put({ entityId: "sensor.ups_battery", above: 10, below: 20 })).status, 400, "the lower limit has to be lower");
assert.equal((await fetch(`${base}/999/entities`)).status, 404);
const list = (await (await fetch(`${base}/${haId}/entities?q=ups`)).json()) as any;
assert.deepEqual(list.entities.map((e: any) => e.entityId), ["sensor.ups_battery"]);
const ok = await put({ entityId: "sensor.ups_battery", name: "UPS", below: 30 });
assert.equal(ok.status, 200);
assert.equal(((await ok.json()) as any).status.ok, true);
assert.equal((await put({ entityId: "switch.pump" })).status, 200);
const [row] = await db.select().from(haEntities).where(eq(haEntities.entityId, "sensor.ups_battery"));
assert.deepEqual([row.state, row.value, row.unit], ["87", 87, "%"]);
});
test("the page lists what is watched with its state; a number keeps a point of history, but two passes close together keep one", async () => {
who = "viewer";
const body = (await (await fetch(base)).json()) as any;
const ha = body.integrations[0];
assert.deepEqual(ha.watched.map((w) => [w.entityId, w.entity?.state]), [["switch.pump", "on"], ["sensor.ups_battery", "87"]], "by the name it is shown under: Pump, then UPS");
assert.equal(ha.fresh, true);
await syncHomeAssistant(haId);
const readings = await db.select().from(haReadings).where(eq(haReadings.entityId, "sensor.ups_battery"));
assert.equal(readings.length, 1, "the pump is not a number, the second pass is too soon");
const hist = (await (await fetch(`${base}/${haId}/history?entity=sensor.ups_battery&days=7`)).json()) as any;
assert.equal(hist.days, 7);
assert.ok(hist.points.length >= 1);
});
test("a number past its limit is an alert, an entity that goes quiet becomes one after a while, and a Home Assistant that is down holds them rather than clearing", async () => {
haStates = [state("sensor.ups_battery", "22", { friendly_name: "UPS battery", unit_of_measurement: "%" }), state("switch.pump", "unavailable", { friendly_name: "Pump" })];
await syncHomeAssistant(haId, new Date());
invalidateAlertsCache();
let report = await getAlerts(true);
const limit = report.alerts.find((a) => a.id === `monitoring:ha-limit:${haId}:sensor.ups_battery`)!;
assert.ok(limit);
assert.deepEqual([limit.source, limit.link], ["Home Assistant", "/home-assistant"]);
assert.equal(report.alerts.some((a) => a.id.includes("ha-unavailable")), false, "the pump just went quiet");
await db.update(haEntities).set({ unavailableSince: new Date(Date.now() - 40 * 60_000).toISOString() }).where(eq(haEntities.entityId, "switch.pump"));
invalidateAlertsCache();
report = await getAlerts(true);
assert.ok(report.alerts.some((a) => a.id === `monitoring:ha-unavailable:${haId}:switch.pump`));
haToken = "revoked";
const down = await syncHomeAssistant(haId);
assert.equal(down.ok, false);
assert.match(down.error ?? "", /did not accept the token/);
invalidateAlertsCache();
report = await getAlerts(true);
assert.ok(report.couldntCheck.some((c) => /Home Assistant/.test(c.name)));
assert.equal(report.alerts.some((a) => a.id.includes("ha-limit")), false, "neither raised nor cleared while it can't be read");
assert.equal(isHaFresh((await haSyncStatuses())[haId], Date.now()), false);
haToken = "good-token";
assert.equal((await syncHomeAssistant(haId)).ok, true);
});
test("an entity that disappears from Home Assistant counts as quiet; stopping watching forgets it and its history", async () => {
haStates = [state("sensor.ups_battery", "50", { unit_of_measurement: "%" })];
await syncHomeAssistant(haId);
const [pump] = await db.select().from(haEntities).where(eq(haEntities.entityId, "switch.pump"));
assert.equal(pump.state, "missing");
who = "operator";
assert.equal((await fetch(`${base}/${haId}/watched/sensor.ups_battery`, { method: "DELETE" })).status, 204);
assert.equal((await db.select().from(haReadings).where(eq(haReadings.entityId, "sensor.ups_battery"))).length, 0);
assert.equal((await fetch(`${base}/${haId}/watched/sensor.ups_battery`, { method: "DELETE" })).status, 404);
});
test("removing the integration removes everything read from it", async () => {
await removeHomeAssistantData(haId);
assert.equal((await db.select().from(haWatched)).length, 0);
assert.equal((await db.select().from(haEntities)).length, 0);
assert.equal((await haSyncStatuses())[haId], undefined);
assert.equal((await db.select({ id: integrationCredentials.id }).from(integrationCredentials)).length >= 1, true);
});
});
});
+140
View File
@@ -0,0 +1,140 @@
/**
* When the operating system a server runs stops being supported: what the table knows, how an agent's answer is read, the alert, and that the agent's own
* script says it (the shell part is checked by reading it; the answer it would give is a plain JSON object).
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
const dir = mkdtempSync(join(tmpdir(), "hm-oslife-"));
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 { db } = await import("../src/db/client.js");
const { servers, maintenanceWindows } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { lifecycleOf, releaseKey, supportState, daysOfSupportLeft } = await import("../src/services/osLifecycle.js");
const { syncServerTasks } = await import("../src/services/taskSync.js");
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
const { updateSettings } = await import("../src/services/settingsStore.js");
const { latestAgentVersions } = await import("../src/services/agentVersions.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
const repo = fileURLToPath(new URL("../../", import.meta.url));
after(() => {
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows may still hold the database file
}
});
describe("reading what an agent says it runs", () => {
test("a release is found by its distribution and version, however the version is written", () => {
assert.deepEqual(releaseKey({ id: "ubuntu", version: "22.04" }), { family: "ubuntu", key: "22.04" });
assert.deepEqual(releaseKey({ id: "debian", version: "12" }), { family: "debian", key: "12" });
assert.deepEqual(releaseKey({ id: "raspbian", version: "11" }), { family: "debian", key: "11" }, "Raspberry Pi OS is Debian");
assert.deepEqual(releaseKey({ id: "rocky", version: "9.4" }), { family: "rocky", key: "9" });
assert.deepEqual(releaseKey({ id: "alpine", version: "3.19.1" }), { family: "alpine", key: "3.19" });
assert.deepEqual(releaseKey({ id: "proxmox-ve", version: "8.2" }), { family: "proxmox-ve", key: "8" });
assert.deepEqual(releaseKey({ id: "centos", name: "CentOS Stream 9", version: "9" }), { family: "centos-stream", key: "9" });
assert.deepEqual(releaseKey({ id: "centos", name: "CentOS Linux 7 (Core)", version: "7" }), { family: "centos-classic", key: "7" });
assert.deepEqual(releaseKey({ id: "windows", name: "Windows Server 2019 Standard", version: "17763" }), { family: "windows-server", key: "17763" });
assert.deepEqual(releaseKey({ id: "windows", name: "Windows 11 Pro", version: "22631" }), { family: "windows-client", key: "22631" });
assert.equal(releaseKey({ id: "arch", version: "rolling" }), null, "a rolling distribution has no end");
assert.equal(releaseKey({ id: "", version: "1" }), null);
assert.equal(releaseKey({ id: "ubuntu" }), null);
});
test("the same build number is a different product on a server and a client", () => {
assert.equal(lifecycleOf({ id: "windows", name: "Windows Server 2025 Datacenter", version: "26100" })?.product, "Windows Server 2025");
assert.equal(lifecycleOf({ id: "windows", name: "Windows 11 Pro", version: "26100" })?.product, "Windows 11 24H2");
});
test("what the table knows: a name and a date; a release it does not know is named as the machine named itself, with no date", () => {
assert.deepEqual(lifecycleOf({ id: "ubuntu", name: "Ubuntu 20.04.6 LTS", version: "20.04" }), { product: "Ubuntu 20.04 LTS", endsOn: "2025-05-31" });
assert.deepEqual(lifecycleOf({ id: "debian", version: "12" }), { product: "Debian 12 (bookworm)", endsOn: "2028-06-30" });
assert.deepEqual(lifecycleOf({ id: "ubuntu", name: "Ubuntu 31.04", version: "31.04" }), { product: "Ubuntu 31.04", endsOn: null });
assert.equal(lifecycleOf({ id: "ubuntu", version: "31.04" }), null, "nothing to call it, nothing to say");
assert.equal(lifecycleOf({ id: "templeos", version: "5" }), null);
});
test("ended once the day is over, soon within the warning, ok beyond it, unknown with no date", () => {
const now = new Date("2026-10-20T12:00:00Z");
assert.equal(supportState("2026-10-19", now, 90), "ended");
assert.equal(supportState("2026-10-20", now, 90), "soon", "the last day is still a day of support");
assert.equal(supportState("2027-01-10", now, 90), "soon");
assert.equal(supportState("2027-06-01", now, 90), "ok");
assert.equal(supportState(null, now, 90), "unknown");
assert.equal(daysOfSupportLeft("2026-10-30", now), 10);
assert.equal(daysOfSupportLeft("2026-10-10", now), -10);
});
});
describe("what the agent says, and what the Alerts page makes of it", () => {
let id = 0;
before(async () => {
id = (await db.insert(servers).values({ name: "old-box", apiTokenHash: "o", apiTokenPrefix: "o", lastSeenAt: new Date().toISOString() }).returning({ id: servers.id }))[0].id;
});
const row = () => db.select().from(servers).where(eq(servers.id, id)).then((r) => r[0]);
const report = (os: unknown) => syncServerTasks(id, { osType: "linux", tasks: [], system: { os } as never });
test("it is stored, bounded; an agent that says nothing leaves what was said", async () => {
await report({ id: "Ubuntu", name: "Ubuntu 20.04.6 LTS", version: "20.04" });
let r = await row();
assert.deepEqual([r.osId, r.osName, r.osVersion], ["ubuntu", "Ubuntu 20.04.6 LTS", "20.04"]);
await syncServerTasks(id, { osType: "linux", tasks: [], system: {} });
r = await row();
assert.equal(r.osId, "ubuntu", "an older agent does not wipe it");
await report({ id: "x".repeat(200), name: "n".repeat(500), version: "v".repeat(200) });
r = await row();
assert.deepEqual([r.osId!.length, r.osName!.length, r.osVersion!.length], [40, 80, 40]);
await report({ id: "ubuntu", name: "Ubuntu 20.04.6 LTS", version: "20.04" });
});
test("a release past its end is a warning with the date, on the Alerts page, under the server", async () => {
invalidateAlertsCache();
const alert = (await getAlerts(true)).alerts.find((a) => a.id === `updates:os-support:${id}`)!;
assert.ok(alert, "it is raised");
assert.deepEqual([alert.severity, alert.category, alert.link, alert.target?.name, alert.silenced], ["warning", "updates", `/servers/${id}`, "old-box", false]);
assert.match(alert.message, /old-box runs Ubuntu 20\.04 LTS, whose support ended on 2025-05-31/);
});
test("one with a supported release is not raised, and the warning is a setting (0 turns it off)", async () => {
await report({ id: "debian", name: "Debian GNU/Linux 12 (bookworm)", version: "12" });
invalidateAlertsCache();
assert.equal((await getAlerts(true)).alerts.some((a) => a.id === `updates:os-support:${id}`), false);
await report({ id: "ubuntu", name: "Ubuntu 20.04.6 LTS", version: "20.04" });
await updateSettings({ healthChecks: { osSupportWarnDays: 0 } });
invalidateAlertsCache();
assert.equal((await getAlerts(true)).alerts.some((a) => a.id === `updates:os-support:${id}`), false, "off");
await updateSettings({ healthChecks: { osSupportWarnDays: 90 } });
});
test("a maintenance window on the server holds it back", async () => {
await db.insert(maintenanceWindows).values({ targetType: "server", targetId: id, startedAt: new Date(Date.now() - 1000).toISOString(), endsAt: new Date(Date.now() + 3600_000).toISOString() });
invalidateAlertsCache();
assert.equal((await getAlerts(true)).alerts.find((a) => a.id === `updates:os-support:${id}`)?.silenced, true);
await db.delete(maintenanceWindows).where(eq(maintenanceWindows.targetId, id));
});
});
describe("the agent scripts say it", () => {
test("Linux reads /etc/os-release (and asks Proxmox by its own command) and reports it; Windows reports the product and the build; both are a new version", () => {
const linux = readFileSync(join(repo, "agent", "linux", "report-tasks.sh"), "utf8");
assert.ok(linux.includes("collect_os()") && linux.includes("OS_RELEASE_FILE") && linux.includes("pveversion") && linux.includes("os: $os"));
const windows = readFileSync(join(repo, "agent", "windows", "report-tasks.ps1"), "utf8");
assert.ok(windows.includes("Win32_OperatingSystem") && windows.includes("os = $osInfo") && windows.includes("BuildNumber"));
const latest = latestAgentVersions();
assert.ok((latest.linux ?? 0) >= 7 && (latest.windows ?? 0) >= 6, "an agent that does not say it is behind");
});
});
+59
View File
@@ -0,0 +1,59 @@
/**
* The rack view: which unit a piece of hardware says it sits in, how the racks are made from that, clashes and what is not placed.
*
* Run with: npm test --workspace server
*/
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { buildRacks, parseRackUnit, type RackAsset } from "../src/services/racks.js";
const asset = (id: number, name: string, location: string | null, rackUnit: string | null, extra: Partial<RackAsset> = {}): RackAsset => ({ id, name, kind: "server", manufacturer: null, model: null, location, rackUnit, powerWatts: null, serverId: null, ...extra });
describe("reading a unit", () => {
test("a unit, or a run of them, in the ways people write them", () => {
assert.deepEqual(parseRackUnit("U12"), { from: 12, to: 12 });
assert.deepEqual(parseRackUnit("u3"), { from: 3, to: 3 });
assert.deepEqual(parseRackUnit("12"), { from: 12, to: 12 });
assert.deepEqual(parseRackUnit("U12-13"), { from: 12, to: 13 });
assert.deepEqual(parseRackUnit("12 – 14"), { from: 12, to: 14 });
assert.deepEqual(parseRackUnit("U14-U12"), { from: 12, to: 14 }, "either way round");
assert.equal(parseRackUnit("top shelf"), null);
assert.equal(parseRackUnit("U0"), null);
assert.equal(parseRackUnit(""), null);
assert.equal(parseRackUnit(null), null);
});
});
describe("making racks", () => {
test("hardware is grouped by where it says it is, placed by unit, in a rack of a real size", () => {
const racks = buildRacks([asset(1, "Switch", "Rack A", "U40", { kind: "network", powerWatts: 40 }), asset(2, "NAS", "Rack A", "U10-13", { powerWatts: 120 }), asset(3, "UPS", "Rack A", "U1-3", { kind: "power" }), asset(4, "Laptop", "Desk", null)]);
assert.equal(racks.length, 1, "a desk with no unit is not a rack");
const a = racks[0];
assert.deepEqual([a.name, a.units, a.usedUnits, a.watts], ["Rack A", 42, 1 + 4 + 3, 160]);
assert.deepEqual(a.slots.map((s) => [s.name, s.from, s.to]), [["UPS", 1, 3], ["NAS", 10, 13], ["Switch", 40, 40]], "from the bottom up");
assert.ok(a.slots.every((s) => !s.clash));
});
test("a small rack is drawn small, and a tall piece makes it as tall as it needs", () => {
assert.equal(buildRacks([asset(1, "A", "R", "U5")])[0].units, 12);
assert.equal(buildRacks([asset(1, "A", "R", "U13")])[0].units, 18);
assert.equal(buildRacks([asset(1, "A", "R", "U43-48")])[0].units, 48);
assert.equal(buildRacks([asset(1, "A", "R", "U60-70")])[0].units, 70, "beyond any real rack it just fits");
});
test("two pieces on the same unit clash, and both are said to", () => {
const [rack] = buildRacks([asset(1, "A", "R", "U4-5"), asset(2, "B", "R", "U5"), asset(3, "C", "R", "U8")]);
assert.deepEqual(rack.slots.map((s) => [s.name, s.clash]), [["A", true], ["B", true], ["C", false]]);
assert.equal(rack.usedUnits, 3, "a unit is used once however many claim it");
});
test("hardware that names a rack and no unit is listed beside it, not placed", () => {
const [rack] = buildRacks([asset(1, "NAS", "Rack A", "U10"), asset(2, "Cable box", "Rack A", null), asset(3, "Patch panel", "Rack A", "somewhere")]);
assert.deepEqual(rack.unplaced.map((u) => u.name), ["Cable box", "Patch panel"]);
});
test("a unit with no place goes in a rack of its own, last; racks are in order, numbers as numbers", () => {
const racks = buildRacks([asset(1, "X", null, "U2"), asset(2, "Y", "Rack 10", "U1"), asset(3, "Z", "Rack 2", "U1")]);
assert.deepEqual(racks.map((r) => r.name), ["Rack 2", "Rack 10", "(no rack named)"]);
});
});
+181
View File
@@ -0,0 +1,181 @@
/**
* The to-do list and notes: who may write, what is checked, ticking off and bringing back, what shows in Coming up and My work.
*
* 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-todos-"));
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, notes, todos, auditLog } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { todosRouter, notesRouter } = await import("../src/routes/todos.js");
const { loadAgendaData, agendaFromData } = await import("../src/services/agenda.js");
const { buildMyWork } = await import("../src/services/myWork.js");
const { isRealDay } = await import("../src/services/todos.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
let app: Server;
let base = "";
let who = "operator";
const ids: Record<string, number> = {};
const send = async (method: string, path: string, body?: unknown) => {
const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
return { status: res.status, body: res.status === 204 ? null : ((await res.json().catch(() => null)) as any) };
};
const day = (offset: number) => new Date(Date.now() + offset * 86_400_000).toISOString().slice(0, 10);
before(async () => {
const rows = await db
.insert(users)
.values([
{ oidcSub: "admin", name: "Ada", role: "admin" },
{ oidcSub: "operator", name: "Olga", role: "operator" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
])
.returning({ id: users.id, oidcSub: users.oidcSub });
for (const r of rows) ids[r.oidcSub] = r.id;
ids.web = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w" }).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/todos", todosRouter);
a.use("/api/notes", notesRouter);
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`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows may still hold the database file
}
});
describe("the to-do list", () => {
let jobId = 0;
test("a real day is a real day", () => {
assert.equal(isRealDay("2026-10-20"), true);
assert.equal(isRealDay("2026-02-30"), false);
assert.equal(isRealDay("next week"), false);
});
test("everyone signed in reads it; only an operator writes", async () => {
who = "viewer";
assert.equal((await send("GET", "/todos")).status, 200);
assert.equal((await send("POST", "/todos", { title: "x" })).status, 403);
assert.equal((await send("PATCH", "/todos/1", { done: true })).status, 403);
assert.equal((await send("DELETE", "/todos/1")).status, 403);
});
test("a job needs a title; the day must be a day; it can be about a server and handed to an operator, and not to a viewer", async () => {
who = "operator";
assert.equal((await send("POST", "/todos", { title: " " })).status, 400);
assert.equal((await send("POST", "/todos", { title: "x", dueDate: "tomorrow" })).body.error, "invalid_date");
assert.equal((await send("POST", "/todos", { title: "x", assigneeId: ids.viewer })).body.error, "invalid_assignee");
assert.equal((await send("POST", "/todos", { title: "x", targetType: "server", targetId: 9999 })).body.error, "unknown_target");
assert.equal((await send("POST", "/todos", { title: "x".repeat(200) })).body.error, "too_long");
const made = await send("POST", "/todos", { title: "Replace the UPS battery", detail: "APC, model in the rack", dueDate: day(1), assigneeId: ids.operator, targetType: "server", targetId: ids.web });
assert.equal(made.status, 201);
jobId = made.body.todo.id;
assert.deepEqual([made.body.todo.title, made.body.todo.assignee.name, made.body.todo.target.name, made.body.todo.doneAt], ["Replace the UPS battery", "Olga", "web", null]);
});
test("open jobs come soonest-due first, with those without a day last; ticking one off keeps it, and it comes back", async () => {
await send("POST", "/todos", { title: "Someday" });
await send("POST", "/todos", { title: "Next week", dueDate: day(7) });
const open = (await send("GET", "/todos")).body.todos.map((t: any) => t.title);
assert.deepEqual(open, ["Replace the UPS battery", "Next week", "Someday"]);
const done = await send("PATCH", `/todos/${jobId}`, { done: true });
assert.ok(done.body.todo.doneAt && done.body.todo.doneBy === "Olga");
const after = (await send("GET", "/todos")).body.todos;
assert.deepEqual(after.map((t: any) => [t.title, t.doneAt !== null]), [["Next week", false], ["Someday", false], ["Replace the UPS battery", true]], "done ones after the open ones");
const back = await send("PATCH", `/todos/${jobId}`, { done: false });
assert.equal(back.body.todo.doneAt, null);
});
test("a job can be changed, and removed; one that is not there is a 404", async () => {
const changed = await send("PATCH", `/todos/${jobId}`, { title: "Replace the UPS battery (APC)", dueDate: null, assigneeId: null });
assert.deepEqual([changed.body.todo.title, changed.body.todo.dueDate, changed.body.todo.assignee], ["Replace the UPS battery (APC)", null, null]);
assert.equal((await send("PATCH", "/todos/99999", { done: true })).status, 404);
assert.equal((await send("DELETE", `/todos/${jobId}`)).status, 204);
assert.equal((await send("DELETE", `/todos/${jobId}`)).status, 404);
const kinds = (await db.select().from(auditLog).where(eq(auditLog.category, "todo"))).map((e) => e.action);
assert.ok(["create", "done", "reopen", "update", "delete"].every((a) => kinds.includes(a)), "each is written down");
});
test("a job about a server that is later removed is still there, about nothing", async () => {
const gone = (await db.insert(servers).values({ name: "temp", apiTokenHash: "t", apiTokenPrefix: "t" }).returning({ id: servers.id }))[0].id;
const made = await send("POST", "/todos", { title: "About temp", targetType: "server", targetId: gone });
await db.delete(servers).where(eq(servers.id, gone));
const found = (await send("GET", "/todos")).body.todos.find((t: any) => t.id === made.body.todo.id);
assert.equal(found.target, null);
await send("DELETE", `/todos/${made.body.todo.id}`);
});
test("an open job with a day is in Coming up (overdue ones too), a done one is not; one handed to somebody is in their My work", async () => {
const soon = (await send("POST", "/todos", { title: "Move the NAS", dueDate: day(3), assigneeId: ids.operator })).body.todo;
const late = (await send("POST", "/todos", { title: "Order a spare disk", dueDate: day(-2), assigneeId: ids.operator })).body.todo;
const finished = (await send("POST", "/todos", { title: "Already done", dueDate: day(2) })).body.todo;
await send("PATCH", `/todos/${finished.id}`, { done: true });
const agenda = agendaFromData(await loadAgendaData(), new Date(), "UTC", 30);
const titles = agenda.items.filter((i) => i.kind === "todo").map((i) => i.title);
assert.ok(titles.includes("To do: Move the NAS") && titles.includes("Overdue: Order a spare disk"));
assert.ok(!titles.some((t) => t.includes("Already done")));
const mine = await buildMyWork({ id: ids.operator, name: "Olga", email: null, oidcSub: "operator" });
assert.deepEqual(mine.todos.map((t) => [t.title, t.overdue, t.dueSoon]), [["Order a spare disk", true, false], ["Move the NAS", false, false]], "overdue first; three days off is not yet soon");
assert.ok(mine.needsAttention >= 1, "an overdue job wants a look");
const theirs = await buildMyWork({ id: ids.admin, name: "Ada", email: null, oidcSub: "admin" });
assert.equal(theirs.todos.length, 0);
await db.delete(todos);
assert.ok(soon && late);
});
});
describe("notes", () => {
test("read by everyone; written by an operator; an empty text takes it away", async () => {
who = "viewer";
assert.equal((await send("GET", `/notes?targetType=server&targetId=${ids.web}`)).body.note, null);
assert.equal((await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: "x" })).status, 403);
who = "operator";
const saved = await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: "Lives in the **rack**.\n\n- PSU is on the left" });
assert.deepEqual([saved.status, saved.body.note.updatedBy, saved.body.note.body.includes("**rack**")], [200, "Olga", true]);
const again = await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: "Replaced." });
assert.equal((await db.select().from(notes)).length, 1, "one text per thing");
assert.equal(again.body.note.body, "Replaced.");
who = "viewer";
assert.equal((await send("GET", `/notes?targetType=server&targetId=${ids.web}`)).body.note.body, "Replaced.");
who = "operator";
assert.equal((await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: " \n " })).body.note, null);
assert.equal((await db.select().from(notes)).length, 0);
});
test("a note for nothing, or too long, or about something unknown, is refused", async () => {
who = "operator";
assert.equal((await send("PUT", "/notes", { targetType: "server", targetId: 99999, body: "x" })).status, 404);
assert.equal((await send("PUT", "/notes", { targetType: "server", targetId: ids.web, body: "x".repeat(9000) })).body.error, "too_long");
assert.equal((await send("PUT", "/notes", { targetType: "rack", targetId: 1, body: "x" })).status, 400);
assert.equal((await send("GET", "/notes?targetType=server")).status, 400);
});
});
+1 -1
View File
@@ -34,7 +34,7 @@ function run(snippet: string): unknown {
describe("the Windows agent's health parts", { skip: !havePwsh }, () => {
test("it says it is version 5, and stays plain ASCII", () => {
const text = readFileSync(script, "utf8");
assert.match(text, /^\$script:AgentVersion = 5\s*$/m);
assert.match(text, /^\$script:AgentVersion = 6\s*$/m);
assert.ok(!/[^\x00-\x7f]/.test(text));
});