/** * Just enough IMAP to read a login code X emailed: log in over TLS, look at the * inbox read-only, read the subjects of X's recent mail. No dependency, so * castle-search keeps having none. * * X puts the code in the subject ("Your X confirmation code is abc12def"), so * only headers are fetched, and nothing is marked read or changed. */ import { connect, type TLSSocket } from "node:tls"; export type ImapAccount = { host: string; port?: number; user: string; password: string }; export type MailHeader = { received: number; from: string; subject: string }; /** RFC 2047 encoded words, the B and Q forms, as subjects use them. */ export const decodeWords = (s: string): string => s .replace(/\?=\s+=\?/g, "?==?") .replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g, (_, charset: string, enc: string, text: string) => { const bytes = enc.toUpperCase() === "B" ? Buffer.from(text, "base64") : Buffer.from( text.replace(/_/g, " ").replace(/=([0-9A-Fa-f]{2})/g, (_m, h: string) => String.fromCharCode(parseInt(h, 16))), "latin1", ); try { return new TextDecoder(charset).decode(bytes); } catch { return bytes.toString("utf8"); } }); /** The code in one of X's subjects, or undefined when the mail is something else. */ export const xCodeFromSubject = (subject: string): string | undefined => { const m = /\bcode is:?\s*([A-Za-z0-9]{5,10})\b/i.exec(subject) ?? /^\s*([A-Za-z0-9]{5,10}) is your X (?:verification|confirmation|login) code\b/i.exec(subject); return m?.[1]; }; /** "18-Nov-2026 10:16:23 +0000" -> epoch ms. */ export const parseInternalDate = (s: string): number => Date.parse(s.replace(/^(\d{1,2})-(\w{3})-(\d{4})/, "$1 $2 $3")); /** Splits a FETCH response into one header set per message. */ export const parseFetch = (raw: string): MailHeader[] => { const out: MailHeader[] = []; for (const part of raw.split(/\r\n(?=\* \d+ FETCH )/)) { const date = /INTERNALDATE "([^"]+)"/.exec(part)?.[1]; if (!date) continue; const unfolded = part.replace(/\r\n[ \t]+/g, " "); const header = (name: string) => new RegExp(`^${name}:\\s*(.*)$`, "im").exec(unfolded)?.[1]?.trim() ?? ""; out.push({ received: parseInternalDate(date), from: decodeWords(header("From")), subject: decodeWords(header("Subject")) }); } return out; }; const quote = (s: string): string => `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; const imapDate = (ms: number): string => { const d = new Date(ms); return `${d.getUTCDate()}-${MONTHS[d.getUTCMonth()]}-${d.getUTCFullYear()}`; }; class Session { readonly #socket: TLSSocket; #buffer = ""; #tag = 0; #waiter: (() => void) | undefined; #error: Error | undefined; constructor(socket: TLSSocket) { this.#socket = socket; socket.setEncoding("latin1"); socket.on("data", (chunk: string) => { this.#buffer += chunk; this.#waiter?.(); }); const fail = (e: Error) => { this.#error ??= e; this.#waiter?.(); }; socket.on("error", fail); socket.on("close", () => fail(new Error("the IMAP server closed the connection"))); } async #until(done: (buffer: string) => boolean, signal: AbortSignal): Promise { while (!done(this.#buffer)) { if (this.#error) throw this.#error; if (signal.aborted) throw signal.reason; await new Promise((resolve) => { this.#waiter = resolve; signal.addEventListener("abort", () => resolve(), { once: true }); }); this.#waiter = undefined; } const out = this.#buffer; this.#buffer = ""; return out; } greeting(signal: AbortSignal): Promise { return this.#until((b) => b.includes("\r\n"), signal); } /** Sends one command; `shown` is what an error may say was sent, so a password never is. */ async command(line: string, signal: AbortSignal, shown = line): Promise { const tag = `c${++this.#tag}`; this.#socket.write(`${tag} ${line}\r\n`); const reply = await this.#until((b) => new RegExp(`(^|\\r\\n)${tag} (OK|NO|BAD)[^\\r\\n]*\\r\\n`).test(b), signal); const status = new RegExp(`(?:^|\\r\\n)${tag} (OK|NO|BAD)([^\\r\\n]*)`).exec(reply); if (status?.[1] !== "OK") throw new Error(`IMAP ${shown.split(" ")[0]} failed: ${status?.[1]}${status?.[2]}`); return reply; } close(): void { this.#socket.end(); this.#socket.destroy(); } } /** Headers of mail from `fromDomain` received at or after `sinceMs`, newest first. */ export const recentMail = async ( account: ImapAccount, fromDomain: string, sinceMs: number, signal: AbortSignal, ): Promise => { const socket = connect({ host: account.host, port: account.port ?? 993, servername: account.host }); const s = new Session(socket); try { await s.greeting(signal); await s.command(`LOGIN ${quote(account.user)} ${quote(account.password)}`, signal, "LOGIN"); await s.command("EXAMINE INBOX", signal); const found = await s.command(`SEARCH SINCE ${imapDate(sinceMs - 86_400_000)} FROM ${quote(fromDomain)}`, signal); const ids = (/\* SEARCH([\d ]*)/.exec(found)?.[1] ?? "").trim().split(/\s+/).filter(Boolean).slice(-10); if (ids.length === 0) return []; const raw = await s.command(`FETCH ${ids.join(",")} (INTERNALDATE BODY.PEEK[HEADER.FIELDS (FROM SUBJECT)])`, signal); await s.command("LOGOUT", signal).catch(() => ""); return parseFetch(raw) .filter((m) => m.received >= sinceMs) .sort((a, b) => b.received - a.received); } finally { s.close(); } };