diff --git a/.env.example b/.env.example index b36edf3..fd8df20 100644 --- a/.env.example +++ b/.env.example @@ -16,7 +16,7 @@ APP_BASE_URL=https://homelab.example.lan SESSION_SECRET=change-me-to-a-random-64-char-hex-string # 32-byte (64 hex char) key used to encrypt stored integration API tokens, and the -# notification channels' credentials (Gotify/ntfy tokens, SMTP password, webhook +# notification channels' credentials (Gotify/ntfy/Telegram tokens, Pushover keys, SMTP password, webhook # secret), at rest (AES-256-GCM). Generate the same way as SESSION_SECRET. # Losing/changing this key makes those stored credentials unreadable. CREDENTIALS_ENCRYPTION_KEY=change-me-to-a-random-64-char-hex-string @@ -38,5 +38,5 @@ AUTHENTIK_ISSUER_URL=https://authentik.example.lan/application/o/homelab-manager AUTHENTIK_CLIENT_ID= AUTHENTIK_CLIENT_SECRET= -# Notification channels (Gotify, ntfy, SMTP, webhook) are configured in-app +# Notification channels (Gotify, ntfy, Telegram, Pushover, SMTP, webhook) are configured in-app # under Settings, not here. diff --git a/BACKUP.md b/BACKUP.md index 56379ba..d23b21e 100644 --- a/BACKUP.md +++ b/BACKUP.md @@ -52,7 +52,7 @@ tool), and it does not replace a restore drill. Access to all of it is for admin | What | Where | Why | If you lose it | |---|---|---|---| | **The database** | `data/homelab-manager.sqlite` | Everything: users and roles, servers and their agent tokens (as hashes) with their history (load, memory, disks), scheduled tasks, secrets, IP addresses, DNS caches, domains, ports, tags, notes, to-do items, runbooks, the hardware inventory, endpoint checks and heartbeats with their results, your own alert rules, maintenance windows and snoozes, dependencies, incidents, what was read from UniFi, Proxmox and Synology storage, and Home Assistant, both logs, settings, the integrations and DNS providers (with their credentials, encrypted), the alert-ticket memory | You start from nothing — see [If there is no backup](#if-there-is-no-backup) | -| **`CREDENTIALS_ENCRYPTION_KEY`** | `.env` | Decrypts every stored credential: integration tokens and passwords, DNS provider credentials, and the Gotify/ntfy/SMTP/webhook credentials | The database restores, but every credential in it is unreadable and has to be entered again | +| **`CREDENTIALS_ENCRYPTION_KEY`** | `.env` | Decrypts every stored credential: integration tokens and passwords, DNS provider credentials, and the Gotify/ntfy/Telegram/Pushover/SMTP/webhook credentials | The database restores, but every credential in it is unreadable and has to be entered again | | **The rest of `.env`** | `.env` | `SESSION_SECRET`, `APP_BASE_URL`, the Authentik client id and secret | `SESSION_SECRET`: everyone has to sign in again, nothing more. The Authentik values can be copied from Authentik again | | Your `docker-compose.yml` and the image version | next to `.env` | So you can bring it back the way it was. Note which **version** each backup came from (the image tag, or the git commit) | Re-create it from the README | diff --git a/DATABASE.md b/DATABASE.md index 2199909..0710d2d 100644 --- a/DATABASE.md +++ b/DATABASE.md @@ -1577,7 +1577,7 @@ What a status page shows, in order. | `servers.listening_ports` | `[{ "protocol": "tcp", "port": 22, "address": "0.0.0.0", "process": "sshd" }]` | | `servers.last_port_scan` | `{ "at": "", "address": "10.0.0.5", "from": 1, "to": 1024, "open": 3, "refused": 1010, "filtered": 11, "responded": true }` | | `servers.tags` | `["prod", "media"]` | -| `audit_log.detail` | Free-form per action — e.g. `{ "name": "pve1" }`, or for settings `{ "sections": [...], "changes": { "
": { "": { "from": …, "to": … } } } }`. For the notification channels (Gotify, ntfy, SMTP, webhook) only the field *names* that changed are recorded, never values. | +| `audit_log.detail` | Free-form per action — e.g. `{ "name": "pve1" }`, or for settings `{ "sections": [...], "changes": { "
": { "": { "from": …, "to": … } } } }`. For the notification channels (Gotify, ntfy, Telegram, Pushover, SMTP, webhook) only the field *names* that changed are recorded, never values. | | `integrations.config` | The non-secret fields for that integration type (table below). | | `dns_providers.config` | Non-secret provider settings (base URL, zone list, …). | @@ -1604,7 +1604,7 @@ that were never changed aren't stored; the app fills in defaults when reading. | Key | Holds | |---|---| -| `gotify`, `ntfy`, `smtp`, `webhook` | The four notification channels: enabled, address, and credentials (token / password / secret). The credential fields are stored encrypted (prefix `enc:v1:`) — see [Retention and backups](#retention-and-backups). | +| `gotify`, `ntfy`, `telegram`, `pushover`, `smtp`, `webhook` | The notification channels (beside `webPush`): enabled, address or chat, and credentials (token / keys / password / secret). Telegram has no address (it is always `api.telegram.org`): `token`, `chatId`, `silent`; Pushover (`api.pushover.net`): `appToken`, `userKey`, `device`, `priority` (-2 to 2). The credential fields are stored encrypted (prefix `enc:v1:`) — see [Retention and backups](#retention-and-backups). | | `routing` | Routing rules: `rules`, an ordered array of `{id, name, enabled, categories, minSeverity, tags, channels}` — the first enabled rule a notification matches decides which channels get it (empty `channels` = nobody). | | `escalation` | `enabled` (false) and up to three `steps` of `{afterMinutes, minSeverity, channels, extraEmail, evenInQuietHours}`, in time order. | | `webPush` | Push to phones and browsers: `enabled` (false) and `contact` (an email or https address the push services may reach whoever runs this on; blank is fine). Who is subscribed is in `push_subscriptions`; the server's key pair is below. | @@ -1721,7 +1721,7 @@ Everything else stays until someone deletes it. **Credentials at rest.** Integration and DNS provider credentials are encrypted in `integration_credentials` (above). The notification channels' -credentials — the Gotify and ntfy tokens, the SMTP password and the webhook +credentials — the Gotify, ntfy and Telegram tokens, the two Pushover keys, the SMTP password and the webhook secret — are in the `settings` rows, and are encrypted in place with the same key: each is stored as `enc:v1:` followed by the same `iv:authTag:ciphertext` form, and the rest of the row (URLs, topics, priorities) stays readable. The app decrypts them when diff --git a/NOTIFICATIONS.md b/NOTIFICATIONS.md index df5cce7..1423342 100644 --- a/NOTIFICATIONS.md +++ b/NOTIFICATIONS.md @@ -2,14 +2,14 @@ Every notification in Homelab Manager is sent through the same pipe (`server/src/services/notify.ts`) to whichever channels are enabled under -**Settings → Notifications**: Gotify, ntfy, SMTP (email), a generic -JSON webhook, and push to phones and browsers. All five fire for every notification below unless a +**Settings → Notifications**: Gotify, ntfy, Telegram, Pushover, SMTP (email), a generic +JSON webhook, and push to phones and browsers. All seven fire for every notification below unless a **routing rule** (see *Who hears what* below) says otherwise; each event also has its on/off toggle and, for the daily ones, one shared time/timezone. The settings page has four tabs, with one Save button for all of them (it shows "Unsaved changes" until you save, and the browser asks before the page -is closed with changes unsaved): **Channels** (the five channels, each a row +is closed with changes unsaved): **Channels** (the seven channels, each a row you open to fill in and send a test), **What to send** (the event toggles grouped by topic, each group's thresholds beside its switches), **Who hears what** (routing rules and escalation) and **When** (the time zone, the daily reminder time, quiet hours and the weekly digest). @@ -76,6 +76,21 @@ the same way. For routing they count as *Monitoring* (a check that fails) and *E server holds them back. A **restore test** that fails, or one that is overdue (when a limit is set), is on the Alerts page and in the incident record but is not sent as a notification of its own — it is something to look at when you are looking at backups. +## Telegram and Pushover + +Two more ways to a phone, for those who already live in one of them. Both are services with one address each (`api.telegram.org`, `api.pushover.net`), so nothing typed into the settings decides where a message is sent. Each has its own *Send test* in +**Settings → Notifications → Channels**, which sends with what is typed there (saved or not) and shows what the service said if it refuses. + +**Telegram** sends through a bot of your own, to one chat. Make the bot by messaging [@BotFather](https://t.me/BotFather) (`/newbot`) and paste its token; the chat id is a number (a group's is negative) or `@yourchannel` — send the bot a message (or add it to the +group or channel and post there), then open `https://api.telegram.org/bot/getUpdates` and read `"chat":{"id":…}`. A bot cannot message a person who has not written to it first. The message is the title, a blank line and the text, as plain text +(nothing in it is read as formatting), cut to Telegram's 4096-character limit. *Send silently* sends without a sound or a buzz. + +**Pushover** needs an application token (pushover.net → *Create an Application/API Token*) and your user key (or a group's), both from your Pushover account; a device name limits it to one of your devices. **Priority** runs from *lowest* (no +notification) to *emergency*, which repeats every minute for an hour until it is acknowledged in the Pushover app. The message is cut to Pushover's 1024 characters and the title to 250. + +The token and the keys are stored encrypted with the same key as the other credentials, and are never put in an error message or the audit log (a change to them is recorded as the field's name). A message that is refused is logged with what the service +said; it never stops the other channels. Both take part in routing rules like any channel. + ## Push to a phone or browser The fifth channel, **Phone and browser**, sends the same messages as the others to browsers that have asked for them — a phone with @@ -208,6 +223,8 @@ that ended, and the escalation reminder — can be acted on from the message: |---|---|---| | **ntfy** | Three buttons (*Acknowledge*, *Silence 1 h* — only when the alert is about something a window can silence — and *Snooze*) that POST to the alert's own link, and a tap that opens the page | One button, *Choose what to do*, to a page that lists them | | **Phone and browser push** | Two buttons on the notification itself (*Acknowledge*, *Silence 1 h*); a press sends it and shows how it went. A tap opens the Alerts page | A tap opens the Alerts page | +| **Telegram** | One button under the message, *Acknowledge, silence or snooze*, that opens the page. (If Telegram will not take the button's address — one on a private network, say — the link is added to the text instead) | The same | +| **Pushover** | The link is attached to the message (*Acknowledge, silence or snooze*), and a tap opens the page | The same | | **Gotify** | The link is added to the text, and a tap opens the page | The same | | **Email**, **the chat webhook**, an escalation's extra address | The link, as a last line of the text | The same | diff --git a/README.md b/README.md index a398e15..72d742d 100644 --- a/README.md +++ b/README.md @@ -188,8 +188,8 @@ All modules from the original plan are built: too, which writes the table as it is on screen — times as exact timestamps, action buttons left out. - **Alert settings** (Monitoring → Alert settings) — what decides what is an alert, on one page with three tabs: *Alert rules*, *Service levels* and *Alert tickets* (`/alert-settings?view=rules|levels|tickets`). Everyone signed in sees the first two; *Alert tickets* is administrators' (it used to be under Settings, and `/alert-rules`, `/service-levels` and `/settings/alert-tickets` still lead to the right tab). Notifications — channels, what is sent, who hears what, quiet hours — serve more than alerts, so they stay under **Settings → Notifications**, with a link to them at the top of this page for administrators. Maintenance stays on its own page. -- **Settings** (admin-only) — notification channels (Gotify, ntfy, SMTP, - generic webhook, and push to phones and browsers) with per-channel test buttons, per-event toggles (DNS +- **Settings** (admin-only) — notification channels (Gotify, ntfy, Telegram, + Pushover, SMTP, generic webhook, and push to phones and browsers) with per-channel test buttons, per-event toggles (DNS record added/updated/deleted, daily secret-expiry reminder and daily Tailscale key-expiry reminder — both sharing one configurable time/timezone), badge-color customization for both DNS @@ -1035,7 +1035,7 @@ change made on the machine itself. Everyone signed in can see it; it is also `GE **Buttons on notifications.** With **Settings → Notifications → Who hears what → Buttons on notifications** switched on (off by default), a notification can be dealt with from the message itself, without opening the app or signing in: **Acknowledge**, **Silence for an hour** (maintenance on what the alert is about) and **Snooze until tomorrow at 09:00** (in the notification time zone). A message about **one** alert gets them as -buttons — three on an ntfy message, two on a phone push (the browser's own notification), with the rest on the page a tap opens — and a message about several gets one link to a page that lists each with its buttons; +buttons — three on an ntfy message, two on a phone push (the browser's own notification), one button on a Telegram message and one link on a Pushover message, with the rest on the page a tap opens — and a message about several gets one link to a page that lists each with its buttons; Gotify, email and the chat webhook get that link as text (and Gotify's tap opens it). Escalation messages carry them too. Each link is a **signed token for the alerts in that one message only**, good for **24 hours**, and it can do just those three things — it cannot read anything or change a setting. **Opening a link never does anything** (so a preview or a mail scanner is harmless); only pressing a button acts, and it is written to the audit log as *from a notification link*, with the address it came from. The price is that **anyone who can read the notification can press its buttons** for those hours: fine for a private ntfy topic, your own Gotify or inbox, not for diff --git a/docs/MONITORING.md b/docs/MONITORING.md index 2b9d4d2..d79e781 100644 --- a/docs/MONITORING.md +++ b/docs/MONITORING.md @@ -48,7 +48,7 @@ This page explains what Homelab Manager watches, how often, how a problem become ``` agents ─────────┐ integrations ───┤ ┌──► Alerts page ──► acknowledge · snooze · close · silence - endpoint checks ┼─► checks ─► conditions ─┼──► notifications ─► Gotify · ntfy · email · webhook · push + endpoint checks ┼─► checks ─► conditions ─┼──► notifications ─► Gotify · ntfy · Telegram · Pushover · email · webhook · push heartbeats ─────┤ (rules) "a problem" ├──► event webhooks (machines) your own rules ─┘ ├──► incidents (the record) and history └──► /metrics and the read API @@ -606,7 +606,7 @@ Several things can quiet an alert. They are different, and it matters which you ### Who hears about it -Notifications go to the channels that are on (**Gotify, ntfy, email, a webhook, push to phones and browsers**), narrowed by **routing rules** (first match wins: by kind, by severity, by the server's tags) and each +Notifications go to the channels that are on (**Gotify, ntfy, Telegram, Pushover, email, a webhook, push to phones and browsers**), narrowed by **routing rules** (first match wins: by kind, by severity, by the server's tags) and each browser's own wishes. **Quiet hours** hold messages and send one digest at the end of the window (critical alerts can be let through); **Away** mode does the same for a stretch you set, "until Sunday". Every message the app can send, and what toggles it, is in [NOTIFICATIONS.md](../NOTIFICATIONS.md). **Event webhooks** are a separate way of being told, for machines: they hear every raise and clear, flapping and snoozed included ([WEBHOOKS.md](WEBHOOKS.md)). diff --git a/docs/WEBHOOKS.md b/docs/WEBHOOKS.md index 233a5aa..b6dd90f 100644 --- a/docs/WEBHOOKS.md +++ b/docs/WEBHOOKS.md @@ -272,7 +272,7 @@ def hook(): ## The notification webhook -The fifth notification channel (beside Gotify, ntfy, email and push) posts each notification to a URL you give it, as the sentence a person would read — handy for chat tools that accept an incoming-webhook post. +A notification channel (beside Gotify, ntfy, Telegram, Pushover, email and push) posts each notification to a URL you give it, as the sentence a person would read — handy for chat tools that accept an incoming-webhook post. **Settings → Notifications → Channels → Webhook**: switch it on, give the address, and optionally a secret. diff --git a/server/src/env.ts b/server/src/env.ts index 37f3832..9a44259 100644 --- a/server/src/env.ts +++ b/server/src/env.ts @@ -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.", ); } } diff --git a/server/src/routes/privacy.ts b/server/src/routes/privacy.ts index f5642cc..7a17c3f 100644 --- a/server/src/routes/privacy.ts +++ b/server/src/routes/privacy.ts @@ -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 …)"), diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.ts index 5f7648d..695b7f1 100644 --- a/server/src/routes/settings.ts +++ b/server/src/routes/settings.ts @@ -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), diff --git a/server/src/services/notify.ts b/server/src/services/notify.ts index fa7163e..c2d8045 100644 --- a/server/src/services/notify.ts +++ b/server/src/services/notify.ts @@ -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 { + const post = async (body: Record) => { + 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 { + 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 = { + 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 { /** 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 { - 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 { + 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 { + await pushoverSend(cfg, "Homelab Manager — Test", "Pushover notifications are working correctly."); +} + export async function testSmtp(cfg: { host: string; port?: number; diff --git a/server/src/services/notifyRouting.ts b/server/src/services/notifyRouting.ts index d31b86c..3923f50 100644 --- a/server/src/services/notifyRouting.ts +++ b/server/src/services/notifyRouting.ts @@ -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[]; diff --git a/server/src/services/settingsDiff.ts b/server/src/services/settingsDiff.ts index b84662a..7606802 100644 --- a/server/src/services/settingsDiff.ts +++ b/server/src/services/settingsDiff.ts @@ -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; diff --git a/server/src/services/settingsStore.ts b/server/src/services/settingsStore.ts index acffcb1..5dc1902 100644 --- a/server/src/services/settingsStore.ts +++ b/server/src/services/settingsStore.ts @@ -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> = { gotify: ["token"], ntfy: ["token"], + telegram: ["token"], + pushover: ["appToken", "userKey"], smtp: ["password"], webhook: ["secret"], }; diff --git a/server/test/telegramPushover.test.ts b/server/test/telegramPushover.test.ts new file mode 100644 index 0000000..870190f --- /dev/null +++ b/server/test/telegramPushover.test.ts @@ -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 }; +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"; + }); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 2ace179..8fb62b9 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -450,6 +450,22 @@ export interface GotifySettings { priority: number; } +export interface TelegramSettings { + enabled: boolean; + token: string; + chatId: string; + silent: boolean; +} + +export interface PushoverSettings { + enabled: boolean; + appToken: string; + userKey: string; + device: string; + /** -2 (no notification) to 2 (emergency: repeats until acknowledged). */ + priority: number; +} + export interface NtfySettings { enabled: boolean; url: string; @@ -475,7 +491,7 @@ export interface WebhookSettings { secret: string; } -export type NotifyChannelId = "gotify" | "ntfy" | "smtp" | "webhook" | "webPush"; +export type NotifyChannelId = "gotify" | "ntfy" | "telegram" | "pushover" | "smtp" | "webhook" | "webPush"; export interface RoutingRule { id: string; @@ -626,6 +642,8 @@ export interface DigestSettings { export interface AppSettings { gotify: GotifySettings; ntfy: NtfySettings; + telegram: TelegramSettings; + pushover: PushoverSettings; smtp: SmtpSettings; webhook: WebhookSettings; webPush: WebPushSettings; @@ -3169,7 +3187,7 @@ export interface PrivacyOverview { servers: number; serversWithAgent: number; profilePictures: ProfilePictureSettings & { identityProviderHost: string | null }; - channels: Record<"gotify" | "ntfy" | "smtp" | "webhook" | "webPush", { enabled: boolean; host: string | null }>; + channels: Record<"gotify" | "ntfy" | "telegram" | "pushover" | "smtp" | "webhook" | "webPush", { enabled: boolean; host: string | null }>; }; } @@ -4361,6 +4379,8 @@ export const api = { request<{ settings: AppSettings }>("/api/settings", { method: "PUT", body: JSON.stringify(data) }), testGotify: (data: { url: string; token: string; priority?: number }) => request<{ ok: true }>("/api/settings/test-gotify", { method: "POST", body: JSON.stringify(data) }), + testTelegram: (data: { token: string; chatId: string; silent?: boolean }) => request<{ ok: true }>("/api/settings/test-telegram", { method: "POST", body: JSON.stringify(data) }), + testPushover: (data: { appToken: string; userKey: string; device?: string; priority?: number }) => request<{ ok: true }>("/api/settings/test-pushover", { method: "POST", body: JSON.stringify(data) }), testNtfy: (data: { url: string; topic: string; token?: string; priority?: number }) => request<{ ok: true }>("/api/settings/test-ntfy", { method: "POST", body: JSON.stringify(data) }), testSmtp: (data: { host: string; port?: number; secure?: boolean; username?: string; password?: string; from: string; to: string }) => diff --git a/web/src/components/RoutingEditor.tsx b/web/src/components/RoutingEditor.tsx index 7694f1a..597e14b 100644 --- a/web/src/components/RoutingEditor.tsx +++ b/web/src/components/RoutingEditor.tsx @@ -1,7 +1,7 @@ import { useState } from "react"; import type { AlertCategory, EscalationSettings, EscalationStep, NotifyChannelId, RoutingRule, RoutingSettings } from "../api/client"; -export const CHANNEL_LABELS: Record = { gotify: "Gotify", ntfy: "ntfy", smtp: "Email", webhook: "Webhook", webPush: "Phone and browser" }; +export const CHANNEL_LABELS: Record = { gotify: "Gotify", ntfy: "ntfy", telegram: "Telegram", pushover: "Pushover", smtp: "Email", webhook: "Webhook", webPush: "Phone and browser" }; const CHANNELS = Object.keys(CHANNEL_LABELS) as NotifyChannelId[]; export const CATEGORY_LABELS: Record = { diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx index b16598f..76d331a 100644 --- a/web/src/pages/Dashboard.tsx +++ b/web/src/pages/Dashboard.tsx @@ -458,7 +458,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) { .get() .then((res) => { const s = res.settings; - setNotifyConfigured(s.gotify.enabled || s.ntfy.enabled || s.smtp.enabled || s.webhook.enabled || !!s.webPush?.enabled); + setNotifyConfigured(s.gotify.enabled || s.ntfy.enabled || s.telegram.enabled || s.pushover.enabled || s.smtp.enabled || s.webhook.enabled || !!s.webPush?.enabled); }) .catch(() => setNotifyConfigured(null)); api.users @@ -753,7 +753,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) { { id: "server", title: "Add a server and install its agent", description: "The agent reports scheduled tasks, disks, memory and open ports, and lets the app tell when a server goes quiet.", to: "/servers", action: "Add a server", done: (serverSummary?.total ?? 0) > 0 }, { id: "dns", title: "Connect a DNS provider", description: "See your zones and records, and have names matched to servers.", to: "/dns", action: "Connect", done: (dnsStats?.totalProviders ?? 0) > 0 }, { id: "secret", title: "Track something that expires", description: "An API token, a certificate or a password — you're warned before it runs out.", to: "/secrets", action: "Add one", done: (secrets?.length ?? 0) > 0 }, - { id: "notify", title: "Choose how you'll be told about problems", description: "Gotify, ntfy, email, a webhook or push to your phone, with the checks you want.", to: "/settings/notifications", action: "Set up", done: notifyConfigured === true }, + { id: "notify", title: "Choose how you'll be told about problems", description: "Gotify, ntfy, Telegram, Pushover, email, a webhook or push to your phone, with the checks you want.", to: "/settings/notifications", action: "Set up", done: notifyConfigured === true }, { id: "people", title: "Let someone else in (optional)", description: "Others sign in with Authentik and appear under Users; you decide their role.", to: "/users", action: "Open Users", done: (userCount ?? 0) > 1 }, ]; diff --git a/web/src/pages/Privacy.tsx b/web/src/pages/Privacy.tsx index 5db1b97..8130461 100644 --- a/web/src/pages/Privacy.tsx +++ b/web/src/pages/Privacy.tsx @@ -7,7 +7,7 @@ import { formatAgo } from "../utils/duration"; import { readableError } from "../utils/errors"; import { ErrorNotice } from "../components/Notice"; -const CHANNEL_LABELS = { gotify: "Gotify", ntfy: "ntfy", smtp: "email (SMTP)", webhook: "webhook", webPush: "web push" } as const; +const CHANNEL_LABELS = { gotify: "Gotify", ntfy: "ntfy", telegram: "Telegram", pushover: "Pushover", smtp: "email (SMTP)", webhook: "webhook", webPush: "web push" } as const; /** SQLite timestamps ("2026-09-26 04:07:21") are UTC without a zone marker. */ function parseTime(value: string): Date { @@ -199,7 +199,7 @@ export default function Privacy() { Integration, DNS and notification credentials - API tokens and passwords — including the Gotify/ntfy tokens, SMTP password and webhook secret — encrypted (AES-256-GCM) with a key held in + API tokens and passwords — including the Gotify/ntfy/Telegram tokens, the Pushover keys, SMTP password and webhook secret — encrypted (AES-256-GCM) with a key held in the server's environment, not in the database. (If that key isn't set, notification credentials are kept unencrypted and the server says so at startup.) Until deleted. Settings → Data → Backup exports include them, encrypted with a passphrase you choose. diff --git a/web/src/pages/settings/AlertActionsCard.tsx b/web/src/pages/settings/AlertActionsCard.tsx index bb0fa51..7e059e6 100644 --- a/web/src/pages/settings/AlertActionsCard.tsx +++ b/web/src/pages/settings/AlertActionsCard.tsx @@ -42,7 +42,7 @@ export default function AlertActionsCard() {

- Let a notification itself carry Acknowledge, Silence for an hour and Snooze until tomorrow — as buttons on an ntfy message or a phone push, and as a link in an email, a Gotify message or the chat + Let a notification itself carry Acknowledge, Silence for an hour and Snooze until tomorrow — as buttons on an ntfy message or a phone push, and as a link in an email, a Gotify message, a Telegram message (a button), a Pushover message (a link) or the chat webhook — so a problem can be dealt with from the lock screen, without opening the app or signing in.

diff --git a/web/src/utils/settingsIndex.ts b/web/src/utils/settingsIndex.ts index 131ba1e..1b1fccd 100644 --- a/web/src/utils/settingsIndex.ts +++ b/web/src/utils/settingsIndex.ts @@ -15,7 +15,7 @@ const N = "/settings/notifications"; export const SETTINGS_INDEX: SettingsEntry[] = [ // Notifications - { title: "Gotify, ntfy, email and webhook channels", where: "Notifications › Channels", to: `${N}?tab=channels`, words: "gotify ntfy smtp email mail webhook push channel test send where notifications go" }, + { title: "Gotify, ntfy, Telegram, Pushover, email and webhook channels", where: "Notifications › Channels", to: `${N}?tab=channels`, words: "gotify ntfy telegram bot chat pushover smtp email mail webhook push channel test send where notifications go" }, { title: "Browser and phone push", where: "Notifications › Channels", to: `${N}?tab=channels`, words: "web push browser phone device subscribe pwa notify vapid" }, { title: "Server offline after (minutes)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "offline stopped reporting silent agent threshold limit minutes" }, { title: "Disk usage alert at (percent)", where: "Notifications › What to send › Servers and disks", to: `${N}?tab=events`, words: "disk full storage percent threshold space" },