| 1 | import { connect } from "cloudflare:sockets"; |
| 2 | import type { Env } from "../env.js"; |
| 3 | import type { Outgoing } from "./send.js"; |
| 4 | |
| 5 | /** |
| 6 | * Sending over SMTP, for an instance without Cloudflare Email Sending (the EMAIL binding), such as |
| 7 | * one on celld. SMTP_URL names the server and the user and SMTP_PASSWORD (a secret) the password: |
| 8 | * `smtps://user@host:465` is TLS from the first byte, and `smtp://user@host:587` upgrades with |
| 9 | * STARTTLS and refuses to go on without it, so the password never crosses the network in the clear. |
| 10 | * Each email is one TCP connection (`cloudflare:sockets`, which celld provides too). Nothing of the |
| 11 | * conversation is logged; errors carry the server's replies, never the commands sent. |
| 12 | */ |
| 13 | |
| 14 | export interface SmtpConfig { |
| 15 | host: string; |
| 16 | port: number; |
| 17 | /** `implicit`: TLS from the start (smtps://). `starttls`: plain until STARTTLS, which is required (smtp://). */ |
| 18 | tls: "implicit" | "starttls"; |
| 19 | user: string | null; |
| 20 | password: string | null; |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * E_SMTP_TRANSIENT (a 4xx reply, a timeout or a dropped connection) is retried. E_SMTP_RECIPIENT_REJECTED |
| 25 | * (the server refused the recipient for good) suppresses the address. E_SMTP_REJECTED (any other 5xx, |
| 26 | * such as a wrong password) and E_SMTP_CONFIG fail the email and change nothing else. |
| 27 | */ |
| 28 | export type SmtpErrorCode = "E_SMTP_CONFIG" | "E_SMTP_TRANSIENT" | "E_SMTP_REJECTED" | "E_SMTP_RECIPIENT_REJECTED"; |
| 29 | |
| 30 | export class SmtpError extends Error { |
| 31 | constructor( |
| 32 | readonly code: SmtpErrorCode, |
| 33 | message: string, |
| 34 | ) { |
| 35 | super(message); |
| 36 | this.name = "SmtpError"; |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | /** The SMTP settings, null when SMTP_URL is unset, or what is wrong with them. */ |
| 41 | export function smtpConfig(env: Pick<Env, "SMTP_URL" | "SMTP_PASSWORD">): SmtpConfig | { error: string } | null { |
| 42 | const raw = env.SMTP_URL?.trim(); |
| 43 | if (!raw) return null; |
| 44 | let u: URL; |
| 45 | try { |
| 46 | u = new URL(raw); |
| 47 | } catch { |
| 48 | return { error: "SMTP_URL is not a URL" }; |
| 49 | } |
| 50 | const tls = u.protocol === "smtps:" ? "implicit" : u.protocol === "smtp:" ? "starttls" : null; |
| 51 | if (!tls) return { error: "SMTP_URL must start with smtps:// or smtp://" }; |
| 52 | if (u.password) return { error: "the password goes in the SMTP_PASSWORD secret, not in SMTP_URL" }; |
| 53 | const host = u.hostname.replace(/^\[(.*)\]$/, "$1"); |
| 54 | if (!host) return { error: "SMTP_URL has no host" }; |
| 55 | if ((u.pathname && u.pathname !== "/") || u.search || u.hash) return { error: "SMTP_URL takes no path or query" }; |
| 56 | let user: string | null; |
| 57 | try { |
| 58 | user = u.username ? decodeURIComponent(u.username) : null; |
| 59 | } catch { |
| 60 | return { error: "SMTP_URL has a badly escaped user" }; |
| 61 | } |
| 62 | const password = env.SMTP_PASSWORD || null; |
| 63 | if (user && !password) return { error: "SMTP_URL names a user but the SMTP_PASSWORD secret is not set" }; |
| 64 | if (password && !user) return { error: "SMTP_PASSWORD is set but SMTP_URL names no user" }; |
| 65 | return { host, port: u.port ? Number(u.port) : tls === "implicit" ? 465 : 587, tls, user, password }; |
| 66 | } |
| 67 | |
| 68 | /** SMTP_URL as an administrator may see it: scheme, user, host and port. */ |
| 69 | export const smtpLabel = (c: SmtpConfig): string => |
| 70 | `${c.tls === "implicit" ? "smtps" : "smtp"}://${c.user ? `${encodeURIComponent(c.user)}@` : ""}${c.host.includes(":") ? `[${c.host}]` : c.host}:${c.port}${c.tls === "starttls" ? " (STARTTLS)" : ""}`; |
| 71 | |
| 72 | /** How long to wait for each reply, and for each write. */ |
| 73 | export const SMTP_TIMEOUT_MS = 30_000; |
| 74 | |
| 75 | const enc = new TextEncoder(); |
| 76 | |
| 77 | function b64(s: string): string { |
| 78 | let bin = ""; |
| 79 | for (const b of enc.encode(s)) bin += String.fromCharCode(b); |
| 80 | return btoa(bin); |
| 81 | } |
| 82 | |
| 83 | /** Base64 in lines of 76 characters (RFC 2045). */ |
| 84 | const b64Lines = (s: string): string => b64(s).replace(/.{76}/g, "$&\r\n"); |
| 85 | |
| 86 | const ASCII = /^[\x20-\x7e]*$/; |
| 87 | |
| 88 | /** A header value with non-ASCII text as RFC 2047 encoded words of at most 39 bytes of UTF-8 each, so a folded line stays under 78 characters. */ |
| 89 | function encodeWords(s: string): string { |
| 90 | if (ASCII.test(s)) return s; |
| 91 | const words: string[] = []; |
| 92 | let cur = ""; |
| 93 | for (const ch of s) { |
| 94 | if (cur && enc.encode(cur + ch).length > 39) { |
| 95 | words.push(cur); |
| 96 | cur = ""; |
| 97 | } |
| 98 | cur += ch; |
| 99 | } |
| 100 | if (cur) words.push(cur); |
| 101 | return words.map((w) => `=?UTF-8?B?${b64(w)}?=`).join("\r\n "); |
| 102 | } |
| 103 | |
| 104 | const oneLine = (s: string): string => s.replace(/[\r\n]+/g, " "); |
| 105 | |
| 106 | function mailbox(m: { name: string; email: string } | string): string { |
| 107 | if (typeof m === "string") return oneLine(m); |
| 108 | const name = oneLine(m.name).trim(); |
| 109 | if (!name) return oneLine(m.email); |
| 110 | return `${ASCII.test(name) ? `"${name.replace(/[\\"]/g, "\\$&")}"` : encodeWords(name)} <${oneLine(m.email)}>`; |
| 111 | } |
| 112 | |
| 113 | /** Headers formatMessage writes itself; the same names in Outgoing.headers are left out. */ |
| 114 | const OWN_HEADERS = new Set(["from", "to", "cc", "bcc", "reply-to", "subject", "date", "message-id", "mime-version", "content-type", "content-transfer-encoding"]); |
| 115 | |
| 116 | /** The email as RFC 5322 text with CRLF line ends: text and HTML as multipart/alternative, each in base64. */ |
| 117 | export function formatMessage(msg: Outgoing, o: { messageId: string; date: Date; boundary?: string }): string { |
| 118 | const boundary = o.boundary ?? `=_diffinery_${crypto.randomUUID().replace(/-/g, "")}`; |
| 119 | const headers: Array<[string, string]> = [ |
| 120 | ["From", mailbox(msg.from)], |
| 121 | ["To", mailbox(msg.to)], |
| 122 | ...(msg.replyTo ? [["Reply-To", mailbox(msg.replyTo)] as [string, string]] : []), |
| 123 | ["Subject", encodeWords(oneLine(msg.subject))], |
| 124 | ["Date", o.date.toUTCString().replace(/GMT$/, "+0000")], |
| 125 | ["Message-ID", o.messageId], |
| 126 | ["MIME-Version", "1.0"], |
| 127 | ...Object.entries(msg.headers) |
| 128 | .filter(([k]) => /^[A-Za-z0-9-]+$/.test(k) && !OWN_HEADERS.has(k.toLowerCase())) |
| 129 | .map(([k, v]) => [k, encodeWords(oneLine(v))] as [string, string]), |
| 130 | ["Content-Type", `multipart/alternative; boundary="${boundary}"`], |
| 131 | ]; |
| 132 | const part = (type: string, body: string) => `--${boundary}\r\nContent-Type: ${type}; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${b64Lines(body)}\r\n`; |
| 133 | return `${headers.map(([k, v]) => `${k}: ${v}\r\n`).join("")}\r\n${part("text/plain", msg.text)}${part("text/html", msg.html)}--${boundary}--\r\n`; |
| 134 | } |
| 135 | |
| 136 | /** Enhanced status codes (RFC 3463) that mean the recipient's address is bad for good: no such mailbox or domain, or a disabled mailbox. */ |
| 137 | const BAD_RECIPIENT = new Set(["5.1.1", "5.1.2", "5.1.3", "5.1.6", "5.1.10", "5.2.1"]); |
| 138 | |
| 139 | interface Reply { |
| 140 | code: number; |
| 141 | text: string; |
| 142 | } |
| 143 | |
| 144 | /** Whether a 5xx reply to RCPT TO is about the address rather than the sender, the relay or the message. */ |
| 145 | function recipientGone(r: Reply): boolean { |
| 146 | const enhanced = /^5\.\d{1,3}\.\d{1,3}\b/.exec(r.text)?.[0]; |
| 147 | return enhanced ? BAD_RECIPIENT.has(enhanced) : r.code === 550 || r.code === 551 || r.code === 553; |
| 148 | } |
| 149 | |
| 150 | function failure(stage: string, r: Reply): SmtpError { |
| 151 | const detail = `SMTP ${stage}: ${r.code} ${r.text}`.slice(0, 300); |
| 152 | if (r.code >= 400 && r.code < 500) return new SmtpError("E_SMTP_TRANSIENT", detail); |
| 153 | if (r.code >= 500) return new SmtpError(stage === "RCPT TO" && recipientGone(r) ? "E_SMTP_RECIPIENT_REJECTED" : "E_SMTP_REJECTED", detail); |
| 154 | return new SmtpError("E_SMTP_TRANSIENT", `${detail} (unexpected reply)`); |
| 155 | } |
| 156 | |
| 157 | /** One SMTP connection: reads replies line by line and writes commands, each within the timeout. */ |
| 158 | class Session { |
| 159 | private reader!: ReadableStreamDefaultReader<Uint8Array>; |
| 160 | private writer!: WritableStreamDefaultWriter<Uint8Array>; |
| 161 | private decoder = new TextDecoder(); |
| 162 | private buf = ""; |
| 163 | |
| 164 | constructor( |
| 165 | private socket: Socket, |
| 166 | private timeoutMs: number, |
| 167 | ) { |
| 168 | this.attach(socket); |
| 169 | } |
| 170 | |
| 171 | private attach(socket: Socket): void { |
| 172 | this.socket = socket; |
| 173 | // A connection that fails shows up in the next read; these would otherwise be unhandled rejections. |
| 174 | socket.opened.catch(() => {}); |
| 175 | socket.closed.catch(() => {}); |
| 176 | this.reader = socket.readable.getReader(); |
| 177 | this.writer = socket.writable.getWriter(); |
| 178 | this.decoder = new TextDecoder(); |
| 179 | this.buf = ""; |
| 180 | } |
| 181 | |
| 182 | private async within<T>(p: Promise<T>, what: string): Promise<T> { |
| 183 | let timer: ReturnType<typeof setTimeout> | null = null; |
| 184 | const timeout = new Promise<never>((_, reject) => { |
| 185 | timer = setTimeout(() => reject(new SmtpError("E_SMTP_TRANSIENT", `SMTP ${what}: no answer from the server in ${this.timeoutMs / 1000} seconds`)), this.timeoutMs); |
| 186 | }); |
| 187 | try { |
| 188 | return await Promise.race([p, timeout]); |
| 189 | } finally { |
| 190 | clearTimeout(timer); |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | private async line(stage: string): Promise<string> { |
| 195 | for (;;) { |
| 196 | const nl = this.buf.indexOf("\n"); |
| 197 | if (nl >= 0) { |
| 198 | const l = this.buf.slice(0, nl).replace(/\r$/, ""); |
| 199 | this.buf = this.buf.slice(nl + 1); |
| 200 | return l; |
| 201 | } |
| 202 | if (this.buf.length > 64_000) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: reply line too long`); |
| 203 | const { value, done } = await this.within(this.reader.read(), stage); |
| 204 | if (done) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: the server closed the connection`); |
| 205 | this.buf += this.decoder.decode(value, { stream: true }); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /** One reply, all lines of a multiline one (`250-...` up to `250 ...`) joined. */ |
| 210 | async reply(stage: string): Promise<Reply> { |
| 211 | const lines: string[] = []; |
| 212 | for (;;) { |
| 213 | const l = await this.line(stage); |
| 214 | const m = /^(\d{3})([ -]|$)(.*)$/.exec(l); |
| 215 | if (!m) throw new SmtpError("E_SMTP_TRANSIENT", `SMTP ${stage}: not an SMTP reply`); |
| 216 | lines.push(m[3]!); |
| 217 | if (m[2] !== "-") return { code: Number(m[1]), text: lines.join("\n") }; |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | async write(data: string, stage: string): Promise<void> { |
| 222 | await this.within(this.writer.write(enc.encode(data)), stage); |
| 223 | } |
| 224 | |
| 225 | /** Send a command and expect one of the codes. `stage` names it in errors, so a command with a password in it never shows up. */ |
| 226 | async command(line: string, ok: number[], stage: string): Promise<Reply> { |
| 227 | await this.write(`${line}\r\n`, stage); |
| 228 | return this.expect(ok, stage); |
| 229 | } |
| 230 | |
| 231 | async expect(ok: number[], stage: string): Promise<Reply> { |
| 232 | const r = await this.reply(stage); |
| 233 | if (!ok.includes(r.code)) throw failure(stage, r); |
| 234 | return r; |
| 235 | } |
| 236 | |
| 237 | /** EHLO, and the extensions the server lists (keyword → parameters). */ |
| 238 | async ehlo(name: string): Promise<Map<string, string>> { |
| 239 | const r = await this.command(`EHLO ${name}`, [250], "EHLO"); |
| 240 | const caps = new Map<string, string>(); |
| 241 | for (const l of r.text.split("\n").slice(1)) { |
| 242 | const [k, ...rest] = l.trim().split(/\s+/); |
| 243 | if (k) caps.set(k.toUpperCase(), rest.join(" ").toUpperCase()); |
| 244 | } |
| 245 | return caps; |
| 246 | } |
| 247 | |
| 248 | /** Switch to TLS after the server's 220 to STARTTLS. Anything it sent before is dropped, so it can't be injected into the TLS session. */ |
| 249 | startTls(): void { |
| 250 | this.reader.releaseLock(); |
| 251 | this.writer.releaseLock(); |
| 252 | this.attach(this.socket.startTls()); |
| 253 | } |
| 254 | |
| 255 | async close(): Promise<void> { |
| 256 | await this.socket.close().catch(() => {}); |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | const ADDRESS = /^[^\s<>()[\],;:"\\@]+@[^\s<>()[\],;:"\\@]+$/; |
| 261 | |
| 262 | /** |
| 263 | * Send one email over SMTP. Resolves with the Message-ID it gave the email; throws SmtpError. |
| 264 | * `ehlo` is the name Diffinery greets the server with (its own hostname). |
| 265 | */ |
| 266 | export async function sendSmtp(cfg: SmtpConfig, msg: Outgoing, opts: { ehlo: string; timeoutMs?: number; now?: Date }): Promise<{ messageId: string }> { |
| 267 | const from = msg.from.email; |
| 268 | const to = typeof msg.to === "string" ? msg.to : msg.to.email; |
| 269 | for (const a of [from, to]) if (!ADDRESS.test(a)) throw new SmtpError("E_SMTP_REJECTED", `not an address SMTP can send to: ${oneLine(a).slice(0, 100)}`); |
| 270 | const messageId = `<${crypto.randomUUID()}@${from.slice(from.lastIndexOf("@") + 1)}>`; |
| 271 | const data = formatMessage(msg, { messageId, date: opts.now ?? new Date() }); |
| 272 | |
| 273 | let session: Session; |
| 274 | try { |
| 275 | session = new Session(connect({ hostname: cfg.host, port: cfg.port }, { secureTransport: cfg.tls === "implicit" ? "on" : "starttls", allowHalfOpen: false }), opts.timeoutMs ?? SMTP_TIMEOUT_MS); |
| 276 | } catch (e) { |
| 277 | throw new SmtpError("E_SMTP_TRANSIENT", `SMTP connect: ${(e as Error).message ?? String(e)}`); |
| 278 | } |
| 279 | try { |
| 280 | await session.expect([220], "greeting"); |
| 281 | let caps = await session.ehlo(opts.ehlo); |
| 282 | if (cfg.tls === "starttls") { |
| 283 | if (!caps.has("STARTTLS")) throw new SmtpError("E_SMTP_REJECTED", "SMTP: the server doesn't offer STARTTLS, and Diffinery doesn't send without TLS"); |
| 284 | await session.command("STARTTLS", [220], "STARTTLS"); |
| 285 | session.startTls(); |
| 286 | caps = await session.ehlo(opts.ehlo); |
| 287 | } |
| 288 | if (cfg.user && cfg.password) { |
| 289 | const mechanisms = (caps.get("AUTH") ?? "").split(" "); |
| 290 | if (mechanisms.includes("PLAIN")) { |
| 291 | await session.command(`AUTH PLAIN ${b64(`\0${cfg.user}\0${cfg.password}`)}`, [235], "AUTH"); |
| 292 | } else if (mechanisms.includes("LOGIN")) { |
| 293 | await session.command("AUTH LOGIN", [334], "AUTH"); |
| 294 | await session.command(b64(cfg.user), [334], "AUTH"); |
| 295 | await session.command(b64(cfg.password), [235], "AUTH"); |
| 296 | } else { |
| 297 | throw new SmtpError("E_SMTP_REJECTED", "SMTP: the server offers neither AUTH PLAIN nor AUTH LOGIN"); |
| 298 | } |
| 299 | } |
| 300 | const utf8 = !ASCII.test(from + to); |
| 301 | if (utf8 && !caps.has("SMTPUTF8")) throw new SmtpError("E_SMTP_REJECTED", "SMTP: the address isn't ASCII and the server doesn't offer SMTPUTF8"); |
| 302 | await session.command(`MAIL FROM:<${from}>${utf8 ? " SMTPUTF8" : ""}`, [250], "MAIL FROM"); |
| 303 | await session.command(`RCPT TO:<${to}>`, [250, 251], "RCPT TO"); |
| 304 | await session.command("DATA", [354], "DATA"); |
| 305 | // A line that starts with a dot gets another (RFC 5321 4.5.2); a dot alone ends the message. |
| 306 | await session.write(`${data.replace(/^\./gm, "..")}.\r\n`, "DATA"); |
| 307 | await session.expect([250], "DATA"); |
| 308 | await session.write("QUIT\r\n", "QUIT").catch(() => {}); |
| 309 | return { messageId }; |
| 310 | } catch (e) { |
| 311 | if (e instanceof SmtpError) throw e; |
| 312 | throw new SmtpError("E_SMTP_TRANSIENT", `SMTP: ${(e as Error).message ?? String(e)}`); |
| 313 | } finally { |
| 314 | await session.close(); |
| 315 | } |
| 316 | } |