Cotton code
153 lines · 5.7 KB · TypeScriptRaw
/** * Sending for a mailbox given to Cotton (Post CONTRACT row 13, `route: "smtp"`): a small SMTP client (RFC 5321, * AUTH PLAIN, RFC 4954) over the same `Wire` the IMAP client uses, implicit TLS on port 465. The message is formed * here (RFC 5322 and MIME: text, and attachments as base64 parts; Bcc never written into it). * * Nothing here logs: AUTH carries the password. */import type { Wire } from "./imap.ts";const enc = new TextEncoder();const dec = new TextDecoder();/** The server refused, or answered nonsense, or closed. `code` is its three-digit reply. */export class SmtpError extends Error {  readonly code: number;  readonly stage: string;  constructor(stage: string, code: number) {    super(`smtp ${stage} ${code}`);    this.stage = stage;    this.code = code;  }}/** The SMTP server of a mailbox read over IMAP: `imap.example.com` → `smtp.example.com`, else the same host. */export function smtpHost(imapHost: string): string {  return imapHost.startsWith("imap.") ? `smtp.${imapHost.slice(5)}` : imapHost;}export const SMTP_PORT = 465;class Replies {  private buf = "";  private readonly wire: Wire;  constructor(wire: Wire) {    this.wire = wire;  }  /** One reply, all its lines (`250-…` continues, `250 …` ends): its code. */  async read(stage: string): Promise<number> {    for (;;) {      let at: number;      while ((at = this.buf.indexOf("\r\n")) >= 0) {        const line = this.buf.slice(0, at);        this.buf = this.buf.slice(at + 2);        const m = /^(\d{3})([ -])/.exec(line);        if (!m) throw new SmtpError(stage, 0);        if (m[2] === " ") return Number(m[1]);      }      const chunk = await this.wire.read();      if (!chunk) throw new SmtpError(stage, 0);      this.buf += dec.decode(chunk);    }  }}export interface Outgoing {  from: string;  /** Every envelope recipient: To, Cc and Bcc. */  recipients: string[];  message: Uint8Array;}/** Send one message: greeting, EHLO, AUTH PLAIN, MAIL, RCPT each, DATA, QUIT. Throws SmtpError on any refusal. */export async function sendOver(wire: Wire, user: string, password: string, out: Outgoing): Promise<void> {  const replies = new Replies(wire);  const say = (line: string) => wire.write(enc.encode(`${line}\r\n`));  const expect = async (stage: string, ok: (code: number) => boolean) => {    const code = await replies.read(stage);    if (!ok(code)) throw new SmtpError(stage, code);  };  try {    await expect("greeting", (c) => c === 220);    await say("EHLO cottondb.com");    await expect("ehlo", (c) => c === 250);    const plain = btoa(String.fromCharCode(...enc.encode(`\0${user}\0${password}`)));    await say(`AUTH PLAIN ${plain}`);    await expect("auth", (c) => c === 235);    await say(`MAIL FROM:<${out.from}>`);    await expect("mail", (c) => c === 250);    for (const r of out.recipients) {      await say(`RCPT TO:<${r}>`);      await expect("rcpt", (c) => c === 250 || c === 251);    }    await say("DATA");    await expect("data", (c) => c === 354);    await wire.write(dotStuffed(out.message));    await wire.write(enc.encode("\r\n.\r\n"));    await expect("sent", (c) => c === 250);    await say("QUIT");  } finally {    wire.close();  }}/** A line that starts with a dot gets a second (RFC 5321 4.5.2); the body's line ends made CRLF. */function dotStuffed(message: Uint8Array): Uint8Array {  const text = dec.decode(message).replace(/\r?\n/g, "\r\n");  return enc.encode(text.replace(/(^|\r\n)\./g, "$1.."));}export interface Attachment {  name: string;  mime: string;  bytes: Uint8Array;}/** Words fit for a header: plain ASCII as they are, anything else as an RFC 2047 encoded word. */export function headerWords(text: string): string {  // eslint-disable-next-line no-control-regex  if (/^[\x20-\x7e]*$/.test(text)) return text;  return `=?utf-8?B?${base64(enc.encode(text))}?=`;}export function base64(bytes: Uint8Array): string {  let s = "";  for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));  return btoa(s);}function wrapped(b64: string): string {  return b64.replace(/.{1,76}/g, "$&\r\n");}/** The message as it goes: headers, the text, and each attachment. Bcc never appears in it. */export function compose(m: { from: string; to: string[]; cc: string[]; subject: string; text: string; messageId: string; inReplyTo: string | null; references: string[]; at: number; attachments: Attachment[] }): Uint8Array {  const head = [    `From: ${m.from}`,    `To: ${m.to.join(", ")}`,    ...(m.cc.length ? [`Cc: ${m.cc.join(", ")}`] : []),    `Subject: ${headerWords(m.subject)}`,    `Date: ${new Date(m.at).toUTCString().replace("GMT", "+0000")}`,    `Message-ID: ${m.messageId}`,    ...(m.inReplyTo ? [`In-Reply-To: ${m.inReplyTo}`] : []),    ...(m.references.length ? [`References: ${m.references.join(" ")}`] : []),    "MIME-Version: 1.0",  ];  const textPart = ["Content-Type: text/plain; charset=utf-8", "Content-Transfer-Encoding: base64", "", wrapped(base64(enc.encode(m.text)))];  if (!m.attachments.length) return enc.encode([...head, ...textPart].join("\r\n"));  const boundary = `cotton-${crypto.randomUUID()}`;  const parts = [    ...head,    `Content-Type: multipart/mixed; boundary="${boundary}"`,    "",    `--${boundary}`,    ...textPart,    ...m.attachments.flatMap((a) => {      const name = headerWords(a.name.replace(/["\r\n]/g, ""));      return [`--${boundary}`, `Content-Type: ${/^[\w.+-]+\/[\w.+-]+$/.test(a.mime) ? a.mime : "application/octet-stream"}; name="${name}"`, `Content-Disposition: attachment; filename="${name}"`, "Content-Transfer-Encoding: base64", "", wrapped(base64(a.bytes))];    }),    `--${boundary}--`,    "",  ];  return enc.encode(parts.join("\r\n"));}