Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions worker/src/services/email.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
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;
from?: string;
fromName?: string;
}

interface SMTPConfig {
export interface SMTPConfig {
host: string;
port: number;
username: string;
Expand Down Expand Up @@ -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,
Expand Down
61 changes: 51 additions & 10 deletions worker/src/services/notify/email-notify.ts
Original file line number Diff line number Diff line change
@@ -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, "&amp;")
Expand All @@ -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, "<br>");

return sendEmail(env, {
to: config.to,
subject: message.title.replace(/[\r\n]+/g, " "),
html: `<h2>${safeTitle}</h2><p>${safeBody}</p>`,
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: `<h2>${safeTitle}</h2><p>${safeBody}</p>`,
fromName: config.from_name?.replace(/[<>"\r\n]/g, "").trim() || undefined,
},
);
}
153 changes: 153 additions & 0 deletions worker/test/email-notify.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import("../src/services/email")>();
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, unknown> = {}): 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<typeof sendSmtpMail>[0],
Parameters<typeof sendSmtpMail>[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(
"<h2>Renewal due</h2><p>Your plan expires soon.</p>",
);
});

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<typeof sendSmtpMail>[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",
});
});
});
Loading