/** * "Coming up": what the agenda gathers and how it dates it, the calendar feed it can be written as, and the routes — the list for people signed in * and the feed behind a share link. * * 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-agenda-")); 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, secrets, domains, assets, endpointChecks, maintenanceWindows, maintenanceSchedules, restoreTests } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const { agendaFromData, buildIcs, foldLine, localDate, addDays, buildAgenda, clearAgendaCacheForTests } = await import("../src/services/agenda.js"); const { agendaRouter } = await import("../src/routes/agenda.js"); const { publicCalendarRouter } = await import("../src/routes/publicCalendar.js"); const { shareLinksRouter } = await import("../src/routes/shareLinks.js"); const { createShareLink } = await import("../src/services/shareLinks.js"); const { updateSettings } = await import("../src/services/settingsStore.js"); await runMigrations(); type Data = Parameters[0]; const NOW = new Date("2026-10-19T12:00:00Z"); const empty = (extra: Partial = {}): Data => ({ secrets: [], domains: [], endpoints: [], tailscale: [], assets: [], windows: [], schedules: [], restoreTests: [], restoreLimitDays: 0, updates: [], notes: [], ...extra }); const titles = (data: Data, days?: number, tz = "UTC") => agendaFromData(data, NOW, tz, days).items.map((i) => [i.daysLeft, i.kind, i.title]); describe("what is gathered, and how it is dated", () => { test("a day that something expires on, with how many days away it is; a secret that is a certificate is a certificate", () => { const data = empty({ secrets: [ { id: 1, name: "API key", type: "api_key", expiryDate: "2026-10-30" }, { id: 2, name: "Wildcard", type: "ssl_certificate", expiryDate: "2026-11-02" }, { id: 3, name: "Never", type: "generic", expiryDate: null }, { id: 4, name: "Garbage", type: "generic", expiryDate: "2026-02-30" }, ], domains: [{ id: 1, name: "example.se", expiresAt: "2027-01-05" }], }); assert.deepEqual(titles(data), [ [11, "secret", "Secret “API key” expires"], [14, "certificate", "Certificate “Wildcard” expires"], [78, "domain", "Domain example.se expires"], ]); }); test("what has just passed is shown as passed, for thirty days; what is further off than asked for is not shown", () => { const data = empty({ secrets: [ { id: 1, name: "Yesterday", type: "generic", expiryDate: "2026-10-18" }, { id: 2, name: "Today", type: "generic", expiryDate: "2026-10-19" }, { id: 3, name: "Last month", type: "generic", expiryDate: "2026-09-19" }, { id: 4, name: "Long ago", type: "generic", expiryDate: "2026-09-18" }, { id: 5, name: "In a year", type: "generic", expiryDate: "2027-10-19" }, ] }); assert.deepEqual(titles(data, 90), [[-30, "secret", "Secret “Last month” expired"], [-1, "secret", "Secret “Yesterday” expired"], [0, "secret", "Secret “Today” expires"]]); assert.equal(titles(data, 400).length, 4, "a year ahead, when asked for"); }); test("certificates that endpoint checks have seen, hardware warranties and end of support — each linking to where they are kept", () => { const agenda = agendaFromData( empty({ endpoints: [ { id: 1, name: "Gitea", enabled: true, certExpiresAt: "2026-11-01T08:00:00.000Z", serverId: 5 }, { id: 2, name: "Paused", enabled: false, certExpiresAt: "2026-11-01T08:00:00.000Z", serverId: null }, { id: 3, name: "No cert", enabled: true, certExpiresAt: null, serverId: null }, ], assets: [{ id: 9, name: "Synology DS920+", warrantyUntil: "2026-12-01", endOfSupport: "2026-12-20", serverId: 2 }], }), NOW, "UTC", ); assert.deepEqual(agenda.items.map((i) => [i.kind, i.title, i.link, i.serverId]), [ ["certificate", "The certificate for Gitea expires", "/endpoints", 5], ["warranty", "Warranty on Synology DS920+ ends", "/inventory?asset=9", 2], ["support", "Support for Synology DS920+ ends", "/inventory?asset=9", 2], ]); }); test("Tailscale keys: only those the integration says are expiring, dated by days left", () => { assert.deepEqual(titles(empty({ tailscale: [{ integrationId: 1, integrationName: "Home", deviceLabel: "laptop", daysLeft: 6 }] })), [[6, "tailscale", "Tailscale key for laptop expires"]]); }); test("a restore test is due a set time after the last good one — only with a limit set, and never for one that failed", () => { const tests = [ { subjectKey: "guest:1:100", label: "elsa", testedAt: "2026-08-01", result: "ok" }, { subjectKey: "guest:1:101", label: "anna", testedAt: "2026-08-01", result: "failed" }, { subjectKey: "custom:photos", label: "Photos share", testedAt: "2026-07-03", result: "partial" }, ]; assert.deepEqual(titles(empty({ restoreTests: tests, restoreLimitDays: 0 })), []); assert.deepEqual(titles(empty({ restoreTests: tests, restoreLimitDays: 90 })), [[-18, "restore", "Restore test was due: Photos share"], [11, "restore", "Restore test due: elsa"]]); }); test("updates that are waiting are one line, from the longest wait", () => { const agenda = agendaFromData(empty({ updates: [{ name: "a", count: 5, security: 2, since: "2026-10-10T08:00:00.000Z" }, { name: "b", count: 1, security: 0, since: "2026-10-17T08:00:00.000Z" }, { name: "c", count: 3, security: null, since: null }] }), NOW, "UTC"); assert.equal(agenda.items.length, 1); assert.deepEqual([agenda.items[0].title, agenda.items[0].detail, agenda.items[0].daysLeft, agenda.items[0].link], ["Updates waiting on 3 servers (1 with security fixes)", "the longest wait is 9 days", -9, "/updates"]); }); test("maintenance that is set up is grouped by when it is, the names kept short; windows a schedule made are left to the schedule, which is read forward", () => { const agenda = agendaFromData( empty({ windows: [ { startedAt: "2026-10-24T01:00:00.000Z", endsAt: "2026-10-24T03:00:00.000Z", reason: "Firmware", source: null, targetName: "nas" }, { startedAt: "2026-10-24T01:00:00.000Z", endsAt: "2026-10-24T03:00:00.000Z", reason: "Firmware", source: null, targetName: "switch" }, { startedAt: "2026-10-21T02:00:00.000Z", endsAt: "2026-10-21T04:00:00.000Z", reason: "Patch night", source: "schedule:1:2026-10-21", targetName: "nas" }, ], schedules: [{ id: 1, name: "Patch night", reason: null, days: JSON.stringify([3]), startTime: "02:00", durationMinutes: 120, timezone: "UTC", targetNames: ["nas", "elsa"] }], }), NOW, "UTC", 30, ); const m = agenda.items.filter((i) => i.kind === "maintenance"); assert.deepEqual(m.map((i) => [i.title, i.at.slice(0, 16), i.allDay, i.endsAt?.slice(11, 16)]), [ ["Recurring maintenance: Patch night", "2026-10-21T02:00", false, "04:00"], ["Maintenance: nas, switch", "2026-10-24T01:00", false, "03:00"], ["Recurring maintenance: Patch night", "2026-10-28T02:00", false, "04:00"], ["Recurring maintenance: Patch night", "2026-11-04T02:00", false, "04:00"], ["Recurring maintenance: Patch night", "2026-11-11T02:00", false, "04:00"], ["Recurring maintenance: Patch night", "2026-11-18T02:00", false, "04:00"], ]); assert.equal(m.filter((i) => i.at.startsWith("2026-10-21")).length, 1, "the window the schedule made and the schedule itself are one entry, not two"); assert.equal(m[1].detail, "Firmware"); assert.equal(m[0].detail, "elsa, nas"); }); test("a day is the day on the clock set for notifications: a window at 23:30 UTC is already tomorrow in Stockholm", () => { const windows = [{ startedAt: "2026-10-19T23:30:00.000Z", endsAt: "2026-10-20T01:00:00.000Z", reason: null, source: null, targetName: "nas" }]; assert.equal(agendaFromData(empty({ windows }), NOW, "UTC").items[0].daysLeft, 0); assert.equal(agendaFromData(empty({ windows }), NOW, "Europe/Stockholm").items[0].daysLeft, 1); assert.equal(localDate(new Date("2026-10-19T23:30:00Z"), "Europe/Stockholm"), "2026-10-20"); assert.equal(addDays("2026-10-31", 1), "2026-11-01"); }); }); describe("the calendar feed", () => { const data = empty({ secrets: [{ id: 1, name: "API key, with; odd\\chars", type: "api_key", expiryDate: "2026-10-30" }], tailscale: [{ integrationId: 1, integrationName: "Home", deviceLabel: "bobs-laptop", daysLeft: 6 }], windows: [{ startedAt: "2026-10-24T01:00:00.000Z", endsAt: "2026-10-24T03:00:00.000Z", reason: "Firmware", source: null, targetName: "nas" }], secretsOld: undefined, updates: [{ name: "a", count: 1, security: 0, since: null }], } as unknown as Partial); const agenda = agendaFromData(data, NOW, "UTC"); const ics = buildIcs(agenda, { name: "Homelab; manager", detail: "names", baseUrl: "https://hm.lan/" }); test("it is a calendar with CRLF lines: all-day events for days, a start and an end for maintenance, nothing for waiting updates", () => { assert.ok(ics.startsWith("BEGIN:VCALENDAR\r\nVERSION:2.0\r\n") && ics.endsWith("END:VCALENDAR\r\n")); assert.equal(ics.includes("\n") && ics.split("\n").every((l, i, a) => i === a.length - 1 || l.endsWith("\r")), true); assert.equal((ics.match(/BEGIN:VEVENT/g) ?? []).length, 3, "the secret, the key and the window — not the updates"); assert.match(ics, /DTSTART;VALUE=DATE:20261030\r\nDTEND;VALUE=DATE:20261031/); assert.match(ics, /DTSTART:20261024T010000Z\r\nDTEND:20261024T030000Z/); assert.match(ics, /X-WR-CALNAME:Homelab\\; manager/); assert.match(ics, /TRANSP:TRANSPARENT/); }); test("text is escaped, and a line is never more than 75 bytes, without splitting a character", () => { assert.match(ics.replace(/\r\n /g, ""), /SUMMARY:Secret “API key\\, with\\; odd\\\\chars” expires/); const long = foldLine(`SUMMARY:${"å".repeat(100)}`); for (const l of long.split("\r\n")) assert.ok(Buffer.byteLength(l, "utf8") <= 75, `${Buffer.byteLength(l, "utf8")} bytes`); assert.equal(long.replace(/\r\n /g, ""), `SUMMARY:${"å".repeat(100)}`, "and it unfolds to what it was"); for (const l of ics.split("\r\n")) assert.ok(Buffer.byteLength(l, "utf8") <= 75); }); test("with names, an event carries the name and a link back; each has a steady id that does not give the name away", () => { const unfolded = ics.replace(/\r\n /g, ""); assert.match(unfolded, /DESCRIPTION:Firmware\\nhttps:\/\/hm\.lan\/maintenance/); const uids = [...ics.matchAll(/UID:(\S+)\r\n/g)].map((m) => m[1]); assert.equal(new Set(uids).size, 3); assert.ok(uids.every((u) => /^[0-9a-f]{24}@homelab-manager$/.test(u))); assert.deepEqual(uids, [...buildIcs(agenda, { name: "x", detail: "names" }).matchAll(/UID:(\S+)\r\n/g)].map((m) => m[1]), "the same on every fetch, or a subscribed calendar would duplicate everything"); }); test("with no names, an event says only what kind of thing it is — and nothing in it gives away a name", () => { const plain = buildIcs(agenda, { name: "Homelab", detail: "summary", baseUrl: "https://hm.lan" }); const unfolded = plain.replace(/\r\n /g, ""); assert.match(unfolded, /SUMMARY:A secret expires/); assert.match(unfolded, /SUMMARY:A Tailscale key expires/); assert.match(unfolded, /SUMMARY:Planned maintenance/); assert.equal(/API key|bobs-laptop|nas|Firmware|hm\.lan|DESCRIPTION/.test(unfolded), false); }); test("an event more than a week old is dropped, one from this week is kept", () => { const old = agendaFromData(empty({ secrets: [{ id: 1, name: "Old", type: "generic", expiryDate: "2026-10-10" }, { id: 2, name: "Recent", type: "generic", expiryDate: "2026-10-15" }] }), NOW, "UTC"); assert.equal((buildIcs(old, { name: "x", detail: "names" }).match(/BEGIN:VEVENT/g) ?? []).length, 1); }); }); describe("from what is stored, through the routes", () => { let app: Server; let base = ""; let who = "admin"; const day = (n: number) => new Date(Date.now() + n * 86_400_000).toISOString().slice(0, 10); before(async () => { await db.insert(users).values([ { oidcSub: "admin", name: "Ada", role: "admin" }, { oidcSub: "viewer", name: "Vic", role: "viewer" }, ]); const [s] = await db .insert(servers) .values({ name: "nas", apiTokenHash: "n", apiTokenPrefix: "n", pendingUpdates: JSON.stringify({ manager: "apt", count: 4, security: 1, rebootRequired: false, reportedAt: new Date().toISOString() }), updatesPendingSince: new Date(Date.now() - 3 * 86_400_000).toISOString() }) .returning({ id: servers.id }); await db.insert(secrets).values({ name: "Deploy key", type: "api_key", expiryDate: day(10) } as never); await db.insert(domains).values({ name: "example.se", expiresAt: day(40) }); await db.insert(assets).values({ name: "Switch", kind: "network", warrantyUntil: day(20), createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() } as never); await db.insert(endpointChecks).values({ name: "Gitea", kind: "http", target: "https://git.lab/", certExpiresAt: new Date(Date.now() + 5 * 86_400_000).toISOString(), serverId: s.id }); await db.insert(maintenanceWindows).values({ targetType: "server", targetId: s.id, reason: "Disk swap", startedAt: new Date(Date.now() + 2 * 86_400_000).toISOString(), endsAt: new Date(Date.now() + 2 * 86_400_000 + 3600_000).toISOString() }); await db.insert(maintenanceSchedules).values({ name: "Patch night", targets: JSON.stringify([{ type: "server", id: s.id }]), days: JSON.stringify([0, 1, 2, 3, 4, 5, 6]), startTime: "03:00", durationMinutes: 60, timezone: "UTC" }); await db.insert(restoreTests).values({ subjectKey: "custom:photos", label: "Photos share", testedAt: day(-80), result: "ok" }); await updateSettings({ healthChecks: { restoreTestDays: 90 } }); clearAgendaCacheForTests(); const a = express(); a.use(express.json()); a.use("/api/public/calendar", publicCalendarRouter); a.use((req, _res, next) => { (req as unknown as { session: unknown }).session = { user: { sub: who } }; next(); }); a.use("/api/agenda", agendaRouter); a.use("/api/share-links", shareLinksRouter); app = await new Promise((resolve) => { const x = a.listen(0, "127.0.0.1", () => resolve(x)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}`; }); after(() => { app.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); test("everything with a date, from every source, for anyone signed in; the days asked for narrow it", async () => { who = "viewer"; const res = await fetch(`${base}/api/agenda`); assert.equal(res.status, 200); const body = await res.json(); const kinds = new Set(body.items.map((i: { kind: string }) => i.kind)); for (const k of ["secret", "domain", "warranty", "certificate", "maintenance", "restore", "updates"]) assert.ok(kinds.has(k), k); assert.ok(body.items.some((i: { title: string }) => i.title === "Restore test due: Photos share"), "tested 80 days ago with a 90-day limit"); assert.ok(body.items.filter((i: { title: string }) => i.title.startsWith("Recurring maintenance")).length >= 60 / 1, "a schedule is read forward, not only the week that has windows"); const near = await (await fetch(`${base}/api/agenda?days=15`)).json(); assert.equal(near.items.some((i: { kind: string }) => i.kind === "domain"), false, "40 days out is beyond 15"); assert.equal(near.items.some((i: { kind: string }) => i.kind === "secret"), true); const bad = await (await fetch(`${base}/api/agenda?days=banana`)).json(); assert.equal(bad.items.length > 0, true, "an unreadable range is the default one"); const direct = await buildAgenda(); assert.equal(direct.items.length, body.items.length, "the route and the service agree"); }); test("a calendar link is made like any share link, by an administrator, and its address is the feed", async () => { who = "viewer"; assert.equal((await fetch(`${base}/api/share-links`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label: "Phone", kind: "calendar", detail: "names", expiresInDays: null }) })).status, 403); who = "admin"; const res = await fetch(`${base}/api/share-links`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label: "Phone", kind: "calendar", detail: "names", expiresInDays: null }) }); assert.equal(res.status, 201); const made = await res.json(); assert.match(made.path, /^\/api\/public\/calendar\/[A-Za-z0-9_-]{20,}\.ics$/); const feed = await fetch(`${base}${made.path}`); assert.equal(feed.status, 200); assert.match(feed.headers.get("content-type") ?? "", /^text\/calendar; charset=utf-8/); const text = (await feed.text()).replace(/\r\n /g, ""); assert.ok(text.startsWith("BEGIN:VCALENDAR")); assert.match(text, /SUMMARY:Secret “Deploy key” expires/); assert.match(text, /SUMMARY:Domain example\.se expires/); const bare = made.path.replace(/\.ics$/, ""); assert.equal((await fetch(`${base}${bare}`)).status, 200, "the extension is for calendar apps; the address works without it"); }); test("a link for no names gives the feed no names; one for something else, a wrong one and an ended one all say the same thing", async () => { const { token } = await createShareLink({ label: "Private", kind: "calendar", detail: "summary", expiresInDays: null, createdBy: "t" }); const text = (await (await fetch(`${base}/api/public/calendar/${token}.ics`)).text()).replace(/\r\n /g, ""); assert.match(text, /SUMMARY:A secret expires/); assert.equal(/Deploy key|example\.se|Gitea|nas/.test(text), false); const wall = await createShareLink({ label: "Wall", kind: "wall", detail: "summary", expiresInDays: null, createdBy: "t" }); const ended = await createShareLink({ label: "Old", kind: "calendar", detail: "names", expiresInDays: 1, createdBy: "t", now: new Date(Date.now() - 3 * 86_400_000) }); const answers = await Promise.all([`${wall.token}.ics`, "nonsense.ics", `${"a".repeat(30)}.ics`, `${ended.token}.ics`].map(async (p) => { const r = await fetch(`${base}/api/public/calendar/${p}`); return [r.status, await r.text()]; })); assert.deepEqual(new Set(answers.map((a) => JSON.stringify(a))).size, 1, "never made, ended, and a wall's: indistinguishable"); assert.equal(answers[0][0], 404); }); });