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, "when": 1789759852933,
"tag": "0005_bent_violations", "tag": "0005_bent_violations",
"breakpoints": true "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)`), .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) ─────────────────────────────────────────────────── // ─── Settings (key/value) ───────────────────────────────────────────────────
export const settings = sqliteTable("settings", { export const settings = sqliteTable("settings", {
+2
View File
@@ -28,6 +28,7 @@ import { initTailscaleKeyExpiryScheduler } from "./services/tailscaleKeyExpirySc
import { initLogRetentionScheduler } from "./services/logRetentionScheduler.js"; import { initLogRetentionScheduler } from "./services/logRetentionScheduler.js";
import { initDockerUpdateScheduler } from "./services/dockerUpdateScheduler.js"; import { initDockerUpdateScheduler } from "./services/dockerUpdateScheduler.js";
import { initProxmoxBackupScheduler } from "./services/proxmoxBackupScheduler.js"; import { initProxmoxBackupScheduler } from "./services/proxmoxBackupScheduler.js";
import { initQuietHoursScheduler } from "./services/quietHoursScheduler.js";
warnIfAuthNotConfigured(); warnIfAuthNotConfigured();
await runMigrations(); await runMigrations();
@@ -36,6 +37,7 @@ await initTailscaleKeyExpiryScheduler();
await initLogRetentionScheduler(); await initLogRetentionScheduler();
await initDockerUpdateScheduler(); await initDockerUpdateScheduler();
await initProxmoxBackupScheduler(); await initProxmoxBackupScheduler();
await initQuietHoursScheduler();
const __dirname = dirname(fileURLToPath(import.meta.url)); const __dirname = dirname(fileURLToPath(import.meta.url));
const webDist = join(__dirname, "..", "..", "web", "dist"); 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 { scheduleProxmoxBackupCheck } from "../services/proxmoxBackupScheduler.js";
import { scheduleLogRetentionPurge } from "../services/logRetentionScheduler.js"; import { scheduleLogRetentionPurge } from "../services/logRetentionScheduler.js";
import { purgeOldLogs } from "../services/logRetention.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 { buildExportPayload, encryptExport, decryptExport, applyImportPayload, type EncryptedExportFile } from "../services/configBackup.js";
import { asyncHandler } from "../utils/asyncHandler.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) }) .object({ enabled: z.boolean(), retentionDays: z.number().int().min(1).max(3650), intervalHours: z.number().int().min(1).max(720) })
.partial() .partial()
.optional(), .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) => { settingsRouter.put("/", requireRole("admin"), asyncHandler(async (req, res) => {
@@ -102,6 +108,9 @@ settingsRouter.put("/", requireRole("admin"), asyncHandler(async (req, res) => {
if (parsed.data.logRetention) { if (parsed.data.logRetention) {
await scheduleLogRetentionPurge(); await scheduleLogRetentionPurge();
} }
if (parsed.data.quietHours || parsed.data.notifications) {
await scheduleQuietHoursFlush();
}
await recordAudit({ await recordAudit({
actor: req.currentUser!, actor: req.currentUser!,
@@ -182,6 +191,17 @@ settingsRouter.post("/purge-logs", requireRole("admin"), asyncHandler(async (req
res.json(result); 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) }); const exportSchema = z.object({ passphrase: z.string().min(8) });
settingsRouter.post("/export", requireRole("admin"), asyncHandler(async (req, res) => { 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 nodemailer from "nodemailer";
import { getSettings, type NotificationEvents } from "./settingsStore.js"; import { getSettings, type NotificationEvents } from "./settingsStore.js";
import { enqueueNotification, listQueuedNotifications, clearQueuedNotifications } from "./notificationQueue.js";
// ─── Channel senders (best-effort — failures are logged, never thrown) ────── // ─── 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)]); 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 ──────────── // ─── Test senders — throw on failure so the route can report it ────────────
export async function testGotify(cfg: { url: string; token: string; priority?: number }): Promise<void> { 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; 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 { export interface AppSettings {
gotify: GotifySettings; gotify: GotifySettings;
ntfy: NtfySettings; ntfy: NtfySettings;
@@ -80,6 +88,7 @@ export interface AppSettings {
integrationColors: IntegrationColors; integrationColors: IntegrationColors;
display: DisplaySettings; display: DisplaySettings;
logRetention: LogRetentionSettings; logRetention: LogRetentionSettings;
quietHours: QuietHoursSettings;
} }
const DEFAULTS: AppSettings = { const DEFAULTS: AppSettings = {
@@ -104,6 +113,7 @@ const DEFAULTS: AppSettings = {
integrationColors: {}, integrationColors: {},
display: { dateFormat: "ymd", timeFormat: "24h", pageSize: 20 }, display: { dateFormat: "ymd", timeFormat: "24h", pageSize: 20 },
logRetention: { enabled: false, retentionDays: 90, intervalHours: 24 }, logRetention: { enabled: false, retentionDays: 90, intervalHours: 24 },
quietHours: { enabled: false, start: "22:00", end: "07:00" },
}; };
const KEYS = Object.keys(DEFAULTS) as (keyof AppSettings)[]; const KEYS = Object.keys(DEFAULTS) as (keyof AppSettings)[];
+12
View File
@@ -175,6 +175,12 @@ export interface LogRetentionSettings {
intervalHours: number; intervalHours: number;
} }
export interface QuietHoursSettings {
enabled: boolean;
start: string;
end: string;
}
export interface AppSettings { export interface AppSettings {
gotify: GotifySettings; gotify: GotifySettings;
ntfy: NtfySettings; ntfy: NtfySettings;
@@ -185,6 +191,7 @@ export interface AppSettings {
integrationColors: Record<string, string>; integrationColors: Record<string, string>;
display: DisplaySettings; display: DisplaySettings;
logRetention: LogRetentionSettings; logRetention: LogRetentionSettings;
quietHours: QuietHoursSettings;
} }
export type AppSettingsPatch = { [K in keyof AppSettings]?: Partial<AppSettings[K]> }; export type AppSettingsPatch = { [K in keyof AppSettings]?: Partial<AppSettings[K]> };
@@ -889,5 +896,10 @@ export const api = {
request<EncryptedExportFile>("/api/settings/export", { method: "POST", body: JSON.stringify({ passphrase }) }), request<EncryptedExportFile>("/api/settings/export", { method: "POST", body: JSON.stringify({ passphrase }) }),
importConfig: (passphrase: string, file: EncryptedExportFile) => importConfig: (passphrase: string, file: EncryptedExportFile) =>
request<ImportResult>("/api/settings/import", { method: "POST", body: JSON.stringify({ passphrase, file }) }), request<ImportResult>("/api/settings/import", { method: "POST", body: JSON.stringify({ passphrase, file }) }),
quietHoursQueue: () =>
request<{ count: number; items: { id: number; title: string; message: string; createdAt: string }[] }>(
"/api/settings/quiet-hours-queue",
),
flushQuietHours: () => request<{ flushed: number }>("/api/settings/flush-quiet-hours", { method: "POST" }),
}, },
}; };
@@ -7,6 +7,7 @@ import {
type SmtpSettings, type SmtpSettings,
type WebhookSettings, type WebhookSettings,
type NotificationEvents, type NotificationEvents,
type QuietHoursSettings,
} from "../../api/client"; } from "../../api/client";
const TIMEZONES = [ const TIMEZONES = [
@@ -49,6 +50,7 @@ const DEFAULT_NOTIFICATIONS: NotificationEvents = {
integrationFailureAlerts: true, integrationFailureAlerts: true,
integrationFailureThreshold: 3, integrationFailureThreshold: 3,
}; };
const DEFAULT_QUIET_HOURS: QuietHoursSettings = { enabled: false, start: "22:00", end: "07:00" };
type TestResult = { ok: boolean; message: string } | null; type TestResult = { ok: boolean; message: string } | null;
@@ -73,6 +75,10 @@ export default function NotificationSettings() {
const [smtp, setSmtp] = useState<SmtpSettings>(DEFAULT_SMTP); const [smtp, setSmtp] = useState<SmtpSettings>(DEFAULT_SMTP);
const [webhook, setWebhook] = useState<WebhookSettings>(DEFAULT_WEBHOOK); const [webhook, setWebhook] = useState<WebhookSettings>(DEFAULT_WEBHOOK);
const [notifications, setNotifications] = useState<NotificationEvents>(DEFAULT_NOTIFICATIONS); const [notifications, setNotifications] = useState<NotificationEvents>(DEFAULT_NOTIFICATIONS);
const [quietHours, setQuietHours] = useState<QuietHoursSettings>(DEFAULT_QUIET_HOURS);
const [queuedCount, setQueuedCount] = useState<number | null>(null);
const [flushing, setFlushing] = useState(false);
const [flushResult, setFlushResult] = useState<string | null>(null);
const [testingGotify, setTestingGotify] = useState(false); const [testingGotify, setTestingGotify] = useState(false);
const [testGotifyResult, setTestGotifyResult] = useState<TestResult>(null); const [testGotifyResult, setTestGotifyResult] = useState<TestResult>(null);
@@ -92,9 +98,14 @@ export default function NotificationSettings() {
setSmtp(res.settings.smtp); setSmtp(res.settings.smtp);
setWebhook(res.settings.webhook); setWebhook(res.settings.webhook);
setNotifications(res.settings.notifications); setNotifications(res.settings.notifications);
setQuietHours(res.settings.quietHours);
}) })
.catch((err) => setLoadError(err instanceof Error ? err.message : String(err))) .catch((err) => setLoadError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoading(false)); .finally(() => setLoading(false));
api.settings
.quietHoursQueue()
.then((res) => setQueuedCount(res.count))
.catch(() => {});
}, []); }, []);
async function handleSave() { async function handleSave() {
@@ -102,7 +113,7 @@ export default function NotificationSettings() {
setSaveError(null); setSaveError(null);
setSaved(false); setSaved(false);
try { try {
await api.settings.update({ gotify, ntfy, smtp, webhook, notifications }); await api.settings.update({ gotify, ntfy, smtp, webhook, notifications, quietHours });
setSaved(true); setSaved(true);
setTimeout(() => setSaved(false), 3000); setTimeout(() => setSaved(false), 3000);
} catch (err) { } catch (err) {
@@ -112,6 +123,20 @@ export default function NotificationSettings() {
} }
} }
async function handleFlushNow() {
setFlushing(true);
setFlushResult(null);
try {
const res = await api.settings.flushQuietHours();
setFlushResult(res.flushed > 0 ? `Sent a digest of ${res.flushed} queued notification${res.flushed !== 1 ? "s" : ""}.` : "Nothing was queued.");
setQueuedCount(0);
} catch (err) {
setFlushResult(err instanceof Error ? err.message : String(err));
} finally {
setFlushing(false);
}
}
async function handleTestGotify() { async function handleTestGotify() {
setTestingGotify(true); setTestingGotify(true);
setTestGotifyResult(null); setTestGotifyResult(null);
@@ -564,6 +589,67 @@ export default function NotificationSettings() {
</div> </div>
</div> </div>
</div> </div>
<div className="col-md-6">
<div className="card">
<div className="card-header">
<h3 className="card-title">Quiet hours</h3>
</div>
<div className="card-body">
<p className="text-secondary">
Notifications that fire during this window are held instead of sent immediately, then delivered
as one digest at the end time (in the timezone set above). Scheduled daily reminders already only
fire once at a time you pick, so this mainly affects instant ones — DNS changes and integration
failure/recovery alerts.
</p>
<label className="form-check mb-3">
<input
type="checkbox"
className="form-check-input"
checked={quietHours.enabled}
onChange={(e) => setQuietHours((q) => ({ ...q, enabled: e.target.checked }))}
/>
<span className="form-check-label">Enable quiet hours</span>
</label>
<div className="row g-2 mb-2">
<div className="col-6">
<label className="form-label">Start</label>
<input
type="time"
className="form-control"
value={quietHours.start}
disabled={!quietHours.enabled}
onChange={(e) => setQuietHours((q) => ({ ...q, start: e.target.value }))}
/>
</div>
<div className="col-6">
<label className="form-label">End</label>
<input
type="time"
className="form-control"
value={quietHours.end}
disabled={!quietHours.enabled}
onChange={(e) => setQuietHours((q) => ({ ...q, end: e.target.value }))}
/>
</div>
</div>
<div className="form-hint mb-3">
A start time later than the end time (e.g. 22:00 → 07:00) is treated as spanning midnight.
</div>
{queuedCount !== null && queuedCount > 0 && (
<div className="alert alert-info d-flex align-items-center justify-content-between mb-0">
<span>
{queuedCount} notification{queuedCount !== 1 ? "s" : ""} currently queued.
</span>
<button className="btn btn-sm btn-outline-secondary" onClick={handleFlushNow} disabled={flushing}>
{flushing ? "Sending…" : "Flush now"}
</button>
</div>
)}
{flushResult && <div className="text-secondary small mt-2">{flushResult}</div>}
</div>
</div>
</div>
</div> </div>
</> </>
); );