Add Telegram and Pushover as notification channels

Both send to one fixed address each (api.telegram.org, api.pushover.net), take part in routing rules and the channel count, have a Send test that shows the service's own refusal, and keep their tokens and keys encrypted and out of errors and the audit log. A Telegram message carries one button, and a Pushover message one link, to the page where an alert can be acknowledged, silenced or snoozed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-05 00:30:29 +01:00
1 parent 9f366c37de
commit 31f4debb9a
22 files changed
+670 -37

No files matched your search

+1 -1
View File
@@ -102,7 +102,7 @@ export function warnIfAuthNotConfigured() {
console.warn(
"CREDENTIALS_ENCRYPTION_KEY is not set to a 64-character hex string. " +
"Saving integration credentials (Proxmox/Synology/etc API tokens) will fail until it is configured, and the " +
"notification channels' credentials (Gotify/ntfy tokens, SMTP password, webhook secret) are stored unencrypted.",
"notification channels' credentials (Gotify/ntfy/Telegram tokens, Pushover keys, SMTP password, webhook secret) are stored unencrypted.",
);
}
}
+2
View File
@@ -63,6 +63,8 @@ privacyRouter.get("/", asyncHandler(async (req, res) => {
channels: {
gotify: channel(settings.gotify.enabled, hostOf(settings.gotify.url)),
ntfy: channel(settings.ntfy.enabled, hostOf(settings.ntfy.url)),
telegram: channel(settings.telegram.enabled, "api.telegram.org"),
pushover: channel(settings.pushover.enabled, "api.pushover.net"),
smtp: channel(settings.smtp.enabled, settings.smtp.host || null),
webhook: channel(settings.webhook.enabled, hostOf(settings.webhook.url)),
webPush: channel(settings.webPush.enabled, "the push services of your browsers (Google, Mozilla, Apple …)"),
+27 -1
View File
@@ -18,7 +18,7 @@ import { buildDigest, sendDigest } from "../services/weeklyDigest.js";
import { enabledChannelCount } from "../services/notify.js";
import { CATEGORIES, CHANNEL_IDS } from "../services/notifyRouting.js";
import { InvalidTagError, normalizeTags } from "../services/serverTags.js";
import { testGotify, testNtfy, testSmtp, testWebhook, flushQuietHoursQueue } from "../services/notify.js";
import { testGotify, testNtfy, testPushover, testTelegram, testSmtp, testWebhook, flushQuietHoursQueue } from "../services/notify.js";
import { listQueuedNotifications } from "../services/notificationQueue.js";
import { buildExportPayload, encryptExport, decryptExport, applyImportPayload, type EncryptedExportFile } from "../services/configBackup.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -97,6 +97,8 @@ const updateSchema = z.object({
escalation: escalationSchema.optional(),
gotify: z.object({ enabled: z.boolean(), url: z.string(), token: z.string(), priority: z.number() }).partial().optional(),
ntfy: z.object({ enabled: z.boolean(), url: z.string(), topic: z.string(), token: z.string(), priority: z.number() }).partial().optional(),
telegram: z.object({ enabled: z.boolean(), token: z.string().trim(), chatId: z.string().trim().max(100), silent: z.boolean() }).partial().optional(),
pushover: z.object({ enabled: z.boolean(), appToken: z.string().trim(), userKey: z.string().trim(), device: z.string().trim().max(100), priority: z.number().int().min(-2).max(2) }).partial().optional(),
smtp: z
.object({
enabled: z.boolean(),
@@ -245,6 +247,30 @@ settingsRouter.post("/test-ntfy", requireRole("admin"), asyncHandler(async (req,
}
}));
settingsRouter.post("/test-telegram", requireRole("admin"), asyncHandler(async (req, res) => {
const schema = z.object({ token: z.string().trim().min(1), chatId: z.string().trim().min(1), silent: z.boolean().optional() });
const parsed = schema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
try {
await testTelegram(parsed.data);
res.json({ ok: true });
} catch (err) {
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
}
}));
settingsRouter.post("/test-pushover", requireRole("admin"), asyncHandler(async (req, res) => {
const schema = z.object({ appToken: z.string().trim().min(1), userKey: z.string().trim().min(1), device: z.string().trim().optional(), priority: z.number().int().min(-2).max(2).optional() });
const parsed = schema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
try {
await testPushover(parsed.data);
res.json({ ok: true });
} catch (err) {
res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
}
}));
settingsRouter.post("/test-smtp", requireRole("admin"), asyncHandler(async (req, res) => {
const schema = z.object({
host: z.string().min(1),
+92 -1
View File
@@ -63,6 +63,85 @@ async function sendNtfy(title: string, message: string, actions?: NotifyActions
}
}
// ─── Telegram and Pushover ──────────────────────────────────────────────────
//
// Both are hosted services with one fixed address each (so nothing a person types decides where a request goes, as it does for a webhook). The addresses are kept here, in one object, so a test can
// point them at a pretend server. Neither says why it refused in its HTTP status alone: Telegram answers { ok: false, description }, Pushover { status: 0, errors: [...] }, and that is what is shown.
export const CHANNEL_ENDPOINTS = { telegram: "https://api.telegram.org", pushover: "https://api.pushover.net" };
const clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`);
/** Telegram allows 4096 characters in a message. */
export const TELEGRAM_MAX = 4000;
/** Pushover allows 1024 in a message, 250 in a title, 512 in a link. */
export const PUSHOVER_MESSAGE_MAX = 1024;
export const PUSHOVER_TITLE_MAX = 250;
export const PUSHOVER_URL_MAX = 512;
const BUTTON_LABEL = "Acknowledge, silence or snooze";
/** Sends one message through a Telegram bot; throws what Telegram says when it refuses. The bot's token is in the address, so it is never put in an error. */
export async function telegramSend(cfg: { token: string; chatId: string; silent?: boolean }, text: string, actions?: NotifyActions | null): Promise<void> {
const post = async (body: Record<string, unknown>) => {
const res = await fetch(`${CHANNEL_ENDPOINTS.telegram}/bot${cfg.token}/sendMessage`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const json = (await res.json().catch(() => null)) as { ok?: boolean; description?: string } | null;
return { ok: res.ok && json?.ok !== false, status: res.status, description: json?.description ?? null };
};
const base = { chat_id: cfg.chatId, disable_web_page_preview: true, ...(cfg.silent ? { disable_notification: true } : {}) };
// A button that opens the page where the alert can be dealt with — plain text for what is said, so nothing in it needs escaping.
let result = await post({ ...base, text: clip(text, TELEGRAM_MAX), ...(actions ? { reply_markup: { inline_keyboard: [[{ text: BUTTON_LABEL, url: actions.pageUrl }]] } } : {}) });
// Telegram refuses a button whose address it cannot open (an address on a private network, say): say it in the text instead.
if (!result.ok && actions && result.status === 400) result = await post({ ...base, text: clip(text + footerText(actions), TELEGRAM_MAX) });
if (!result.ok) throw new Error(`Telegram: ${result.description ?? `HTTP ${result.status}`}`);
}
/** Sends one message through Pushover; throws what Pushover says when it refuses. */
export async function pushoverSend(cfg: { appToken: string; userKey: string; device?: string; priority?: number }, title: string, message: string, actions?: NotifyActions | null): Promise<void> {
const priority = Number.isInteger(cfg.priority) ? Math.min(2, Math.max(-2, cfg.priority as number)) : 0;
const link = actions && actions.pageUrl.length <= PUSHOVER_URL_MAX ? actions.pageUrl : null;
const body: Record<string, string | number> = {
token: cfg.appToken,
user: cfg.userKey,
title: clip(title, PUSHOVER_TITLE_MAX),
// A link too long for Pushover goes in the text instead.
message: clip(actions && !link ? message + footerText(actions) : message, PUSHOVER_MESSAGE_MAX),
priority,
};
if (cfg.device?.trim()) body.device = cfg.device.trim();
// An emergency message repeats until someone acknowledges it: Pushover wants to be told how often (every minute) and for how long (an hour).
if (priority === 2) {
body.retry = 60;
body.expire = 3600;
}
if (link) {
body.url = link;
body.url_title = BUTTON_LABEL;
}
const res = await fetch(`${CHANNEL_ENDPOINTS.pushover}/1/messages.json`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const json = (await res.json().catch(() => null)) as { status?: number; errors?: string[] } | null;
if (!res.ok || json?.status !== 1) throw new Error(`Pushover: ${json?.errors?.length ? json.errors.join(", ") : `HTTP ${res.status}`}`);
}
async function sendTelegram(title: string, message: string, actions?: NotifyActions | null) {
const { telegram } = await getSettings();
if (!telegram.enabled || !telegram.token || !telegram.chatId) return;
try {
await telegramSend(telegram, `${title}\n\n${message}`, actions);
} catch (err) {
console.error("[notify]", err instanceof Error ? err.message : "Telegram failed");
}
}
async function sendPushover(title: string, message: string, actions?: NotifyActions | null) {
const { pushover } = await getSettings();
if (!pushover.enabled || !pushover.appToken || !pushover.userKey) return;
try {
await pushoverSend(pushover, title, message, actions);
} catch (err) {
console.error("[notify]", err instanceof Error ? err.message : "Pushover failed");
}
}
async function sendSmtp(title: string, message: string, actions?: NotifyActions | null) {
const { smtp } = await getSettings();
if (!smtp.enabled || !smtp.host || !smtp.to || !smtp.from) return;
@@ -175,6 +254,8 @@ async function sendToChannels(title: string, message: string, audience: Audience
await Promise.all([
to("gotify") ? sendGotify(title, message, actions) : undefined,
to("ntfy") ? sendNtfy(title, message, actions) : undefined,
to("telegram") ? sendTelegram(title, message, actions) : undefined,
to("pushover") ? sendPushover(title, message, actions) : undefined,
to("smtp") ? sendSmtp(title, message, actions) : undefined,
to("webhook") ? sendWebhook(title, message, actions) : undefined,
to("webPush") ? sendWebPush(title, message, audience.pushIds, actions) : undefined,
@@ -221,11 +302,13 @@ export async function notifyNow(title: string, message: string): Promise<void> {
/** How many channels are switched on and filled in enough to send, so a "send it now" can say when there is nowhere to send to. */
export async function enabledChannelCount(): Promise<number> {
const { gotify, ntfy, smtp, webhook, webPush } = await getSettings();
const { gotify, ntfy, telegram, pushover, smtp, webhook, webPush } = await getSettings();
return [
webPush.enabled && (await subscriptionCount()) > 0,
gotify.enabled && gotify.url && gotify.token,
ntfy.enabled && ntfy.url && ntfy.topic,
telegram.enabled && telegram.token && telegram.chatId,
pushover.enabled && pushover.appToken && pushover.userKey,
smtp.enabled && smtp.host && smtp.to && smtp.from,
webhook.enabled && webhook.url,
].filter(Boolean).length;
@@ -298,6 +381,14 @@ export async function testNtfy(cfg: { url: string; topic: string; token?: string
if (!res.ok) throw new Error(`ntfy returned ${res.status}: ${await res.text().catch(() => "")}`);
}
export async function testTelegram(cfg: { token: string; chatId: string; silent?: boolean }): Promise<void> {
await telegramSend(cfg, "Homelab Manager — Test\n\nTelegram notifications are working correctly.");
}
export async function testPushover(cfg: { appToken: string; userKey: string; device?: string; priority?: number }): Promise<void> {
await pushoverSend(cfg, "Homelab Manager — Test", "Pushover notifications are working correctly.");
}
export async function testSmtp(cfg: {
host: string;
port?: number;
+1 -1
View File
@@ -6,7 +6,7 @@
*/
import type { AlertCategory, AlertSeverity } from "./alertTypes.js";
export const CHANNEL_IDS = ["gotify", "ntfy", "smtp", "webhook", "webPush"] as const;
export const CHANNEL_IDS = ["gotify", "ntfy", "telegram", "pushover", "smtp", "webhook", "webPush"] as const;
export type ChannelId = (typeof CHANNEL_IDS)[number];
export const CATEGORIES = ["offline", "disk", "services", "backup", "updates", "expiry", "automation", "integration", "monitoring", "tickets"] as const satisfies readonly AlertCategory[];
+2 -2
View File
@@ -2,11 +2,11 @@
* What a settings update actually changed, in a form fit for the audit log.
*
* The audit log can be read by operators, but Settings can't — so values only go in for sections an operator could
* already see in the app. The notification channels (Gotify, ntfy, SMTP, webhook) hold credentials, and even their
* already see in the app. The notification channels (Gotify, ntfy, Telegram, Pushover, SMTP, webhook) hold credentials, and even their
* addresses can act as one (a webhook URL carries its own token; a public ntfy topic is the only thing protecting
* it), so for those only the names of the fields that changed are recorded, never what they changed to or from.
*/
const NAMES_ONLY_SECTIONS = new Set(["gotify", "ntfy", "smtp", "webhook"]);
const NAMES_ONLY_SECTIONS = new Set(["gotify", "ntfy", "telegram", "pushover", "smtp", "webhook"]);
/** Anything longer than this isn't a useful thing to read in a table cell. */
const MAX_VALUE_JSON = 300;
+27 -1
View File
@@ -21,6 +21,26 @@ export interface NtfySettings {
priority: number;
}
/** A Telegram bot (made with @BotFather) that messages one chat: a person, a group or a channel. The bot's token is a secret; the chat id is a number (negative for a group) or @channelname. */
export interface TelegramSettings {
enabled: boolean;
token: string;
chatId: string;
/** Send without a sound or a buzz (Telegram's own "silent" messages). */
silent: boolean;
}
/** Pushover: an application's API token (made on pushover.net) and the user or group key that is to hear it. Both are secrets. */
export interface PushoverSettings {
enabled: boolean;
appToken: string;
userKey: string;
/** Only this one of the user's devices (blank: all of them). */
device: string;
/** -2 (no notification) to 2 (emergency: repeats until it is acknowledged). */
priority: number;
}
export interface SmtpSettings {
enabled: boolean;
host: string;
@@ -272,6 +292,8 @@ export interface VersionCheckSettings {
export interface AppSettings {
gotify: GotifySettings;
ntfy: NtfySettings;
telegram: TelegramSettings;
pushover: PushoverSettings;
smtp: SmtpSettings;
webhook: WebhookSettings;
webPush: WebPushSettings;
@@ -305,6 +327,8 @@ const DEFAULTS: AppSettings = {
versionChecks: { enabled: false, alertAfterDays: 0 },
gotify: { enabled: false, url: "", token: "", priority: 5 },
ntfy: { enabled: false, url: "https://ntfy.sh", topic: "", token: "", priority: 3 },
telegram: { enabled: false, token: "", chatId: "", silent: false },
pushover: { enabled: false, appToken: "", userKey: "", device: "", priority: 0 },
smtp: { enabled: false, host: "", port: 587, secure: false, username: "", password: "", from: "", to: "" },
webhook: { enabled: false, url: "", secret: "" },
webPush: { enabled: false, contact: "" },
@@ -368,13 +392,15 @@ const KEYS = Object.keys(DEFAULTS) as (keyof AppSettings)[];
// ─── Encrypting the notification channels' credentials ─────────────────────────────────────
//
// A Gotify/ntfy token, the SMTP password and the webhook secret are stored encrypted with the same key as integration
// A Gotify/ntfy/Telegram token, the Pushover keys, the SMTP password and the webhook secret are stored encrypted with the same key as integration
// credentials (CREDENTIALS_ENCRYPTION_KEY). Everything above this file sees them as plain text — they're opened when
// settings are read and sealed when they're written — so nothing else needs to know. An encrypted value is marked
// with a prefix, which is how a value saved before this existed (plain text) is told apart and picked up later.
const SECRET_FIELDS: Partial<Record<keyof AppSettings, string[]>> = {
gotify: ["token"],
ntfy: ["token"],
telegram: ["token"],
pushover: ["appToken", "userKey"],
smtp: ["password"],
webhook: ["secret"],
};
+321
View File
@@ -0,0 +1,321 @@
/**
* 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<string, unknown> };
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<string>((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<void>((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<string, any> | 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<Server>((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";
});
});