aboutsummaryrefslogtreecommitdiff
path: root/castle-search/src/imap.ts
diff options
context:
space:
mode:
authorIgor Soarez <igor@soarez.org>2026-11-18 10:50:14 +0000
committerIgor Soarez <igor@soarez.org>2026-11-18 10:50:14 +0000
commit910ac7cd424f6401ea042a84603c42ba055994f8 (patch)
tree3ff40da7d14c644428c71cab1b005eca0b186d13 /castle-search/src/imap.ts
parent39f887e07721c5b3ddd31657e5e8e25e4486d2e5 (diff)
castle-search: sign X back in when a search finds it signed out
Username, password, the authenticator code (TOTP) and, when X asks, the code it emails, read over IMAP. At most one try per 30 minutes, the password never sent twice, and any unknown step (a captcha) fails saying a person has to sign in. Details from the file CCS_X_LOGIN_FILE names.
Diffstat (limited to 'castle-search/src/imap.ts')
-rw-r--r--castle-search/src/imap.ts148
1 files changed, 148 insertions, 0 deletions
diff --git a/castle-search/src/imap.ts b/castle-search/src/imap.ts
new file mode 100644
index 0000000..ef02979
--- /dev/null
+++ b/castle-search/src/imap.ts
@@ -0,0 +1,148 @@
+/**
+ * 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<string> {
+ while (!done(this.#buffer)) {
+ if (this.#error) throw this.#error;
+ if (signal.aborted) throw signal.reason;
+ await new Promise<void>((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<string> {
+ 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<string> {
+ 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<MailHeader[]> => {
+ 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();
+ }
+};