diff --git a/worker/src/routes/me.ts b/worker/src/routes/me.ts index ca42bae..b3ea4e8 100644 --- a/worker/src/routes/me.ts +++ b/worker/src/routes/me.ts @@ -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 = {}; for (const [k, v] of Object.entries(parsed)) { diff --git a/worker/src/services/email.ts b/worker/src/services/email.ts index 087258d..40793e2 100644 --- a/worker/src/services/email.ts +++ b/worker/src/services/email.ts @@ -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"); } @@ -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; - private writer: WritableStreamDefaultWriter; - - constructor(socket: any) { - this.socket = socket; - this.reader = socket.readable.getReader(); - this.writer = socket.writable.getWriter(); - } - - async tryStartTls(): Promise { - 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 { - 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 { - 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 { - await this.cmd("QUIT").catch(() => {}); - } - - async cmd(text: string): Promise { - await this.writer.write(new TextEncoder().encode(text + "\r\n")); - } - - async expect(code: number): Promise { - 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; } diff --git a/worker/src/services/notify/email-notify.ts b/worker/src/services/notify/email-notify.ts index 7b710eb..5ac1694 100644 --- a/worker/src/services/notify/email-notify.ts +++ b/worker/src/services/notify/email-notify.ts @@ -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 { @@ -15,27 +25,108 @@ function escapeHtml(s: string): string { .replace(/"/g, """); } +/** `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, "
"); - 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 sendSmtpMessage( + { host, port, username, password }, + { + to, + subject: message.title.replace(/[\r\n]+/g, " "), + html: `

${safeTitle}

${safeBody}

`, + from, + fromName: fromName || undefined, + }, + ); } diff --git a/worker/src/services/smtp-transport.ts b/worker/src/services/smtp-transport.ts new file mode 100644 index 0000000..ca49ee2 --- /dev/null +++ b/worker/src/services/smtp-transport.ts @@ -0,0 +1,205 @@ +import { connect } from "cloudflare:sockets"; + +// Low-level SMTP transport shared by the system mail path (`services/email.ts`, +// configured globally in the settings table) and the per-user Email +// notification channel (`services/notify/email-notify.ts`). The caller decides +// where host/port/credentials come from; this module only speaks SMTP. + +export interface SmtpTransportConfig { + host: string; + port: number; + username?: string; + password?: string; +} + +export interface SmtpMessage { + to: string; + subject: string; + html: string; + /** Envelope/header sender address. */ + from: string; + /** Display name for the From header (optional). */ + fromName?: string; +} + +export async function sendSmtpMessage( + config: SmtpTransportConfig, + message: SmtpMessage, +): Promise<{ success: boolean; error?: string }> { + const from = message.from || "noreply@example.com"; + const fromName = (message.fromName || "eNotify").replace(/[\r\n]/g, ""); + 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, + message.to, + message.subject, + message.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(() => {}); + } +} + +export class SmtpSession { + private buf = ""; + private readonly dec = new TextDecoder(); + private socket: any; + private reader: ReadableStreamDefaultReader; + private writer: WritableStreamDefaultWriter; + + constructor(socket: any) { + this.socket = socket; + this.reader = socket.readable.getReader(); + this.writer = socket.writable.getWriter(); + } + + async tryStartTls(): Promise { + 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 { + 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 { + 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 { + await this.cmd("QUIT").catch(() => {}); + } + + async cmd(text: string): Promise { + await this.writer.write(new TextEncoder().encode(text + "\r\n")); + } + + async expect(code: number): Promise { + 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") }; + } + } + } +} + +export 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); +} + +export function wrapBase64(b64: string): string { + return b64.match(/.{1,76}/g)?.join("\r\n") ?? b64; +} diff --git a/worker/test/email-notify.test.ts b/worker/test/email-notify.test.ts new file mode 100644 index 0000000..3310b91 --- /dev/null +++ b/worker/test/email-notify.test.ts @@ -0,0 +1,492 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { sendNotifyEmail } from "../src/services/notify/email-notify"; +import { sendNotifications } from "../src/services/notify/index"; +import type { Env } from "../src/types"; +import { setConnectFactory } from "./stubs/sockets"; + +// ─── Fake SMTP server over an in-memory duplex socket ──────────────────────── + +interface FakeOptions { + supportsStartTls?: boolean; + rejectAuth?: boolean; + rejectRecipient?: boolean; +} + +class FakeSmtpServer { + commands: string[] = []; + connectCalls: { address: unknown; options: unknown }[] = []; + message = ""; + startTlsUsed = false; + authSeen: { user?: string; pass?: string; afterTls: boolean } | null = null; + + private controller!: ReadableStreamDefaultController; + private stream = new ReadableStream({ + start: (controller) => { + this.controller = controller; + this.push("220 fake.example.com ESMTP"); + }, + }); + private lineBuf = ""; + private inData = false; + private pending: "user" | "pass" | null = null; + + constructor(private readonly opts: FakeOptions = {}) {} + + socket() { + const self = this; + return { + readable: this.stream, + writable: new WritableStream({ + write(chunk) { + self.handleChunk(new TextDecoder().decode(chunk)); + }, + }), + startTls() { + self.startTlsUsed = true; + return self.socket(); + }, + close: async () => { + try { + self.controller.close(); + } catch { + /* already closed */ + } + }, + }; + } + + install(): void { + setConnectFactory((address, options) => { + this.connectCalls.push({ address, options }); + return this.socket(); + }); + } + + private push(line: string): void { + this.controller.enqueue(new TextEncoder().encode(`${line}\r\n`)); + } + + private handleChunk(text: string): void { + this.lineBuf += text; + let idx = this.lineBuf.indexOf("\r\n"); + while (idx >= 0) { + const line = this.lineBuf.slice(0, idx); + this.lineBuf = this.lineBuf.slice(idx + 2); + this.onLine(line); + idx = this.lineBuf.indexOf("\r\n"); + } + } + + private onLine(line: string): void { + if (this.inData) { + if (line === ".") { + this.inData = false; + this.push("250 2.0.0 queued"); + } else { + this.message += `${line}\r\n`; + } + return; + } + + if (this.pending === "user") { + this.authSeen = { + ...this.authSeen, + user: Buffer.from(line, "base64").toString("utf8"), + afterTls: this.startTlsUsed, + }; + this.pending = "pass"; + this.push("334 UGFzc3dvcmQ6"); + return; + } + if (this.pending === "pass") { + if (this.authSeen) { + this.authSeen.pass = Buffer.from(line, "base64").toString("utf8"); + this.authSeen.afterTls = this.startTlsUsed; + } + this.pending = null; + this.push(this.opts.rejectAuth ? "535 auth failed" : "235 2.7.0 ok"); + return; + } + + this.commands.push(line); + const upper = line.toUpperCase(); + + if (upper.startsWith("EHLO")) { + if (this.opts.supportsStartTls === false) { + this.push("250 fake.example.com"); + } else { + this.push("250-fake.example.com"); + this.push("250 STARTTLS"); + } + return; + } + if (upper === "STARTTLS") { + this.push( + this.opts.supportsStartTls === false + ? "500 5.5.1 unknown" + : "220 go ahead", + ); + return; + } + if (upper === "AUTH LOGIN") { + this.pending = "user"; + this.push("334 VXNlcm5hbWU6"); + return; + } + if (upper.startsWith("MAIL FROM")) { + this.push("250 2.1.0 ok"); + return; + } + if (upper.startsWith("RCPT TO")) { + this.push( + this.opts.rejectRecipient ? "550 5.1.1 no such user" : "250 2.1.5 ok", + ); + return; + } + if (upper === "DATA") { + this.inData = true; + this.push("354 end with ."); + return; + } + if (upper === "QUIT") { + this.push("221 bye"); + return; + } + this.push("500 5.5.1 unrecognized"); + } +} + +/** Env whose DB throws on any access — proves no global settings are read. */ +function makeEnvWithoutSettings(): Env { + return Object.defineProperty({}, "DB", { + get() { + throw new Error("settings table must not be read by the email channel"); + }, + }) as Env; +} + +function config(overrides: Record = {}): string { + return JSON.stringify({ + to: "user@example.com", + smtp_host: "smtp.example.com", + smtp_port: "587", + smtp_username: "login@example.com", + smtp_password: "s3cret-pass", + smtp_from: "notify@example.com", + ...overrides, + }); +} + +const MESSAGE = { title: "Renewal due", body: "Your plan expires soon." }; + +afterEach(() => { + setConnectFactory(undefined); +}); + +describe("sendNotifyEmail", () => { + it("fails without SMTP host configured and does not fall back to system mail", async () => { + const result = await sendNotifyEmail( + JSON.stringify({ to: "user@example.com" }), + MESSAGE, + makeEnvWithoutSettings(), + ); + + expect(result.success).toBe(false); + expect(result.error).toBe("Email channel SMTP not configured"); + }); + + it("still requires a valid recipient address", async () => { + const env = makeEnvWithoutSettings(); + + await expect(sendNotifyEmail("{}", MESSAGE, env)).resolves.toEqual({ + success: false, + error: "Email recipient required", + }); + await expect( + sendNotifyEmail(config({ to: "a@b.com,c@d.com" }), MESSAGE, env), + ).resolves.toEqual({ success: false, error: "Invalid email recipient" }); + await expect( + sendNotifyEmail(config({ to: "not-an-email" }), MESSAGE, env), + ).resolves.toEqual({ + success: false, + error: "Invalid recipient email address", + }); + }); + + it("rejects an unusable smtp_port instead of guessing one", async () => { + const env = makeEnvWithoutSettings(); + for (const port of ["", "abc", "0", "70000"]) { + const result = await sendNotifyEmail( + config({ smtp_port: port }), + MESSAGE, + env, + ); + expect(result).toEqual({ + success: false, + error: "Invalid Email channel SMTP port", + }); + } + }); + + it("rejects a smtp_host that is not a plain hostname/IP", async () => { + const env = makeEnvWithoutSettings(); + for (const host of [ + "smtp.example.com\r\nX-Injected: 1", + "smtp.example.com/evil", + "user@smtp.example.com", + "smtp example com", + "smtp.example.com;evil", + ]) { + const result = await sendNotifyEmail( + config({ smtp_host: host }), + MESSAGE, + env, + ); + expect(result).toEqual({ + success: false, + error: "Invalid Email channel SMTP host", + }); + } + }); + + it("accepts a plain hostname, an IPv4 address and a bracketed IPv6 address", async () => { + const env = makeEnvWithoutSettings(); + for (const host of ["smtp.example.com", "192.0.2.10", "[2001:db8::1]"]) { + const server = new FakeSmtpServer(); + server.install(); + const result = await sendNotifyEmail( + config({ smtp_host: host }), + MESSAGE, + env, + ); + expect(result).toEqual({ success: true }); + expect(server.connectCalls[0].address).toMatchObject({ hostname: host }); + } + }); + + it("rejects a sender address that would inject headers or is malformed", async () => { + const env = makeEnvWithoutSettings(); + for (const from of [ + "notify@example.com\r\nBcc: victim@example.com", + "notify@example.com,eve@example.com", + "notify@example.com>", + "not-an-email", + ]) { + const server = new FakeSmtpServer(); + server.install(); + const result = await sendNotifyEmail( + config({ smtp_from: from }), + MESSAGE, + env, + ); + expect(result).toEqual({ + success: false, + error: "Invalid Email channel SMTP sender address", + }); + // Nothing was ever sent, not even a connection attempt. + expect(server.connectCalls).toHaveLength(0); + expect(server.commands).toHaveLength(0); + } + }); + + it("rejects an injection attempt that comes in through smtp_username", async () => { + const env = makeEnvWithoutSettings(); + const result = await sendNotifyEmail( + config({ + smtp_from: "", + smtp_username: "login@example.com\r\nBcc: victim@example.com", + }), + MESSAGE, + env, + ); + expect(result).toEqual({ + success: false, + error: "Invalid Email channel SMTP sender address", + }); + }); + + it("falls back to smtp_username as the sender when smtp_from is empty", async () => { + const server = new FakeSmtpServer(); + server.install(); + + const result = await sendNotifyEmail( + config({ smtp_from: "" }), + MESSAGE, + makeEnvWithoutSettings(), + ); + + expect(result).toEqual({ success: true }); + expect(server.commands).toContain("MAIL FROM:"); + expect(server.message).toContain("From: eNotify "); + }); + + it("does not throw on non-string config values", async () => { + const env = makeEnvWithoutSettings(); + await expect( + sendNotifyEmail(config({ to: 12345 }), MESSAGE, env), + ).resolves.toEqual({ + success: false, + error: "Invalid recipient email address", + }); + await expect( + sendNotifyEmail(config({ smtp_host: null }), MESSAGE, env), + ).resolves.toEqual({ + success: false, + error: "Email channel SMTP not configured", + }); + }); + + it("uses implicit TLS on port 465 and authenticates in the TLS session", async () => { + const server = new FakeSmtpServer(); + server.install(); + + const result = await sendNotifyEmail( + config({ smtp_port: "465" }), + MESSAGE, + makeEnvWithoutSettings(), + ); + + expect(result).toEqual({ success: true }); + expect(server.connectCalls[0].address).toEqual({ + hostname: "smtp.example.com", + port: 465, + }); + expect(server.connectCalls[0].options).toEqual({ secureTransport: "on" }); + expect(server.commands.some((c) => c.toUpperCase() === "STARTTLS")).toBe( + false, + ); + expect(server.authSeen?.user).toBe("login@example.com"); + expect(server.authSeen?.pass).toBe("s3cret-pass"); + expect(server.message).toContain("From: eNotify "); + expect(server.message).toContain("To: user@example.com"); + expect(server.commands).toContain("MAIL FROM:"); + expect(server.commands).toContain("RCPT TO:"); + }); + + it("converts the string port to a number and negotiates STARTTLS otherwise", async () => { + const server = new FakeSmtpServer(); + server.install(); + + const result = await sendNotifyEmail( + config({ smtp_port: "587" }), + MESSAGE, + makeEnvWithoutSettings(), + ); + + expect(result).toEqual({ success: true }); + expect(server.connectCalls[0].address).toEqual({ + hostname: "smtp.example.com", + port: 587, + }); + expect(server.connectCalls[0].options).toEqual({ + secureTransport: "starttls", + }); + expect(server.startTlsUsed).toBe(true); + expect( + server.commands.filter((c) => c.toUpperCase().startsWith("EHLO")), + ).toHaveLength(2); + expect(server.authSeen?.afterTls).toBe(true); + }); + + it("refuses to send credentials in plaintext when STARTTLS is unsupported", async () => { + const server = new FakeSmtpServer({ supportsStartTls: false }); + server.install(); + + const result = await sendNotifyEmail( + config(), + MESSAGE, + makeEnvWithoutSettings(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("refusing to send credentials in plaintext"); + expect(server.commands).not.toContain("AUTH LOGIN"); + expect(server.message).toBe(""); + }); + + it("sends without authentication when only a sender is configured", async () => { + const server = new FakeSmtpServer({ supportsStartTls: false }); + server.install(); + + const result = await sendNotifyEmail( + config({ smtp_username: "", smtp_password: "" }), + MESSAGE, + makeEnvWithoutSettings(), + ); + + expect(result).toEqual({ success: true }); + expect(server.commands).not.toContain("AUTH LOGIN"); + expect(server.commands).toContain("MAIL FROM:"); + }); + + it("refuses to send when no sender can be derived from the config", async () => { + const result = await sendNotifyEmail( + config({ smtp_username: "", smtp_from: "" }), + MESSAGE, + makeEnvWithoutSettings(), + ); + + expect(result).toEqual({ + success: false, + error: + "Invalid Email channel SMTP sender (set smtp_from or smtp_username)", + }); + }); + + it("surfaces SMTP server rejections as errors", async () => { + const server = new FakeSmtpServer({ rejectRecipient: true }); + server.install(); + + const result = await sendNotifyEmail( + config(), + MESSAGE, + makeEnvWithoutSettings(), + ); + + expect(result.success).toBe(false); + expect(result.error).toContain("SMTP error"); + }); + + it("records the failure in notification history without falling back", async () => { + const inserts: unknown[][] = []; + const db = { + prepare: (sql: string) => ({ + bind: (...args: unknown[]) => ({ + run: async () => { + if (sql.includes("notification_history")) inserts.push(args); + return { success: true }; + }, + }), + }), + }; + + const results = await sendNotifications( + { + user_id: "user-1", + enabled_channels: JSON.stringify(["email"]), + email_config: JSON.stringify({ to: "user@example.com" }), + } as any, + MESSAGE, + { DB: db } as unknown as Env, + { + db: db as unknown as D1Database, + prefix: "", + userId: "user-1", + itemId: "item-1", + }, + ); + + expect(results).toEqual([ + { + channel: "email", + success: false, + error: "Email channel SMTP not configured", + }, + ]); + expect(inserts).toHaveLength(1); + // (id, user_id, item_id, channel, title, body, success, error, created_at) + expect(inserts[0][3]).toBe("email"); + expect(inserts[0][6]).toBe(0); + expect(String(inserts[0][7])).toMatch(/SMTP not configured/); + }); +}); diff --git a/worker/test/me-notifications.test.ts b/worker/test/me-notifications.test.ts new file mode 100644 index 0000000..b0094a0 --- /dev/null +++ b/worker/test/me-notifications.test.ts @@ -0,0 +1,262 @@ +import { Hono } from "hono"; +import { beforeEach, describe, expect, it } from "vitest"; +import { meRoutes } from "../src/routes/me"; +import { + cookieHeader, + MockKV, + makeToken, + request, + seedSession, +} from "./helpers"; + +// Minimal in-memory stand-in for the `notification_configs` table, enough for +// the GET/PUT notification-config round trip in routes/me.ts. +class ConfigDB { + rows = new Map>(); + + prepare(sql: string) { + const s = sql.replace(/\s+/g, " "); + + if (/^SELECT \* FROM .*notification_configs WHERE user_id = \?/i.test(s)) { + return { + bind: (userId: string) => ({ + first: async () => this.rows.get(userId) ?? null, + }), + }; + } + + if (/^INSERT INTO .*notification_configs/i.test(s)) { + return { + bind: (...args: unknown[]) => ({ + run: async () => { + const cols = (s.match(/\(([^)]*)\) VALUES/i)?.[1] ?? "") + .split(",") + .map((c) => c.trim()); + const userId = String(args[0]); + const row: Record = {}; + cols.forEach((col, i) => { + row[col] = args[i]; + }); + this.rows.set(userId, row); + return { success: true }; + }, + }), + }; + } + + throw new Error(`ConfigDB: unsupported SQL: ${s}`); + } +} + +function makeApp() { + const app = new Hono(); + app.route("/api/me", meRoutes); + return app; +} + +async function makeLoggedInEnv(db: ConfigDB): Promise> { + const env: Record = { + DB: db, + KV: new MockKV(), + JWT_SECRET: "test-jwt-secret-0123456789abcdef", + SETUP_SECRET: "test-setup-secret", + TABLE_PREFIX: "", + ASSETS: {}, + }; + await seedSession(env, "user-1", "session-1"); + return env; +} + +describe("GET/PUT /api/me/notifications — per-user SMTP credentials", () => { + let db: ConfigDB; + let app: Hono; + let env: Record; + let token: string; + + beforeEach(async () => { + db = new ConfigDB(); + app = makeApp(); + env = await makeLoggedInEnv(db); + token = await makeToken("user", { sub: "user-1", sid: "session-1" }); + }); + + it("stores the SMTP fields sent by the client", async () => { + const res = await request(app, env, "/api/me/notifications", { + method: "PUT", + headers: { ...cookieHeader(token), "Content-Type": "application/json" }, + body: JSON.stringify({ + enabled_channels: ["email"], + email_config: { + to: "user@example.com", + smtp_host: "smtp.example.com", + smtp_port: "465", + smtp_username: "login@example.com", + smtp_password: "s3cret-pass", + smtp_from: "notify@example.com", + }, + }), + }); + + expect(res.status).toBe(200); + const stored = JSON.parse(db.rows.get("user-1")?.email_config ?? "{}"); + expect(stored).toEqual({ + to: "user@example.com", + smtp_host: "smtp.example.com", + smtp_port: "465", + smtp_username: "login@example.com", + smtp_password: "s3cret-pass", + smtp_from: "notify@example.com", + }); + }); + + it("masks smtp_password on read and keeps the stored password when the mask is sent back", async () => { + db.rows.set("user-1", { + user_id: "user-1", + enabled_channels: JSON.stringify(["email"]), + notification_hours: JSON.stringify([]), + email_config: JSON.stringify({ + to: "user@example.com", + smtp_host: "smtp.example.com", + smtp_port: "587", + smtp_username: "login@example.com", + smtp_password: "s3cret-pass", + smtp_from: "notify@example.com", + }), + updated_at: new Date().toISOString(), + }); + + const got = await request(app, env, "/api/me/notifications", { + headers: cookieHeader(token), + }); + expect(got.status).toBe(200); + expect(got.body.email_config).toEqual({ + to: "user@example.com", + smtp_host: "smtp.example.com", + smtp_port: "587", + smtp_username: "login@example.com", + smtp_password: "••••••", + smtp_from: "notify@example.com", + }); + expect(got.body.email_configured).toBe(true); + + const put = await request(app, env, "/api/me/notifications", { + method: "PUT", + headers: { ...cookieHeader(token), "Content-Type": "application/json" }, + body: JSON.stringify({ + email_config: { + ...got.body.email_config, + smtp_port: "465", + }, + }), + }); + expect(put.status).toBe(200); + + const stored = JSON.parse(db.rows.get("user-1")?.email_config ?? "{}"); + expect(stored.smtp_password).toBe("s3cret-pass"); + expect(stored.smtp_port).toBe("465"); + }); + + it("keeps the stored password when an empty password is sent back", async () => { + db.rows.set("user-1", { + user_id: "user-1", + enabled_channels: JSON.stringify(["email"]), + notification_hours: JSON.stringify([]), + email_config: JSON.stringify({ + to: "user@example.com", + smtp_host: "smtp.example.com", + smtp_username: "login@example.com", + smtp_password: "s3cret-pass", + }), + updated_at: new Date().toISOString(), + }); + + const res = await request(app, env, "/api/me/notifications", { + method: "PUT", + headers: { ...cookieHeader(token), "Content-Type": "application/json" }, + body: JSON.stringify({ + email_config: { + to: "user@example.com", + smtp_host: "smtp.example.com", + smtp_username: "login@example.com", + smtp_password: "", + }, + }), + }); + expect(res.status).toBe(200); + expect( + JSON.parse(db.rows.get("user-1")?.email_config ?? "{}").smtp_password, + ).toBe("s3cret-pass"); + }); +}); + +describe("GET /api/me/notifications — email_configured", () => { + let db: ConfigDB; + let app: Hono; + let env: Record; + let token: string; + + beforeEach(async () => { + db = new ConfigDB(); + app = makeApp(); + env = await makeLoggedInEnv(db); + token = await makeToken("user", { sub: "user-1", sid: "session-1" }); + }); + + async function configuredFor(emailConfig: Record) { + db.rows.set("user-1", { + user_id: "user-1", + enabled_channels: JSON.stringify(["email"]), + notification_hours: JSON.stringify([]), + email_config: JSON.stringify(emailConfig), + updated_at: new Date().toISOString(), + }); + const res = await request(app, env, "/api/me/notifications", { + headers: cookieHeader(token), + }); + expect(res.status).toBe(200); + return res.body; + } + + it("is true only when both to and smtp_host are filled in", async () => { + const both = await configuredFor({ + to: "user@example.com", + smtp_host: "smtp.example.com", + }); + expect(both.email_configured).toBe(true); + }); + + it("is false when only the recipient is configured", async () => { + const onlyTo = await configuredFor({ to: "user@example.com" }); + expect(onlyTo.email_configured).toBe(false); + }); + + it("is false when only the SMTP host is configured", async () => { + const onlyHost = await configuredFor({ smtp_host: "smtp.example.com" }); + expect(onlyHost.email_configured).toBe(false); + }); + + it("is false for whitespace-only values and for an empty config", async () => { + const blank = await configuredFor({ to: " ", smtp_host: " " }); + expect(blank.email_configured).toBe(false); + + const empty = await configuredFor({}); + expect(empty.email_configured).toBe(false); + }); + + it("does not tighten the heuristic for other channels", async () => { + db.rows.set("user-1", { + user_id: "user-1", + enabled_channels: JSON.stringify(["telegram", "email"]), + notification_hours: JSON.stringify([]), + telegram_config: JSON.stringify({ token: "123:abc", chat_id: "1" }), + email_config: JSON.stringify({ to: "user@example.com" }), + updated_at: new Date().toISOString(), + }); + const res = await request(app, env, "/api/me/notifications", { + headers: cookieHeader(token), + }); + expect(res.status).toBe(200); + expect(res.body.telegram_configured).toBe(true); + expect(res.body.email_configured).toBe(false); + }); +}); diff --git a/worker/test/stubs/sockets.ts b/worker/test/stubs/sockets.ts index 84aa26c..a93930d 100644 --- a/worker/test/stubs/sockets.ts +++ b/worker/test/stubs/sockets.ts @@ -1,6 +1,20 @@ // Stub for Cloudflare's `cloudflare:sockets` module, which is unavailable in -// the Node test environment. `sendEmail` imports `connect` but never calls it -// in these tests, so this only needs to satisfy the import. -export function connect(): never { - throw new Error("cloudflare:sockets connect is not available in unit tests"); +// the Node test environment. Tests that need a real SMTP conversation install a +// fake socket factory via `setConnectFactory`; everything else keeps the +// original "not available" behaviour. +type ConnectFactory = (address: unknown, options?: unknown) => unknown; + +let factory: ConnectFactory | undefined; + +export function setConnectFactory(fn: ConnectFactory | undefined): void { + factory = fn; +} + +export function connect(address: unknown, options?: unknown): any { + if (!factory) { + throw new Error( + "cloudflare:sockets connect is not available in unit tests", + ); + } + return factory(address, options); }