Notification routing rules, per-browser push wishes, escalation of unacknowledged alerts
- Routing: rules pick channels by kind, severity and server tags (first match wins, none = nobody); mixed batches split per route; recoveries follow their alert; quiet-hours digest keeps each notification's audience - Push: each subscribed browser can ask for a minimum severity and some kinds - Escalation: up to three timed steps re-notify alerts nobody has acknowledged, through chosen channels and an optional extra email; an acknowledgement stops them - Fix ntfy: titles with an em dash made every ntfy send fail (header not Latin-1); now RFC 2047 encoded Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9caa414829
commit
43fc5e0272
21 files changed
+4769
-55
No files matched your search
@@ -7,6 +7,7 @@ import { requireAuth } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { getSettings } from "../services/settingsStore.js";
|
||||
import { checkEndpoint, getVapidKeys, sendPush } from "../services/webPush.js";
|
||||
import { CATEGORIES, parseCategories } from "../services/notifyRouting.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const pushRouter = Router();
|
||||
@@ -45,7 +46,7 @@ pushRouter.get("/mine", asyncHandler(async (req, res) => {
|
||||
const { webPush } = await getSettings();
|
||||
res.json({
|
||||
enabled: webPush.enabled,
|
||||
subscriptions: rows.map((r) => ({ id: r.id, label: r.label, host: hostOf(r.endpoint), endpoint: r.endpoint, createdAt: r.createdAt, lastSuccessAt: r.lastSuccessAt })),
|
||||
subscriptions: rows.map((r) => ({ id: r.id, label: r.label, host: hostOf(r.endpoint), endpoint: r.endpoint, createdAt: r.createdAt, lastSuccessAt: r.lastSuccessAt, minSeverity: r.minSeverity === "critical" || r.minSeverity === "warning" ? r.minSeverity : null, categories: parseCategories(r.categories) })),
|
||||
});
|
||||
}));
|
||||
|
||||
@@ -74,6 +75,25 @@ pushRouter.post("/subscribe", asyncHandler(async (req, res) => {
|
||||
res.status(201).json({ id: row.id });
|
||||
}));
|
||||
|
||||
// What a browser wants to be told: only the worse alerts, only some kinds. Its owner's to say (an administrator may too).
|
||||
const prefsSchema = z.object({
|
||||
minSeverity: z.enum(["warning", "critical"]).nullable(),
|
||||
categories: z.array(z.enum(CATEGORIES)).max(10).nullable(),
|
||||
});
|
||||
|
||||
pushRouter.patch("/:id", asyncHandler(async (req, res) => {
|
||||
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : NaN;
|
||||
const parsed = prefsSchema.safeParse(req.body);
|
||||
if (!Number.isInteger(id) || !parsed.success) return res.status(400).json({ error: "invalid_body", message: "Choose a severity (or any) and the kinds of alert (or all).", details: parsed.success ? undefined : parsed.error.flatten() });
|
||||
const me = req.currentUser!;
|
||||
const [row] = await db.select().from(pushSubscriptions).where(eq(pushSubscriptions.id, id)).limit(1);
|
||||
if (!row || (row.userId !== me.id && me.role !== "admin")) return res.status(404).json({ error: "not_found" });
|
||||
const categories = parsed.data.categories && parsed.data.categories.length > 0 ? parsed.data.categories : null;
|
||||
await db.update(pushSubscriptions).set({ minSeverity: parsed.data.minSeverity, categories: categories ? JSON.stringify(categories) : null }).where(eq(pushSubscriptions.id, id));
|
||||
await recordAudit({ actor: me, category: "push", action: "preferences", targetType: "push_subscription", targetId: id, detail: { host: hostOf(row.endpoint), label: row.label, minSeverity: parsed.data.minSeverity, categories } });
|
||||
res.json({ minSeverity: parsed.data.minSeverity, categories });
|
||||
}));
|
||||
|
||||
// Stops a browser being written to. A person removes their own; an administrator may remove anyone's.
|
||||
pushRouter.delete("/:id", asyncHandler(async (req, res) => {
|
||||
const id = /^\d+$/.test(req.params.id) ? Number(req.params.id) : NaN;
|
||||
|
||||
@@ -15,6 +15,8 @@ import { scheduleQuietHoursFlush } from "../services/quietHoursScheduler.js";
|
||||
import { scheduleWeeklyDigest } from "../services/weeklyDigestScheduler.js";
|
||||
import { buildDigest, sendDigest } from "../services/weeklyDigest.js";
|
||||
import { enabledChannelCount } from "../services/notify.js";
|
||||
import { CATEGORIES, CHANNEL_IDS } from "../services/notifyRouting.js";
|
||||
import { InvalidTagError, normalizeTags } from "../services/serverTags.js";
|
||||
import { testGotify, testNtfy, testSmtp, testWebhook, flushQuietHoursQueue } from "../services/notify.js";
|
||||
import { listQueuedNotifications } from "../services/notificationQueue.js";
|
||||
import { buildExportPayload, encryptExport, decryptExport, applyImportPayload, type EncryptedExportFile } from "../services/configBackup.js";
|
||||
@@ -47,7 +49,51 @@ settingsRouter.get("/display", asyncHandler(async (_req, res) => {
|
||||
res.json({ display });
|
||||
}));
|
||||
|
||||
const channelEnum = z.enum(CHANNEL_IDS);
|
||||
|
||||
// Routing rules: which channels hear which notifications. A rule with no channels means "tell nobody" (the Alerts page still shows it).
|
||||
const routingSchema = z.object({
|
||||
rules: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string().trim().min(1).max(40),
|
||||
name: z.string().trim().min(1).max(60),
|
||||
enabled: z.boolean(),
|
||||
categories: z.array(z.enum(CATEGORIES)).max(10),
|
||||
minSeverity: z.enum(["warning", "critical"]).nullable(),
|
||||
tags: z.array(z.string().trim().min(1).max(30)).max(10),
|
||||
channels: z.array(channelEnum).max(5),
|
||||
}),
|
||||
)
|
||||
.max(30),
|
||||
});
|
||||
|
||||
// Escalation: a few steps in time order. Each must say who to tell — a channel, or an address.
|
||||
const escalationSchema = z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
steps: z
|
||||
.array(
|
||||
z.object({
|
||||
afterMinutes: z.number().int().min(5).max(10080),
|
||||
minSeverity: z.enum(["warning", "critical"]),
|
||||
channels: z.array(channelEnum).max(5),
|
||||
extraEmail: z.string().trim().max(200).refine((v) => v === "" || /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v), "That isn't an email address"),
|
||||
evenInQuietHours: z.boolean(),
|
||||
}),
|
||||
)
|
||||
.max(3),
|
||||
})
|
||||
.superRefine((v, ctx) => {
|
||||
v.steps.forEach((s, i) => {
|
||||
if (s.channels.length === 0 && s.extraEmail === "") ctx.addIssue({ code: "custom", path: ["steps", i], message: "Choose a channel to tell, or an address to email." });
|
||||
if (i > 0 && s.afterMinutes <= v.steps[i - 1].afterMinutes) ctx.addIssue({ code: "custom", path: ["steps", i, "afterMinutes"], message: "Each step must come later than the one before." });
|
||||
});
|
||||
});
|
||||
|
||||
const updateSchema = z.object({
|
||||
routing: routingSchema.optional(),
|
||||
escalation: escalationSchema.optional(),
|
||||
gotify: z.object({ enabled: z.boolean(), url: z.string(), token: z.string(), priority: z.number() }).partial().optional(),
|
||||
ntfy: z.object({ enabled: z.boolean(), url: z.string(), topic: z.string(), token: z.string(), priority: z.number() }).partial().optional(),
|
||||
smtp: z
|
||||
@@ -126,6 +172,14 @@ settingsRouter.put("/", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
||||
}
|
||||
|
||||
// Tags in routing rules are written the way server tags are, so they match.
|
||||
try {
|
||||
if (parsed.data.routing) for (const rule of parsed.data.routing.rules) rule.tags = normalizeTags(rule.tags);
|
||||
} catch (err) {
|
||||
if (err instanceof InvalidTagError) return res.status(400).json({ error: "invalid_tag", message: err.message });
|
||||
throw err;
|
||||
}
|
||||
|
||||
const before = await getSettings();
|
||||
const updated = await updateSettings(parsed.data);
|
||||
|
||||
|
||||
Reference in new issue
Block a user