Cotton code
486 lines · 18.5 KB · TypeScriptRaw
/** * A small IMAP client (RFC 3501, with Gmail's X-GM-EXT-1) for Cotton's fetcher (src/mail/fetch.ts, src/mail/fetcher.ts; * Post CONTRACT row 13): only what the fetcher says. Greeting, CAPABILITY, LOGIN, LIST, SELECT, UID SEARCH, UID * FETCH, UID STORE (flags and Gmail's labels), UID MOVE / COPY, APPEND, LOGOUT. It never sets \Deleted and never * says EXPUNGE: a person's mail leaves a server only by the server's own Trash. * * The bytes travel over a `Wire`: a TLS socket from `cloudflare:sockets` on a Worker (`dial`), or an in-memory fake * server in the tests. Nothing here logs: a command may carry a password. */export interface Wire {  write(bytes: Uint8Array): Promise<void>;  /** The next bytes the server sent; null once it closed. */  read(): Promise<Uint8Array | null>;  close(): void;}export type Dial = (host: string, port: number, tls: boolean) => Promise<Wire>;/** A TCP socket from the Worker: TLS on, save to this machine's loopback (a fake server, dev and test alone). */export const dial: Dial = async (host, port, tls) => {  const { connect } = await import("cloudflare:sockets");  const socket = connect({ hostname: host, port }, { secureTransport: tls ? "on" : "off", allowHalfOpen: false });  try {    await socket.opened;  } catch {    // The host does not resolve, or refuses, or the TLS handshake fails: the fetch log says `unreachable`, never why.    socket.close().catch(() => undefined);    throw new ImapError("unreachable", "");  }  const writer = socket.writable.getWriter();  const reader = socket.readable.getReader();  return {    write: (bytes) => writer.write(bytes),    read: async () => {      const got = await reader.read();      return got.done ? null : (got.value as Uint8Array);    },    close: () => {      socket.close().catch(() => undefined);    },  };};/** A token of a response: an atom or a quoted string (string), a literal (bytes), a parenthesised list, or NIL (null). */export type Token = string | Uint8Array | null | Token[];export interface Response {  /** `*` for untagged, `+` for a continuation, else the command's tag. */  tag: string;  tokens: Token[];  /** The response's text after the tag, literals left out: what a refusal says. */  text: string;}/** The server said NO or BAD to a command, or closed, or answered nonsense. `code` is the response code when it gave one (`AUTHENTICATIONFAILED`). */export class ImapError extends Error {  readonly kind: "no" | "bad" | "closed" | "protocol" | "bye" | "unreachable";  readonly said: string;  readonly code: string | null;  constructor(kind: ImapError["kind"], said: string, code: string | null = null) {    super(`imap ${kind}${code ? ` [${code}]` : ""}`);    this.kind = kind;    this.said = said;    this.code = code;  }}const enc = new TextEncoder();const dec = new TextDecoder();/** A response line longer than this is not one a server sends a fetcher. */const LINE_MAX = 1 << 20;/** Reads lines and literals off the wire. */class Reader {  private buf = new Uint8Array(0);  private readonly wire: Wire;  constructor(wire: Wire) {    this.wire = wire;  }  private async more(): Promise<void> {    const chunk = await this.wire.read();    if (!chunk) throw new ImapError("closed", "the server closed the connection");    const next = new Uint8Array(this.buf.length + chunk.length);    next.set(this.buf);    next.set(chunk, this.buf.length);    this.buf = next;  }  async line(): Promise<string> {    let from = 0;    for (;;) {      for (let i = Math.max(from, 1); i < this.buf.length; i++) {        if (this.buf[i - 1] === 13 && this.buf[i] === 10) {          const out = dec.decode(this.buf.subarray(0, i - 1));          this.buf = this.buf.slice(i + 1);          return out;        }      }      from = this.buf.length;      if (from > LINE_MAX) throw new ImapError("protocol", "a line too long");      await this.more();    }  }  async bytes(n: number): Promise<Uint8Array> {    while (this.buf.length < n) await this.more();    const out = this.buf.slice(0, n);    this.buf = this.buf.slice(n);    return out;  }}/** One response off the wire: its lines and the literals between them. */async function readResponse(reader: Reader): Promise<Response> {  const parts: (string | Uint8Array)[] = [];  for (;;) {    const line = await reader.line();    const literal = /\{(\d+)\+?\}$/.exec(line);    if (!literal) {      parts.push(line);      break;    }    parts.push(line.slice(0, literal.index));    parts.push(await reader.bytes(Number(literal[1])));  }  const first = parts[0] as string;  const space = first.indexOf(" ");  const tag = space < 0 ? first : first.slice(0, space);  parts[0] = space < 0 ? "" : first.slice(space + 1);  const text = parts.filter((p): p is string => typeof p === "string").join("");  return { tag, tokens: tag === "+" ? [] : tokenize(parts), text };}/** The tokens of a response's parts (text with literals between). */export function tokenize(parts: (string | Uint8Array)[]): Token[] {  const root: Token[] = [];  const stack: Token[][] = [root];  const top = () => stack[stack.length - 1]!;  for (const part of parts) {    if (typeof part !== "string") {      top().push(part);      continue;    }    let i = 0;    while (i < part.length) {      const c = part[i]!;      if (c === " ") i++;      else if (c === "(") {        const list: Token[] = [];        top().push(list);        stack.push(list);        i++;      } else if (c === ")") {        if (stack.length > 1) stack.pop();        i++;      } else if (c === '"') {        let out = "";        i++;        while (i < part.length && part[i] !== '"') {          if (part[i] === "\\" && i + 1 < part.length) i++;          out += part[i];          i++;        }        i++;        top().push(out);      } else if (c === "[") {        // A response code ([UIDVALIDITY 3], [AUTHENTICATIONFAILED]): kept whole, as one atom.        const end = part.indexOf("]", i);        const stop = end < 0 ? part.length : end + 1;        top().push(part.slice(i, stop));        i = stop;      } else {        let j = i;        // An atom; BODY[] keeps its brackets.        while (j < part.length && !" ()\"".includes(part[j]!)) {          if (part[j] === "[") {            const end = part.indexOf("]", j);            j = end < 0 ? part.length : end + 1;          } else j++;        }        const atom = part.slice(i, j);        top().push(atom.toUpperCase() === "NIL" ? null : atom);        i = j;      }    }  }  return root;}/** A string as IMAP takes it: an atom-safe quoted string, or a literal when it holds a byte a quoted string cannot. */type Arg = string | { quoted: string } | { literal: Uint8Array };export function quoted(value: string): Arg {  // eslint-disable-next-line no-control-regex  if (/[\x00\r\n\x80-￿]/.test(value)) return { literal: enc.encode(value) };  return { quoted: value };}/** One message as a FETCH answered it. */export interface Fetched {  uid: number;  flags: string[];  /** Gmail's X-GM-MSGID and X-GM-THRID, decimal, when the server is Gmail. */  msgid?: string;  thrid?: string;  labels: string[];  /** INTERNALDATE in milliseconds. */  internal?: number;  size?: number;  body?: Uint8Array;}export interface Selected {  uidvalidity: number;  exists: number;  uidnext: number | null;}export class Imap {  private readonly reader: Reader;  private n = 0;  capabilities = new Set<string>();  private readonly wire: Wire;  private constructor(wire: Wire) {    this.wire = wire;    this.reader = new Reader(wire);  }  /** The connection, its greeting read and its capabilities asked. */  static async open(wire: Wire): Promise<Imap> {    const imap = new Imap(wire);    const hello = await readResponse(imap.reader);    if (hello.tag !== "*" || !/^(OK|PREAUTH)\b/i.test(hello.text)) {      wire.close();      throw new ImapError("bye", hello.text);    }    await imap.capability();    return imap;  }  get gmail(): boolean {    return this.capabilities.has("X-GM-EXT-1");  }  close(): void {    this.wire.close();  }  /** Run one command: its untagged responses, once its tagged OK came; NO and BAD throw. */  async command(...args: Arg[]): Promise<Response[]> {    const tag = `c${++this.n}`;    const untagged: Response[] = [];    // A literal waits for the server's go-ahead (+) before its bytes.    let pending = `${tag}`;    for (const a of args) {      if (typeof a === "string") pending += ` ${a}`;      else if ("quoted" in a) pending += ` "${a.quoted.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;      else {        await this.wire.write(enc.encode(`${pending} {${a.literal.length}}\r\n`));        for (;;) {          const r = await readResponse(this.reader);          if (r.tag === "+") break;          if (r.tag === tag) throw refusal(r);          untagged.push(r);        }        await this.wire.write(a.literal);        pending = "";      }    }    await this.wire.write(enc.encode(`${pending}\r\n`));    for (;;) {      const r = await readResponse(this.reader);      if (r.tag === tag) {        if (/^OK\b/i.test(r.text)) return untagged;        throw refusal(r);      }      if (r.tag === "*" && /^BYE\b/i.test(r.text)) {        // Wait for the tagged answer a LOGOUT gets; anywhere else a BYE ends it.        if (!/LOGOUT/i.test(String(args[0]))) throw new ImapError("bye", r.text);      }      untagged.push(r);    }  }  async capability(): Promise<void> {    for (const r of await this.command("CAPABILITY")) {      if (String(r.tokens[0]).toUpperCase() === "CAPABILITY") this.capabilities = new Set(r.tokens.slice(1).map((t) => String(t).toUpperCase()));    }  }  async login(user: string, password: string): Promise<void> {    await this.command("LOGIN", quoted(user), quoted(password));    // Servers may say more once signed in (Gmail does).    await this.capability();  }  /** Every mailbox: its name and its flags (`\All`, `\Sent`, `\Trash`, `\Junk`). */  async list(): Promise<{ name: string; flags: string[] }[]> {    const out: { name: string; flags: string[] }[] = [];    for (const r of await this.command("LIST", { quoted: "" }, { quoted: "*" })) {      if (String(r.tokens[0]).toUpperCase() !== "LIST") continue;      const flags = Array.isArray(r.tokens[1]) ? r.tokens[1].map((f) => String(f)) : [];      const name = r.tokens[3];      out.push({ name: typeof name === "string" ? name : name instanceof Uint8Array ? dec.decode(name) : "", flags });    }    return out;  }  /** The mailbox by its special-use flag (`\All`, `\Sent`, `\Trash`), or null. */  async special(flag: string): Promise<string | null> {    return (await this.list()).find((m) => m.flags.some((f) => f.toLowerCase() === flag.toLowerCase()))?.name ?? null;  }  async select(mailbox: string, readOnly = false): Promise<Selected> {    const out: Selected = { uidvalidity: 0, exists: 0, uidnext: null };    for (const r of await this.command(readOnly ? "EXAMINE" : "SELECT", quoted(mailbox))) {      const code = /\[(UIDVALIDITY|UIDNEXT) (\d+)\]/i.exec(r.text);      if (code) {        if (code[1]!.toUpperCase() === "UIDVALIDITY") out.uidvalidity = Number(code[2]);        else out.uidnext = Number(code[2]);      }      if (String(r.tokens[1]).toUpperCase() === "EXISTS") out.exists = Number(r.tokens[0]);    }    return out;  }  /** `UID SEARCH <criteria>`: the UIDs, ascending. */  async search(criteria: string): Promise<number[]> {    const out: number[] = [];    for (const r of await this.command("UID", "SEARCH", criteria)) {      if (String(r.tokens[0]).toUpperCase() === "SEARCH") for (const t of r.tokens.slice(1)) if (/^\d+$/.test(String(t))) out.push(Number(t));    }    return out.sort((a, b) => a - b);  }  /** `UID FETCH`: what each message answered. `body` asks BODY.PEEK[] (never marks it read). */  async fetch(uids: number[], body: boolean): Promise<Fetched[]> {    if (!uids.length) return [];    const items = ["UID", "FLAGS", "INTERNALDATE", "RFC822.SIZE", ...(this.gmail ? ["X-GM-MSGID", "X-GM-THRID", "X-GM-LABELS"] : []), ...(body ? ["BODY.PEEK[]"] : [])];    const out: Fetched[] = [];    for (const r of await this.command("UID", "FETCH", uids.join(","), `(${items.join(" ")})`)) {      if (String(r.tokens[1]).toUpperCase() !== "FETCH" || !Array.isArray(r.tokens[2])) continue;      const attrs = r.tokens[2];      const f: Fetched = { uid: 0, flags: [], labels: [] };      for (let i = 0; i + 1 < attrs.length; i += 2) {        const name = String(attrs[i]).toUpperCase();        const v = attrs[i + 1]!;        if (name === "UID") f.uid = Number(v);        else if (name === "FLAGS") f.flags = Array.isArray(v) ? v.map(String) : [];        else if (name === "X-GM-MSGID") f.msgid = String(v);        else if (name === "X-GM-THRID") f.thrid = String(v);        else if (name === "X-GM-LABELS") f.labels = Array.isArray(v) ? v.map((l) => (l instanceof Uint8Array ? dec.decode(l) : String(l))) : [];        else if (name === "INTERNALDATE" && typeof v === "string") f.internal = internalDate(v);        else if (name === "RFC822.SIZE") f.size = Number(v);        else if (name.startsWith("BODY[")) f.body = v instanceof Uint8Array ? v : typeof v === "string" ? enc.encode(v) : undefined;      }      if (f.uid) out.push(f);    }    return out;  }  /** `UID STORE set ±FLAGS.SILENT (…)`: `set` is one UID or several, comma-separated. */  async store(set: number | string, sign: "+" | "-", flags: string[]): Promise<void> {    await this.command("UID", "STORE", String(set), `${sign}FLAGS.SILENT`, `(${flags.join(" ")})`);  }  /** Gmail: `UID STORE set ±X-GM-LABELS.SILENT (…)`. */  async labels(set: number | string, sign: "+" | "-", labels: string[]): Promise<void> {    await this.command("UID", "STORE", String(set), `${sign}X-GM-LABELS.SILENT`, `(${labels.map((l) => (l.startsWith("\\") ? l : `"${l.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`)).join(" ")})`);  }  /** `UID MOVE set to`, or `UID COPY` when `copy` (Gmail without MOVE: a copy into Trash is the move). Never expunged. */  async move(set: number | string, to: string, copy = false): Promise<void> {    await this.command("UID", copy ? "COPY" : "MOVE", String(set), quoted(to));  }  /** Each message's header fields named (`FROM`, `MESSAGE-ID`), read without marking it read: uid → the header text. */  async headers(uids: number[], fields: string[]): Promise<Map<number, string>> {    const out = new Map<number, string>();    if (!uids.length) return out;    for (const r of await this.command("UID", "FETCH", uids.join(","), `(UID BODY.PEEK[HEADER.FIELDS (${fields.join(" ")})])`)) {      if (String(r.tokens[1]).toUpperCase() !== "FETCH" || !Array.isArray(r.tokens[2])) continue;      const attrs = r.tokens[2];      let uid = 0;      let text = "";      for (let i = 0; i + 1 < attrs.length; i += 2) {        const name = String(attrs[i]).toUpperCase();        const v = attrs[i + 1];        if (name === "UID") uid = Number(v);        else if (name.startsWith("BODY[")) text = v instanceof Uint8Array ? dec.decode(v) : typeof v === "string" ? v : "";      }      if (uid) out.set(uid, text);    }    return out;  }  /** The special-use mailboxes a fetcher and its acts need. */  async uses(): Promise<{ all: string | null; trash: string | null; archive: string | null; sent: string | null }> {    const boxes = await this.list();    const find = (flag: string) => boxes.find((m) => m.flags.some((f) => f.toLowerCase() === flag))?.name ?? null;    return { all: find("\\all"), trash: find("\\trash"), archive: find("\\archive"), sent: find("\\sent") };  }  /** `APPEND mailbox (flags) {n}`: a sent message kept in Sent. */  async append(mailbox: string, flags: string[], message: Uint8Array): Promise<void> {    await this.command("APPEND", quoted(mailbox), `(${flags.join(" ")})`, { literal: message });  }  /**   * `IDLE` (RFC 2177) on the mailbox selected: waits until the server says the mailbox changed (`EXISTS`) or `ms`   * pass, then `DONE`. Answers whether new mail was said. A closed connection (the password removed) throws.   */  async idle(ms: number): Promise<boolean> {    if (!this.capabilities.has("IDLE")) {      // A server without IDLE is asked again each minute.      await new Promise((r) => setTimeout(r, Math.min(ms, 60_000)));      return true;    }    const tag = `c${++this.n}`;    await this.wire.write(enc.encode(`${tag} IDLE\r\n`));    for (;;) {      const r = await readResponse(this.reader);      if (r.tag === "+") break;      if (r.tag === tag) throw refusal(r);    }    const deadline = Date.now() + ms;    let pending: Promise<Response> | null = readResponse(this.reader);    let woke = false;    for (;;) {      const left = deadline - Date.now();      if (left <= 0) break;      let timer: ReturnType<typeof setTimeout> | undefined = undefined;      const r = await Promise.race([pending, new Promise<null>((done) => (timer = setTimeout(() => done(null), left)))]);      if (timer !== undefined) clearTimeout(timer);      if (r === null) break;      pending = null;      if (r.tag === "*" && /^BYE\b/i.test(r.text)) throw new ImapError("bye", r.text);      if (r.tag === "*" && String(r.tokens[1]).toUpperCase() === "EXISTS") {        woke = true;        break;      }      pending = readResponse(this.reader);    }    await this.wire.write(enc.encode("DONE\r\n"));    for (;;) {      const r: Response = await (pending ?? readResponse(this.reader));      pending = null;      if (r.tag === tag) {        if (/^OK\b/i.test(r.text)) return woke;        throw refusal(r);      }      if (r.tag === "*" && String(r.tokens[1]).toUpperCase() === "EXISTS") woke = true;    }  }  async logout(): Promise<void> {    try {      await this.command("LOGOUT");    } catch {      // gone already    }    this.wire.close();  }}function refusal(r: Response): ImapError {  const code = /\[([A-Z-]+)/.exec(r.text)?.[1] ?? null;  return new ImapError(/^BAD\b/i.test(r.text) ? "bad" : "no", r.text, code);}const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];/** `05-Oct-2026 09:30:00 +0530` in milliseconds; undefined when it is not one. */export function internalDate(v: string): number | undefined {  const m = /^\s*(\d{1,2})-(\w{3})-(\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+-])(\d{2})(\d{2})$/.exec(v);  if (!m) return undefined;  const month = MONTHS.indexOf(m[2]!);  if (month < 0) return undefined;  const utc = Date.UTC(Number(m[3]), month, Number(m[1]), Number(m[4]), Number(m[5]), Number(m[6]));  const offset = (Number(m[8]) * 60 + Number(m[9])) * 60_000 * (m[7] === "+" ? 1 : -1);  return utc - offset;}