mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
feat(notifications): add SMTP email channel
Alerts and reminders over email — the one channel every self-hoster already has. The SMTP transport (host/port/auth/from) is operator-supplied via SMTP_* env and loaded once per process like the APNs key; the only per-user value is the recipient address, so SMTP credentials never enter a user's encrypted channel blob. Absent SMTP env disables the channel cleanly: the dispatcher skips it and the Settings card hides itself. Bodies are plain text — HTML is stripped and routine reminders run through the emoji-strip path; no markdown library is added. SMTP 5xx maps to a hard reject (permanent — auto-disable); connection/4xx errors are transient and ride the backoff schedule. Adds nodemailer (the standard, well-audited mail transport) and its types.
This commit is contained in:
1 parent
7532bbcc05
commit
909c2aa99e
9 files changed
+774
-6
No files matched your search
@@ -0,0 +1,82 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess, apiError, safeJson } from "@/lib/api-response";
|
||||
import { emailSettingsSchema } 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";
|
||||
import { isEmailConfigured } from "@/lib/notifications/senders/email-config";
|
||||
|
||||
/**
|
||||
* Email channel config (v1.17.1).
|
||||
* GET: per-user recipient + opt-in, plus `smtpConfigured` so the UI can hide
|
||||
* the card on an instance where the operator hasn't set `SMTP_*`.
|
||||
* PUT: upsert recipient + enabled.
|
||||
*
|
||||
* The SMTP transport (host/port/auth/from) is operator-supplied via env; only
|
||||
* the recipient address is per-user, so SMTP credentials never enter a user's
|
||||
* encrypted channel blob.
|
||||
*/
|
||||
export const GET = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
const smtpConfigured = isEmailConfigured();
|
||||
|
||||
const channel = await prisma.notificationChannel.findUnique({
|
||||
where: { userId_type: { userId: user.id, type: "EMAIL" } },
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return apiSuccess({ enabled: false, recipient: "", smtpConfigured });
|
||||
}
|
||||
|
||||
const config = JSON.parse(decrypt(channel.config)) as { recipient: string };
|
||||
|
||||
annotate({ action: { name: "settings.email.get" } });
|
||||
|
||||
return apiSuccess({
|
||||
enabled: channel.enabled,
|
||||
recipient: config.recipient,
|
||||
smtpConfigured,
|
||||
});
|
||||
});
|
||||
|
||||
export const PUT = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
if (!isEmailConfigured()) {
|
||||
return apiError("Email is not configured on this instance", 400);
|
||||
}
|
||||
|
||||
const { data: body, error: jsonError } = await safeJson(request, {
|
||||
maxBytes: 16 * 1024,
|
||||
});
|
||||
|
||||
if (jsonError) return jsonError;
|
||||
const parsed = emailSettingsSchema.safeParse(body);
|
||||
if (!parsed.success) return apiError("Invalid data", 422);
|
||||
|
||||
const { recipient, enabled } = parsed.data;
|
||||
|
||||
if (enabled && !recipient) {
|
||||
return apiError("A recipient address is required when email is enabled", 422);
|
||||
}
|
||||
|
||||
const config = JSON.stringify({ recipient: recipient || "" });
|
||||
const encryptedConfig = encrypt(config);
|
||||
|
||||
await prisma.notificationChannel.upsert({
|
||||
where: { userId_type: { userId: user.id, type: "EMAIL" } },
|
||||
create: {
|
||||
userId: user.id,
|
||||
type: "EMAIL",
|
||||
enabled,
|
||||
config: encryptedConfig,
|
||||
},
|
||||
update: { enabled, config: encryptedConfig },
|
||||
});
|
||||
|
||||
annotate({ action: { name: "settings.email.update" }, meta: { enabled } });
|
||||
|
||||
return apiSuccess({ saved: true });
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiSuccess, apiError } from "@/lib/api-response";
|
||||
import { decrypt } from "@/lib/crypto";
|
||||
import { sendViaEmail } from "@/lib/notifications/senders/email";
|
||||
import type { EmailChannelConfig } from "@/lib/notifications/types";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { isEmailConfigured } from "@/lib/notifications/senders/email-config";
|
||||
|
||||
/**
|
||||
* POST: send a test email to the configured recipient.
|
||||
*/
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
|
||||
if (!isEmailConfigured()) {
|
||||
return apiError("Email is not configured on this instance", 400);
|
||||
}
|
||||
|
||||
const rl = await checkRateLimit(`email-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: "EMAIL" } },
|
||||
});
|
||||
|
||||
if (!channel) {
|
||||
return apiError("Email is not configured", 400);
|
||||
}
|
||||
|
||||
const config = JSON.parse(decrypt(channel.config)) as EmailChannelConfig;
|
||||
|
||||
if (!config.recipient) {
|
||||
return apiError("A recipient address is required", 400);
|
||||
}
|
||||
|
||||
const result = await sendViaEmail(config, {
|
||||
eventType: "SYSTEM_ALERT",
|
||||
userId: user.id,
|
||||
title: "HealthLog Test",
|
||||
message: "HealthLog: Connection successful! Email notifications are active.",
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
return apiError("Failed to send test email", 500);
|
||||
}
|
||||
|
||||
annotate({ action: { name: "settings.email.test" }, meta: { success: true } });
|
||||
|
||||
return apiSuccess({ sent: true });
|
||||
});
|
||||
Reference in new issue
Block a user