Files
Homelab-manager/server/test/kumaMaintenanceSync.test.ts
T
bobbanandClaude Sonnet 5.5 3e6404371b Match Uptime Kuma monitors to integrations and DNS providers as well as servers
A monitor whose address is the host of an integration's or DNS provider's own
address now gets a maintenance window there, alongside the existing match
against servers. Matching stays exact (no inference through DNS), and monitors
that match nothing are listed with their address in the sync result.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-12 00:13:04 +02:00

462 lines
22 KiB
TypeScript

/**
* Mirroring Uptime Kuma's maintenance schedule as maintenance windows.
*
* The first half tests the pure parts (reading Kuma's dates, deciding what windows to make or change). The second half runs the
* real sync and route against a stand-in Uptime Kuma that speaks the same protocol as the real one: an HTTP /metrics endpoint and
* a Socket.IO connection with "login", "maintenanceList" and "getMonitorMaintenance".
*
* 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-kuma-sync-"));
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 { Server: IOServer } = await import("socket.io");
const { db } = await import("../src/db/client.js");
const { users, servers, integrations, dnsProviders, maintenanceWindows } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { maintenanceRouter } = await import("../src/routes/maintenance.js");
const { kumaInstant, normalizeMaintenanceList, monitorIdsFromReply } = await import("../src/integrations/uptimekuma/maintenanceFeed.js");
const { planWindowSync, desiredWindows, MANUAL_WINDOW_MS } = await import("../src/services/kumaMaintenanceSync.js");
const { hostOfAddress, targetsForHost } = await import("../src/services/kumaTargets.js");
const { listActiveWindows, listUpcomingWindows } = await import("../src/services/maintenance.js");
await runMigrations();
const iso = (ms: number) => new Date(ms).toISOString();
const MIN = 60_000;
const HOUR = 60 * MIN;
describe("kumaInstant", () => {
test("a time with an offset or Z is taken as given", () => {
assert.equal(kumaInstant("2026-10-12T02:00:00.000Z", null)?.toISOString(), "2026-10-12T02:00:00.000Z");
assert.equal(kumaInstant("2026-10-12T04:00:00+02:00", null)?.toISOString(), "2026-10-12T02:00:00.000Z");
});
test("a local time is read in the window's own timezone, summer and winter", () => {
assert.equal(kumaInstant("2026-07-01 02:00:00", "Europe/Stockholm")?.toISOString(), "2026-07-01T00:00:00.000Z"); // UTC+2
assert.equal(kumaInstant("2026-12-01 02:00:00", "Europe/Stockholm")?.toISOString(), "2026-12-01T01:00:00.000Z"); // UTC+1
assert.equal(kumaInstant("2026-12-01 02:00", "America/New_York")?.toISOString(), "2026-12-01T07:00:00.000Z");
assert.equal(kumaInstant("2026-12-01 02:00:00", "UTC")?.toISOString(), "2026-12-01T02:00:00.000Z");
});
test("something unreadable gives null, not a wrong time", () => {
assert.equal(kumaInstant("2026-12-01 02:00:00", null), null);
assert.equal(kumaInstant("2026-12-01 02:00:00", "Mars/Olympus"), null);
assert.equal(kumaInstant("tomorrow", "UTC"), null);
assert.equal(kumaInstant(undefined, "UTC"), null);
});
});
describe("reading Kuma's lists", () => {
test("maintenanceList becomes plain records; unreadable entries are skipped", () => {
const list = normalizeMaintenanceList({
"2": { id: 2, title: "Nightly", strategy: "recurring-interval", active: true, status: "scheduled", timezone: "Europe/Stockholm", timeslotList: [{ startDate: "2026-10-12T00:00:00.000Z", endDate: "2026-10-12T01:00:00.000Z" }, { startDate: "junk", endDate: "junk" }] },
"1": { id: 1, title: "Once", strategy: "single", active: true, status: "scheduled", timezone: "UTC", timeslotList: [{ startDate: "2026-12-01 02:00:00", endDate: "2026-12-01 03:00:00" }] },
"3": "not an object",
});
assert.deepEqual(list.map((m) => m.id), [1, 2]);
assert.deepEqual(list[0].timeslots, [{ start: "2026-12-01T02:00:00.000Z", end: "2026-12-01T03:00:00.000Z" }]);
assert.equal(list[1].timeslots.length, 1, "the unreadable slot is dropped, the good one kept");
});
test("the monitors of a window, in either reply shape", () => {
assert.deepEqual(monitorIdsFromReply({ ok: true, monitors: [{ id: 4 }, { id: 9 }] }), ["4", "9"]);
assert.deepEqual(monitorIdsFromReply({ ok: true, monitorID: [4, 9] }), ["4", "9"]);
assert.deepEqual(monitorIdsFromReply({ ok: false }), []);
assert.deepEqual(monitorIdsFromReply(null), []);
});
});
describe("which things a monitor's address belongs to", () => {
const serverList = [{ id: 1, name: "elsa", hostname: "elsa.lab.example", ips: ["10.0.0.5", "fd00::5"] }];
const addressed = [
{ type: "integration" as const, id: 2, name: "Proxmox", host: "pve.lab.example" },
{ type: "integration" as const, id: 3, name: "NAS", host: "10.0.0.20" },
{ type: "dns_provider" as const, id: 4, name: "Technitium", host: "fd00:0:0:0:0:0:0:53" },
];
const names = (host: string | null) => targetsForHost(host, serverList, addressed).map((t) => `${t.type}:${t.name}`);
test("the address a monitor watches is matched to a server, an integration or a DNS provider", () => {
assert.deepEqual(names("10.0.0.5"), ["server:elsa"]);
assert.deepEqual(names("pve.lab.example"), ["integration:Proxmox"]);
assert.deepEqual(names("PVE.lab.example."), ["integration:Proxmox"]);
assert.deepEqual(names("10.0.0.20"), ["integration:NAS"]);
});
test("an IPv6 address matches however it is written", () => {
assert.deepEqual(names("fd00::53"), ["dns_provider:Technitium"]);
});
test("nothing is inferred: a name that is merely near, or no address, matches nothing", () => {
assert.deepEqual(names("www.lab.example"), []);
assert.deepEqual(names("10.0.0.21"), []);
assert.deepEqual(names(null), []);
assert.deepEqual(names(""), []);
});
test("the host is read out of an address as typed", () => {
assert.equal(hostOfAddress("https://PVE.lab.example:8006/"), "pve.lab.example");
assert.equal(hostOfAddress("10.0.0.5:8006"), "10.0.0.5");
assert.equal(hostOfAddress("http://[fd00::1]:5380"), "fd00::1");
assert.equal(hostOfAddress(""), null);
assert.equal(hostOfAddress(null), null);
});
});
describe("planWindowSync", () => {
const now = new Date("2026-10-10T12:00:00.000Z");
const S = "kuma:1:5";
const want = (start: string | null, end: string, targetId = 7) => ({ source: S, targetType: "server" as const, targetId, start, end, reason: "r" });
const row = (id: number, startedAt: string, endsAt: string, targetId = 7) => ({ id, source: S, targetType: "server" as const, targetId, startedAt, endsAt });
test("a slot Kuma reports that isn't here yet is added", () => {
const plan = planWindowSync([want("2026-10-11T00:00:00.000Z", "2026-10-11T01:00:00.000Z")], [], now);
assert.equal(plan.insert.length, 1);
assert.equal(plan.insert[0].start, "2026-10-11T00:00:00.000Z");
});
test("running it again changes nothing", () => {
const plan = planWindowSync([want("2026-10-11T00:00:00.000Z", "2026-10-11T01:00:00.000Z")], [row(1, "2026-10-11T00:00:00.000Z", "2026-10-11T01:00:00.000Z")], now);
assert.deepEqual(plan, { insert: [], setEnd: [], remove: [] });
});
test("a changed end is adjusted", () => {
const plan = planWindowSync([want("2026-10-11T00:00:00.000Z", "2026-10-11T02:00:00.000Z")], [row(1, "2026-10-11T00:00:00.000Z", "2026-10-11T01:00:00.000Z")], now);
assert.deepEqual(plan.setEnd, [{ id: 1, endsAt: "2026-10-11T02:00:00.000Z" }]);
});
test("a future window Kuma no longer has is removed", () => {
const plan = planWindowSync([], [row(1, "2026-10-11T00:00:00.000Z", "2026-10-11T01:00:00.000Z")], now);
assert.deepEqual(plan.remove, [1]);
});
test("a running window Kuma no longer has is cut short, not deleted", () => {
const plan = planWindowSync([], [row(1, "2026-10-10T11:00:00.000Z", "2026-10-10T13:00:00.000Z")], now);
assert.deepEqual(plan.setEnd, [{ id: 1, endsAt: now.toISOString() }]);
assert.deepEqual(plan.remove, []);
});
test("a window ended by hand stays ended while Kuma still lists it", () => {
const ended = row(1, "2026-10-10T11:00:00.000Z", "2026-10-10T11:30:00.000Z");
const plan = planWindowSync([want("2026-10-10T11:00:00.000Z", "2026-10-10T13:00:00.000Z")], [ended], now);
assert.deepEqual(plan, { insert: [], setEnd: [], remove: [] });
});
test("a window cancelled before it began stays cancelled", () => {
const cancelled = row(1, "2026-10-11T00:00:00.000Z", "2026-10-11T00:00:00.000Z");
const plan = planWindowSync([want("2026-10-11T00:00:00.000Z", "2026-10-11T01:00:00.000Z")], [cancelled], now);
assert.deepEqual(plan, { insert: [], setEnd: [], remove: [] });
});
test("a manual window carries on the running one instead of starting another", () => {
const running = row(1, "2026-10-10T11:50:00.000Z", "2026-10-10T12:20:00.000Z");
const plan = planWindowSync([want(null, "2026-10-10T12:45:00.000Z")], [running], now);
assert.deepEqual(plan.insert, []);
assert.deepEqual(plan.setEnd, [{ id: 1, endsAt: "2026-10-10T12:45:00.000Z" }]);
});
test("a manual window with nothing running starts now", () => {
const plan = planWindowSync([want(null, "2026-10-10T12:45:00.000Z")], [], now);
assert.equal(plan.insert[0].start, now.toISOString());
});
test("windows long over are tidied away", () => {
const plan = planWindowSync([], [row(1, "2026-10-01T00:00:00.000Z", "2026-10-01T01:00:00.000Z")], now);
assert.deepEqual(plan.remove, [1]);
});
});
describe("desiredWindows", () => {
const now = new Date("2026-10-10T12:00:00.000Z");
const server = (id: string) =>
id === "1" ? [{ type: "server" as const, id: 10, name: "elsa" }] : id === "2" ? [{ type: "server" as const, id: 20, name: "anna" }] : [];
const label = (id: string) => `monitor ${id}`;
const base = { id: 5, title: "Nightly", strategy: "recurring-interval", active: true, status: "scheduled", timezone: "UTC", timeslots: [] as { start: string; end: string }[], monitorIds: ["1", "2", "3"] };
const run = (m: Partial<typeof base>) => desiredWindows(1, "Kuma", [{ ...base, ...m }], server, label, now);
test("each slot on each matching server; monitors that match no server are reported", () => {
const { desired, summary } = run({ timeslots: [{ start: iso(now.getTime() + 2 * HOUR), end: iso(now.getTime() + 3 * HOUR) }] });
assert.equal(desired.length, 2);
assert.deepEqual(desired.map((d) => d.targetId).sort(), [10, 20]);
assert.deepEqual(summary[0].targets.map((t) => t.name), ["anna", "elsa"]);
assert.deepEqual(summary[0].unmatched, ["monitor 3"]);
assert.equal(summary[0].note, null);
});
test("a switched-off or ended window makes nothing", () => {
assert.equal(run({ active: false, status: "inactive", timeslots: [{ start: iso(now.getTime() + HOUR), end: iso(now.getTime() + 2 * HOUR) }] }).desired.length, 0);
assert.equal(run({ status: "ended" }).desired.length, 0);
});
test("a slot already over, or too far ahead, is left out", () => {
const over = { start: iso(now.getTime() - 3 * HOUR), end: iso(now.getTime() - 2 * HOUR) };
const far = { start: iso(now.getTime() + 30 * 24 * HOUR), end: iso(now.getTime() + 30 * 24 * HOUR + HOUR) };
assert.equal(run({ timeslots: [over, far] }).desired.length, 0);
});
test("a slot is capped at 31 days, however long Kuma's is", () => {
const start = now.getTime() + HOUR;
const { desired } = run({ timeslots: [{ start: iso(start), end: iso(start + 365 * 24 * HOUR) }] });
assert.equal(Date.parse(desired[0].end) - start, 31 * 24 * HOUR);
});
test("a manual window that is on is mirrored for a short while; one that is off is not", () => {
const on = run({ strategy: "manual", status: "under-maintenance" });
assert.equal(on.desired[0].start, null);
assert.equal(Date.parse(on.desired[0].end) - now.getTime(), MANUAL_WINDOW_MS);
assert.equal(run({ strategy: "manual", status: "inactive", active: true }).desired.length, 0);
});
test("a window covering no monitors says why it made nothing", () => {
const { desired, summary } = run({ monitorIds: [], timeslots: [{ start: iso(now.getTime() + HOUR), end: iso(now.getTime() + 2 * HOUR) }] });
assert.equal(desired.length, 0);
assert.equal(summary[0].note, "covers no monitors");
});
});
// ─── The whole thing, against a stand-in Uptime Kuma ────────────────────────
describe("syncing from a stand-in Uptime Kuma", () => {
const kuma = {
list: {} as Record<string, unknown>,
monitorsOf: {} as Record<string, number[]>,
password: "pw",
twofa: false,
logins: 0,
};
let httpServer: http.Server;
let io: InstanceType<typeof IOServer>;
let app: http.Server;
let base = "";
let integrationId = 0;
let elsaId = 0;
let annaId = 0;
const metric = (id: number, host: string) =>
`monitor_status{monitor_id="${id}",monitor_name="m${id}",monitor_type="ping",monitor_url="",monitor_hostname="${host}",monitor_port=""} 1`;
before(async () => {
httpServer = http.createServer((req, res) => {
if (req.url === "/metrics") {
res.end([metric(1, "elsa.lab.example"), metric(2, "anna.lab.example"), metric(3, "10.9.9.9"), metric(4, "pve.lab.example"), metric(5, "10.0.0.53")].join("\n"));
} else {
res.statusCode = 404;
res.end();
}
});
io = new IOServer(httpServer);
io.on("connection", (socket) => {
socket.on("login", (data: { username: string; password: string }, cb: (r: unknown) => void) => {
kuma.logins++;
if (kuma.twofa) return cb({ tokenRequired: true });
if (data.username !== "admin" || data.password !== kuma.password) return cb({ ok: false, msg: "authIncorrectCreds", msgi18n: true });
socket.emit("maintenanceList", kuma.list);
cb({ ok: true, token: "t" });
});
socket.on("getMonitorMaintenance", (id: number, cb: (r: unknown) => void) => {
cb({ ok: true, monitors: (kuma.monitorsOf[String(id)] ?? []).map((m) => ({ id: m })) });
});
});
await new Promise<void>((resolve) => httpServer.listen(0, "127.0.0.1", resolve));
const kumaUrl = `http://127.0.0.1:${(httpServer.address() as AddressInfo).port}`;
await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "admin" });
elsaId = (await db.insert(servers).values({ name: "elsa", hostname: "elsa.lab.example", apiTokenHash: "x", apiTokenPrefix: "x" }).returning())[0].id;
annaId = (await db.insert(servers).values({ name: "anna", hostname: "anna.lab.example", apiTokenHash: "y", apiTokenPrefix: "y" }).returning())[0].id;
integrationId = (
await db
.insert(integrations)
.values({
type: "uptimekuma",
name: "Kuma",
baseUrl: kumaUrl,
config: JSON.stringify({ url: kumaUrl, password: "key", loginUsername: "admin", loginPassword: "pw", syncMaintenance: true }),
})
.returning()
)[0].id;
// Things that are not servers: a Proxmox integration reached by name, and a DNS provider reached by IP.
await db.insert(integrations).values({ type: "proxmox", name: "Proxmox Felicia", baseUrl: "https://pve.lab.example:8006", config: "{}" });
await db.insert(dnsProviders).values({ providerType: "technitium", name: "Technitium Ginny", config: JSON.stringify({ url: "http://10.0.0.53:5380" }) });
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "tester" } };
next();
});
a.use("/api/maintenance", maintenanceRouter);
app = await new Promise<http.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/maintenance`;
});
after(async () => {
await io.close();
app.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
async function sync() {
const res = await fetch(`${base}/sync/uptimekuma`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ integrationId }),
});
return { status: res.status, body: await res.json() };
}
const daily = (start: number, end: number, extra: Record<string, unknown> = {}) => ({
id: 5,
title: "Nightly patching",
strategy: "recurring-interval",
active: true,
status: "scheduled",
timezone: "UTC",
timeslotList: [{ startDate: iso(start), endDate: iso(end) }],
...extra,
});
test("a daily window becomes a scheduled window on the servers it covers", async () => {
const start = Date.now() + 3 * HOUR;
kuma.list = { "5": daily(start, start + HOUR) };
kuma.monitorsOf = { "5": [1, 2, 3] };
const { status, body } = await sync();
assert.equal(status, 200);
assert.equal(body.started, 2);
assert.deepEqual(body.maintenances[0].targets.map((t: { name: string }) => t.name), ["anna", "elsa"]);
assert.deepEqual(body.maintenances[0].unmatched, ["m3 (10.9.9.9)"]);
assert.equal((await listActiveWindows()).length, 0, "it hasn't begun, so it silences nothing yet");
const upcoming = await listUpcomingWindows();
assert.deepEqual(upcoming.map((w) => w.targetId).sort(), [elsaId, annaId].sort());
assert.equal(upcoming[0].source, `kuma:${integrationId}:5`);
assert.match(upcoming[0].reason ?? "", /Nightly patching/);
});
test("monitors on an integration's or a DNS provider's own address get windows there too", async () => {
await db.delete(maintenanceWindows);
const start = Date.now() + 4 * HOUR;
kuma.list = { "6": daily(start, start + HOUR, { id: 6, title: "Sunday" }) };
kuma.monitorsOf = { "6": [4, 5] };
const { body } = await sync();
assert.equal(body.started, 2);
assert.deepEqual(
body.maintenances[0].targets.map((t: { type: string; name: string }) => `${t.type}:${t.name}`).sort(),
["dns_provider:Technitium Ginny", "integration:Proxmox Felicia"],
);
const types = (await listUpcomingWindows()).map((w) => w.targetType).sort();
assert.deepEqual(types, ["dns_provider", "integration"]);
// Back to the first scenario, for the tests that follow.
kuma.list = { "5": daily(start, start + HOUR) };
kuma.monitorsOf = { "5": [1, 2, 3] };
await db.delete(maintenanceWindows);
await sync();
});
test("syncing again adds nothing", async () => {
const { body } = await sync();
assert.deepEqual([body.started, body.updated, body.removed], [0, 0, 0]);
assert.equal((await listUpcomingWindows()).length, 2);
});
test("when the slot is running it is an active window that silences, ending when Kuma's slot does", async () => {
await db.delete(maintenanceWindows);
const start = Date.now() - 10 * MIN;
kuma.list = { "5": daily(start, start + HOUR, { status: "under-maintenance" }) };
const { body } = await sync();
assert.equal(body.started, 2);
const active = await listActiveWindows();
assert.equal(active.length, 2);
assert.equal(Date.parse(active[0].endsAt), start + HOUR);
});
test("a window ended by hand is not brought back by the next sync", async () => {
const [w] = await listActiveWindows();
const res = await fetch(`${base}/${w.id}`, { method: "DELETE" });
assert.equal(res.status, 204);
const { body } = await sync();
assert.equal(body.started, 0);
assert.equal((await listActiveWindows()).length, 1);
});
test("a window deleted in Kuma stops silencing here", async () => {
kuma.list = {};
const { body } = await sync();
assert.ok(body.updated >= 1);
assert.equal((await listActiveWindows()).length, 0);
});
test("a future window Kuma drops is removed, and one cancelled by hand stays cancelled", async () => {
await db.delete(maintenanceWindows);
const start = Date.now() + 5 * HOUR;
kuma.list = { "5": daily(start, start + HOUR) };
await sync();
const [first] = await listUpcomingWindows();
await fetch(`${base}/${first.id}`, { method: "DELETE" });
assert.equal((await listUpcomingWindows()).length, 1, "the cancelled one no longer counts");
const again = await sync();
assert.equal(again.body.started, 0, "and the sync does not recreate it");
kuma.list = {};
const { body } = await sync();
assert.ok(body.removed >= 1);
assert.equal((await listUpcomingWindows()).length, 0);
});
test("a wrong password says so", async () => {
kuma.password = "something else";
const { status, body } = await sync();
assert.equal(status, 502);
assert.match(body.message, /rejected the login username or password/);
kuma.password = "pw";
});
test("a login with two-factor says it can't be used", async () => {
kuma.twofa = true;
const { status, body } = await sync();
assert.equal(status, 502);
assert.match(body.message, /two-factor/);
kuma.twofa = false;
});
test("without a login on the integration it asks for one", async () => {
const [bare] = await db
.insert(integrations)
.values({ type: "uptimekuma", name: "Bare", baseUrl: "http://127.0.0.1:1", config: JSON.stringify({ url: "http://127.0.0.1:1", password: "key" }) })
.returning();
const res = await fetch(`${base}/sync/uptimekuma`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ integrationId: bare.id }) });
const body = await res.json();
assert.equal(res.status, 400);
assert.match(body.message, /needs a login/);
});
test("an unreachable Uptime Kuma gives a readable message", async () => {
const [dead] = await db
.insert(integrations)
.values({ type: "uptimekuma", name: "Dead", baseUrl: "http://127.0.0.1:1", config: JSON.stringify({ url: "http://127.0.0.1:1", password: "key", loginUsername: "admin", loginPassword: "pw" }) })
.returning();
const res = await fetch(`${base}/sync/uptimekuma`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ integrationId: dead.id }) });
const body = await res.json();
assert.equal(res.status, 502);
assert.match(body.message, /Couldn't (connect to|read) Uptime Kuma/);
});
});