Buttons on notifications: acknowledge, silence and snooze from the message
- A switch (off by default) under Settings -> Notifications -> Who hears what - ntfy gets buttons (three for one alert, one link for several); phone push gets two buttons handled by the service worker; Gotify, email and the chat webhook get the link as text; escalation messages carry them too - Each link is a signed token for the alerts in that one message only, good for 24 hours, for three actions; opening it changes nothing, only a POST acts; everything is audited as "from a notification link" - Docs updated Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0277126add
commit
aebf3c6ce1
22 files changed
+895
-28
No files matched your search
@@ -9,11 +9,12 @@ import { pushSubscriptions, servers } from "../db/schema.js";
|
||||
import { parseTags } from "./serverTags.js";
|
||||
import { dampRaised, dampRecovered } from "./flapGuard.js";
|
||||
import { withoutSnoozed } from "./alertSnoozes.js";
|
||||
import { actionsFor, footerText, ntfyActionsHeader, type NotifyActions } from "./alertActionLinks.js";
|
||||
import { firstMatchingRule, metaOfConditionKey, pushAccepts, type ChannelId, type NotifyMeta } from "./notifyRouting.js";
|
||||
|
||||
// ─── Channel senders (best-effort — failures are logged, never thrown) ──────
|
||||
|
||||
async function sendGotify(title: string, message: string) {
|
||||
async function sendGotify(title: string, message: string, actions?: NotifyActions | null) {
|
||||
const { gotify } = await getSettings();
|
||||
if (!gotify.enabled || !gotify.url || !gotify.token) return;
|
||||
const base = gotify.url.replace(/\/$/, "");
|
||||
@@ -21,7 +22,8 @@ async function sendGotify(title: string, message: string) {
|
||||
const res = await fetch(`${base}/message?token=${encodeURIComponent(gotify.token)}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ title, message, priority: gotify.priority ?? 5 }),
|
||||
// Gotify has no buttons: a tap opens the page with them (and the address is in the text, for a client that does not tap).
|
||||
body: JSON.stringify({ title, message: actions ? message + footerText(actions) : message, priority: gotify.priority ?? 5, ...(actions ? { extras: { "client::notification": { click: { url: actions.pageUrl } } } } : {}) }),
|
||||
});
|
||||
if (!res.ok) console.error(`[notify] Gotify error ${res.status}: ${await res.text().catch(() => "")}`);
|
||||
} catch (err) {
|
||||
@@ -38,7 +40,7 @@ export function headerSafe(text: string): string {
|
||||
return /^[ -~]*$/.test(text) ? text : `=?UTF-8?B?${Buffer.from(text, "utf8").toString("base64")}?=`;
|
||||
}
|
||||
|
||||
async function sendNtfy(title: string, message: string) {
|
||||
async function sendNtfy(title: string, message: string, actions?: NotifyActions | null) {
|
||||
const { ntfy } = await getSettings();
|
||||
if (!ntfy.enabled || !ntfy.url || !ntfy.topic) return;
|
||||
const base = ntfy.url.replace(/\/$/, "");
|
||||
@@ -48,6 +50,10 @@ async function sendNtfy(title: string, message: string) {
|
||||
Priority: String(ntfy.priority ?? 3),
|
||||
};
|
||||
if (ntfy.token) headers.Authorization = `Bearer ${ntfy.token}`;
|
||||
if (actions) {
|
||||
headers.Actions = ntfyActionsHeader(actions);
|
||||
headers.Click = actions.pageUrl;
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`${base}/${encodeURIComponent(ntfy.topic)}`, { method: "POST", headers, body: message });
|
||||
if (!res.ok) console.error(`[notify] ntfy error ${res.status}: ${await res.text().catch(() => "")}`);
|
||||
@@ -56,7 +62,7 @@ async function sendNtfy(title: string, message: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function sendSmtp(title: string, message: string) {
|
||||
async function sendSmtp(title: string, message: string, actions?: NotifyActions | null) {
|
||||
const { smtp } = await getSettings();
|
||||
if (!smtp.enabled || !smtp.host || !smtp.to || !smtp.from) return;
|
||||
try {
|
||||
@@ -66,13 +72,13 @@ async function sendSmtp(title: string, message: string) {
|
||||
secure: !!smtp.secure,
|
||||
auth: smtp.username ? { user: smtp.username, pass: smtp.password } : undefined,
|
||||
});
|
||||
await transporter.sendMail({ from: smtp.from, to: smtp.to, subject: title, text: message });
|
||||
await transporter.sendMail({ from: smtp.from, to: smtp.to, subject: title, text: actions ? message + footerText(actions) : message });
|
||||
} catch (err) {
|
||||
console.error("[notify] SMTP failed:", err instanceof Error ? err.message : err);
|
||||
}
|
||||
}
|
||||
|
||||
async function sendWebhook(title: string, message: string) {
|
||||
async function sendWebhook(title: string, message: string, actions?: NotifyActions | null) {
|
||||
const { webhook } = await getSettings();
|
||||
if (!webhook.enabled || !webhook.url) return;
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
@@ -81,7 +87,7 @@ async function sendWebhook(title: string, message: string) {
|
||||
const res = await fetch(webhook.url, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify({ content: `**${title}**\n${message}` }),
|
||||
body: JSON.stringify({ content: `**${title}**\n${message}${actions ? footerText(actions) : ""}` }),
|
||||
});
|
||||
if (!res.ok) console.error(`[notify] Webhook error ${res.status}: ${await res.text().catch(() => "")}`);
|
||||
} catch (err) {
|
||||
@@ -89,12 +95,15 @@ async function sendWebhook(title: string, message: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function sendWebPush(title: string, message: string, only: number[] | null) {
|
||||
async function sendWebPush(title: string, message: string, only: number[] | null, actions?: NotifyActions | null) {
|
||||
const { webPush } = await getSettings();
|
||||
if (!webPush.enabled) return;
|
||||
// For one alert, buttons on the notification itself (browsers show two); for several, a tap opens the app.
|
||||
const buttons = actions?.direct.slice(0, 2).map((d) => ({ action: d.id, title: d.label, path: d.path }));
|
||||
const message_ = { title, body: message, ...(buttons?.length ? { actions: buttons } : {}) };
|
||||
try {
|
||||
if (only === null) await sendPush({ title, body: message });
|
||||
else if (only.length > 0) await sendPush({ title, body: message }, await db.select().from(pushSubscriptions).where(inArray(pushSubscriptions.id, only)));
|
||||
if (only === null) await sendPush(message_);
|
||||
else if (only.length > 0) await sendPush(message_, await db.select().from(pushSubscriptions).where(inArray(pushSubscriptions.id, only)));
|
||||
} catch (err) {
|
||||
console.error("[notify] Web push failed:", err instanceof Error ? err.message : err);
|
||||
}
|
||||
@@ -160,15 +169,15 @@ export async function audienceFor(meta?: NotifyMeta): Promise<Audience> {
|
||||
return { channels, pushIds };
|
||||
}
|
||||
|
||||
async function sendToChannels(title: string, message: string, audience: Audience = EVERYONE): Promise<void> {
|
||||
async function sendToChannels(title: string, message: string, audience: Audience = EVERYONE, actions: NotifyActions | null = null): Promise<void> {
|
||||
const to = (c: ChannelId) => audience.channels === null || audience.channels.includes(c);
|
||||
await Promise.all([
|
||||
to("gotify") ? sendGotify(title, message) : undefined,
|
||||
to("ntfy") ? sendNtfy(title, message) : undefined,
|
||||
to("smtp") ? sendSmtp(title, message) : undefined,
|
||||
to("webhook") ? sendWebhook(title, message) : undefined,
|
||||
to("webPush") ? sendWebPush(title, message, audience.pushIds) : undefined,
|
||||
audience.email ? sendExtraEmail(title, message, audience.email) : undefined,
|
||||
to("gotify") ? sendGotify(title, message, actions) : undefined,
|
||||
to("ntfy") ? sendNtfy(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,
|
||||
audience.email ? sendExtraEmail(title, actions ? message + footerText(actions) : message, audience.email) : undefined,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -176,17 +185,17 @@ async function sendToChannels(title: string, message: string, audience: Audience
|
||||
* Sends to an audience that is already worked out: held for the quiet-hours digest if it is quiet (unless told not to), nowhere if a rule
|
||||
* said nobody. Escalations use this with their own channels.
|
||||
*/
|
||||
export async function notifyAudience(title: string, message: string, audience: Audience, options: { quietHours?: boolean } = {}): Promise<void> {
|
||||
export async function notifyAudience(title: string, message: string, audience: Audience, options: { quietHours?: boolean; actions?: NotifyActions | null } = {}): Promise<void> {
|
||||
if (isMuted(audience)) return;
|
||||
if (options.quietHours !== false && (await isQuietHoursActive())) {
|
||||
await enqueueNotification(title, message, audience.channels === null && audience.pushIds === null && !audience.email ? null : JSON.stringify(audience));
|
||||
return;
|
||||
}
|
||||
await sendToChannels(title, message, audience);
|
||||
await sendToChannels(title, message, audience, options.actions ?? null);
|
||||
}
|
||||
|
||||
/** Items that may each be for a different audience (a rule can send a disk warning one place and a server outage another): sent as one message per audience. */
|
||||
async function notifyGrouped<T>(items: T[], metaOf: (item: T) => NotifyMeta, build: (group: T[]) => { title: string; message: string }): Promise<void> {
|
||||
async function notifyGrouped<T>(items: T[], metaOf: (item: T) => NotifyMeta, build: (group: T[]) => { title: string; message: string }, keysOf?: (item: T) => string | undefined): Promise<void> {
|
||||
const groups = new Map<string, { audience: Audience; items: T[] }>();
|
||||
for (const item of items) {
|
||||
const audience = await audienceFor(metaOf(item));
|
||||
@@ -197,7 +206,8 @@ async function notifyGrouped<T>(items: T[], metaOf: (item: T) => NotifyMeta, bui
|
||||
}
|
||||
for (const group of groups.values()) {
|
||||
const { title, message } = build(group.items);
|
||||
await notifyAudience(title, message, group.audience);
|
||||
// Buttons, when the message is about alerts that have a key and an administrator has switched them on (a message held for quiet hours is sent without them).
|
||||
await notifyAudience(title, message, group.audience, keysOf ? { actions: await actionsFor(group.items.map(keysOf)) } : {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -497,7 +507,7 @@ export async function notifyHealthIssues(issues: { message: string; key?: string
|
||||
await notifyGrouped(issues, issueMeta, (group) => ({
|
||||
title: "Homelab Manager — Health Alert",
|
||||
message: `${group.length} new issue${group.length !== 1 ? "s" : ""}:\n\n${group.map((i) => `⚠ ${i.message}`).join("\n")}`,
|
||||
}));
|
||||
}), (i) => i.key);
|
||||
}
|
||||
|
||||
export async function notifyHealthRecovered(resolved: { message: string; key?: string; severity?: string }[]): Promise<void> {
|
||||
@@ -521,7 +531,7 @@ export async function notifySnoozeEnded(items: { message: string; key?: string;
|
||||
await notifyGrouped(items, issueMeta, (group) => ({
|
||||
title: "Homelab Manager — Snooze ended",
|
||||
message: `${group.length === 1 ? "An alert you snoozed is" : `${group.length} alerts you snoozed are`} still there:\n\n${group.map((i) => `⏰ ${i.message}`).join("\n")}`,
|
||||
}));
|
||||
}), (i) => i.key);
|
||||
}
|
||||
|
||||
/** An alert that has just been called flapping: said once, with how often it has come, instead of each time. */
|
||||
@@ -530,7 +540,7 @@ export async function notifyFlapping(items: { message: string; key?: string; sev
|
||||
await notifyGrouped(items, issueMeta, (group) => ({
|
||||
title: "Homelab Manager — Flapping alert",
|
||||
message: `${group.length === 1 ? "An alert keeps" : `${group.length} alerts keep`} coming and going:\n\n${group.map((i) => `↻ ${i.message} — raised ${i.count} times within an hour`).join("\n")}\n\nIts further messages are held back until it has been quiet for an hour; it stays on the Alerts page, marked as flapping.`,
|
||||
}));
|
||||
}), (i) => i.key);
|
||||
}
|
||||
|
||||
/** Flapping alerts that have been quiet for an hour: what state each is in now. */
|
||||
@@ -551,7 +561,7 @@ export async function notifyAutomationFailed(issues: { message: string; key?: st
|
||||
await notifyGrouped(issues, issueMeta, (group) => ({
|
||||
title: "Homelab Manager — Automation Failed",
|
||||
message: `${group.length} run${group.length !== 1 ? "s" : ""} failed:\n\n${group.map((i) => `✕ ${i.message}`).join("\n")}`,
|
||||
}));
|
||||
}), (i) => i.key);
|
||||
}
|
||||
|
||||
export async function notifyAutomationRecovered(resolved: { message: string; key?: string; severity?: string }[]): Promise<void> {
|
||||
|
||||
Reference in new issue
Block a user