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:
1 parent
9f366c37de
commit
31f4debb9a
22 files changed
+670
-37
No files matched your search
+1
-1
@@ -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.",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 …)"),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,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;
|
||||
|
||||
@@ -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"],
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user