/** * Telegram and Pushover as notification channels: what is sent to each (a bot's sendMessage, Pushover's messages.json), what is done when one refuses, that the credentials are kept encrypted and * never put in an error or the audit log, how they take part in routing, and the settings routes (save, and the test button). * * Run with: npm test --workspace server */ import { test, describe, before, after, beforeEach } from "node:test"; import assert from "node:assert/strict"; import { createServer, type IncomingMessage, type Server } from "node:http"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { AddressInfo } from "node:net"; const dir = mkdtempSync(join(tmpdir(), "hm-tgpo-")); 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, auditLog, settings } = await import("../src/db/schema.js"); const { runMigrations } = await import("../src/db/migrate.js"); const notify = await import("../src/services/notify.js"); const { updateSettings, getSettings } = await import("../src/services/settingsStore.js"); const { CHANNEL_IDS } = await import("../src/services/notifyRouting.js"); const { describeSettingsChanges } = await import("../src/services/settingsDiff.js"); const { settingsRouter } = await import("../src/routes/settings.js"); const { eq } = await import("drizzle-orm"); await runMigrations(); type Call = { path: string; body: Record }; const TG_TOKEN = "123456:SECRET-telegram-token"; const PO_APP = "appSECRETpushovertoken0123456789"; const PO_USER = "userSECRETpushoverkey0123456789"; const actions = (url = "https://hm.example.lan/api/alert-actions/abc") => ({ pagePath: "/api/alert-actions/abc", pageUrl: url, direct: [], count: 1 }); let fake: Server; let base = ""; const calls: Call[] = []; /** What the pretend services answer next: a status and a body (a function sees the request). */ let telegramReply: (c: Call) => { status: number; json: unknown } = () => ({ status: 200, json: { ok: true, result: {} } }); let pushoverReply: (c: Call) => { status: number; json: unknown } = () => ({ status: 200, json: { status: 1, request: "r" } }); const readBody = (req: IncomingMessage) => new Promise((resolve) => { let t = ""; req.on("data", (c) => (t += c)); req.on("end", () => resolve(t)); }); before(async () => { fake = createServer(async (req, res) => { const call: Call = { path: req.url ?? "", body: JSON.parse((await readBody(req)) || "{}") }; calls.push(call); const r = call.path.startsWith("/bot") ? telegramReply(call) : pushoverReply(call); res.writeHead(r.status, { "content-type": "application/json" }); res.end(JSON.stringify(r.json)); }); await new Promise((resolve) => fake.listen(0, "127.0.0.1", resolve)); base = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`; notify.CHANNEL_ENDPOINTS.telegram = base; notify.CHANNEL_ENDPOINTS.pushover = base; }); beforeEach(() => { calls.length = 0; telegramReply = () => ({ status: 200, json: { ok: true, result: {} } }); pushoverReply = () => ({ status: 200, json: { status: 1, request: "r" } }); }); after(() => { fake.close(); try { rmSync(dir, { recursive: true, force: true }); } catch { // Windows keeps the database file locked until the process exits. } }); describe("Telegram", () => { const cfg = { token: TG_TOKEN, chatId: "-100123" }; test("a message goes to the bot's sendMessage with the chat, the text and no link preview — and silent only when asked", async () => { await notify.telegramSend(cfg, "Title\n\nBody"); assert.equal(calls[0].path, `/bot${TG_TOKEN}/sendMessage`); assert.deepEqual(calls[0].body, { chat_id: "-100123", text: "Title\n\nBody", disable_web_page_preview: true }); await notify.telegramSend({ ...cfg, silent: true }, "x"); assert.equal(calls[1].body.disable_notification, true); }); test("for an alert with buttons it carries one button to the page where it can be dealt with", async () => { await notify.telegramSend(cfg, "x", actions()); assert.deepEqual(calls[0].body.reply_markup, { inline_keyboard: [[{ text: "Acknowledge, silence or snooze", url: "https://hm.example.lan/api/alert-actions/abc" }]] }); }); test("when Telegram refuses the button's address, it is sent again as plain text with the link in it", async () => { telegramReply = (c) => (c.body.reply_markup ? { status: 400, json: { ok: false, error_code: 400, description: "Bad Request: wrong HTTP URL" } } : { status: 200, json: { ok: true } }); await notify.telegramSend(cfg, "Body", actions("http://localhost:3000/api/alert-actions/abc")); assert.equal(calls.length, 2); assert.equal(calls[1].body.reply_markup, undefined); assert.match(String(calls[1].body.text), /^Body\n\nAcknowledge, silence or snooze: http:\/\/localhost:3000\/api\/alert-actions\/abc$/); }); test("a refusal says what Telegram said, and never the bot's token", async () => { telegramReply = () => ({ status: 401, json: { ok: false, error_code: 401, description: "Unauthorized" } }); await assert.rejects(() => notify.telegramSend(cfg, "x"), (err: Error) => err.message === "Telegram: Unauthorized" && !err.message.includes("SECRET")); telegramReply = () => ({ status: 400, json: { ok: false, error_code: 400, description: "Bad Request: chat not found" } }); await assert.rejects(() => notify.telegramSend(cfg, "x"), /Telegram: Bad Request: chat not found/); telegramReply = () => ({ status: 502, json: {} }); await assert.rejects(() => notify.telegramSend(cfg, "x"), /Telegram: HTTP 502/); }); test("a service that cannot be reached throws something that does not contain the token either", async () => { const saved = notify.CHANNEL_ENDPOINTS.telegram; notify.CHANNEL_ENDPOINTS.telegram = "http://127.0.0.1:1"; try { await assert.rejects(() => notify.telegramSend(cfg, "x"), (err: Error) => !String(err.message).includes("SECRET") && !String((err as { cause?: { message?: string } }).cause?.message ?? "").includes("SECRET")); } finally { notify.CHANNEL_ENDPOINTS.telegram = saved; } }); test("a long message is cut to what Telegram allows", async () => { await notify.telegramSend(cfg, "a".repeat(9000)); const text = String(calls[0].body.text); assert.equal(text.length, notify.TELEGRAM_MAX); assert.ok(text.endsWith("…")); }); }); describe("Pushover", () => { const cfg = { appToken: PO_APP, userKey: PO_USER }; test("a message has the token, the user, a title and the text, at normal priority, and goes to everything unless a device is named", async () => { await notify.pushoverSend(cfg, "Title", "Body"); assert.equal(calls[0].path, "/1/messages.json"); assert.deepEqual(calls[0].body, { token: PO_APP, user: PO_USER, title: "Title", message: "Body", priority: 0 }); await notify.pushoverSend({ ...cfg, device: " phone " }, "T", "B"); assert.equal(calls[1].body.device, "phone"); }); test("priority is kept between -2 and 2, and an emergency says how often to repeat and for how long", async () => { await notify.pushoverSend({ ...cfg, priority: 9 }, "T", "B"); await notify.pushoverSend({ ...cfg, priority: -9 }, "T", "B"); await notify.pushoverSend({ ...cfg, priority: 1 }, "T", "B"); assert.deepEqual(calls.map((c) => [c.body.priority, c.body.retry ?? null, c.body.expire ?? null]), [[2, 60, 3600], [-2, null, null], [1, null, null]]); }); test("for an alert with buttons the link to the page goes with it; one too long for Pushover goes in the text instead", async () => { await notify.pushoverSend(cfg, "T", "B", actions()); assert.deepEqual([calls[0].body.url, calls[0].body.url_title], ["https://hm.example.lan/api/alert-actions/abc", "Acknowledge, silence or snooze"]); const long = `https://hm.example.lan/api/alert-actions/${"x".repeat(600)}`; await notify.pushoverSend(cfg, "T", "B", actions(long)); assert.equal(calls[1].body.url, undefined); assert.match(String(calls[1].body.message), /^B\n\nAcknowledge, silence or snooze: https:\/\/hm\.example\.lan\//); }); test("title and message are cut to what Pushover allows", async () => { await notify.pushoverSend(cfg, "t".repeat(400), "m".repeat(3000)); assert.equal(String(calls[0].body.title).length, notify.PUSHOVER_TITLE_MAX); assert.equal(String(calls[0].body.message).length, notify.PUSHOVER_MESSAGE_MAX); }); test("a refusal says what Pushover said (all of it), and a body that is not a success is a failure whatever the status", async () => { pushoverReply = () => ({ status: 400, json: { status: 0, errors: ["application token is invalid", "user identifier is invalid"] } }); await assert.rejects(() => notify.pushoverSend(cfg, "T", "B"), (err: Error) => err.message === "Pushover: application token is invalid, user identifier is invalid" && !err.message.includes("SECRET")); pushoverReply = () => ({ status: 200, json: { status: 0 } }); await assert.rejects(() => notify.pushoverSend(cfg, "T", "B"), /Pushover: HTTP 200/); }); }); describe("as channels of the app", () => { before(async () => { await updateSettings({ telegram: { enabled: true, token: TG_TOKEN, chatId: "42" }, pushover: { enabled: true, appToken: PO_APP, userKey: PO_USER, priority: 1 } }); }); test("a notification goes to both, with the title and the text", async () => { await notify.notifyNow("Disk full", "web-1 is at 97%"); const tg = calls.find((c) => c.path.startsWith("/bot"))!; const po = calls.find((c) => c.path === "/1/messages.json")!; assert.equal(tg.body.text, "Disk full\n\nweb-1 is at 97%"); assert.deepEqual([po.body.title, po.body.message, po.body.priority], ["Disk full", "web-1 is at 97%", 1]); }); test("a routing rule that names only one of them sends to that one", async () => { await notify.notifyAudience("Only here", "text", { channels: ["telegram"], pushIds: null }, { quietHours: false }); assert.deepEqual(calls.map((c) => (c.path.startsWith("/bot") ? "telegram" : "pushover")), ["telegram"]); calls.length = 0; await notify.notifyAudience("Only there", "text", { channels: ["pushover"], pushIds: null }, { quietHours: false }); assert.deepEqual(calls.map((c) => (c.path.startsWith("/bot") ? "telegram" : "pushover")), ["pushover"]); assert.ok((CHANNEL_IDS as readonly string[]).includes("telegram") && (CHANNEL_IDS as readonly string[]).includes("pushover")); }); test("one that is switched off, or not filled in, is not used — and both are counted when they can send", async () => { assert.equal(await notify.enabledChannelCount(), 2); await updateSettings({ telegram: { enabled: false } }); await notify.notifyNow("t", "m"); assert.deepEqual(calls.map((c) => c.path), ["/1/messages.json"]); await updateSettings({ telegram: { enabled: true, chatId: "" }, pushover: { enabled: true, userKey: "" } }); calls.length = 0; await notify.notifyNow("t", "m"); assert.deepEqual(calls, []); assert.equal(await notify.enabledChannelCount(), 0); await updateSettings({ telegram: { enabled: true, chatId: "42" }, pushover: { enabled: true, userKey: PO_USER } }); }); test("one that refuses is logged without its credentials and does not stop the other, or throw", async () => { telegramReply = () => ({ status: 400, json: { ok: false, description: "Bad Request: chat not found" } }); const logged: string[] = []; const original = console.error; console.error = (...a: unknown[]) => void logged.push(a.map(String).join(" ")); try { await notify.notifyNow("t", "m"); } finally { console.error = original; } assert.ok(calls.some((c) => c.path === "/1/messages.json"), "Pushover was still told"); assert.ok(logged.some((l) => l.includes("Telegram: Bad Request: chat not found"))); assert.ok(!logged.join("\n").includes("SECRET")); }); }); describe("keeping the credentials", () => { test("the token and the keys are stored encrypted, and read back as they were", async () => { const tg = (await db.select().from(settings).where(eq(settings.key, "telegram")))[0]; const po = (await db.select().from(settings).where(eq(settings.key, "pushover")))[0]; assert.ok(!tg.value.includes("SECRET"), "the Telegram token is not in the database in the clear"); assert.ok(!po.value.includes("SECRET"), "the Pushover keys are not either"); assert.match(JSON.parse(tg.value).token, /^enc:v1:/); assert.match(JSON.parse(po.value).appToken, /^enc:v1:/); assert.match(JSON.parse(po.value).userKey, /^enc:v1:/); const s = await getSettings(); assert.deepEqual([s.telegram.token, s.pushover.appToken, s.pushover.userKey], [TG_TOKEN, PO_APP, PO_USER]); }); test("a change to them is in the audit trail as a name, never a value", () => { const d = describeSettingsChanges({ telegram: { token: "old", chatId: "1" }, pushover: { appToken: "a", userKey: "b", priority: 0 } }, { telegram: { token: "NEWSECRET", chatId: "2" }, pushover: { appToken: "NEWAPP", userKey: "NEWUSER", priority: 1 } }); assert.equal(JSON.stringify(d).includes("NEW"), false); assert.deepEqual(Object.keys(d.telegram).sort(), ["chatId", "token"]); assert.deepEqual(Object.keys(d.pushover).sort(), ["appToken", "priority", "userKey"]); }); }); describe("the settings routes", () => { let app: Server; let url = ""; let who = "admin"; const call = async (method: string, path: string, body?: unknown) => { const res = await fetch(`${url}${path}`, { method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }); return { status: res.status, body: (await res.json().catch(() => null)) as Record | null }; }; before(async () => { await db.insert(users).values([ { oidcSub: "admin", name: "Ada", role: "admin" }, { oidcSub: "operator", name: "Olle", role: "operator" }, ]); 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/settings", settingsRouter); app = await new Promise((resolve) => { const s = a.listen(0, "127.0.0.1", () => resolve(s)); }); url = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/settings`; }); after(() => app.close()); test("an administrator saves them, and the audit entry names what changed without the values", async () => { const res = await call("PUT", "", { telegram: { enabled: true, token: "Brand:NEWSECRETTOKEN", chatId: " @alerts " }, pushover: { enabled: true, appToken: "NEWAPPTOKEN", userKey: "NEWUSERKEY", device: "phone", priority: 2 } }); assert.equal(res.status, 200); assert.deepEqual([res.body!.settings.telegram.chatId, res.body!.settings.pushover.priority, res.body!.settings.pushover.device], ["@alerts", 2, "phone"], "trimmed, and kept"); const entry = (await db.select().from(auditLog).where(eq(auditLog.category, "settings"))).pop()!; assert.ok(!String(entry.detail).includes("NEWSECRET") && !String(entry.detail).includes("NEWAPPTOKEN") && !String(entry.detail).includes("NEWUSERKEY")); assert.match(String(entry.detail), /"telegram"/); await updateSettings({ telegram: { token: TG_TOKEN, chatId: "42" }, pushover: { appToken: PO_APP, userKey: PO_USER, priority: 0 } }); }); test("a priority outside -2 to 2 is refused", async () => { assert.equal((await call("PUT", "", { pushover: { priority: 5 } })).status, 400); assert.equal((await call("PUT", "", { pushover: { priority: 0.5 } })).status, 400); }); test("a routing rule may name them, and an unknown channel is still refused", async () => { const ok = await call("PUT", "", { routing: { rules: [{ id: "r1", name: "phones", enabled: true, categories: [], minSeverity: null, tags: [], channels: ["telegram", "pushover"] }] } }); assert.equal(ok.status, 200); const bad = await call("PUT", "", { routing: { rules: [{ id: "r2", name: "x", enabled: true, categories: [], minSeverity: null, tags: [], channels: ["carrier-pigeon"] }] } }); assert.equal(bad.status, 400); await call("PUT", "", { routing: { rules: [] } }); }); test("the test buttons send a real message with what is typed (saved or not) and say what the service said when it refuses", async () => { const t = await call("POST", "/test-telegram", { token: "typed:TOKEN", chatId: "7", enabled: true }); assert.equal(t.status, 200); assert.equal(calls[0].path, "/bottyped:TOKEN/sendMessage"); assert.deepEqual([calls[0].body.chat_id, String(calls[0].body.text).startsWith("Homelab Manager — Test")], ["7", true]); telegramReply = () => ({ status: 401, json: { ok: false, description: "Unauthorized" } }); const bad = await call("POST", "/test-telegram", { token: "typed:TOKEN", chatId: "7" }); assert.deepEqual([bad.status, bad.body!.error], [502, "Telegram: Unauthorized"]); const p = await call("POST", "/test-pushover", { appToken: "A", userKey: "U", priority: 1 }); assert.equal(p.status, 200); assert.deepEqual([calls[calls.length - 1].body.token, calls[calls.length - 1].body.user, calls[calls.length - 1].body.title], ["A", "U", "Homelab Manager — Test"]); pushoverReply = () => ({ status: 400, json: { status: 0, errors: ["user identifier is invalid"] } }); const badP = await call("POST", "/test-pushover", { appToken: "A", userKey: "U" }); assert.deepEqual([badP.status, badP.body!.error], [502, "Pushover: user identifier is invalid"]); }); test("the test buttons need what they send with, and are for administrators", async () => { assert.equal((await call("POST", "/test-telegram", { token: "t" })).status, 400); assert.equal((await call("POST", "/test-pushover", { appToken: "a" })).status, 400); assert.equal((await call("POST", "/test-pushover", { appToken: "a", userKey: "u", priority: 7 })).status, 400); who = "operator"; assert.equal((await call("POST", "/test-telegram", { token: "t", chatId: "1" })).status, 403); assert.equal((await call("POST", "/test-pushover", { appToken: "a", userKey: "u" })).status, 403); who = "admin"; }); });