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
@@ -52,6 +52,7 @@ import { notesRouter, todosRouter } from "./routes/todos.js";
|
||||
import { npmRouter } from "./routes/npm.js";
|
||||
import { alertRulesRouter } from "./routes/alertRules.js";
|
||||
import { storageRouter } from "./routes/storage.js";
|
||||
import { alertActionsRouter } from "./routes/alertActions.js";
|
||||
import { homeAssistantRouter } from "./routes/homeAssistant.js";
|
||||
import { publicApiRouter } from "./routes/publicApi.js";
|
||||
import { generatorRouter } from "./routes/generator.js";
|
||||
@@ -92,6 +93,8 @@ export function createApp() {
|
||||
app.use("/api/heartbeat", heartbeatPingRouter);
|
||||
// The read API: a personal token in a header, GET only, no session and nothing for the same-origin check to protect.
|
||||
app.use("/api/v1", publicApiRouter);
|
||||
// What the buttons on a notification lead to: a signed token in the address, for named alerts only, no session.
|
||||
app.use("/api/alert-actions", alertActionsRouter);
|
||||
// Everything after this is reached with a session cookie, so a request that came from another origin is refused here.
|
||||
app.use(sameOriginGuard);
|
||||
app.use(express.json());
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import express, { Router, type Request, type Response } from "express";
|
||||
import { env } from "../env.js";
|
||||
import { loadAck } from "../services/alertAcks.js";
|
||||
import { ACTION_IDS, verifyToken, type ActionId } from "../services/alertActionLinks.js";
|
||||
import { currentAlertFor, performAction, SILENCE_MINUTES, tomorrowMorning } from "../services/alertActions.js";
|
||||
import { getSettings } from "../services/settingsStore.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
import { rateLimit } from "../utils/rateLimit.js";
|
||||
|
||||
/**
|
||||
* What the buttons on a notification lead to (services/alertActionLinks.ts says what they are and why they are safe enough). No session: the signed token in the address is the whole
|
||||
* of the access, and it is for the alerts in that one message only.
|
||||
*
|
||||
* GET /api/alert-actions/<token> a page that says what each button would do — opening it never does anything
|
||||
* POST /api/alert-actions/<token>/<ack|silence|snooze>[?key=<alert>] does it (the key is optional when the token is for one alert)
|
||||
*
|
||||
* A browser form gets a page back, anything else gets JSON.
|
||||
*/
|
||||
export const alertActionsRouter = Router();
|
||||
|
||||
const limiter = rateLimit({ windowMs: 60_000, max: 60, message: "Too many requests." });
|
||||
alertActionsRouter.use(limiter, (_req, res, next) => {
|
||||
// The address is the secret: nothing may carry it on to another site, and no copy of the answer is kept.
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("Referrer-Policy", "no-referrer");
|
||||
res.setHeader("X-Robots-Tag", "noindex, nofollow");
|
||||
next();
|
||||
});
|
||||
|
||||
const esc = (v: string) => v.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!);
|
||||
|
||||
const STYLE = `body{font-family:system-ui,-apple-system,sans-serif;max-width:34rem;margin:0 auto;padding:1rem;line-height:1.45;color:#1d273b;background:#f6f8fb}
|
||||
h1{font-size:1.25rem;margin:.5rem 0 1rem}.card{background:#fff;border:1px solid #dce1e7;border-radius:.5rem;padding:.9rem 1rem;margin-bottom:.9rem}
|
||||
.sev{font-size:.75rem;font-weight:600;text-transform:uppercase;letter-spacing:.04em}.critical{color:#c0392b}.warning{color:#b9770e}.info{color:#206bc4}
|
||||
.msg{font-weight:600;margin:.2rem 0 .6rem}.state{color:#667382;font-size:.9rem;margin-bottom:.6rem}form{display:inline-block;margin:0 .4rem .4rem 0}
|
||||
button{font:inherit;padding:.5rem .8rem;border-radius:.4rem;border:1px solid #206bc4;background:#206bc4;color:#fff;cursor:pointer}button.secondary{background:#fff;color:#206bc4}
|
||||
.small{color:#667382;font-size:.85rem}a{color:#206bc4}.ok{border-color:#2fb344}.bad{border-color:#d63939}`;
|
||||
|
||||
function page(res: Response, status: number, title: string, body: string) {
|
||||
res
|
||||
.status(status)
|
||||
.type("html")
|
||||
.send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${esc(title)}</title><style>${STYLE}</style></head><body><h1>${esc(title)}</h1>${body}<p class="small">Homelab Manager</p></body></html>`);
|
||||
}
|
||||
|
||||
const wantsHtml = (req: Request) => (req.get("accept") ?? "").includes("text/html") && (req.get("content-type") ?? "").includes("application/x-www-form-urlencoded");
|
||||
|
||||
alertActionsRouter.get("/:token", asyncHandler(async (req, res) => {
|
||||
const check = verifyToken(req.params.token);
|
||||
if (!check.ok) return page(res, check.reason === "expired" ? 410 : 404, check.reason === "expired" ? "This link has run out" : "Not found", check.reason === "expired" ? "<p>The buttons in a notification work for 24 hours. Open the Alerts page in Homelab Manager instead.</p>" : "<p>This link is not one this installation made.</p>");
|
||||
const settings = await getSettings();
|
||||
if (!settings.alertActions.enabled) return page(res, 404, "Switched off", "<p>Buttons in notifications are switched off in Homelab Manager.</p>");
|
||||
|
||||
const now = new Date();
|
||||
const tz = settings.notifications.timezone;
|
||||
const until = tomorrowMorning(now, tz);
|
||||
const untilText = new Intl.DateTimeFormat("en-GB", { timeZone: tz, weekday: "short", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(until);
|
||||
const base = env.appBaseUrl.replace(/\/+$/, "");
|
||||
let cards = "";
|
||||
for (const key of check.keys) {
|
||||
const alert = await currentAlertFor(key);
|
||||
if (!alert) {
|
||||
cards += `<div class="card"><div class="msg">${esc(key)}</div><div class="state">This alert isn't there any more — it has cleared.</div></div>`;
|
||||
continue;
|
||||
}
|
||||
const ack = await loadAck(alert.id, now);
|
||||
const state = alert.snoozed ? `Snoozed until ${esc(new Date(alert.snoozed.until).toISOString().slice(0, 16).replace("T", " "))} UTC.` : ack?.active ? `Acknowledged by ${esc(ack.ackedBy)}.` : alert.silenced ? "Held back (under maintenance, or folded under something that is down)." : "Nobody has acknowledged it.";
|
||||
const form = (action: ActionId, label: string, secondary = false) =>
|
||||
`<form method="post" action="/api/alert-actions/${esc(req.params.token)}/${action}"><input type="hidden" name="key" value="${esc(key)}"><button type="submit"${secondary ? ' class="secondary"' : ""}>${esc(label)}</button></form>`;
|
||||
cards += `<div class="card"><div class="sev ${esc(alert.severity)}">${esc(alert.severity)}</div><div class="msg">${esc(alert.message)}</div><div class="state">${state}</div>${form("ack", "Acknowledge")}${alert.target ? form("silence", `Silence for ${SILENCE_MINUTES === 60 ? "an hour" : `${SILENCE_MINUTES} min`}`, true) : ""}${form("snooze", `Snooze until ${untilText}`, true)}<div class="small"><a href="${esc(base + (alert.link ?? "/alerts"))}">Open in Homelab Manager</a></div></div>`;
|
||||
}
|
||||
page(res, 200, check.keys.length === 1 ? "What to do with this alert" : `What to do with these ${check.keys.length} alerts`, `${cards}<p class="small">Opening this page changed nothing; a button does. The buttons work until ${esc(check.expiresAt.toISOString().slice(0, 16).replace("T", " "))} UTC, for the alerts on this page only.</p>`);
|
||||
}));
|
||||
|
||||
alertActionsRouter.post("/:token/:action", express.urlencoded({ extended: false, limit: "2kb" }), asyncHandler(async (req, res) => {
|
||||
const html = wantsHtml(req);
|
||||
const fail = (status: number, error: string, message: string) => (html ? page(res, status, "Not done", `<div class="card bad"><p>${esc(message)}</p></div>`) : res.status(status).json({ error, message }));
|
||||
|
||||
const check = verifyToken(req.params.token);
|
||||
if (!check.ok) return check.reason === "expired" ? fail(410, "expired", "This link has run out. Open the Alerts page in Homelab Manager instead.") : fail(404, "not_found", "Not found.");
|
||||
const action = req.params.action as ActionId;
|
||||
if (!ACTION_IDS.includes(action)) return fail(404, "not_found", "Not found.");
|
||||
const asked = typeof req.query.key === "string" ? req.query.key : typeof req.body?.key === "string" ? req.body.key : null;
|
||||
const key = asked ?? (check.keys.length === 1 ? check.keys[0] : null);
|
||||
if (key === null || !check.keys.includes(key)) return fail(400, "invalid_key", "This link is not for that alert.");
|
||||
|
||||
const result = await performAction(action, key, { ip: req.ip });
|
||||
if (!html) return res.status(result.status).json({ ok: result.ok, message: result.message });
|
||||
page(res, result.status, result.ok ? "Done" : "Not done", `<div class="card ${result.ok ? "ok" : "bad"}"><p>${esc(result.message)}</p></div><p><a href="/api/alert-actions/${esc(req.params.token)}">Back to the alerts</a></p>`);
|
||||
}));
|
||||
@@ -162,6 +162,7 @@ const updateSchema = z.object({
|
||||
.partial()
|
||||
.optional(),
|
||||
profilePictures: z.object({ gravatar: z.boolean(), identityProvider: z.boolean() }).partial().optional(),
|
||||
alertActions: z.object({ enabled: z.boolean() }).partial().optional(),
|
||||
digest: z
|
||||
.object({ enabled: z.boolean(), day: z.number().int().min(0).max(6), time: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/) })
|
||||
.partial()
|
||||
|
||||
@@ -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}`;
|
||||
|
||||
@@ -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.` };
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
/**
|
||||
* Buttons on notifications: the signed links, what each does to an alert, the page and the addresses behind them, and what the channels send.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createServer, type IncomingMessage, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hm-actions-"));
|
||||
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";
|
||||
process.env.APP_BASE_URL = "https://hm.example.lan";
|
||||
|
||||
const express = (await import("express")).default;
|
||||
const { db } = await import("../src/db/client.js");
|
||||
const { servers, auditLog, maintenanceWindows, alertAcks, alertSnoozes } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const links = await import("../src/services/alertActionLinks.js");
|
||||
const { performAction, tomorrowMorning } = await import("../src/services/alertActions.js");
|
||||
const { updateSettings } = await import("../src/services/settingsStore.js");
|
||||
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
|
||||
const { notifyHealthIssues } = await import("../src/services/notify.js");
|
||||
const { alertActionsRouter } = await import("../src/routes/alertActions.js");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
after(() => {
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows may still hold the database file
|
||||
}
|
||||
});
|
||||
|
||||
const HOUR = 3600_000;
|
||||
|
||||
describe("the signed links", () => {
|
||||
const NOW = new Date("2026-10-20T12:00:00Z");
|
||||
|
||||
test("a token carries the alerts it is for and when it ends, and nothing else; it comes back as it went in", () => {
|
||||
const token = links.signToken(["offline:server:3", "disk:server:3:/"], NOW);
|
||||
const check = links.verifyToken(token, new Date(NOW.getTime() + HOUR));
|
||||
assert.ok(check.ok);
|
||||
if (check.ok) assert.deepEqual([check.keys, check.expiresAt.toISOString()], [["offline:server:3", "disk:server:3:/"], "2026-10-21T12:00:00.000Z"]);
|
||||
assert.deepEqual(JSON.parse(Buffer.from(token.split(".")[0], "base64url").toString()), { k: ["offline:server:3", "disk:server:3:/"], e: Date.parse("2026-10-21T12:00:00Z") / 1000 });
|
||||
});
|
||||
|
||||
test("it lasts 24 hours, not a minute more; one that has been tampered with, cut short or made by someone else is refused", () => {
|
||||
const token = links.signToken(["offline:server:3"], NOW);
|
||||
assert.ok(links.verifyToken(token, new Date(NOW.getTime() + 24 * HOUR - 1000)).ok);
|
||||
assert.deepEqual(links.verifyToken(token, new Date(NOW.getTime() + 24 * HOUR + 1000)), { ok: false, reason: "expired" });
|
||||
const [body, sig] = token.split(".");
|
||||
const forged = Buffer.from(JSON.stringify({ k: ["offline:server:9"], e: Date.parse("2030-01-01") / 1000 })).toString("base64url");
|
||||
assert.deepEqual(links.verifyToken(`${forged}.${sig}`, NOW), { ok: false, reason: "invalid" }, "another alert, a later end, the old signature");
|
||||
assert.deepEqual(links.verifyToken(`${body}.${sig.slice(0, -2)}AA`, NOW), { ok: false, reason: "invalid" });
|
||||
for (const junk of ["", "x", "a.b.c", `${body}.`, `.${sig}`, "not base64!.not base64!", "x".repeat(5000)]) assert.deepEqual(links.verifyToken(junk, NOW), { ok: false, reason: "invalid" }, junk.slice(0, 20));
|
||||
});
|
||||
|
||||
test("a token is for twenty alerts at most", () => {
|
||||
const check = links.verifyToken(links.signToken(Array.from({ length: 50 }, (_, i) => `offline:server:${i}`), NOW), NOW);
|
||||
assert.ok(check.ok && check.keys.length === links.MAX_KEYS);
|
||||
});
|
||||
|
||||
test("tomorrow at nine is by the clocks of the time zone, summer time and all", () => {
|
||||
assert.equal(tomorrowMorning(new Date("2026-10-20T12:00:00Z"), "UTC").toISOString(), "2026-10-21T09:00:00.000Z");
|
||||
assert.equal(tomorrowMorning(new Date("2026-10-20T12:00:00Z"), "Europe/Stockholm").toISOString(), "2026-10-21T07:00:00.000Z", "still summer time (UTC+2)");
|
||||
assert.equal(tomorrowMorning(new Date("2026-10-24T12:00:00Z"), "Europe/Stockholm").toISOString(), "2026-10-25T08:00:00.000Z", "the clocks go back that night: nine is UTC+1");
|
||||
assert.equal(tomorrowMorning(new Date("2026-03-28T12:00:00Z"), "Europe/Stockholm").toISOString(), "2026-03-29T07:00:00.000Z", "and forward that night");
|
||||
assert.equal(tomorrowMorning(new Date("2026-10-20T23:30:00Z"), "Europe/Stockholm").toISOString(), "2026-10-22T07:00:00.000Z", "half past one on the 21st there: tomorrow is the 22nd");
|
||||
assert.equal(tomorrowMorning(new Date("2026-10-20T12:00:00Z"), "America/New_York").toISOString(), "2026-10-21T13:00:00.000Z");
|
||||
assert.equal(tomorrowMorning(new Date("2026-10-20T12:00:00Z"), "Not/AZone").toISOString(), "2026-10-21T09:00:00.000Z", "an unknown zone is UTC");
|
||||
});
|
||||
});
|
||||
|
||||
describe("what a message carries", () => {
|
||||
test("off, it carries nothing; on, a message about one alert has its buttons, and one about several has a page", async () => {
|
||||
await updateSettings({ alertActions: { enabled: false } });
|
||||
assert.equal(await links.actionsFor(["offline:server:3"]), null);
|
||||
await updateSettings({ alertActions: { enabled: true } });
|
||||
assert.equal(await links.actionsFor([]), null);
|
||||
assert.equal(await links.actionsFor([undefined]), null);
|
||||
|
||||
const one = (await links.actionsFor(["offline:server:3"]))!;
|
||||
assert.deepEqual(one.direct.map((d) => [d.id, d.label]), [["ack", "Acknowledge"], ["silence", "Silence 1 h"], ["snooze", "Snooze"]]);
|
||||
assert.match(one.direct[0].url, /^https:\/\/hm\.example\.lan\/api\/alert-actions\/[\w-]+\.[\w-]+\/ack$/);
|
||||
assert.ok(one.pageUrl.startsWith("https://hm.example.lan/api/alert-actions/") && one.direct.every((d) => d.path.startsWith("/api/alert-actions/")));
|
||||
assert.deepEqual((await links.actionsFor(["endpoint:5"]))!.direct.map((d) => d.id), ["ack", "snooze"], "nothing to silence an endpoint check with");
|
||||
|
||||
const several = (await links.actionsFor(["offline:server:3", "disk:server:4:/", "offline:server:3"]))!;
|
||||
assert.deepEqual([several.count, several.direct.length], [2, 0], "the same alert twice is one");
|
||||
});
|
||||
|
||||
test("ntfy gets buttons for one alert and a single link for several; the other channels get the link as text", async () => {
|
||||
const one = (await links.actionsFor(["offline:server:3"]))!;
|
||||
const header = links.ntfyActionsHeader(one);
|
||||
assert.equal(header.split("; ").length, 3, "ntfy allows three");
|
||||
assert.match(header, /^http, Acknowledge, https:\/\/hm\.example\.lan\/api\/alert-actions\/[^,]+\/ack, method=POST, clear=true; http, Silence 1 h, /);
|
||||
assert.ok(/^[ -~]*$/.test(header), "a header is plain ASCII");
|
||||
const several = (await links.actionsFor(["offline:server:3", "offline:server:4"]))!;
|
||||
assert.match(links.ntfyActionsHeader(several), /^view, Choose what to do, https:\/\/hm\.example\.lan\/api\/alert-actions\//);
|
||||
assert.match(links.footerText(one), /\n\nAcknowledge, silence or snooze: https:\/\/hm\.example\.lan\/api\/alert-actions\//);
|
||||
});
|
||||
});
|
||||
|
||||
describe("doing it", () => {
|
||||
let serverId = 0;
|
||||
let key = "";
|
||||
|
||||
before(async () => {
|
||||
const [s] = await db.insert(servers).values({ name: "web", apiTokenHash: "h", apiTokenPrefix: "p", lastSeenAt: new Date(Date.now() - 3 * HOUR).toISOString(), ipAddresses: "[]" }).returning();
|
||||
serverId = s.id;
|
||||
key = `offline:server:${s.id}`;
|
||||
await updateSettings({ alertActions: { enabled: true }, notifications: { timezone: "Europe/Stockholm" } });
|
||||
invalidateAlertsCache();
|
||||
});
|
||||
|
||||
test("acknowledging marks the alert as acknowledged by the link, is written down with where it came from, and is not done twice", async () => {
|
||||
const res = await performAction("ack", key, { ip: "10.0.0.7" });
|
||||
assert.deepEqual([res.ok, res.status, res.message], [true, 200, "Acknowledged."]);
|
||||
const [ack] = await db.select().from(alertAcks);
|
||||
assert.deepEqual([ack.alertKey, ack.ackedBy, ack.note, ack.until], [`offline:${key}`, "a notification link", "Acknowledged from a notification", null]);
|
||||
const [entry] = await db.select().from(auditLog).where(eq(auditLog.action, "ack"));
|
||||
const detail = JSON.parse(entry.detail!);
|
||||
assert.deepEqual([entry.category, entry.targetType, entry.targetId, detail.via, detail.ip], ["alert", "server", String(serverId), "a notification link", "10.0.0.7"]);
|
||||
const again = await performAction("ack", key, {});
|
||||
assert.deepEqual([again.ok, again.message], [true, "Already acknowledged by a notification link."]);
|
||||
assert.equal((await db.select().from(alertAcks)).length, 1);
|
||||
});
|
||||
|
||||
test("silencing starts an hour of maintenance on what the alert is about, and the alert is then held back", async () => {
|
||||
const res = await performAction("silence", key, { ip: "10.0.0.7" });
|
||||
assert.deepEqual([res.ok, res.message], [true, "Silenced for an hour: web."]);
|
||||
const [w] = await db.select().from(maintenanceWindows).where(eq(maintenanceWindows.targetId, serverId));
|
||||
assert.deepEqual([w.targetType, w.reason, w.createdBy], ["server", "Silenced from a notification", "a notification link"]);
|
||||
assert.ok(Math.abs(Date.parse(w.endsAt) - Date.parse(w.startedAt) - HOUR) < 2000);
|
||||
invalidateAlertsCache();
|
||||
assert.equal((await getAlerts(true)).alerts.find((a) => a.id === `offline:${key}`)!.silenced, true);
|
||||
const [entry] = await db.select().from(auditLog).where(eq(auditLog.category, "maintenance"));
|
||||
assert.equal(JSON.parse(entry.detail!).via, "a notification link");
|
||||
await db.delete(maintenanceWindows).where(eq(maintenanceWindows.targetId, serverId));
|
||||
invalidateAlertsCache();
|
||||
});
|
||||
|
||||
test("snoozing hides the alert until tomorrow at nine in the notification time zone", async () => {
|
||||
const now = new Date();
|
||||
const res = await performAction("snooze", key, {}, now);
|
||||
assert.equal(res.ok, true);
|
||||
const [s] = await db.select().from(alertSnoozes);
|
||||
assert.equal(s.until, tomorrowMorning(now, "Europe/Stockholm").toISOString());
|
||||
assert.equal(s.snoozedBy, "a notification link");
|
||||
invalidateAlertsCache();
|
||||
const alert = (await getAlerts(true)).alerts.find((a) => a.id === `offline:${key}`)!;
|
||||
assert.deepEqual([alert.silenced, alert.snoozed?.until], [true, s.until]);
|
||||
await db.delete(alertSnoozes);
|
||||
});
|
||||
|
||||
test("an alert that has cleared says so; switched off, nothing works; an unknown action is not one", async () => {
|
||||
assert.deepEqual(await performAction("ack", "offline:server:99999", {}), { ok: false, status: 404, message: "That alert isn't there any more — it has cleared." });
|
||||
await updateSettings({ alertActions: { enabled: false } });
|
||||
assert.deepEqual(await performAction("ack", key, {}), { ok: false, status: 404, message: "Buttons in notifications are switched off." });
|
||||
await updateSettings({ alertActions: { enabled: true } });
|
||||
});
|
||||
|
||||
describe("the addresses", () => {
|
||||
let app: Server;
|
||||
let base = "";
|
||||
before(async () => {
|
||||
const a = express();
|
||||
a.use("/api/alert-actions", alertActionsRouter);
|
||||
app = await new Promise<Server>((resolve) => {
|
||||
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/alert-actions`;
|
||||
});
|
||||
after(() => app.close());
|
||||
|
||||
const post = (path: string, body?: string, headers: Record<string, string> = {}) => fetch(`${base}${path}`, { method: "POST", headers: { connection: "close", ...headers }, body });
|
||||
|
||||
test("opening the page shows the alert and its buttons and changes nothing; the answer is not kept or passed on", async () => {
|
||||
await db.delete(alertAcks);
|
||||
invalidateAlertsCache();
|
||||
const token = links.signToken([key]);
|
||||
const res = await fetch(`${base}/${token}`, { headers: { connection: "close" } });
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual([res.headers.get("cache-control"), res.headers.get("referrer-policy"), res.headers.get("x-robots-tag")], ["no-store", "no-referrer", "noindex, nofollow"]);
|
||||
const html = await res.text();
|
||||
assert.match(html, /web hasn('|')t reported for/);
|
||||
assert.match(html, /<form method="post" action="\/api\/alert-actions\/[^"]+\/ack">/);
|
||||
assert.match(html, /Silence for an hour/);
|
||||
assert.match(html, /Snooze until \w{3} 09:00/, "in the notification zone");
|
||||
assert.match(html, /Opening this page changed nothing/);
|
||||
assert.equal((await db.select().from(alertAcks)).length, 0, "opening it did nothing");
|
||||
assert.ok(!html.includes("<script"), "no script at all");
|
||||
});
|
||||
|
||||
test("a browser form acts and gets a page; anything else gets JSON; one alert's link does not do another", async () => {
|
||||
const token = links.signToken([key, "offline:server:99999"]);
|
||||
const form = await post(`/${token}/ack`, `key=${encodeURIComponent(key)}`, { "content-type": "application/x-www-form-urlencoded", accept: "text/html" });
|
||||
assert.equal(form.status, 200);
|
||||
assert.match(await form.text(), /Done<\/h1>[\s\S]*Acknowledged\./);
|
||||
assert.equal((await db.select().from(alertAcks)).length, 1);
|
||||
|
||||
const json = await post(`/${token}/snooze?key=${encodeURIComponent(key)}`);
|
||||
assert.deepEqual([json.status, ((await json.json()) as any).ok], [200, true]);
|
||||
await db.delete(alertSnoozes);
|
||||
invalidateAlertsCache();
|
||||
|
||||
const gone = await post(`/${token}/ack?key=${encodeURIComponent("offline:server:99999")}`);
|
||||
assert.equal(gone.status, 404, "a key in the token, but that alert has cleared");
|
||||
const other = await post(`/${token}/ack?key=${encodeURIComponent("offline:server:777")}`);
|
||||
assert.equal(other.status, 400, "a key that is not in the token");
|
||||
const unnamed = await post(`/${token}/ack`);
|
||||
assert.equal(unnamed.status, 400, "two alerts and no way to know which");
|
||||
});
|
||||
|
||||
test("a link for one alert needs no key; an unknown action, a forged or ended link and a switched-off setting are refused", async () => {
|
||||
const single = links.signToken([key]);
|
||||
assert.equal((await post(`/${single}/ack`)).status, 200);
|
||||
assert.equal((await post(`/${single}/delete`)).status, 404);
|
||||
assert.equal((await post(`/${single.slice(0, -3)}abc/ack`)).status, 404);
|
||||
const old = links.signToken([key], new Date(Date.now() - 25 * HOUR));
|
||||
const ended = await post(`/${old}/ack`);
|
||||
assert.equal(ended.status, 410);
|
||||
assert.match(((await ended.json()) as any).message, /run out/);
|
||||
assert.equal((await fetch(`${base}/${old}`, { headers: { connection: "close" } })).status, 410);
|
||||
assert.equal((await fetch(`${base}/not-a-token`, { headers: { connection: "close" } })).status, 404);
|
||||
await updateSettings({ alertActions: { enabled: false } });
|
||||
assert.equal((await post(`/${single}/ack`)).status, 404);
|
||||
assert.equal((await fetch(`${base}/${single}`, { headers: { connection: "close" } })).status, 404);
|
||||
await updateSettings({ alertActions: { enabled: true } });
|
||||
});
|
||||
|
||||
test("a message carrying text from an alert cannot put markup in the page", async () => {
|
||||
const [s] = await db.insert(servers).values({ name: "<img src=x onerror=alert(1)>", apiTokenHash: "h2", apiTokenPrefix: "q", lastSeenAt: new Date(Date.now() - 3 * HOUR).toISOString(), ipAddresses: "[]" }).returning();
|
||||
invalidateAlertsCache();
|
||||
const html = await (await fetch(`${base}/${links.signToken([`offline:server:${s.id}`])}`, { headers: { connection: "close" } })).text();
|
||||
assert.ok(!html.includes("<img src=x"), "escaped");
|
||||
assert.match(html, /<img src=x onerror=alert\(1\)>/);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("what the channels send", () => {
|
||||
let ntfy: Server;
|
||||
let gotify: Server;
|
||||
const ntfyGot: { headers: IncomingMessage["headers"]; body: string }[] = [];
|
||||
const gotifyGot: any[] = [];
|
||||
|
||||
before(async () => {
|
||||
const listen = (handler: (req: IncomingMessage, body: string) => void) =>
|
||||
new Promise<Server>((resolve) => {
|
||||
const s = createServer((req, res) => {
|
||||
let b = "";
|
||||
req.on("data", (c) => (b += c));
|
||||
req.on("end", () => {
|
||||
handler(req, b);
|
||||
res.end("{}");
|
||||
});
|
||||
}).listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
ntfy = await listen((req, body) => ntfyGot.push({ headers: req.headers, body }));
|
||||
gotify = await listen((_req, body) => gotifyGot.push(JSON.parse(body)));
|
||||
await updateSettings({
|
||||
ntfy: { enabled: true, url: `http://127.0.0.1:${(ntfy.address() as AddressInfo).port}`, topic: "homelab", token: "", priority: 3 },
|
||||
gotify: { enabled: true, url: `http://127.0.0.1:${(gotify.address() as AddressInfo).port}`, token: "tok", priority: 5 },
|
||||
alertActions: { enabled: true },
|
||||
});
|
||||
});
|
||||
after(() => {
|
||||
ntfy.close();
|
||||
gotify.close();
|
||||
});
|
||||
|
||||
const issue = (n: number) => ({ key: `offline:server:${n}`, message: `server ${n} hasn't reported for 2 h`, severity: "critical" });
|
||||
|
||||
test("one alert: ntfy has three buttons and a tap that opens the page; Gotify has a tap and the link in its text", async () => {
|
||||
await notifyHealthIssues([issue(11)]);
|
||||
const sent = ntfyGot.at(-1)!;
|
||||
const actions = String(sent.headers.actions);
|
||||
assert.equal(actions.split("; ").length, 3);
|
||||
assert.match(actions, /^http, Acknowledge, https:\/\/hm\.example\.lan\/api\/alert-actions\/[^,]+\/ack, method=POST, clear=true/);
|
||||
assert.match(String(sent.headers.click), /^https:\/\/hm\.example\.lan\/api\/alert-actions\//);
|
||||
assert.match(sent.body, /server 11 hasn't reported/);
|
||||
const g = gotifyGot.at(-1);
|
||||
assert.match(g.message, /Acknowledge, silence or snooze: https:\/\/hm\.example\.lan\/api\/alert-actions\//);
|
||||
assert.equal(g.extras["client::notification"].click.url, String(sent.headers.click));
|
||||
});
|
||||
|
||||
test("several alerts: ntfy has one button to the page, and the page lists them", async () => {
|
||||
await notifyHealthIssues([issue(12), issue(13)]);
|
||||
const sent = ntfyGot.at(-1)!;
|
||||
assert.match(String(sent.headers.actions), /^view, Choose what to do, https:\/\/hm\.example\.lan\/api\/alert-actions\/[^,]+$/);
|
||||
const page = String(sent.headers.click).replace("https://hm.example.lan", "");
|
||||
const check = links.verifyToken(page.split("/").pop()!);
|
||||
assert.ok(check.ok && check.keys.join() === "offline:server:12,offline:server:13");
|
||||
});
|
||||
|
||||
test("switched off, there are no buttons, no links and no extras", async () => {
|
||||
await updateSettings({ alertActions: { enabled: false } });
|
||||
await notifyHealthIssues([issue(14)]);
|
||||
const sent = ntfyGot.at(-1)!;
|
||||
assert.deepEqual([sent.headers.actions, sent.headers.click], [undefined, undefined]);
|
||||
const g = gotifyGot.at(-1);
|
||||
assert.ok(!g.message.includes("alert-actions") && g.extras === undefined);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* The browser's service worker (web/public/sw.js): shows a push with its buttons, and a press on one sends that alert's own address and says how it went. It is run here against a
|
||||
* stand-in for the browser's worker scope, since there is no browser to push to.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import vm from "node:vm";
|
||||
|
||||
const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "..", "web", "public", "sw.js"), "utf8");
|
||||
|
||||
function load(fetchImpl: (url: string, init: any) => Promise<any> = async () => ({ ok: true, json: async () => ({ ok: true, message: "Acknowledged." }) })) {
|
||||
const handlers: Record<string, (e: any) => void> = {};
|
||||
const shown: { title: string; options: any }[] = [];
|
||||
const fetched: { url: string; init: any }[] = [];
|
||||
const opened: string[] = [];
|
||||
const scope: any = {
|
||||
addEventListener: (type: string, fn: (e: any) => void) => (handlers[type] = fn),
|
||||
skipWaiting: () => undefined,
|
||||
clients: { claim: () => undefined, matchAll: async () => [], openWindow: async (url: string) => opened.push(url) },
|
||||
location: { origin: "https://hm.example.lan" },
|
||||
registration: { showNotification: async (title: string, options: any) => shown.push({ title, options }) },
|
||||
};
|
||||
scope.self = scope;
|
||||
scope.URL = URL;
|
||||
scope.fetch = (url: string, init: any) => {
|
||||
fetched.push({ url, init });
|
||||
return fetchImpl(url, init);
|
||||
};
|
||||
vm.runInNewContext(source, scope);
|
||||
const run = async (type: string, event: any) => {
|
||||
const waits: Promise<unknown>[] = [];
|
||||
handlers[type]({ ...event, waitUntil: (p: Promise<unknown>) => waits.push(p) });
|
||||
await Promise.all(waits);
|
||||
};
|
||||
return { run, shown, fetched, opened };
|
||||
}
|
||||
|
||||
const plain = <T>(v: T): T => JSON.parse(JSON.stringify(v)); // objects made inside the worker scope have their own prototypes
|
||||
const push = (payload: unknown) => ({ data: { json: () => payload, text: () => "" } });
|
||||
|
||||
test("a push for one alert shows its buttons, and a plain one shows none", async () => {
|
||||
const sw = load();
|
||||
await sw.run("push", push({ title: "Health alert", body: "web is down", actions: [{ action: "ack", title: "Acknowledge", path: "/api/alert-actions/T/ack" }, { action: "silence", title: "Silence 1 h", path: "/api/alert-actions/T/silence" }] }));
|
||||
assert.deepEqual(plain(sw.shown[0].options.actions), [{ action: "ack", title: "Acknowledge" }, { action: "silence", title: "Silence 1 h" }], "the browser is told the labels only");
|
||||
assert.equal(sw.shown[0].options.data.actions[0].path, "/api/alert-actions/T/ack", "the addresses are kept for the press");
|
||||
await sw.run("push", push({ title: "Plain", body: "x" }));
|
||||
assert.deepEqual(plain(sw.shown[1].options.actions), []);
|
||||
await sw.run("push", push({ title: "Odd", body: "x", actions: ["nonsense", { action: 1 }, null] }));
|
||||
assert.deepEqual(plain(sw.shown[2].options.actions), [], "malformed buttons are dropped");
|
||||
});
|
||||
|
||||
test("pressing a button POSTs that alert's address with no cookies, and says how it went", async () => {
|
||||
const sw = load();
|
||||
await sw.run("notificationclick", { action: "ack", notification: { close: () => undefined, data: { url: "/alerts", actions: [{ action: "ack", title: "Acknowledge", path: "/api/alert-actions/T/ack" }] } } });
|
||||
assert.deepEqual([sw.fetched[0].url, sw.fetched[0].init.method, sw.fetched[0].init.credentials], ["/api/alert-actions/T/ack", "POST", "omit"]);
|
||||
assert.deepEqual([sw.shown[0].title, sw.shown[0].options.body], ["Acknowledge: done", "Acknowledged."]);
|
||||
assert.deepEqual(plain(sw.opened), [], "the app is not opened");
|
||||
});
|
||||
|
||||
test("a button that did not work says so; one that cannot reach the app says that", async () => {
|
||||
const refused = load(async () => ({ ok: false, json: async () => ({ message: "That alert isn't there any more — it has cleared." }) }));
|
||||
await refused.run("notificationclick", { action: "ack", notification: { close: () => undefined, data: { actions: [{ action: "ack", title: "Acknowledge", path: "/api/alert-actions/T/ack" }] } } });
|
||||
assert.deepEqual([refused.shown[0].title, refused.shown[0].options.body], ["Not done", "That alert isn't there any more — it has cleared."]);
|
||||
const down = load(async () => {
|
||||
throw new Error("offline");
|
||||
});
|
||||
await down.run("notificationclick", { action: "ack", notification: { close: () => undefined, data: { actions: [{ action: "ack", title: "Acknowledge", path: "/api/alert-actions/T/ack" }] } } });
|
||||
assert.deepEqual([down.shown[0].title, down.shown[0].options.body], ["Not done", "Couldn't reach Homelab Manager."]);
|
||||
});
|
||||
|
||||
test("only an address under /api/alert-actions can be sent; a press on anything else, or a tap, opens the app", async () => {
|
||||
const sw = load();
|
||||
await sw.run("notificationclick", { action: "evil", notification: { close: () => undefined, data: { url: "/alerts", actions: [{ action: "evil", title: "Hm", path: "/api/servers/1" }, { action: "abs", title: "Hm", path: "https://evil.example/x" }] } } });
|
||||
await sw.run("notificationclick", { action: "abs", notification: { close: () => undefined, data: { url: "/alerts", actions: [{ action: "abs", title: "Hm", path: "https://evil.example/x" }] } } });
|
||||
assert.deepEqual(plain(sw.fetched), [], "nothing else is ever fetched");
|
||||
await sw.run("notificationclick", { action: "", notification: { close: () => undefined, data: { url: "/alerts", actions: [] } } });
|
||||
assert.deepEqual(plain(sw.opened), ["https://hm.example.lan/alerts", "https://hm.example.lan/alerts", "https://hm.example.lan/alerts"]);
|
||||
});
|
||||
Reference in new issue
Block a user