feat(notifications): add generic webhook channel

A single WEBHOOK channel covers Gotify, Discord, Slack, Matrix, and Home
Assistant: the user supplies a public URL and an optional shared-secret
header, and the dispatcher POSTs a small plain-text JSON envelope. The
outbound goes through safeFetch with requirePublicHost so the SSRF floor
and the connect-time DNS-rebinding pin apply to the user-supplied host,
exactly as they do for ntfy. Responses classify 404/410/401/403 as hard
rejects (auto-disable) and 5xx/429/timeout as transient (backoff).

Settings card mirrors the ntfy card with a save + test-connection flow;
the header value is never returned by the GET and is preserved across a
save round-trip when left blank.
This commit is contained in:
Marc-André Bombeck committed 2026-06-15 00:45:50 +02:00
1 parent aec41e154f
commit 7532bbcc05
5 files changed
+594

No files matched your search

+106
View File
@@ -0,0 +1,106 @@
import { prisma } from "@/lib/db";
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
import { webhookSettingsSchema } from "@/lib/validations/notifications";
import { encrypt, decrypt } from "@/lib/crypto";
import { NextRequest } from "next/server";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
/**
* Generic-webhook channel config (v1.17.1).
* GET: current config (header value redacted — only presence flagged).
* PUT: upsert config.
*
* Covers Gotify / Discord / Slack / Matrix-bridge / Home Assistant in one
* channel: the user supplies a public URL and an optional shared-secret
* header. SSRF is enforced at input time (`isPublicUrl` in the schema) and
* again at dispatch time (`safeFetch({ requirePublicHost: true })`).
*/
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
const channel = await prisma.notificationChannel.findUnique({
where: { userId_type: { userId: user.id, type: "WEBHOOK" } },
});
if (!channel) {
return apiSuccess({
enabled: false,
url: "",
headerName: "",
hasHeaderValue: false,
});
}
const config = JSON.parse(decrypt(channel.config)) as {
url: string;
headerName?: string;
headerValue?: string;
};
annotate({ action: { name: "settings.webhook.get" } });
return apiSuccess({
enabled: channel.enabled,
url: config.url,
headerName: config.headerName ?? "",
hasHeaderValue: !!config.headerValue,
});
});
export const PUT = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 64 * 1024,
});
if (jsonError) return jsonError;
const parsed = webhookSettingsSchema.safeParse(body);
if (!parsed.success) return apiError("Invalid data", 422);
const { url, headerName, headerValue, enabled } = parsed.data;
if (enabled && !url) {
return apiError("Webhook URL is required when the webhook is enabled", 422);
}
// Preserve an existing header value when the client sends an empty one (the
// GET path never returns the secret, so a save round-trip would otherwise
// wipe it). A non-empty value replaces it.
let nextHeaderValue = headerValue || undefined;
if (!nextHeaderValue) {
const existing = await prisma.notificationChannel.findUnique({
where: { userId_type: { userId: user.id, type: "WEBHOOK" } },
});
if (existing) {
const prev = JSON.parse(decrypt(existing.config)) as {
headerValue?: string;
};
nextHeaderValue = prev.headerValue || undefined;
}
}
const config = JSON.stringify({
url: url || "",
...(headerName ? { headerName } : {}),
...(nextHeaderValue ? { headerValue: nextHeaderValue } : {}),
});
const encryptedConfig = encrypt(config);
await prisma.notificationChannel.upsert({
where: { userId_type: { userId: user.id, type: "WEBHOOK" } },
create: {
userId: user.id,
type: "WEBHOOK",
enabled,
config: encryptedConfig,
},
update: { enabled, config: encryptedConfig },
});
annotate({ action: { name: "settings.webhook.update" }, meta: { enabled } });
return apiSuccess({ saved: true });
});
@@ -0,0 +1,52 @@
import { prisma } from "@/lib/db";
import { apiSuccess, apiError } from "@/lib/api-response";
import { decrypt } from "@/lib/crypto";
import { sendViaWebhook } from "@/lib/notifications/senders/webhook";
import type { WebhookChannelConfig } from "@/lib/notifications/types";
import { checkRateLimit } from "@/lib/rate-limit";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
/**
* POST: send a test notification via the configured generic webhook.
*/
export const POST = apiHandler(async () => {
const { user } = await requireAuth();
const rl = await checkRateLimit(`webhook-test:${user.id}`, 5, 5 * 60 * 1000);
if (!rl.allowed) {
return apiError("Maximum 5 tests in 5 minutes", 429);
}
const channel = await prisma.notificationChannel.findUnique({
where: { userId_type: { userId: user.id, type: "WEBHOOK" } },
});
if (!channel) {
return apiError("Webhook is not configured", 400);
}
const config = JSON.parse(decrypt(channel.config)) as WebhookChannelConfig;
if (!config.url) {
return apiError("Webhook URL is required", 400);
}
const result = await sendViaWebhook(config, {
eventType: "SYSTEM_ALERT",
userId: user.id,
title: "HealthLog Test",
message: "HealthLog: Connection successful! Webhook notifications are active.",
});
if (!result.ok) {
return apiError("Failed to send test message", 500);
}
annotate({
action: { name: "settings.webhook.test" },
meta: { success: true },
});
return apiSuccess({ sent: true });
});