Add notification quiet hours with digest delivery

Instant notifications (DNS changes, integration failure/recovery
alerts) had no way to avoid pinging overnight. Adds a "Quiet hours"
window under Settings -> Notifications: notifications that would fire
during the window are held in a new notification_queue table instead
of sent immediately, then delivered as one combined digest at the end
time (in the same timezone already used for the daily checks) via a
new scheduled flush job. The scheduled daily checks (secret expiry,
Tailscale key, Docker updates, Proxmox backups) already only fire
once at a chosen time, so this mainly matters for the instant ones.
Includes a live "N queued" indicator with a manual "Flush now" button
for visibility, and correctly falls back to sending immediately
whenever the feature is disabled (the default).

Gating lives at the single choke point every notification already
flows through (notify()), so no per-event-type wiring was needed.

Verified against a fake webhook receiver on an isolated scratch
database: exhaustively checked the midnight-wraparound window math
(9 cases including exact-boundary inclusive/exclusive edges) against
synthetic "now" values rather than depending on when the test
happens to run, then end-to-end through the real notify()/
flushQuietHoursQueue() functions with a window constructed around the
actual current time — confirmed a notification during the window
queues instead of sending, the flush produces one digest with the
original title/message intact and clears the queue, a notification
outside the window sends immediately, and disabling the feature
entirely sends immediately regardless of the window. Confirmed the
real dev database's mtime was untouched throughout.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5 committed 2026-09-22 20:56:33 +02:00
1 parent 99db7e1cf0
commit 73d649377e
12 files changed
+1445 -3

No files matched your search

