1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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();
}
};
|