Cotton code
323 lines · 12.2 KB · TypeScriptRaw
/** * An in-memory IMAP server for the fetcher's tests (src/mail/imap.ts, src/mail/fetcher.ts): it speaks over a `Wire` * the way Gmail (X-GM-EXT-1, All Mail, labels) or a plain server (INBOX) does, for exactly the commands the client * says. Invented mail only. It records every command (with the password masked) so a test can say what was asked. */import type { Dial, Wire } from "../src/mail/imap.ts";export interface FakeMessage {  uid: number;  raw: string;  flags?: string[];  labels?: string[];  msgid?: string;  thrid?: string;  /** INTERNALDATE as IMAP spells it. */  internal?: string;}export interface FakeBox {  validity: number;  flags?: string[];  messages: FakeMessage[];}export class FakeImap {  readonly boxes = new Map<string, FakeBox>();  readonly said: string[] = [];  /** How many bodies were fetched, by UID. */  readonly bodies = new Map<number, number>();  dials = 0;  opened = 0;  closed = 0;  readonly gmail: boolean;  /** A label Gmail keeps on however it is asked (to prove an archive is read back). */  sticky: string | null = null;  /** Whether the server has MOVE. */  canMove = true;  readonly user: string;  readonly password: string;  constructor(o: { gmail: boolean; user: string; password: string }) {    this.gmail = o.gmail;    this.user = o.user;    this.password = o.password;  }  /** Sessions in IDLE, told when mail is delivered. */  private readonly idlers = new Set<(box: FakeBox) => void>();  /** Whether the server has IDLE. */  canIdle = true;  /** New mail arriving in `name`: a session idling there hears EXISTS at once. */  deliver(name: string, message: FakeMessage): void {    const box = this.boxes.get(name)!;    box.messages.push(message);    for (const tell of [...this.idlers]) tell(box);  }  box(name: string, box: FakeBox): this {    this.boxes.set(name, box);    return this;  }  readonly dial: Dial = async (_host, _port, _tls) => {    this.dials++;    return this.session();  };  private session(): Wire {    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 | Uint8Array) => {      const bytes = typeof text === "string" ? enc.encode(text) : text;      if (waiting) {        const w = waiting;        waiting = null;        w(bytes);      } else out.push(bytes);    };    let inbuf = "";    let literalLeft = 0;    let pendingLine = "";    let selected: FakeBox | null = null;    let signedIn = false;    this.opened++;    send("* OK [CAPABILITY IMAP4rev1] invented server ready\r\n");    const caps = () => `* CAPABILITY IMAP4rev1${this.canMove ? " MOVE" : ""}${this.canIdle ? " IDLE" : ""}${this.gmail ? " X-GM-EXT-1" : ""}\r\n`;    let idling: { tag: string; tell: (box: FakeBox) => void } | null = null;    let shut = false;    const words = (line: string): string[] => {      const out: string[] = [];      let i = 0;      while (i < line.length) {        if (line[i] === " ") {          i++;          continue;        }        if (line[i] === '"') {          let s = "";          i++;          while (i < line.length && line[i] !== '"') {            if (line[i] === "\\") i++;            s += line[i];            i++;          }          i++;          out.push(s);        } else if (line[i] === "(") {          let depth = 0;          let j = i;          for (; j < line.length; j++) {            if (line[j] === "(") depth++;            else if (line[j] === ")" && --depth === 0) break;          }          out.push(line.slice(i, j + 1));          i = j + 1;        } else {          const end = line.indexOf(" ", i);          const stop = end < 0 ? line.length : end;          out.push(line.slice(i, stop));          i = stop;        }      }      return out;    };    const uidSet = (set: string, box: FakeBox): number[] => {      const max = Math.max(0, ...box.messages.map((m) => m.uid));      const hit = new Set<number>();      for (const part of set.split(",")) {        const [a, b] = part.split(":");        const lo = a === "*" ? max : Number(a);        const hi = b === undefined ? lo : b === "*" ? max : Number(b);        for (const m of box.messages) if (m.uid >= Math.min(lo, hi) && m.uid <= Math.max(lo, hi)) hit.add(m.uid);      }      return [...hit].sort((x, y) => x - y);    };    const quote = (s: string) => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;    const run = (line: string) => {      if (idling && line.trim().toUpperCase() === "DONE") {        this.idlers.delete(idling.tell);        send(`${idling.tag} OK IDLE terminated\r\n`);        idling = null;        return;      }      const w = words(line);      const tag = w[0]!;      const cmd = (w[1] ?? "").toUpperCase();      this.said.push(cmd === "LOGIN" ? `${cmd} ${w[2]} ‹password›` : w.slice(1).join(" "));      const ok = (t = "done") => send(`${tag} OK ${t}\r\n`);      if (cmd === "CAPABILITY") {        send(caps());        return ok();      }      if (cmd === "LOGIN") {        if (w[2] === this.user && w[3] === this.password) {          signedIn = true;          return ok("signed in");        }        return send(`${tag} NO [AUTHENTICATIONFAILED] Invalid credentials\r\n`);      }      if (cmd === "LOGOUT") {        send("* BYE logging out\r\n");        ok();        ended = true;        return;      }      if (!signedIn) return send(`${tag} BAD sign in first\r\n`);      if (cmd === "LIST") {        for (const [name, box] of this.boxes) send(`* LIST (${(box.flags ?? []).join(" ")}) "/" ${quote(name)}\r\n`);        return ok();      }      if (cmd === "SELECT" || cmd === "EXAMINE") {        const box = this.boxes.get(w[2]!);        if (!box) return send(`${tag} NO no such mailbox\r\n`);        selected = box;        const next = Math.max(0, ...box.messages.map((m) => m.uid)) + 1;        send(`* ${box.messages.length} EXISTS\r\n* OK [UIDVALIDITY ${box.validity}] ok\r\n* OK [UIDNEXT ${next}] ok\r\n`);        return ok(`[${cmd === "EXAMINE" ? "READ-ONLY" : "READ-WRITE"}] selected`);      }      if (cmd === "APPEND") {        const box = this.boxes.get(w[2]!);        if (!box) return send(`${tag} NO [TRYCREATE] no such mailbox\r\n`);        box.messages.push({ uid: Math.max(0, ...box.messages.map((m) => m.uid)) + 1, flags: (w[3] ?? "()").slice(1, -1).split(" ").filter(Boolean), raw: w[4] ?? "" });        return ok("appended");      }      if (!selected) return send(`${tag} BAD select first\r\n`);      const box = selected;      if (cmd === "IDLE" && this.canIdle) {        const tell = (changed: FakeBox) => {          if (changed === box) send(`* ${box.messages.length} EXISTS\r\n`);        };        idling = { tag, tell };        this.idlers.add(tell);        this.said.push("IDLE");        return send("+ idling\r\n");      }      if (cmd === "UID" && (w[2] ?? "").toUpperCase() === "SEARCH") {        const crit = w.slice(3);        const head = crit[0]!.toUpperCase();        const fromOf = (m: FakeMessage) => (/^From:.*$/im.exec(m.raw)?.[0] ?? "").toLowerCase();        const uids =          head === "ALL"            ? box.messages.map((m) => m.uid).sort((a, b) => a - b)            : head === "FROM"              ? box.messages.filter((m) => fromOf(m).includes(crit[1]!.toLowerCase())).map((m) => m.uid).sort((a, b) => a - b)              : head === "X-GM-MSGID"                ? box.messages.filter((m) => m.msgid === crit[1]).map((m) => m.uid)                : uidSet(crit[1]!, box);        // As real servers do: n:* names the highest UID even when n is above it.        if (crit[0]!.toUpperCase() === "UID" && crit[1]!.endsWith(":*") && !uids.length && box.messages.length) uids.push(Math.max(...box.messages.map((m) => m.uid)));        send(`* SEARCH${uids.map((u) => ` ${u}`).join("")}\r\n`);        return ok();      }      if (cmd === "UID" && (w[2] ?? "").toUpperCase() === "FETCH") {        const items = w[4]!.toUpperCase();        for (const uid of uidSet(w[3]!, box)) {          const m = box.messages.find((x) => x.uid === uid)!;          const seq = box.messages.indexOf(m) + 1;          const raw = enc.encode(m.raw);          let attrs = `UID ${uid} FLAGS (${(m.flags ?? []).join(" ")}) INTERNALDATE "${m.internal ?? "05-Oct-2026 09:30:00 +0000"}" RFC822.SIZE ${raw.length}`;          if (this.gmail && items.includes("X-GM-MSGID")) attrs += ` X-GM-MSGID ${m.msgid ?? "0"} X-GM-THRID ${m.thrid ?? m.msgid ?? "0"} X-GM-LABELS (${(m.labels ?? []).map((l) => (l.startsWith("\\") ? l : quote(l))).join(" ")})`;          if (items.includes("HEADER.FIELDS")) {            const header = enc.encode(`${/^From:.*$/im.exec(m.raw)?.[0] ?? ""}\r\n\r\n`);            send(`* ${seq} FETCH (UID ${uid} BODY[HEADER.FIELDS (FROM)] {${header.length}}\r\n`);            send(header);            send(")\r\n");            continue;          }          if (items.includes("BODY.PEEK[]")) {            this.bodies.set(uid, (this.bodies.get(uid) ?? 0) + 1);            send(`* ${seq} FETCH (${attrs} BODY[] {${raw.length}}\r\n`);            send(raw);            send(")\r\n");          } else send(`* ${seq} FETCH (${attrs})\r\n`);        }        return ok();      }      if (cmd === "UID" && (w[2] ?? "").toUpperCase() === "STORE") {        const op = (w[4] ?? "").toUpperCase();        const list = (w[5] ?? "()").slice(1, -1).split(" ").filter(Boolean).map((s) => s.replace(/^"|"$/g, ""));        for (const uid of uidSet(w[3]!, box)) {          const m = box.messages.find((x) => x.uid === uid)!;          const key = op.includes("X-GM-LABELS") ? "labels" : "flags";          const now = new Set(m[key] ?? []);          for (const f of list) op.startsWith("+") ? now.add(f) : now.delete(f);          // Gmail keeps a label it is set to keep (a test's `sticky`).          if (key === "labels" && this.sticky) for (const l of m.labels ?? []) if (l === this.sticky) now.add(l);          m[key] = [...now];        }        return ok();      }      if (cmd === "UID" && ((w[2] ?? "").toUpperCase() === "MOVE" || (w[2] ?? "").toUpperCase() === "COPY")) {        const to = this.boxes.get(w[4]!);        if (!to) return send(`${tag} NO [TRYCREATE] no such mailbox\r\n`);        for (const uid of uidSet(w[3]!, box)) {          const m = box.messages.find((x) => x.uid === uid)!;          to.messages.push({ ...m, uid: Math.max(0, ...to.messages.map((x) => x.uid)) + 1 });          if ((w[2] ?? "").toUpperCase() === "MOVE") box.messages.splice(box.messages.indexOf(m), 1);        }        return ok();      }      return send(`${tag} BAD unknown command\r\n`);    };    const feed = () => {      for (;;) {        if (literalLeft > 0) {          // The literal's length is in bytes: take characters until their bytes make it.          let take = 0;          let bytes = 0;          while (take < inbuf.length && bytes < literalLeft) bytes += enc.encode(inbuf[take++]!).length;          if (bytes < literalLeft) return;          pendingLine += `"${inbuf.slice(0, take).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;          inbuf = inbuf.slice(take);          literalLeft = 0;        }        const at = inbuf.indexOf("\r\n");        if (at < 0) return;        const line = pendingLine + inbuf.slice(0, at);        inbuf = inbuf.slice(at + 2);        const lit = /\{(\d+)\}$/.exec(line);        if (lit) {          pendingLine = line.slice(0, lit.index);          literalLeft = Number(lit[1]);          send("+ go ahead\r\n");          continue;        }        pendingLine = "";        run(line);      }    };    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: () => {        if (idling) this.idlers.delete(idling.tell);        // A connection closed twice (the removal, then the reader's own finally) is one closed connection.        if (!shut) this.closed++;        shut = true;        ended = true;        if (waiting) {          const w = waiting;          waiting = null;          w(null);        }      },    };  }}