diff --git a/worker/src/services/email.ts b/worker/src/services/email.ts index 087258d..f824922 100644 --- a/worker/src/services/email.ts +++ b/worker/src/services/email.ts @@ -1,16 +1,16 @@ -import { getTablePrefix } from "../types"; -import type { Env } from "../types"; -import { getSetting } from "../db/queries/settings"; import { connect } from "cloudflare:sockets"; +import { getSetting } from "../db/queries/settings"; +import type { Env } from "../types"; +import { getTablePrefix } from "../types"; const EMAIL_RE = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -function isValidEmail(email: string): boolean { +export function isValidEmail(email: string): boolean { return EMAIL_RE.test(email) && !email.includes("\r") && !email.includes("\n"); } -interface EmailOptions { +export interface EmailOptions { to: string; subject: string; html: string; @@ -18,7 +18,7 @@ interface EmailOptions { fromName?: string; } -interface SMTPConfig { +export interface SMTPConfig { host: string; port: number; username: string; @@ -112,6 +112,20 @@ async function sendViaSMTP( if (!config.host) return { success: false, error: "SMTP host not configured" }; + return sendSmtpMail(config, options); +} + +/** + * Send a single message through an explicit SMTP account. + * + * Shared by the system mailer (global `smtp_config` setting) and the per-user + * Email notification channel (`notification_configs.email_config`). + * Callers are responsible for validating the recipient and supplying a sender. + */ +export async function sendSmtpMail( + config: SMTPConfig, + options: EmailOptions, +): Promise<{ success: boolean; error?: string }> { const from = options.from || config.from || "noreply@example.com"; const fromName = (options.fromName || config.from_name || "eNotify").replace( /[\r\n]/g, diff --git a/worker/src/services/notify/email-notify.ts b/worker/src/services/notify/email-notify.ts index 7b710eb..c65cede 100644 --- a/worker/src/services/notify/email-notify.ts +++ b/worker/src/services/notify/email-notify.ts @@ -1,12 +1,19 @@ -import type { NotifyMessage } from "./index"; import type { Env } from "../../types"; -import { sendEmail } from "../email"; +import { isValidEmail, sendSmtpMail } from "../email"; +import type { NotifyMessage } from "./index"; interface EmailNotifyConfig { to: string; from_name?: string; + smtp_host?: string; + smtp_port?: string; + smtp_username?: string; + smtp_password?: string; + smtp_from?: string; } +const DEFAULT_SMTP_PORT = 587; + function escapeHtml(s: string): string { return s .replace(/&/g, "&") @@ -18,24 +25,58 @@ function escapeHtml(s: string): string { export async function sendNotifyEmail( configJson: string, message: NotifyMessage, - env: Env, + // Kept for the channel-sender signature; this channel reads only per-user + // config and never the global `Env` settings. + _env: Env, ): Promise<{ success: boolean; error?: string }> { const config: EmailNotifyConfig = JSON.parse(configJson); if (!config.to) { return { success: false, error: "Email recipient required" }; } - if (/[\r\n,;<>]/.test(config.to)) { + if (/[\r\n,;<>]/.test(config.to) || !isValidEmail(config.to)) { return { success: false, error: "Invalid email recipient" }; } + // Per-user SMTP only: never fall back to the global system mailer. + const host = config.smtp_host?.trim(); + if (!host) { + return { success: false, error: "Email channel SMTP not configured" }; + } + + const rawPort = config.smtp_port?.trim(); + const port = rawPort ? Number(rawPort) : DEFAULT_SMTP_PORT; + if (!Number.isInteger(port) || port <= 0 || port > 65535) { + return { success: false, error: "Invalid Email channel SMTP port" }; + } + + const from = (config.smtp_from || config.smtp_username || "").trim(); + if (!from || /[\s\r\n,;<>]/.test(from)) { + return { + success: false, + error: + "Invalid Email channel SMTP sender (set smtp_from or smtp_username)", + }; + } + const safeTitle = escapeHtml(message.title); const safeBody = escapeHtml(message.body).replace(/\n/g, "
"); - return sendEmail(env, { - to: config.to, - subject: message.title.replace(/[\r\n]+/g, " "), - html: `

${safeTitle}

${safeBody}

`, - fromName: config.from_name?.replace(/[<>"\r\n]/g, "").trim() || undefined, - }); + return sendSmtpMail( + { + host, + port, + username: config.smtp_username || "", + password: config.smtp_password || "", + from, + from_name: config.from_name || "", + secure: port === 465, + }, + { + to: config.to, + subject: message.title.replace(/[\r\n]+/g, " "), + html: `

${safeTitle}

${safeBody}

`, + fromName: config.from_name?.replace(/[<>"\r\n]/g, "").trim() || undefined, + }, + ); } diff --git a/worker/test/email-notify.test.ts b/worker/test/email-notify.test.ts new file mode 100644 index 0000000..3312290 --- /dev/null +++ b/worker/test/email-notify.test.ts @@ -0,0 +1,153 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { sendSmtpMail } from "../src/services/email"; +import { sendNotifyEmail } from "../src/services/notify/email-notify"; +import type { Env } from "../src/types"; + +vi.mock("../src/services/email", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + sendSmtpMail: vi.fn(async () => ({ success: true })), + }; +}); + +const smtpMock = vi.mocked(sendSmtpMail); + +const message = { + title: "Renewal due", + body: "Your plan expires soon.", +}; + +// The per-user channel must never touch the global settings/DB path. +const env = {} as Env; + +function config(overrides: Record = {}): string { + return JSON.stringify({ + to: "recipient@example.com", + from_name: "eNotify", + smtp_host: "smtp.example.com", + smtp_port: "465", + smtp_username: "user@example.com", + smtp_password: "test-smtp-password", + smtp_from: "sender@example.com", + ...overrides, + }); +} + +beforeEach(() => { + smtpMock.mockClear(); + smtpMock.mockResolvedValue({ success: true }); +}); + +describe("sendNotifyEmail config validation", () => { + it("requires a recipient", async () => { + await expect( + sendNotifyEmail(config({ to: "" }), message, env), + ).resolves.toEqual({ success: false, error: "Email recipient required" }); + expect(smtpMock).not.toHaveBeenCalled(); + }); + + it("rejects a recipient containing header separators", async () => { + await expect( + sendNotifyEmail(config({ to: "a@b.com\r\nBcc: c@d.com" }), message, env), + ).resolves.toEqual({ success: false, error: "Invalid email recipient" }); + expect(smtpMock).not.toHaveBeenCalled(); + }); + + it("fails with a clear error when smtp_host is empty, without falling back to the system mailer", async () => { + for (const host of ["", " ", undefined]) { + await expect( + sendNotifyEmail(config({ smtp_host: host }), message, env), + ).resolves.toEqual({ + success: false, + error: "Email channel SMTP not configured", + }); + } + expect(smtpMock).not.toHaveBeenCalled(); + }); + + it("rejects a non-numeric smtp_port", async () => { + await expect( + sendNotifyEmail(config({ smtp_port: "abc" }), message, env), + ).resolves.toEqual({ + success: false, + error: "Invalid Email channel SMTP port", + }); + expect(smtpMock).not.toHaveBeenCalled(); + }); + + it("rejects a missing sender", async () => { + await expect( + sendNotifyEmail( + config({ smtp_from: "", smtp_username: "" }), + message, + env, + ), + ).resolves.toEqual({ + success: false, + error: + "Invalid Email channel SMTP sender (set smtp_from or smtp_username)", + }); + expect(smtpMock).not.toHaveBeenCalled(); + }); +}); + +describe("sendNotifyEmail per-user SMTP send", () => { + it("sends with the per-user SMTP account and the frozen field mapping", async () => { + const result = await sendNotifyEmail( + config({ smtp_port: "465", from_name: ' Alerts "HQ" ' }), + message, + env, + ); + + expect(result).toEqual({ success: true }); + expect(smtpMock).toHaveBeenCalledTimes(1); + + const [smtpConfig, options] = smtpMock.mock.calls[0] as unknown as [ + Parameters[0], + Parameters[1], + ]; + expect(smtpConfig).toEqual({ + host: "smtp.example.com", + port: 465, + username: "user@example.com", + password: "test-smtp-password", + from: "sender@example.com", + from_name: ' Alerts "HQ" ', + secure: true, + }); + expect(options.to).toBe("recipient@example.com"); + expect(options.fromName).toBe("Alerts HQ"); + expect(options.subject).toBe("Renewal due"); + expect(options.html).toBe( + "

Renewal due

Your plan expires soon.

", + ); + }); + + it("falls back to smtp_username for the sender and uses STARTTLS on non-465 ports", async () => { + await sendNotifyEmail( + config({ smtp_from: "", smtp_port: "587" }), + message, + env, + ); + + const [smtpConfig] = smtpMock.mock.calls[0] as unknown as [ + Parameters[0], + ]; + expect(smtpConfig.from).toBe("user@example.com"); + expect(smtpConfig.port).toBe(587); + expect(smtpConfig.secure).toBe(false); + }); + + it("relays SMTP failures into the channel result", async () => { + smtpMock.mockResolvedValue({ + success: false, + error: "SMTP error: auth failed", + }); + + await expect(sendNotifyEmail(config(), message, env)).resolves.toEqual({ + success: false, + error: "SMTP error: auth failed", + }); + }); +});