117 lines · 3.6 KB · TypeScriptRaw
/** * An in-memory SMTP server for the send tests (src/mail/smtp.ts): greeting, EHLO, AUTH PLAIN, MAIL, RCPT, DATA, * QUIT. It keeps each message it took, its envelope, and who signed in. Invented mail only. */import type { Wire } from "../src/mail/imap.ts";export interface Taken { user: string; from: string; recipients: string[]; message: string;}export class FakeSmtp { readonly taken: Taken[] = []; readonly hosts: string[] = []; readonly user: string; readonly password: string; /** A recipient the server refuses. */ refuse: string | null = null; constructor(o: { user: string; password: string }) { this.user = o.user; this.password = o.password; } session(host: string): Wire { this.hosts.push(host); const enc = new TextEncoder(); const dec = new TextDecoder(); const out: Uint8Array[] = []; let waiting: ((b: Uint8Array | null) => void) | null = null; let ended = false; const send = (text: string) => { const bytes = enc.encode(text); if (waiting) { const w = waiting; waiting = null; w(bytes); } else out.push(bytes); }; let inbuf = ""; let data: string | null = null; let user = ""; let from = ""; let recipients: string[] = []; send("220 invented.example ESMTP ready\r\n"); const feed = () => { for (;;) { if (data !== null) { const end = inbuf.indexOf("\r\n.\r\n"); if (end < 0) return; data += inbuf.slice(0, end); inbuf = inbuf.slice(end + 5); this.taken.push({ user, from, recipients, message: data.replace(/(^|\r\n)\.\./g, "$1.") }); data = null; send("250 2.0.0 taken\r\n"); continue; } const at = inbuf.indexOf("\r\n"); if (at < 0) return; const line = inbuf.slice(0, at); inbuf = inbuf.slice(at + 2); const verb = line.split(" ")[0]!.toUpperCase(); if (verb === "EHLO") send("250-invented.example\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n"); else if (verb === "AUTH") { const [, u, p] = atob(line.split(" ")[2] ?? "").split("\0"); const password = new TextDecoder().decode(Uint8Array.from(p ?? "", (c) => c.charCodeAt(0))); if (u === this.user && password === this.password) { user = u!; send("235 2.7.0 accepted\r\n"); } else send("535 5.7.8 credentials refused\r\n"); } else if (verb === "MAIL") { if (!user) send("530 sign in first\r\n"); else { from = /<([^>]*)>/.exec(line)?.[1] ?? ""; recipients = []; send("250 ok\r\n"); } } else if (verb === "RCPT") { const r = /<([^>]*)>/.exec(line)?.[1] ?? ""; if (r === this.refuse) send("550 no such user\r\n"); else { recipients.push(r); send("250 ok\r\n"); } } else if (verb === "DATA") { data = ""; send("354 go ahead\r\n"); } else if (verb === "QUIT") { send("221 bye\r\n"); ended = true; } else send("502 not here\r\n"); } }; return { write: async (bytes) => { inbuf += dec.decode(bytes); feed(); }, read: () => { const next = out.shift(); if (next) return Promise.resolve(next); if (ended) return Promise.resolve(null); return new Promise((resolve) => (waiting = resolve)); }, close: () => { ended = true; if (waiting) { const w = waiting; waiting = null; w(null); } }, }; }}