Files
Homelab-manager/server/test/serviceWorker.test.ts
T
bobbanandClaude Sonnet 5.5 aebf3c6ce1 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>
2026-10-21 20:42:04 +02:00

84 lines
5.6 KiB
TypeScript

/**
* 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"]);
});