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
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user