@@ -0,0 +1,6 @@
CREATE TABLE `notification_queue` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`title` text NOT NULL,
`message` text NOT NULL,
`created_at` text DEFAULT (current_timestamp) NOT NULL
);
File diff suppressed because it is too large. Load diff
+7
View File
@@ -43,6 +43,13 @@
"when": 1789759852933,
"tag": "0005_bent_violations",
"breakpoints": true
},
{
"idx": 6,
"version": "6",
"when": 1790103102037,
"tag": "0006_aberrant_darkhawk",
"breakpoints": true
}
]
}
+11
View File
@@ -48,6 +48,17 @@ export const diagLog = sqliteTable("diag_log", {
.default(sql`(current_timestamp)`),
});
// ─── Notification queue — pending notifications held during quiet hours ────
export const notificationQueue = sqliteTable("notification_queue", {
id: integer("id").primaryKey({ autoIncrement: true }),
title: text("title").notNull(),
message: text("message").notNull(),
createdAt: text("created_at")
.notNull()
.default(sql`(current_timestamp)`),
});
// ─── Settings (key/value) ───────────────────────────────────────────────────
export const settings = sqliteTable("settings", {
+2
View File
@@ -28,6 +28,7 @@ import { initTailscaleKeyExpiryScheduler } from "./services/tailscaleKeyExpirySc
import { initLogRetentionScheduler } from "./services/logRetentionScheduler.js";
import { initDockerUpdateScheduler } from "./services/dockerUpdateScheduler.js";
import { initProxmoxBackupScheduler } from "./services/proxmoxBackupScheduler.js";
import { initQuietHoursScheduler } from "./services/quietHoursScheduler.js";
warnIfAuthNotConfigured();
await runMigrations();
@@ -36,6 +37,7 @@ await initTailscaleKeyExpiryScheduler();
await initLogRetentionScheduler();
await initDockerUpdateScheduler();
await initProxmoxBackupScheduler();
await initQuietHoursScheduler();
const __dirname = dirname(fileURLToPath(import.meta.url));
const webDist = join(__dirname, "..", "..", "web", "dist");
+21 -1
View File
@@ -9,7 +9,9 @@ import { scheduleDockerUpdateCheck } from "../services/dockerUpdateScheduler.js"
import { scheduleProxmoxBackupCheck } from "../services/proxmoxBackupScheduler.js";
import { scheduleLogRetentionPurge } from "../services/logRetentionScheduler.js";
import { purgeOldLogs } from "../services/logRetention.js";
import { testGotify, testNtfy, testSmtp, testWebhook } from "../services/notify.js";
import { scheduleQuietHoursFlush } from "../services/quietHoursScheduler.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";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -83,6 +85,10 @@ const updateSchema = z.object({
.object({ enabled: z.boolean(), retentionDays: z.number().int().min(1).max(3650), intervalHours: z.number().int().min(1).max(720) })
.partial()
.optional(),
quietHours: z
.object({ enabled: z.boolean(), start: z.string().regex(/^\d{2}:\d{2}$/), end: z.string().regex(/^\d{2}:\d{2}$/) })
.partial()
.optional(),
});
settingsRouter.put("/", requireRole("admin"), asyncHandler(async (req, res) => {
@@ -102,6 +108,9 @@ settingsRouter.put("/", requireRole("admin"), asyncHandler(async (req, res) => {
if (parsed.data.logRetention) {
await scheduleLogRetentionPurge();
}
if (parsed.data.quietHours || parsed.data.notifications) {
await scheduleQuietHoursFlush();
}
await recordAudit({
actor: req.currentUser!,
@@ -182,6 +191,17 @@ settingsRouter.post("/purge-logs", requireRole("admin"), asyncHandler(async (req
res.json(result);
}));
settingsRouter.get("/quiet-hours-queue", requireRole("admin"), asyncHandler(async (_req, res) => {
const items = await listQueuedNotifications();
res.json({ count: items.length, items });
}));
settingsRouter.post("/flush-quiet-hours", requireRole("admin"), asyncHandler(async (req, res) => {
const flushed = await flushQuietHoursQueue();
await recordAudit({ actor: req.currentUser!, category: "settings", action: "flush_quiet_hours", detail: { flushed } });
res.json({ flushed });
}));
const exportSchema = z.object({ passphrase: z.string().min(8) });
settingsRouter.post("/export", requireRole("admin"), asyncHandler(async (req, res) => {
+21
View File
@@ -0,0 +1,21 @@
import { db } from "../db/client.js";
import { notificationQueue } from "../db/schema.js";
export interface QueuedNotification {
id: number;
title: string;
message: string;
createdAt: string;
}
export async function enqueueNotification(title: string, message: string): Promise<void> {
await db.insert(notificationQueue).values({ title, message });
}
export async function listQueuedNotifications(): Promise<QueuedNotification[]> {
return db.select().from(notificationQueue);
}
export async function clearQueuedNotifications(): Promise<void> {
await db.delete(notificationQueue);
}
+52 -1
View File
@@ -1,5 +1,6 @@
import nodemailer from "nodemailer";
import { getSettings, type NotificationEvents } from "./settingsStore.js";
import { enqueueNotification, listQueuedNotifications, clearQueuedNotifications } from "./notificationQueue.js";
// ─── Channel senders (best-effort — failures are logged, never thrown) ──────
@@ -70,10 +71,60 @@ async function sendWebhook(title: string, message: string) {
}
}
export async function notify(title: string, message: string): Promise<void> {
async function sendToChannels(title: string, message: string): Promise<void> {
await Promise.all([sendGotify(title, message), sendNtfy(title, message), sendSmtp(title, message), sendWebhook(title, message)]);
}
function currentTimeInZone(timezone: string): { hh: number; mm: number } {
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: timezone, hour: "2-digit", minute: "2-digit", hour12: false }).formatToParts(
new Date(),
);
return {
hh: Number(parts.find((p) => p.type === "hour")?.value ?? "0"),
mm: Number(parts.find((p) => p.type === "minute")?.value ?? "0"),
};
}
function toMinutes(hhmm: string): number {
const [h, m] = hhmm.split(":").map(Number);
return (Number.isFinite(h) ? h : 0) * 60 + (Number.isFinite(m) ? m : 0);
}
async function isQuietHoursActive(): Promise<boolean> {
const { quietHours, notifications } = await getSettings();
if (!quietHours.enabled) return false;
const { hh, mm } = currentTimeInZone(notifications.timezone);
const nowMin = hh * 60 + mm;
const startMin = toMinutes(quietHours.start);
const endMin = toMinutes(quietHours.end);
if (startMin === endMin) return false; // zero-length window — treat as always off
// A same-day window (e.g. 09:00 -> 17:00) is a simple range; a window that
// wraps past midnight (e.g. 22:00 -> 07:00, the common case) means "active"
// is everything outside [end, start) instead.
return startMin < endMin ? nowMin >= startMin && nowMin < endMin : nowMin >= startMin || nowMin < endMin;
}
export async function notify(title: string, message: string): Promise<void> {
if (await isQuietHoursActive()) {
await enqueueNotification(title, message);
return;
}
await sendToChannels(title, message);
}
/** Called by the daily scheduler at quiet-hours end (or manually) — sends everything queued during the window as one digest, then clears it. */
export async function flushQuietHoursQueue(): Promise<number> {
const queued = await listQueuedNotifications();
if (queued.length === 0) return 0;
const sections = queued.map((q) => `— ${q.title} —\n${q.message}`);
await sendToChannels(
"Homelab Manager — Notifications from quiet hours",
`${queued.length} notification${queued.length !== 1 ? "s were" : " was"} held during quiet hours:\n\n${sections.join("\n\n")}`,
);
await clearQueuedNotifications();
return queued.length;
}
// ─── Test senders — throw on failure so the route can report it ────────────
export async function testGotify(cfg: { url: string; token: string; priority?: number }): Promise<void> {
@@ -0,0 +1,31 @@
import schedule from "node-schedule";
import { flushQuietHoursQueue } from "./notify.js";
import { getSettings } from "./settingsStore.js";
function cronFromTime(time: string): string {
const [h, m] = time.split(":").map(Number);
return `${Number.isFinite(m) ? m : 0} ${Number.isFinite(h) ? h : 8} * * *`;
}
let currentJob: schedule.Job | null = null;
/** (Re)schedules the daily queue flush at quiet-hours end per the current settings. Call again after settings change. */
export async function scheduleQuietHoursFlush(): Promise<void> {
if (currentJob) {
currentJob.cancel();
currentJob = null;
}
const { quietHours, notifications } = await getSettings();
if (!quietHours.enabled) {
console.log("[quietHours] disabled, nothing scheduled");
return;
}
currentJob = schedule.scheduleJob({ rule: cronFromTime(quietHours.end), tz: notifications.timezone }, () => {
flushQuietHoursQueue().catch((err) => console.error("[quietHours] flush failed:", err));
});
console.log(`Quiet hours flush scheduled at ${quietHours.end} (${notifications.timezone})`);
}
export async function initQuietHoursScheduler(): Promise<void> {
await scheduleQuietHoursFlush();
}
+10
View File
@@ -70,6 +70,14 @@ export interface LogRetentionSettings {
intervalHours: number;
}
export interface QuietHoursSettings {
enabled: boolean;
/** "HH:MM", local to notifications.timezone. Notifications from `start` to `end` are queued, not sent immediately. */
start: string;
/** "HH:MM" — when `start`..`end` wraps past midnight (e.g. 22:00 -> 07:00), the queue is flushed as one digest at this time. */
end: string;
}
export interface AppSettings {
gotify: GotifySettings;
ntfy: NtfySettings;
@@ -80,6 +88,7 @@ export interface AppSettings {
integrationColors: IntegrationColors;
display: DisplaySettings;
logRetention: LogRetentionSettings;
quietHours: QuietHoursSettings;
}
const DEFAULTS: AppSettings = {
@@ -104,6 +113,7 @@ const DEFAULTS: AppSettings = {
integrationColors: {},
display: { dateFormat: "ymd", timeFormat: "24h", pageSize: 20 },
logRetention: { enabled: false, retentionDays: 90, intervalHours: 24 },
quietHours: { enabled: false, start: "22:00", end: "07:00" },
};
const KEYS = Object.keys(DEFAULTS) as (keyof AppSettings)[];