Files
bobbanandClaude Sonnet 5.5 4e0c6927b2 Heartbeats, Coming up and suggested checks; Operations menu tidied
Heartbeats: a cron job or script calls /api/heartbeat/<token> (and /start, /fail); the app
alerts when the call is late or the job says it failed. Coming up: one agenda of everything
dated (expiries, warranties, end of support, planned and recurring maintenance, restore tests,
waiting updates), with a dashboard card and an iCalendar feed behind a share link. Suggested
checks: web ports and certificates the app already knows about, added with a click.

Menu: Incidents become Alerts -> History (old /incidents links redirect); new Monitoring group
(Endpoints, Heartbeats, Uptime Kuma); osTicket under Automation, Admin Links under
Infrastructure, Generator under Administration. Also makes the restore-test metrics test follow
the real clock.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-19 21:42:34 +02:00

163 lines
10 KiB
TypeScript

/**
* The change log: the sentences, what is left out, the filters (kind, server, time, a word), paging, and who may read it.
*
* 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-changes-"));
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, auditLog, alertIncidents } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { describeChange, getChangeLog } = await import("../src/services/changeLog.js");
const { changesRouter } = await import("../src/routes/changes.js");
await runMigrations();
describe("the sentences", () => {
test("maintenance, dependencies, hardware, restore tests and settings read as sentences", () => {
assert.deepEqual(describeChange("maintenance", "start", { name: "nas", minutes: 60, reason: "reboot" }), { title: "Maintenance started on nas", tone: "info", detail: "for 60 min · reboot" });
assert.equal(describeChange("maintenance", "extend", { name: "nas", minutes: 240 }).detail, "for 4 h from now");
assert.equal(describeChange("dependency", "create", { from: "Gitea", to: "nas" }).title, "Gitea now needs nas");
assert.equal(describeChange("dependency", "delete", { from: "Gitea", to: "nas" }).title, "Gitea no longer needs nas");
assert.equal(describeChange("inventory", "create", { name: "NAS", kind: "storage" }).title, "Hardware added: NAS");
assert.deepEqual(describeChange("restore_test", "record", { name: "elsa", result: "failed", testedAt: "2026-10-01", note: "no boot" }), { title: "Restore test of elsa failed", tone: "bad", detail: "2026-10-01 · no boot" });
assert.equal(describeChange("restore_test", "record", { name: "elsa", result: "ok" }).tone, "good");
const s = describeChange("settings", "update", { sections: ["notifications", "webhook"], changes: { notifications: { healthAlerts: { from: true, to: false } }, webhook: { url: "(changed)" } } });
assert.equal(s.title, "Settings changed: notifications, webhook");
assert.equal(s.detail, 'notifications.healthAlerts: true → false · webhook.url changed', "a secret's value is never in it");
});
test("a server's own entries use the wording of its Activity card; anything else is made readable", () => {
assert.equal(describeChange("server", "agent_updated", { from: 4, to: 6 }).title, "Agent updated to version 6");
assert.equal(describeChange("alert", "ack", { assignee: "Olle", hours: 4 }).title, "Acknowledged, handed to Olle");
assert.deepEqual(describeChange("dns", "add_record", { name: "a.example.com", type: "A" }), { title: "Dns: add record — a.example.com", tone: "neutral", detail: "type: A" });
});
});
describe("through the routes", () => {
let app: Server;
let base = "";
let who = "operator";
let nas = 0;
let elsa = 0;
const audit = (category: string, action: string, extra: { targetType?: string; targetId?: string; detail?: unknown; actor?: string; at: string }) =>
db.insert(auditLog).values({ category, action, targetType: extra.targetType ?? null, targetId: extra.targetId ?? null, detail: extra.detail === undefined ? null : JSON.stringify(extra.detail), actorLabel: extra.actor ?? "Ada", createdAt: extra.at });
const ago = (min: number) => new Date(Date.now() - min * 60_000).toISOString().slice(0, 19).replace("T", " ");
before(async () => {
await db.insert(users).values([
{ oidcSub: "operator", name: "Olga", role: "operator" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
const made = await db.insert(servers).values([{ name: "nas", apiTokenHash: "n", apiTokenPrefix: "n" }, { name: "elsa", apiTokenHash: "e", apiTokenPrefix: "e" }]).returning({ id: servers.id });
nas = made[0].id;
elsa = made[1].id;
await audit("maintenance", "start", { targetType: "server", targetId: String(nas), detail: { name: "nas", minutes: 60, reason: "reboot" }, at: ago(10) });
await audit("server", "agent_updated", { targetType: "server", targetId: String(elsa), detail: { from: 4, to: 6 }, actor: "system", at: ago(20) });
await audit("dependency", "create", { targetType: "dependency", targetId: "1", detail: { from: "Gitea", to: "nas", fromKey: "integration:1", toKey: `server:${nas}` }, at: ago(30) });
await audit("settings", "update", { targetType: "settings", detail: { sections: ["display"], changes: { display: { pageSize: { from: 20, to: 50 } } } }, at: ago(40) });
await audit("session", "login", { at: ago(5) });
await audit("privacy", "export_own_data", { at: ago(6) });
await audit("inventory", "create", { targetType: "asset", targetId: "7", detail: { name: "Core switch", kind: "network" }, at: ago(60 * 24 * 3) });
await audit("server", "update", { targetType: "server", targetId: String(nas), detail: { name: "nas" }, at: ago(60 * 24 * 20) });
await db.insert(alertIncidents).values({ alertKey: "offline:offline:server:1", severity: "critical", peakSeverity: "critical", category: "offline", source: "Server", message: "nas hasn't reported for 3 h", targetType: "server", targetId: nas, targetName: "nas", openedAt: new Date(Date.now() - 50 * 60_000).toISOString(), resolvedAt: new Date(Date.now() - 15 * 60_000).toISOString(), lastSeenAt: new Date().toISOString() });
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/changes", changesRouter);
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/changes`;
});
after(() => {
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const get = async (query = "") => (await fetch(`${base}${query}`)).json();
const titles = (r: { entries: { title: string }[] }) => r.entries.map((e) => e.title);
test("everything of the last week, newest first, with the alerts raised and cleared in between; sign-ins and data exports are not changes", async () => {
const r = await get();
assert.deepEqual(titles(r), [
"Maintenance started on nas",
"Alert cleared: nas hasn't reported for 3 h",
"Agent updated to version 6",
"Gitea now needs nas",
"Settings changed: display",
"Alert raised: nas hasn't reported for 3 h",
"Hardware added: Core switch",
]);
assert.ok(!r.entries.some((e: { title: string }) => /login|export/i.test(e.title)));
const maint = r.entries[0];
assert.deepEqual([maint.kind, maint.actor, maint.link, maint.serverId], ["maintenance", "Ada", `/servers/${nas}`, nas]);
assert.equal(r.entries.find((e: { title: string }) => e.title.startsWith("Alert raised")).link.startsWith("/alerts/incidents/"), true);
assert.equal(r.kinds.length, 10);
});
test("by kind, by how far back, and by a word", async () => {
assert.deepEqual(titles(await get("?kind=maintenance")), ["Maintenance started on nas"]);
assert.deepEqual(titles(await get("?kind=alerts")).length, 2);
assert.equal((await get("?days=1")).entries.length, 6, "the hardware added three days ago is out");
assert.equal((await get("?days=30")).entries.length, 8, "and a month covers the old edit too");
assert.deepEqual(titles(await get("?q=gitea")), ["Gitea now needs nas"]);
assert.deepEqual(titles(await get("?q=version%20elsa")), ["Agent updated to version 6"], "every word must appear somewhere, the server's name included");
assert.deepEqual((await get("?kind=nonsense")).entries.length, 7, "an unknown kind is no filter");
});
test("by server: its own entries, its alerts, and what mentions it by key — not the other server's", async () => {
assert.deepEqual(titles(await get(`?serverId=${nas}`)), ["Maintenance started on nas", "Alert cleared: nas hasn't reported for 3 h", "Gitea now needs nas", "Alert raised: nas hasn't reported for 3 h"]);
assert.deepEqual(titles(await get(`?serverId=${elsa}`)), ["Agent updated to version 6"]);
assert.deepEqual((await get("?serverId=99999")).entries, []);
});
test("paged: a limit says there is more, and 'before' goes on from where it stopped", async () => {
const first = await get("?limit=3");
assert.equal(first.entries.length, 3);
assert.equal(first.more, true);
const next = await get(`?limit=3&before=${encodeURIComponent(first.entries[2].at)}`);
assert.deepEqual(titles(next), ["Gitea now needs nas", "Settings changed: display", "Alert raised: nas hasn't reported for 3 h"]);
assert.ok(next.entries.every((e: { at: string }) => e.at < first.entries[2].at));
assert.equal(next.more, true, "the hardware added three days ago is still to come");
const last = await get(`?limit=3&before=${encodeURIComponent(next.entries[2].at)}`);
assert.deepEqual(titles(last), ["Hardware added: Core switch"]);
assert.equal(last.more, false);
});
test("operators and administrators can read it; a viewer can't", async () => {
who = "viewer";
assert.equal((await fetch(base)).status, 403);
who = "operator";
assert.equal((await fetch(base)).status, 200);
});
test("the service on its own gives the same answer for any moment it is asked about", async () => {
const future = await getChangeLog({ now: new Date(Date.now() + 40 * 86_400_000), days: 1 });
assert.deepEqual(future.entries, [], "nothing in the day before a month from now");
});
});