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:
bobbanandClaude Sonnet 5.5 committed 2026-10-21 20:42:04 +02:00
1 parent 0277126add
commit aebf3c6ce1
22 files changed
+895 -28

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
/**
* The links behind buttons on a notification (see services/alertActions.ts for what they do): Acknowledge, Silence for an hour, Snooze until tomorrow morning — from the phone push, an ntfy message, a link in an email or a Gotify message,
* without signing in to the app. A switch an administrator turns on (Settings → Notifications → Who hears what); off, no link works.
*
* What makes it safe enough to have is how little each link can do:
*
* - it is for **named alerts only** — the ones in that message — and carries nothing else; a link for one alert cannot touch another;
* - it can do **three things**: acknowledge, silence the thing the alert is about for an hour, snooze until tomorrow morning. It cannot read anything, change a setting, end a window
* or reach any other part of the app;
* - it **expires** after 24 hours;
* - it is a signed token (HMAC-SHA256 with a key derived from the app's own secret), so there is nothing stored and nothing to guess; changing \`SESSION_SECRET\` ends every link at once;
* - **opening** a link never does anything: a page opened by a browser, a chat preview or a mail scanner shows what the buttons would do, and only a deliberate press (a POST) acts;
* - everything it does is in the audit log, said to be done "from a notification link", with the address it came from.
*
* The honest cost: **anyone who can read the notification can use its buttons** for those 24 hours. That is fine for a private ntfy topic, a Gotify server of your own or a phone; it is not for a
* public topic on ntfy.sh. The settings page says so.
*/
import { createHmac, timingSafeEqual } from "node:crypto";
import { env } from "../env.js";
import { subjectOfConditionKey } from "./maintenance.js";
import { getSettings } from "./settingsStore.js";
export const TOKEN_TTL_MS = 24 * 3600_000;
export const MAX_KEYS = 20;
export type ActionId = "ack" | "silence" | "snooze";
export const ACTION_IDS: readonly ActionId[] = ["ack", "silence", "snooze"];
// ─── The signed token ──────────────────────────────────────────────────────
const secret = () => createHmac("sha256", env.sessionSecret).update("homelab-manager:alert-actions:v1").digest();
const b64u = (b: Buffer) => b.toString("base64url");
interface Payload {
/** The condition keys of the alerts this link is for. */
k: string[];
/** When it ends, epoch seconds. */
e: number;
}
/** A link's token: the alerts it is for and when it ends, signed. */
export function signToken(keys: string[], now: Date = new Date()): string {
const payload: Payload = { k: keys.slice(0, MAX_KEYS), e: Math.floor((now.getTime() + TOKEN_TTL_MS) / 1000) };
const body = b64u(Buffer.from(JSON.stringify(payload)));
return `${body}.${b64u(createHmac("sha256", secret()).update(body).digest())}`;
}
export type TokenCheck = { ok: true; keys: string[]; expiresAt: Date } | { ok: false; reason: "invalid" | "expired" };
export function verifyToken(token: string, now: Date = new Date()): TokenCheck {
const [body, sig, extra] = token.split(".");
if (!body || !sig || extra !== undefined || token.length > 4000) return { ok: false, reason: "invalid" };
const expected = createHmac("sha256", secret()).update(body).digest();
let given: Buffer;
try {
given = Buffer.from(sig, "base64url");
} catch {
return { ok: false, reason: "invalid" };
}
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return { ok: false, reason: "invalid" };
let payload: Payload;
try {
payload = JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as Payload;
} catch {
return { ok: false, reason: "invalid" };
}
if (!Array.isArray(payload.k) || payload.k.length === 0 || !payload.k.every((k) => typeof k === "string" && k.length > 0 && k.length <= 600) || typeof payload.e !== "number") return { ok: false, reason: "invalid" };
if (payload.e * 1000 <= now.getTime()) return { ok: false, reason: "expired" };
return { ok: true, keys: payload.k.slice(0, MAX_KEYS), expiresAt: new Date(payload.e * 1000) };
}
// ─── What a message carries ────────────────────────────────────────────────
export interface ActionLink {
id: ActionId;
label: string;
/** A path in the app (POST). */
path: string;
/** The same as a full address. */
url: string;
}
export interface NotifyActions {
/** A page that lists the alerts with the buttons; opening it does nothing. */
pagePath: string;
pageUrl: string;
/** For a message about one alert: its buttons, ready to POST (silence only when there is something to silence). Empty for several. */
direct: ActionLink[];
/** How many alerts it is for. */
count: number;
}
const baseUrl = () => env.appBaseUrl.replace(/\/+$/, "");
/** Whether a condition key is about something a maintenance window can silence. */
export const canSilenceKey = (key: string) => subjectOfConditionKey(key) !== null;
/** The links for a message about these alerts, or null when the switch is off or there are no alerts. */
export async function actionsFor(keys: (string | undefined)[], now: Date = new Date()): Promise<NotifyActions | null> {
const list = [...new Set(keys.filter((k): k is string => typeof k === "string" && k.length > 0))].slice(0, MAX_KEYS);
if (list.length === 0) return null;
if (!(await getSettings()).alertActions.enabled) return null;
const token = signToken(list, now);
const pagePath = `/api/alert-actions/${token}`;
const link = (id: ActionId, label: string): ActionLink => ({ id, label, path: `/api/alert-actions/${token}/${id}`, url: `${baseUrl()}/api/alert-actions/${token}/${id}` });
const direct = list.length === 1 ? [link("ack", "Acknowledge"), ...(canSilenceKey(list[0]) ? [link("silence", "Silence 1 h")] : []), link("snooze", "Snooze")] : [];
return { pagePath, pageUrl: `${baseUrl()}${pagePath}`, direct, count: list.length };
}
/** ntfy's `Actions` header: buttons for one alert (it allows three), one button to a page for several. Plain ASCII, as a header must be. */
export function ntfyActionsHeader(a: NotifyActions): string {
if (a.direct.length > 0) return a.direct.map((d) => `http, ${d.label}, ${d.url}, method=POST, clear=true`).join("; ");
return `view, Choose what to do, ${a.pageUrl}`;
}
/** The line added to the text of a message for the channels that have no buttons (email, a chat webhook, Gotify). */
export const footerText = (a: NotifyActions) => `\n\nAcknowledge, silence or snooze: ${a.pageUrl}`;
+94
View File
@@ -0,0 +1,94 @@
/**
* Doing what a notification's buttons say: acknowledge, silence the thing an alert is about for an hour, or snooze until tomorrow morning — for one alert, when the link
* is for it and the alert is still raised. Everything it does is written to the audit log, said to be done "from a notification link". The links themselves, what they
* are for and why they are safe enough are in services/alertActionLinks.ts.
*/
import { getAlerts, invalidateAlertsCache } from "./alerts.js";
import { loadAck, setAck } from "./alertAcks.js";
import { setSnooze } from "./alertSnoozes.js";
import { recordAudit } from "./audit.js";
import { keyOfAlertId } from "./flapGuard.js";
import { startOrExtendWindow } from "./maintenance.js";
import { getSettings } from "./settingsStore.js";
import type { ActionId } from "./alertActionLinks.js";
export const SILENCE_MINUTES = 60;
/** What a link says it was done by, in the audit log and on an acknowledgement. */
export const VIA = "a notification link";
// ─── "Tomorrow at 09:00", in the notification time zone ────────────────────
function zoneParts(ms: number, timeZone: string) {
const p = new Intl.DateTimeFormat("en-GB", { timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" }).formatToParts(new Date(ms));
const n = (t: string) => Number(p.find((x) => x.type === t)?.value);
return { y: n("year"), m: n("month"), d: n("day"), hh: n("hour"), mm: n("minute"), ss: n("second") };
}
/** The moment it is next 09:00 tomorrow by the clocks of `timeZone` (an unknown zone is read as UTC). */
export function tomorrowMorning(now: Date, timeZone: string, hour = 9): Date {
let tz = timeZone;
try {
new Intl.DateTimeFormat("en-GB", { timeZone: tz });
} catch {
tz = "UTC";
}
const today = zoneParts(now.getTime(), tz);
// Tomorrow's date by that zone's calendar, then the instant whose local time there is that date at `hour`:00 (twice round, so a change of summer time between is handled).
const wanted = Date.UTC(today.y, today.m - 1, today.d + 1, hour, 0, 0);
let guess = wanted;
for (let i = 0; i < 3; i++) {
const p = zoneParts(guess, tz);
guess += wanted - Date.UTC(p.y, p.m - 1, p.d, p.hh, p.mm, p.ss);
}
return new Date(guess);
}
// ─── Doing it ──────────────────────────────────────────────────────────────
export interface ActionResult {
ok: boolean;
/** HTTP status to answer with. */
status: number;
message: string;
}
/** The alert a condition key is about right now, if it is still raised. */
export async function currentAlertFor(key: string) {
const report = await getAlerts(false);
return report.alerts.find((a) => keyOfAlertId(a.id, a.category) === key) ?? null;
}
const auditTarget = (t: { type: string; id: number } | null) => (t ? { targetType: t.type, targetId: t.id } : {});
/** Does one of the three things to one alert, if the link is for it and it is still there. Everything it does is written down. */
export async function performAction(action: ActionId, key: string, context: { ip?: string }, now: Date = new Date()): Promise<ActionResult> {
const settings = await getSettings();
if (!settings.alertActions.enabled) return { ok: false, status: 404, message: "Buttons in notifications are switched off." };
const alert = await currentAlertFor(key);
if (!alert) return { ok: false, status: 404, message: "That alert isn't there any more — it has cleared." };
const via = { via: VIA, ip: context.ip ?? null };
if (action === "ack") {
const existing = await loadAck(alert.id, now);
if (existing?.active) return { ok: true, status: 200, message: `Already acknowledged by ${existing.ackedBy}.` };
const { ack } = await setAck({ alertId: alert.id, note: "Acknowledged from a notification", assigneeId: null, hours: null, actor: VIA }, now);
await recordAudit({ category: "alert", action: "ack", ...auditTarget(alert.target), detail: { alertId: alert.id, message: alert.message, note: ack.note, assignee: null, hours: null, changed: false, ...via } });
invalidateAlertsCache();
return { ok: true, status: 200, message: "Acknowledged." };
}
if (action === "silence") {
if (!alert.target) return { ok: false, status: 409, message: "There is nothing to silence this with — it is not about a server or an integration." };
const result = await startOrExtendWindow(alert.target.type, alert.target.id, SILENCE_MINUTES, "Silenced from a notification", VIA);
if (!result) return { ok: false, status: 404, message: "What it is about isn't there any more." };
await recordAudit({ category: "maintenance", action: result.extended ? "extend" : "start", targetType: alert.target.type, targetId: alert.target.id, detail: { name: result.target.name, minutes: SILENCE_MINUTES, reason: "Silenced from a notification", ...via } });
invalidateAlertsCache();
return { ok: true, status: 200, message: `Silenced for ${SILENCE_MINUTES === 60 ? "an hour" : `${SILENCE_MINUTES} minutes`}: ${result.target.name}.` };
}
const until = tomorrowMorning(now, settings.notifications.timezone);
const snooze = await setSnooze({ alertId: alert.id, conditionKey: key, message: alert.message, until, actor: VIA }, now);
await recordAudit({ category: "alert", action: "snooze", ...auditTarget(alert.target), detail: { alertId: alert.id, message: alert.message, until: snooze.until, ...via } });
invalidateAlertsCache();
return { ok: true, status: 200, message: `Snoozed until ${until.toISOString().slice(0, 16).replace("T", " ")} UTC.` };
}
+4 -1
View File
@@ -12,6 +12,8 @@ import { getAlerts } from "./alerts.js";
import { loadAcks } from "./alertAcks.js";
import { recordAudit } from "./audit.js";
import { notifyAudience } from "./notify.js";
import { actionsFor } from "./alertActionLinks.js";
import { keyOfAlertId } from "./flapGuard.js";
import { getSettings } from "./settingsStore.js";
import { severityRank, type EscalationStep } from "./notifyRouting.js";
@@ -79,6 +81,7 @@ export async function runEscalation(now: Date = new Date()): Promise<number> {
});
// One message for each step, listing the alerts it is for.
const categoryOf = new Map(report.alerts.map((a) => [a.id, a.category]));
const byStep = new Map<number, DueEscalation[]>();
for (const d of due) byStep.set(d.step, [...(byStep.get(d.step) ?? []), d]);
for (const [step, items] of byStep) {
@@ -86,7 +89,7 @@ export async function runEscalation(now: Date = new Date()): Promise<number> {
const lines = items.map((d) => `${d.alert.severity === "critical" ? "✕" : "⚠"} ${d.alert.message}`);
const message = `Nobody has acknowledged ${items.length === 1 ? "this alert" : `these ${items.length} alerts`} after ${words(def.afterMinutes)}:\n\n${lines.join("\n")}\n\nAcknowledge ${items.length === 1 ? "it" : "them"} on the Alerts page to stop the reminders.`;
try {
await notifyAudience("Homelab Manager — Still not acknowledged", message, { channels: def.channels, pushIds: null, ...(def.extraEmail ? { email: def.extraEmail } : {}) }, { quietHours: !def.evenInQuietHours });
await notifyAudience("Homelab Manager — Still not acknowledged", message, { channels: def.channels, pushIds: null, ...(def.extraEmail ? { email: def.extraEmail } : {}) }, { quietHours: !def.evenInQuietHours, actions: await actionsFor(items.map((d) => keyOfAlertId(d.alert.id, categoryOf.get(d.alert.id) ?? ""))) });
} catch (err) {
console.error("[escalation] couldn't send step", step, err);
continue; // not marked as sent: the next look tries again
+35 -25
View File
@@ -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> {
+7
View File
@@ -163,6 +163,11 @@ export interface ProfilePictureSettings {
identityProvider: boolean;
}
/** Buttons on notifications (services/alertActionLinks.ts): Acknowledge, Silence, Snooze from the message itself, with no sign-in. Off until an administrator turns it on. */
export interface AlertActionSettings {
enabled: boolean;
}
/** How the agents out on the servers are kept up to date. Off until an administrator turns it on. */
export interface AgentSettings {
/** An agent that is behind downloads the newer script from this app, checks it and replaces itself. */
@@ -248,6 +253,7 @@ export interface AppSettings {
inventory: InventorySettings;
selfBackup: SelfBackupSettings;
agents: AgentSettings;
alertActions: AlertActionSettings;
consistency: ConsistencySettings;
nameGenerator: NameGeneratorSettings;
alertTickets: AlertTicketSettings;
@@ -288,6 +294,7 @@ const DEFAULTS: AppSettings = {
monthlyReport: { enabled: false, day: 1, time: "08:00" },
inventory: { currency: "", pricePerKwh: null },
agents: { autoUpdate: false },
alertActions: { enabled: false },
selfBackup: { enabled: true, time: "03:30", keep: 14 },
profilePictures: { gravatar: false, identityProvider: false },
signIn: { roleFromGroups: false, groupsClaim: "groups", adminGroups: [], operatorGroups: [], otherwise: "viewer" },
+3 -1
View File
@@ -177,6 +177,8 @@ export interface PushMessage {
url?: string;
/** A later message with the same tag replaces an earlier one that is still showing. */
tag?: string;
/** Buttons on the notification: a press POSTs to `path` (a path in this app, so the browser's service worker sends it to the origin it runs on). At most two are shown by most browsers. */
actions?: { action: string; title: string; path: string }[];
}
/** Sends one message to one subscription. Resolves to what the push service said; never throws. */
@@ -212,7 +214,7 @@ export async function sendPush(message: PushMessage, only?: { id: number; endpoi
if (subs.length === 0) return outcome;
const keys = await getVapidKeys();
const subject = await vapidSubject();
const payload = Buffer.from(JSON.stringify({ title: message.title.slice(0, 120), body: message.body.slice(0, 600), url: message.url ?? "/alerts", tag: message.tag }));
const payload = Buffer.from(JSON.stringify({ title: message.title.slice(0, 120), body: message.body.slice(0, 600), url: message.url ?? "/alerts", tag: message.tag, ...(message.actions?.length ? { actions: message.actions.slice(0, 3) } : {}) }));
await Promise.all(
subs.map(async (s) => {
let body: Buffer;