Skip to content
Merged
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
8 changes: 8 additions & 0 deletions worker/src/routes/me.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,14 @@ meRoutes.get("/notifications", async (c) => {
typeof v === "string" &&
v.length > 0,
);
// Email needs both a recipient and its own SMTP host to be usable, so it
// gets a dedicated check instead of the "any field is filled" heuristic.
if (ch === "email") {
const to = typeof parsed.to === "string" ? parsed.to.trim() : "";
const host =
typeof parsed.smtp_host === "string" ? parsed.smtp_host.trim() : "";
safeConfig[`${ch}_configured`] = Boolean(to && host);
}
// Return non-sensitive fields only
const redacted: Record<string, any> = {};
for (const [k, v] of Object.entries(parsed)) {
Expand Down
200 changes: 18 additions & 182 deletions worker/src/services/email.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { getTablePrefix } from "../types";
import type { Env } from "../types";
import { getSetting } from "../db/queries/settings";
import { connect } from "cloudflare:sockets";
import type { Env } from "../types";
import { getTablePrefix } from "../types";
import { sendSmtpMessage } from "./smtp-transport";

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");
}

Expand Down Expand Up @@ -112,183 +112,19 @@ async function sendViaSMTP(
if (!config.host)
return { success: false, error: "SMTP host not configured" };

const from = options.from || config.from || "noreply@example.com";
const fromName = (options.fromName || config.from_name || "eNotify").replace(
/[\r\n]/g,
"",
return sendSmtpMessage(
{
host: config.host,
port: config.port,
username: config.username,
password: config.password,
},
{
to: options.to,
subject: options.subject,
html: options.html,
from: options.from || config.from || "noreply@example.com",
fromName: options.fromName || config.from_name || "eNotify",
},
);
const isImplicitTls = config.port === 465;

const socket: any = connect({ hostname: config.host, port: config.port }, {
secureTransport: isImplicitTls ? "on" : "starttls",
} as any);

try {
const session = new SmtpSession(socket);

await session.expect(220);
await session.cmd("EHLO enotify");
await session.expect(250);

if (!isImplicitTls) {
const upgraded = await session.tryStartTls();
if (!upgraded && config.username && config.password) {
throw new Error(
"Server does not support STARTTLS; refusing to send credentials in plaintext",
);
}
}

if (config.username && config.password) {
await session.authLogin(config.username, config.password);
}

await session.sendMessage(
from,
fromName,
options.to,
options.subject,
options.html,
);
await session.quit();

return { success: true };
} catch (err) {
return {
success: false,
error: `SMTP error: ${err instanceof Error ? err.message : String(err)}`,
};
} finally {
await socket.close().catch(() => {});
}
}

class SmtpSession {
private buf = "";
private readonly dec = new TextDecoder();
private socket: any;
private reader: ReadableStreamDefaultReader<any>;
private writer: WritableStreamDefaultWriter<any>;

constructor(socket: any) {
this.socket = socket;
this.reader = socket.readable.getReader();
this.writer = socket.writable.getWriter();
}

async tryStartTls(): Promise<boolean> {
await this.cmd("STARTTLS");
const resp = await this.readResponse();
if (resp.code !== 220) return false;

this.reader.releaseLock();
this.writer.releaseLock();

const tls = this.socket.startTls();
this.socket = tls;
this.reader = tls.readable.getReader();
this.writer = tls.writable.getWriter();
this.buf = "";

await this.cmd("EHLO enotify");
await this.expect(250);
return true;
}

async authLogin(user: string, pass: string): Promise<void> {
await this.cmd("AUTH LOGIN");
await this.expect(334);
await this.cmd(btoa(user));
await this.expect(334);
await this.cmd(btoa(pass));
await this.expect(235);
}

async sendMessage(
from: string,
fromName: string,
to: string,
subject: string,
html: string,
): Promise<void> {
await this.cmd(`MAIL FROM:<${from}>`);
await this.expect(250);
await this.cmd(`RCPT TO:<${to}>`);
await this.expect(250);
await this.cmd("DATA");
await this.expect(354);

const date = new Date().toUTCString();
const msgId = `<${Date.now()}.${Math.random().toString(36).slice(2)}@enotify>`;
const b64Body = wrapBase64(encodeUtf8Base64(html));
const encodedSubject = `=?UTF-8?B?${encodeUtf8Base64(subject)}?=`;

const message =
`From: ${fromName} <${from}>\r\n` +
`To: ${to}\r\n` +
`Subject: ${encodedSubject}\r\n` +
`Date: ${date}\r\n` +
`Message-ID: ${msgId}\r\n` +
`MIME-Version: 1.0\r\n` +
`Content-Type: text/html; charset=UTF-8\r\n` +
`Content-Transfer-Encoding: base64\r\n` +
`\r\n` +
`${b64Body}\r\n` +
`.\r\n`;

await this.writer.write(new TextEncoder().encode(message));
await this.expect(250);
}

async quit(): Promise<void> {
await this.cmd("QUIT").catch(() => {});
}

async cmd(text: string): Promise<void> {
await this.writer.write(new TextEncoder().encode(text + "\r\n"));
}

async expect(code: number): Promise<void> {
const resp = await this.readResponse();
if (resp.code !== code) {
throw new Error(
`SMTP: expected ${code}, got ${resp.code} — ${resp.message}`,
);
}
}

async readResponse(): Promise<{ code: number; message: string }> {
const lines: string[] = [];
for (;;) {
while (!this.buf.includes("\r\n")) {
const { value, done } = await this.reader.read();
if (done) throw new Error("SMTP: connection closed unexpectedly");
this.buf += this.dec.decode(value);
}

const eol = this.buf.indexOf("\r\n");
const line = this.buf.slice(0, eol);
this.buf = this.buf.slice(eol + 2);
lines.push(line);

// RFC 5321: last line has space at position 3; continuation lines have '-'
if (line.length <= 3 || line[3] === " ") {
const code = Number.parseInt(line.slice(0, 3), 10);
if (Number.isNaN(code))
throw new Error(`SMTP: invalid response line: ${line}`);
return { code, message: lines.map((l) => l.slice(4)).join("\n") };
}
}
}
}

function encodeUtf8Base64(str: string): string {
const bytes = new TextEncoder().encode(str);
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
}

function wrapBase64(b64: string): string {
return b64.match(/.{1,76}/g)?.join("\r\n") ?? b64;
}
117 changes: 104 additions & 13 deletions worker/src/services/notify/email-notify.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
import type { NotifyMessage } from "./index";
import type { Env } from "../../types";
import { sendEmail } from "../email";
import { isValidEmail } from "../email";
import { sendSmtpMessage } from "../smtp-transport";
import type { NotifyMessage } from "./index";

// Per-user Email channel config, stored in `notification_configs.email_config`.
// Delivery always uses the user's own SMTP server; the global email settings
// (settings table: email_provider / smtp_config / resend_config) are never read
// here, and there is no fallback to the system mail path.
interface EmailNotifyConfig {
to: string;
to?: string;
from_name?: string;
smtp_host?: string;
smtp_port?: string | number;
smtp_username?: string;
smtp_password?: string;
smtp_from?: string;
}

function escapeHtml(s: string): string {
Expand All @@ -15,27 +25,108 @@ function escapeHtml(s: string): string {
.replace(/"/g, "&quot;");
}

/** `smtp_port` is stored as a string in the JSON config; SMTP needs a number. */
function parsePort(raw: string | number | undefined): number | null {
if (raw === undefined || raw === null) return null;
const text = String(raw).trim();
if (!text) return null;
const port = Number(text);
if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
return port;
}

function clean(value: unknown): string {
return String(value ?? "").trim();
}

/**
* Header/envelope injection guards. `to` and `from` both end up verbatim in
* `MAIL FROM:`/`RCPT TO:` and in message headers, so they are validated the
* same way.
*/
function hasInjectionChars(value: string): boolean {
return /[\r\n,;<>]/.test(value);
}

/** Conservative hostname / IPv4 / bracketed IPv6 check (no spaces, no userinfo). */
function isValidSmtpHost(host: string): boolean {
return /^[A-Za-z0-9._\-:[\]]+$/.test(host);
}

export async function sendNotifyEmail(
configJson: string,
message: NotifyMessage,
env: Env,
_env: Env,
): Promise<{ success: boolean; error?: string }> {
const config: EmailNotifyConfig = JSON.parse(configJson);
if (!config.to) {
let config: EmailNotifyConfig;
try {
config = JSON.parse(configJson);
} catch {
return { success: false, error: "Invalid email config" };
}

const to = clean(config.to);
if (!to) {
return { success: false, error: "Email recipient required" };
}

if (/[\r\n,;<>]/.test(config.to)) {
if (hasInjectionChars(to)) {
return { success: false, error: "Invalid email recipient" };
}

if (!isValidEmail(to)) {
return { success: false, error: "Invalid recipient email address" };
}

const host = clean(config.smtp_host);
if (!host) {
return { success: false, error: "Email channel SMTP not configured" };
}

if (!isValidSmtpHost(host)) {
return { success: false, error: "Invalid Email channel SMTP host" };
}

const port = parsePort(config.smtp_port);
if (port === null) {
return { success: false, error: "Invalid Email channel SMTP port" };
}

const username = clean(config.smtp_username);
const password = config.smtp_password ?? "";
// `from` comes from the user's own config only — never a shared default.
const from = clean(config.smtp_from) || username;
if (!from) {
return {
success: false,
error:
"Invalid Email channel SMTP sender (set smtp_from or smtp_username)",
};
}

// `from` lands in `MAIL FROM:<…>` and the `From:` header, so it gets the same
// injection + format validation as `to`.
if (hasInjectionChars(from) || !isValidEmail(from)) {
return {
success: false,
error: "Invalid Email channel SMTP sender address",
};
}
const fromName = clean(config.from_name)
.replace(/[<>"\r\n]/g, "")
.trim();

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 sendSmtpMessage(
{ host, port, username, password },
{
to,
subject: message.title.replace(/[\r\n]+/g, " "),
html: `<h2>${safeTitle}</h2><p>${safeBody}</p>`,
from,
fromName: fromName || undefined,
},
);
}
Loading
Loading