/** * Buttons on notifications: the signed links, what each does to an alert, the page and the addresses behind them, and what the channels send. * * 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 } from "node:http"; import type { AddressInfo } from "node:net"; const dir = mkdtempSync(join(tmpdir(), "hm-actions-")); 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"; process.env.APP_BASE_URL = "https://hm.example.lan"; const express = (await import("express")).default; const { db } = await import("../src/db/client.js"); const { servers, auditLog, maintenanceWindows, alertAcks, alertSnoozes } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const links = await import("../src/services/alertActionLinks.js"); const { performAction, tomorrowMorning } = await import("../src/services/alertActions.js"); const { updateSettings } = await import("../src/services/settingsStore.js"); const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js"); const { notifyHealthIssues } = await import("../src/services/notify.js"); const { alertActionsRouter } = await import("../src/routes/alertActions.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); after(() => { try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows may still hold the database file } }); const HOUR = 3600_000; describe("the signed links", () => { const NOW = new Date("2026-10-20T12:00:00Z"); test("a token carries the alerts it is for and when it ends, and nothing else; it comes back as it went in", () => { const token = links.signToken(["offline:server:3", "disk:server:3:/"], NOW); const check = links.verifyToken(token, new Date(NOW.getTime() + HOUR)); assert.ok(check.ok); if (check.ok) assert.deepEqual([check.keys, check.expiresAt.toISOString()], [["offline:server:3", "disk:server:3:/"], "2026-10-21T12:00:00.000Z"]); assert.deepEqual(JSON.parse(Buffer.from(token.split(".")[0], "base64url").toString()), { k: ["offline:server:3", "disk:server:3:/"], e: Date.parse("2026-10-21T12:00:00Z") / 1000 }); }); test("it lasts 24 hours, not a minute more; one that has been tampered with, cut short or made by someone else is refused", () => { const token = links.signToken(["offline:server:3"], NOW); assert.ok(links.verifyToken(token, new Date(NOW.getTime() + 24 * HOUR - 1000)).ok); assert.deepEqual(links.verifyToken(token, new Date(NOW.getTime() + 24 * HOUR + 1000)), { ok: false, reason: "expired" }); const [body, sig] = token.split("."); const forged = Buffer.from(JSON.stringify({ k: ["offline:server:9"], e: Date.parse("2030-01-01") / 1000 })).toString("base64url"); assert.deepEqual(links.verifyToken(`${forged}.${sig}`, NOW), { ok: false, reason: "invalid" }, "another alert, a later end, the old signature"); assert.deepEqual(links.verifyToken(`${body}.${sig.slice(0, -2)}AA`, NOW), { ok: false, reason: "invalid" }); for (const junk of ["", "x", "a.b.c", `${body}.`, `.${sig}`, "not base64!.not base64!", "x".repeat(5000)]) assert.deepEqual(links.verifyToken(junk, NOW), { ok: false, reason: "invalid" }, junk.slice(0, 20)); }); test("a token is for twenty alerts at most", () => { const check = links.verifyToken(links.signToken(Array.from({ length: 50 }, (_, i) => `offline:server:${i}`), NOW), NOW); assert.ok(check.ok && check.keys.length === links.MAX_KEYS); }); test("tomorrow at nine is by the clocks of the time zone, summer time and all", () => { assert.equal(tomorrowMorning(new Date("2026-10-20T12:00:00Z"), "UTC").toISOString(), "2026-10-21T09:00:00.000Z"); assert.equal(tomorrowMorning(new Date("2026-10-20T12:00:00Z"), "Europe/Stockholm").toISOString(), "2026-10-21T07:00:00.000Z", "still summer time (UTC+2)"); assert.equal(tomorrowMorning(new Date("2026-10-24T12:00:00Z"), "Europe/Stockholm").toISOString(), "2026-10-25T08:00:00.000Z", "the clocks go back that night: nine is UTC+1"); assert.equal(tomorrowMorning(new Date("2026-03-28T12:00:00Z"), "Europe/Stockholm").toISOString(), "2026-03-29T07:00:00.000Z", "and forward that night"); assert.equal(tomorrowMorning(new Date("2026-10-20T23:30:00Z"), "Europe/Stockholm").toISOString(), "2026-10-22T07:00:00.000Z", "half past one on the 21st there: tomorrow is the 22nd"); assert.equal(tomorrowMorning(new Date("2026-10-20T12:00:00Z"), "America/New_York").toISOString(), "2026-10-21T13:00:00.000Z"); assert.equal(tomorrowMorning(new Date("2026-10-20T12:00:00Z"), "Not/AZone").toISOString(), "2026-10-21T09:00:00.000Z", "an unknown zone is UTC"); }); }); describe("what a message carries", () => { test("off, it carries nothing; on, a message about one alert has its buttons, and one about several has a page", async () => { await updateSettings({ alertActions: { enabled: false } }); assert.equal(await links.actionsFor(["offline:server:3"]), null); await updateSettings({ alertActions: { enabled: true } }); assert.equal(await links.actionsFor([]), null); assert.equal(await links.actionsFor([undefined]), null); const one = (await links.actionsFor(["offline:server:3"]))!; assert.deepEqual(one.direct.map((d) => [d.id, d.label]), [["ack", "Acknowledge"], ["silence", "Silence 1 h"], ["snooze", "Snooze"]]); assert.match(one.direct[0].url, /^https:\/\/hm\.example\.lan\/api\/alert-actions\/[\w-]+\.[\w-]+\/ack$/); assert.ok(one.pageUrl.startsWith("https://hm.example.lan/api/alert-actions/") && one.direct.every((d) => d.path.startsWith("/api/alert-actions/"))); assert.deepEqual((await links.actionsFor(["endpoint:5"]))!.direct.map((d) => d.id), ["ack", "snooze"], "nothing to silence an endpoint check with"); const several = (await links.actionsFor(["offline:server:3", "disk:server:4:/", "offline:server:3"]))!; assert.deepEqual([several.count, several.direct.length], [2, 0], "the same alert twice is one"); }); test("ntfy gets buttons for one alert and a single link for several; the other channels get the link as text", async () => { const one = (await links.actionsFor(["offline:server:3"]))!; const header = links.ntfyActionsHeader(one); assert.equal(header.split("; ").length, 3, "ntfy allows three"); assert.match(header, /^http, Acknowledge, https:\/\/hm\.example\.lan\/api\/alert-actions\/[^,]+\/ack, method=POST, clear=true; http, Silence 1 h, /); assert.ok(/^[ -~]*$/.test(header), "a header is plain ASCII"); const several = (await links.actionsFor(["offline:server:3", "offline:server:4"]))!; assert.match(links.ntfyActionsHeader(several), /^view, Choose what to do, https:\/\/hm\.example\.lan\/api\/alert-actions\//); assert.match(links.footerText(one), /\n\nAcknowledge, silence or snooze: https:\/\/hm\.example\.lan\/api\/alert-actions\//); }); }); describe("doing it", () => { let serverId = 0; let key = ""; before(async () => { const [s] = await db.insert(servers).values({ name: "web", apiTokenHash: "h", apiTokenPrefix: "p", lastSeenAt: new Date(Date.now() - 3 * HOUR).toISOString(), ipAddresses: "[]" }).returning(); serverId = s.id; key = `offline:server:${s.id}`; await updateSettings({ alertActions: { enabled: true }, notifications: { timezone: "Europe/Stockholm" } }); invalidateAlertsCache(); }); test("acknowledging marks the alert as acknowledged by the link, is written down with where it came from, and is not done twice", async () => { const res = await performAction("ack", key, { ip: "10.0.0.7" }); assert.deepEqual([res.ok, res.status, res.message], [true, 200, "Acknowledged."]); const [ack] = await db.select().from(alertAcks); assert.deepEqual([ack.alertKey, ack.ackedBy, ack.note, ack.until], [`offline:${key}`, "a notification link", "Acknowledged from a notification", null]); const [entry] = await db.select().from(auditLog).where(eq(auditLog.action, "ack")); const detail = JSON.parse(entry.detail!); assert.deepEqual([entry.category, entry.targetType, entry.targetId, detail.via, detail.ip], ["alert", "server", String(serverId), "a notification link", "10.0.0.7"]); const again = await performAction("ack", key, {}); assert.deepEqual([again.ok, again.message], [true, "Already acknowledged by a notification link."]); assert.equal((await db.select().from(alertAcks)).length, 1); }); test("silencing starts an hour of maintenance on what the alert is about, and the alert is then held back", async () => { const res = await performAction("silence", key, { ip: "10.0.0.7" }); assert.deepEqual([res.ok, res.message], [true, "Silenced for an hour: web."]); const [w] = await db.select().from(maintenanceWindows).where(eq(maintenanceWindows.targetId, serverId)); assert.deepEqual([w.targetType, w.reason, w.createdBy], ["server", "Silenced from a notification", "a notification link"]); assert.ok(Math.abs(Date.parse(w.endsAt) - Date.parse(w.startedAt) - HOUR) < 2000); invalidateAlertsCache(); assert.equal((await getAlerts(true)).alerts.find((a) => a.id === `offline:${key}`)!.silenced, true); const [entry] = await db.select().from(auditLog).where(eq(auditLog.category, "maintenance")); assert.equal(JSON.parse(entry.detail!).via, "a notification link"); await db.delete(maintenanceWindows).where(eq(maintenanceWindows.targetId, serverId)); invalidateAlertsCache(); }); test("snoozing hides the alert until tomorrow at nine in the notification time zone", async () => { const now = new Date(); const res = await performAction("snooze", key, {}, now); assert.equal(res.ok, true); const [s] = await db.select().from(alertSnoozes); assert.equal(s.until, tomorrowMorning(now, "Europe/Stockholm").toISOString()); assert.equal(s.snoozedBy, "a notification link"); invalidateAlertsCache(); const alert = (await getAlerts(true)).alerts.find((a) => a.id === `offline:${key}`)!; assert.deepEqual([alert.silenced, alert.snoozed?.until], [true, s.until]); await db.delete(alertSnoozes); }); test("an alert that has cleared says so; switched off, nothing works; an unknown action is not one", async () => { assert.deepEqual(await performAction("ack", "offline:server:99999", {}), { ok: false, status: 404, message: "That alert isn't there any more — it has cleared." }); await updateSettings({ alertActions: { enabled: false } }); assert.deepEqual(await performAction("ack", key, {}), { ok: false, status: 404, message: "Buttons in notifications are switched off." }); await updateSettings({ alertActions: { enabled: true } }); }); describe("the addresses", () => { let app: Server; let base = ""; before(async () => { const a = express(); a.use("/api/alert-actions", alertActionsRouter); app = await new Promise((resolve) => { const s = a.listen(0, "127.0.0.1", () => resolve(s)); }); base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/alert-actions`; }); after(() => app.close()); const post = (path: string, body?: string, headers: Record = {}) => fetch(`${base}${path}`, { method: "POST", headers: { connection: "close", ...headers }, body }); test("opening the page shows the alert and its buttons and changes nothing; the answer is not kept or passed on", async () => { await db.delete(alertAcks); invalidateAlertsCache(); const token = links.signToken([key]); const res = await fetch(`${base}/${token}`, { headers: { connection: "close" } }); assert.equal(res.status, 200); assert.deepEqual([res.headers.get("cache-control"), res.headers.get("referrer-policy"), res.headers.get("x-robots-tag")], ["no-store", "no-referrer", "noindex, nofollow"]); const html = await res.text(); assert.match(html, /web hasn('|')t reported for/); assert.match(html, /
/); assert.match(html, /Silence for an hour/); assert.match(html, /Snooze until \w{3} 09:00/, "in the notification zone"); assert.match(html, /Opening this page changed nothing/); assert.equal((await db.select().from(alertAcks)).length, 0, "opening it did nothing"); assert.ok(!html.includes(" { const token = links.signToken([key, "offline:server:99999"]); const form = await post(`/${token}/ack`, `key=${encodeURIComponent(key)}`, { "content-type": "application/x-www-form-urlencoded", accept: "text/html" }); assert.equal(form.status, 200); assert.match(await form.text(), /Done<\/h1>[\s\S]*Acknowledged\./); assert.equal((await db.select().from(alertAcks)).length, 1); const json = await post(`/${token}/snooze?key=${encodeURIComponent(key)}`); assert.deepEqual([json.status, ((await json.json()) as any).ok], [200, true]); await db.delete(alertSnoozes); invalidateAlertsCache(); const gone = await post(`/${token}/ack?key=${encodeURIComponent("offline:server:99999")}`); assert.equal(gone.status, 404, "a key in the token, but that alert has cleared"); const other = await post(`/${token}/ack?key=${encodeURIComponent("offline:server:777")}`); assert.equal(other.status, 400, "a key that is not in the token"); const unnamed = await post(`/${token}/ack`); assert.equal(unnamed.status, 400, "two alerts and no way to know which"); }); test("a link for one alert needs no key; an unknown action, a forged or ended link and a switched-off setting are refused", async () => { const single = links.signToken([key]); assert.equal((await post(`/${single}/ack`)).status, 200); assert.equal((await post(`/${single}/delete`)).status, 404); assert.equal((await post(`/${single.slice(0, -3)}abc/ack`)).status, 404); const old = links.signToken([key], new Date(Date.now() - 25 * HOUR)); const ended = await post(`/${old}/ack`); assert.equal(ended.status, 410); assert.match(((await ended.json()) as any).message, /run out/); assert.equal((await fetch(`${base}/${old}`, { headers: { connection: "close" } })).status, 410); assert.equal((await fetch(`${base}/not-a-token`, { headers: { connection: "close" } })).status, 404); await updateSettings({ alertActions: { enabled: false } }); assert.equal((await post(`/${single}/ack`)).status, 404); assert.equal((await fetch(`${base}/${single}`, { headers: { connection: "close" } })).status, 404); await updateSettings({ alertActions: { enabled: true } }); }); test("a message carrying text from an alert cannot put markup in the page", async () => { const [s] = await db.insert(servers).values({ name: "", apiTokenHash: "h2", apiTokenPrefix: "q", lastSeenAt: new Date(Date.now() - 3 * HOUR).toISOString(), ipAddresses: "[]" }).returning(); invalidateAlertsCache(); const html = await (await fetch(`${base}/${links.signToken([`offline:server:${s.id}`])}`, { headers: { connection: "close" } })).text(); assert.ok(!html.includes(" { let ntfy: Server; let gotify: Server; const ntfyGot: { headers: IncomingMessage["headers"]; body: string }[] = []; const gotifyGot: any[] = []; before(async () => { const listen = (handler: (req: IncomingMessage, body: string) => void) => new Promise((resolve) => { const s = createServer((req, res) => { let b = ""; req.on("data", (c) => (b += c)); req.on("end", () => { handler(req, b); res.end("{}"); }); }).listen(0, "127.0.0.1", () => resolve(s)); }); ntfy = await listen((req, body) => ntfyGot.push({ headers: req.headers, body })); gotify = await listen((_req, body) => gotifyGot.push(JSON.parse(body))); await updateSettings({ ntfy: { enabled: true, url: `http://127.0.0.1:${(ntfy.address() as AddressInfo).port}`, topic: "homelab", token: "", priority: 3 }, gotify: { enabled: true, url: `http://127.0.0.1:${(gotify.address() as AddressInfo).port}`, token: "tok", priority: 5 }, alertActions: { enabled: true }, }); }); after(() => { ntfy.close(); gotify.close(); }); const issue = (n: number) => ({ key: `offline:server:${n}`, message: `server ${n} hasn't reported for 2 h`, severity: "critical" }); test("one alert: ntfy has three buttons and a tap that opens the page; Gotify has a tap and the link in its text", async () => { await notifyHealthIssues([issue(11)]); const sent = ntfyGot.at(-1)!; const actions = String(sent.headers.actions); assert.equal(actions.split("; ").length, 3); assert.match(actions, /^http, Acknowledge, https:\/\/hm\.example\.lan\/api\/alert-actions\/[^,]+\/ack, method=POST, clear=true/); assert.match(String(sent.headers.click), /^https:\/\/hm\.example\.lan\/api\/alert-actions\//); assert.match(sent.body, /server 11 hasn't reported/); const g = gotifyGot.at(-1); assert.match(g.message, /Acknowledge, silence or snooze: https:\/\/hm\.example\.lan\/api\/alert-actions\//); assert.equal(g.extras["client::notification"].click.url, String(sent.headers.click)); }); test("several alerts: ntfy has one button to the page, and the page lists them", async () => { await notifyHealthIssues([issue(12), issue(13)]); const sent = ntfyGot.at(-1)!; assert.match(String(sent.headers.actions), /^view, Choose what to do, https:\/\/hm\.example\.lan\/api\/alert-actions\/[^,]+$/); const page = String(sent.headers.click).replace("https://hm.example.lan", ""); const check = links.verifyToken(page.split("/").pop()!); assert.ok(check.ok && check.keys.join() === "offline:server:12,offline:server:13"); }); test("switched off, there are no buttons, no links and no extras", async () => { await updateSettings({ alertActions: { enabled: false } }); await notifyHealthIssues([issue(14)]); const sent = ntfyGot.at(-1)!; assert.deepEqual([sent.headers.actions, sent.headers.click], [undefined, undefined]); const g = gotifyGot.at(-1); assert.ok(!g.message.includes("alert-actions") && g.extras === undefined); }); });