Files
Homelab-manager/server/test/routingAndEscalation.test.ts
T
bobbanandClaude Sonnet 5.5 73a06ebe63 Flapping alerts, a noise report and bulk actions with undo
Flapping: an alert raised three times within an hour is announced once as
flapping, its further raise/clear messages are held until it has been calm
for an hour, and one message then says whether it is still active. Event
webhooks still hear everything. The state survives restarts.

Alerts > Noise lists the alerts that keep coming back (7-180 days): how often,
how long, most in an hour, and a hint on what helps.

Bulk actions on Alerts (acknowledge, remove acknowledgement, silence), Servers
(tag, silence, runs on) and Inventory (location and dates, print labels). Each
reports what it left alone and why, and has an Undo on the toast.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-19 23:55:09 +02:00

453 lines
26 KiB
TypeScript

/**
* Who hears what (routing rules and browsers' wishes) and escalation of alerts nobody has acknowledged.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer, type Server } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
const dir = mkdtempSync(join(tmpdir(), "hm-routing-"));
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";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, pushSubscriptions, alertIncidents, auditLog, notificationQueue } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { ruleMatches, firstMatchingRule, pushAccepts, metaOfConditionKey } = await import("../src/services/notifyRouting.js");
const { dueEscalations, runEscalation } = await import("../src/services/escalation.js");
const { audienceFor, notifyHealthIssues, notifyHealthRecovered, flushQuietHoursQueue, notify } = await import("../src/services/notify.js");
const { updateSettings } = await import("../src/services/settingsStore.js");
const { diffConditions } = await import("../src/services/healthMonitor.js");
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
const { setAck } = await import("../src/services/alertAcks.js");
const { settingsRouter } = await import("../src/routes/settings.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
type Rule = import("../src/services/notifyRouting.js").RoutingRule;
const rule = (extra: Partial<Rule>): Rule => ({ id: "r", name: "rule", enabled: true, categories: [], minSeverity: null, tags: [], channels: [], ...extra });
describe("routing rules", () => {
test("a rule matches on kind, severity and the server's tags; asking about something the notification doesn't say never matches", () => {
assert.equal(ruleMatches(rule({}), {}), true, "a rule that asks nothing matches everything");
assert.equal(ruleMatches(rule({ categories: ["disk"] }), { category: "disk" }), true);
assert.equal(ruleMatches(rule({ categories: ["disk"] }), { category: "offline" }), false);
assert.equal(ruleMatches(rule({ categories: ["disk"] }), {}), false, "no kind to compare");
assert.equal(ruleMatches(rule({ minSeverity: "critical" }), { severity: "warning" }), false);
assert.equal(ruleMatches(rule({ minSeverity: "critical" }), { severity: "critical" }), true);
assert.equal(ruleMatches(rule({ minSeverity: "warning" }), { severity: "critical" }), true);
assert.equal(ruleMatches(rule({ tags: ["prod"] }), { tags: ["Prod", "db"] }), true, "tags compare without regard to case");
assert.equal(ruleMatches(rule({ tags: ["prod"] }), { tags: ["lab"] }), false);
assert.equal(ruleMatches(rule({ tags: ["prod"] }), {}), false);
assert.equal(ruleMatches(rule({ enabled: false }), {}), false);
});
test("the first rule that matches decides; none matching is no decision", () => {
const rules = [rule({ id: "a", categories: ["disk"], channels: ["ntfy"] }), rule({ id: "b", minSeverity: "critical", channels: ["gotify", "webPush"] }), rule({ id: "c", channels: [] })];
assert.equal(firstMatchingRule(rules, { category: "disk", severity: "critical" })!.id, "a", "order matters");
assert.equal(firstMatchingRule(rules, { category: "offline", severity: "critical" })!.id, "b");
assert.equal(firstMatchingRule(rules, { category: "offline", severity: "warning" })!.id, "c");
assert.equal(firstMatchingRule([rules[0]], { category: "offline" }), null);
});
test("a problem's key says what kind it is and which server", () => {
assert.deepEqual(metaOfConditionKey("offline:server:7", "critical"), { category: "offline", severity: "critical", serverId: 7 });
assert.deepEqual(metaOfConditionKey("disk:server:7:/data"), { category: "disk", severity: "warning", serverId: 7 });
assert.deepEqual(metaOfConditionKey("failed-units:server:2"), { category: "services", severity: "warning", serverId: 2 });
assert.deepEqual(metaOfConditionKey("disk:proxmox:3:local"), { category: "disk", severity: "warning", serverId: null });
assert.deepEqual(metaOfConditionKey("automation:semaphore:1:5"), { category: "automation", severity: "warning", serverId: null });
});
test("a browser's wishes: a floor on severity and a list of kinds; what a notification doesn't say can't exclude it", () => {
assert.equal(pushAccepts({ minSeverity: null, categories: null }, { category: "disk", severity: "warning" }), true);
assert.equal(pushAccepts({ minSeverity: "critical", categories: null }, { severity: "warning" }), false);
assert.equal(pushAccepts({ minSeverity: "critical", categories: null }, { severity: "critical" }), true);
assert.equal(pushAccepts({ minSeverity: null, categories: JSON.stringify(["offline", "disk"]) }, { category: "backup" }), false);
assert.equal(pushAccepts({ minSeverity: null, categories: JSON.stringify(["offline", "disk"]) }, { category: "disk" }), true);
assert.equal(pushAccepts({ minSeverity: "critical", categories: JSON.stringify(["disk"]) }, undefined), true, "no meta, no judgement");
assert.equal(pushAccepts({ minSeverity: null, categories: JSON.stringify(["disk"]) }, { severity: "warning" }), true, "no kind, no judgement");
assert.equal(pushAccepts({ minSeverity: null, categories: "garbage" }, { category: "backup" }), true, "unreadable wishes are no wishes");
});
});
describe("what the health monitor remembers", () => {
test("a recovery carries how bad the problem was, so it is routed like the alert was", () => {
const first = diffConditions({}, [
{ key: "offline:server:1", source: "server", message: "a is down", severity: "critical" },
{ key: "disk:server:1:/", source: "server", message: "a disk" },
]);
assert.equal(first.next["offline:server:1"].severity, "critical");
assert.equal(first.next["disk:server:1:/"].severity, undefined);
const gone = diffConditions(first.next, []);
assert.deepEqual(gone.resolved.map((r) => [r.key, r.severity]).sort(), [["disk:server:1:/", undefined], ["offline:server:1", "critical"]]);
});
});
describe("escalation: what is due", () => {
const steps = [
{ afterMinutes: 30, minSeverity: "warning" as const, channels: ["webPush" as const], extraEmail: "", evenInQuietHours: false },
{ afterMinutes: 120, minSeverity: "critical" as const, channels: ["smtp" as const], extraEmail: "neighbour@example.com", evenInQuietHours: true },
];
const now = new Date("2026-10-18T12:00:00Z");
const ago = (min: number) => new Date(now.getTime() - min * 60_000).toISOString();
const alert = (id: string, severity: "critical" | "warning" | "info", extra: Record<string, unknown> = {}) => ({ id, severity, silenced: false, message: id, source: "Server", ...extra });
const run = (alerts: ReturnType<typeof alert>[], incidents: Record<string, { openedAt: string; escalatedStep?: number }>, acknowledged: string[] = []) =>
dueEscalations({
alerts,
acknowledged: new Set(acknowledged),
incidents: new Map(Object.entries(incidents).map(([k, v], i) => [k, { id: i + 1, openedAt: v.openedAt, escalatedStep: v.escalatedStep ?? 0 }])),
steps,
now,
}).map((d) => [d.alert.id, d.step]);
test("a step is due once the alert has been up that long; nothing before", () => {
assert.deepEqual(run([alert("a", "warning")], { a: { openedAt: ago(29) } }), []);
assert.deepEqual(run([alert("a", "warning")], { a: { openedAt: ago(31) } }), [["a", 1]]);
});
test("a step is sent once, and a neglected alert is told about one step at a time", () => {
assert.deepEqual(run([alert("a", "critical")], { a: { openedAt: ago(200), escalatedStep: 0 } }), [["a", 1]], "step 1 first, though step 2 is due too");
assert.deepEqual(run([alert("a", "critical")], { a: { openedAt: ago(200), escalatedStep: 1 } }), [["a", 2]]);
assert.deepEqual(run([alert("a", "critical")], { a: { openedAt: ago(200), escalatedStep: 2 } }), []);
});
test("a step that asks for a worse severity is passed over, and later ones still apply", () => {
// a warning is never bad enough for step 2, so it ends after step 1
assert.deepEqual(run([alert("w", "warning")], { w: { openedAt: ago(500), escalatedStep: 1 } }), []);
const critOnlyFirst = [{ ...steps[0], minSeverity: "critical" as const }, { ...steps[1], minSeverity: "warning" as const }];
const due = dueEscalations({ alerts: [alert("w", "warning")], acknowledged: new Set(), incidents: new Map([["w", { id: 1, openedAt: ago(500), escalatedStep: 0 }]]), steps: critOnlyFirst, now });
assert.deepEqual(due.map((d) => d.step), [2], "step 1 wasn't for it, step 2 was");
});
test("an acknowledgement stops it; so do maintenance, being held back by another alert, and info", () => {
assert.deepEqual(run([alert("a", "critical")], { a: { openedAt: ago(200) } }, ["a"]), []);
assert.deepEqual(run([alert("a", "critical", { silenced: true })], { a: { openedAt: ago(200) } }), []);
assert.deepEqual(run([alert("a", "info")], { a: { openedAt: ago(200) } }), []);
assert.deepEqual(run([alert("a", "critical")], {}), [], "no incident recorded yet, nothing to measure from");
});
});
describe("through the channels", () => {
type Hit = { path: string; body: string };
const hits: Record<"gotify" | "ntfy" | "webhook", Hit[]> = { gotify: [], ntfy: [], webhook: [] };
const fake: Server[] = [];
const base: Record<string, string> = {};
let proddy = 0;
const text = (h: Hit) => {
try {
const j = JSON.parse(h.body);
return String(j.message ?? j.content ?? h.body);
} catch {
return h.body;
}
};
const clear = () => {
for (const k of Object.keys(hits) as (keyof typeof hits)[]) hits[k].length = 0;
};
before(async () => {
for (const name of ["gotify", "ntfy", "webhook"] as const) {
const s = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
hits[name].push({ path: req.url ?? "", body: Buffer.concat(chunks).toString() });
res.statusCode = 200;
res.end("{}");
});
});
await new Promise<void>((r) => s.listen(0, "127.0.0.1", r));
fake.push(s);
base[name] = `http://127.0.0.1:${(s.address() as AddressInfo).port}`;
}
await updateSettings({
gotify: { enabled: true, url: base.gotify, token: "g" },
ntfy: { enabled: true, url: base.ntfy, topic: "lab" },
webhook: { enabled: true, url: base.webhook },
// These tests raise the same problem again and again as fixtures; they are about routing, not about flapping.
healthChecks: { flapRaises: 0 },
});
proddy = (await db.insert(servers).values({ name: "prod-db", apiTokenHash: "p", apiTokenPrefix: "p", tags: JSON.stringify(["prod"]) }).returning({ id: servers.id }))[0].id;
});
after(() => {
for (const s of fake) s.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const offline = (id: number) => ({ key: `offline:server:${id}`, message: `server ${id} is offline`, severity: "critical" });
const disk = (id: number) => ({ key: `disk:server:${id}:/`, message: `disk on ${id} is full`, severity: "warning" });
test("with no rules everything goes everywhere, in one message, as it always did", async () => {
clear();
await notifyHealthIssues([offline(proddy), disk(proddy)]);
for (const k of ["gotify", "ntfy", "webhook"] as const) {
assert.equal(hits[k].length, 1, k);
assert.match(text(hits[k][0]), /2 new issues/);
}
});
test("a rule sends one kind to one channel; the rest still goes everywhere, as a message of its own", async () => {
await updateSettings({ routing: { rules: [rule({ id: "d", name: "Disks to ntfy", categories: ["disk"], channels: ["ntfy"] })] } });
clear();
await notifyHealthIssues([offline(proddy), disk(proddy)]);
assert.equal(hits.gotify.length, 1);
assert.match(text(hits.gotify[0]), /1 new issue:[\s\S]*is offline/);
assert.doesNotMatch(text(hits.gotify[0]), /disk/);
assert.equal(hits.webhook.length, 1);
assert.equal(hits.ntfy.length, 2, "its own message for the disk, and the offline one with the rest");
assert.ok(hits.ntfy.some((h) => /disk on/.test(text(h)) && !/offline/.test(text(h))));
});
test("a rule can mute: nobody is told, and nothing is queued", async () => {
await updateSettings({ routing: { rules: [rule({ id: "m", name: "Prod disks: nobody", categories: ["disk"], tags: ["prod"], channels: [] })] } });
clear();
await notifyHealthIssues([disk(proddy)]);
assert.deepEqual([hits.gotify.length, hits.ntfy.length, hits.webhook.length], [0, 0, 0]);
// the same disk problem on a server without the tag is not muted
const plain = (await db.insert(servers).values({ name: "plain", apiTokenHash: "q", apiTokenPrefix: "q" }).returning({ id: servers.id }))[0].id;
await notifyHealthIssues([disk(plain)]);
assert.equal(hits.gotify.length, 1);
});
test("a recovery follows the route its alert took", async () => {
await updateSettings({ routing: { rules: [rule({ id: "c", name: "Critical to webhook", minSeverity: "critical", channels: ["webhook"] })] } });
clear();
await notifyHealthRecovered([{ key: `offline:server:${proddy}`, message: "back", severity: "critical" }]);
assert.deepEqual([hits.gotify.length, hits.ntfy.length, hits.webhook.length], [0, 0, 1]);
clear();
await notifyHealthRecovered([{ key: `disk:server:${proddy}:/`, message: "ok", severity: "warning" }]);
assert.deepEqual([hits.gotify.length, hits.ntfy.length, hits.webhook.length], [1, 1, 1], "a warning isn't covered by that rule, so it goes everywhere");
});
test("a rule that is switched off does nothing", async () => {
await updateSettings({ routing: { rules: [rule({ id: "x", enabled: false, channels: [] })] } });
clear();
await notifyHealthIssues([offline(proddy)]);
assert.equal(hits.webhook.length, 1);
});
test("held for quiet hours, a notification is still only for the channels its rule picked", async () => {
await updateSettings({ routing: { rules: [rule({ id: "q", categories: ["backup"], channels: ["ntfy"] })] }, quietHours: { enabled: true, start: "00:00", end: "23:59" } });
clear();
await notify("Backups", "a backup is stale", { category: "backup", severity: "warning" });
assert.deepEqual([hits.gotify.length, hits.ntfy.length, hits.webhook.length], [0, 0, 0], "held");
const queued = await db.select().from(notificationQueue);
assert.equal(queued.length, 1);
assert.ok(queued[0].audience, "who it was for is kept");
await updateSettings({ quietHours: { enabled: false } });
assert.equal(await flushQuietHoursQueue(), 1);
assert.deepEqual([hits.gotify.length, hits.ntfy.length, hits.webhook.length], [0, 1, 0]);
assert.equal((await db.select().from(notificationQueue)).length, 0);
});
test("browsers' wishes narrow who a push goes to, and only when somebody has stated any", async () => {
await updateSettings({ routing: { rules: [] } });
const [u] = await db.insert(users).values({ oidcSub: "u1", name: "U", role: "operator" }).returning({ id: users.id });
const sub = (n: string, extra: Partial<typeof pushSubscriptions.$inferInsert>) => db.insert(pushSubscriptions).values({ userId: u.id, endpoint: `https://push.example/${n}`, p256dh: "k", auth: "a", ...extra }).returning({ id: pushSubscriptions.id });
const [all] = await sub("all", {});
assert.equal((await audienceFor({ category: "disk", severity: "warning" })).pushIds, null, "nobody asked for less");
const [critical] = await sub("critical", { minSeverity: "critical" });
const [disks] = await sub("disks", { categories: JSON.stringify(["disk"]) });
const a = await audienceFor({ category: "disk", severity: "warning" });
assert.deepEqual([...a.pushIds!].sort(), [all.id, disks.id].sort(), "the one wanting only critical stays out");
const b = await audienceFor({ category: "backup", severity: "critical" });
assert.deepEqual([...b.pushIds!].sort(), [all.id, critical.id].sort(), "and the one wanting only disks stays out of backups");
assert.equal((await audienceFor()).pushIds, null, "a notification that says nothing about itself goes to all");
});
});
describe("escalation, end to end", () => {
const hits: { path: string; body: string }[] = [];
let fakeHook: Server;
before(async () => {
fakeHook = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
hits.push({ path: req.url ?? "", body: Buffer.concat(chunks).toString() });
res.end("{}");
});
});
await new Promise<void>((r) => fakeHook.listen(0, "127.0.0.1", r));
await db.delete(servers);
await db.insert(servers).values({ name: "late", apiTokenHash: "l", apiTokenPrefix: "l", lastSeenAt: new Date(Date.now() - 5 * 3600_000).toISOString() });
await updateSettings({
gotify: { enabled: false },
ntfy: { enabled: false },
webhook: { enabled: true, url: `http://127.0.0.1:${(fakeHook.address() as AddressInfo).port}/hook` },
routing: { rules: [] },
quietHours: { enabled: false },
escalation: {
enabled: true,
steps: [
{ afterMinutes: 30, minSeverity: "warning", channels: ["webhook"], extraEmail: "", evenInQuietHours: false },
{ afterMinutes: 90, minSeverity: "critical", channels: ["webhook"], extraEmail: "", evenInQuietHours: true },
],
},
});
});
after(() => fakeHook.close());
const setAge = async (minutes: number) => {
await db.update(alertIncidents).set({ openedAt: new Date(Date.now() - minutes * 60_000).toISOString() });
};
const text = () => hits.map((h) => JSON.parse(h.body).content as string);
test("nothing happens until the alert has been up long enough; then the steps go out one by one, each once", async () => {
invalidateAlertsCache();
await getAlerts(true);
await new Promise((r) => setTimeout(r, 300)); // the incident is recorded in the background
assert.equal(await runEscalation(), 0, "just raised");
assert.equal(hits.length, 0);
await setAge(40);
assert.equal(await runEscalation(), 1);
assert.equal(hits.length, 1);
assert.match(text()[0], /Still not acknowledged/);
assert.match(text()[0], /late hasn't reported/);
assert.match(text()[0], /after 30 minutes/);
assert.equal(await runEscalation(), 0, "step 1 is not repeated");
await setAge(100);
assert.equal(await runEscalation(), 1);
assert.match(text()[1], /after 90 minutes/);
assert.equal(await runEscalation(), 0, "and that was the last step");
const [inc] = await db.select().from(alertIncidents);
assert.equal(inc.escalatedStep, 2);
assert.equal((await db.select().from(auditLog)).filter((e) => e.action === "escalate").length, 2);
});
test("an acknowledgement stops it, and so does switching it off", async () => {
await db.update(alertIncidents).set({ escalatedStep: 0, escalatedAt: null });
await setAge(500);
const before = hits.length;
const alert = (await getAlerts(false)).alerts.find((a) => a.category === "offline")!;
await setAck({ alertId: alert.id, note: "on it", assigneeId: null, hours: null, actor: "Ada" });
assert.equal(await runEscalation(), 0);
await db.delete((await import("../src/db/schema.js")).alertAcks);
await updateSettings({ escalation: { enabled: false } });
assert.equal(await runEscalation(), 0);
assert.equal(hits.length, before);
await updateSettings({ escalation: { enabled: true } });
assert.equal(await runEscalation(), 1, "and it carries on once it is on and nobody is on it");
});
});
describe("saving the settings", () => {
let app: Server;
let base = "";
before(async () => {
await db.insert(users).values({ oidcSub: "admin", name: "Ada", role: "admin" }).onConflictDoNothing();
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "admin" } };
next();
});
a.use("/api/settings", settingsRouter);
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/settings`;
});
after(() => app.close());
const put = (body: unknown) => fetch(base, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
const step = (afterMinutes: number, extra: Record<string, unknown> = {}) => ({ afterMinutes, minSeverity: "critical", channels: ["webPush"], extraEmail: "", evenInQuietHours: false, ...extra });
test("rules are kept, with their tags written the way server tags are", async () => {
const res = await put({ routing: { rules: [{ id: "a1", name: "Prod", enabled: true, categories: ["disk"], minSeverity: "critical", tags: [" Prod ", "Db Servers"], channels: ["ntfy"] }] } });
assert.equal(res.status, 200);
const saved = (await (await fetch(base)).json()).settings.routing.rules[0];
assert.deepEqual(saved.tags, ["db-servers", "prod"]);
});
test("a rule that isn't one is refused", async () => {
assert.equal((await put({ routing: { rules: [{ id: "a", name: "x", enabled: true, categories: ["toast"], minSeverity: null, tags: [], channels: [] }] } })).status, 400);
assert.equal((await put({ routing: { rules: [{ id: "a", name: "x", enabled: true, categories: [], minSeverity: null, tags: [], channels: ["carrier-pigeon"] }] } })).status, 400);
assert.equal((await put({ routing: { rules: [{ id: "a", name: "x", enabled: true, categories: [], minSeverity: null, tags: ["not a tag!"], channels: [] }] } })).status, 400);
});
test("escalation steps must be in time order, say who to tell, and be few", async () => {
assert.equal((await put({ escalation: { enabled: true, steps: [step(30), step(120, { extraEmail: "x@example.com", channels: [] })] } })).status, 200);
assert.equal((await put({ escalation: { enabled: true, steps: [step(60), step(30)] } })).status, 400, "out of order");
assert.equal((await put({ escalation: { enabled: true, steps: [step(30, { channels: [], extraEmail: "" })] } })).status, 400, "nobody to tell");
assert.equal((await put({ escalation: { enabled: true, steps: [step(30, { extraEmail: "not an address" })] } })).status, 400);
assert.equal((await put({ escalation: { enabled: true, steps: [step(10), step(20), step(30), step(40)] } })).status, 400, "at most three");
assert.equal((await put({ escalation: { enabled: true, steps: [step(2)] } })).status, 400, "not sooner than five minutes");
});
});
describe("ntfy titles", () => {
test("a title with an em dash can be sent as a header; plain ones are left as they are", async () => {
const { headerSafe } = await import("../src/services/notify.js");
assert.equal(headerSafe("Plain title"), "Plain title");
const encoded = headerSafe("Homelab Manager — Health Alert");
assert.match(encoded, /^=\?UTF-8\?B\?[A-Za-z0-9+/=]+\?=$/);
assert.equal(Buffer.from(encoded.slice(10, -2), "base64").toString("utf8"), "Homelab Manager — Health Alert");
assert.doesNotThrow(() => new Headers({ Title: encoded }), "and the runtime takes it");
assert.throws(() => new Headers({ Title: "Homelab Manager — Health Alert" }), "which it would not take as it was");
});
});
describe("a browser's preferences, over the routes", () => {
let app: Server;
let base = "";
let who = "p1";
let mine = 0;
before(async () => {
const { pushRouter } = await import("../src/routes/push.js");
const made = await db.insert(users).values([{ oidcSub: "p1", name: "P1", role: "viewer" }, { oidcSub: "p2", name: "P2", role: "viewer" }]).returning({ id: users.id });
mine = (await db.insert(pushSubscriptions).values({ userId: made[0].id, endpoint: "https://push.example/mine", p256dh: "k", auth: "a" }).returning({ id: pushSubscriptions.id }))[0].id;
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
a.use("/api/push", pushRouter);
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/push`;
});
after(() => app.close());
const patch = (id: number, body: unknown) => fetch(`${base}/${id}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
test("a person sets what reaches a browser and reads it back; someone else's browser is not theirs to set", async () => {
const first = await patch(mine, { minSeverity: "critical", categories: ["offline", "disk"] });
assert.equal(first.status, 200, JSON.stringify(await first.clone().json()));
const list = (await (await fetch(`${base}/mine`)).json()).subscriptions[0];
assert.equal(list.minSeverity, "critical");
assert.deepEqual(list.categories, ["offline", "disk"]);
assert.equal((await patch(mine, { minSeverity: null, categories: [] })).status, 200, "an empty list is every kind");
const cleared = (await (await fetch(`${base}/mine`)).json()).subscriptions[0];
assert.deepEqual([cleared.minSeverity, cleared.categories], [null, null]);
who = "p2";
assert.equal((await patch(mine, { minSeverity: "critical", categories: null })).status, 404);
who = "p1";
assert.equal((await patch(mine, { minSeverity: "info", categories: null })).status, 400, "info never notifies, so it isn't a floor");
assert.equal((await patch(mine, { minSeverity: null, categories: ["toast"] })).status, 400);
});
});