dsh-postbox 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/imap.js ADDED
@@ -0,0 +1,635 @@
1
+ // lib/imap.js — 纯 Node IMAP over TLS(面向 Outlook/Hotmail 个人邮箱)。
2
+ //
3
+ // 协议层:tagged 命令 + 无标签响应 + {N} 字面量状态机。
4
+ // 行尾字面量声明: … {N} \r\n → 紧接 N 字节(可含换行)→ 回行模式
5
+ // 独立字面量行: {N} → 同上
6
+ // 认证: AUTHENTICATE XOAUTH2 <base64>(一步完成,2xx 直接收尾)。
7
+ // 全部 FETCH 用 BODY.PEEK 变体,读写 SELECT 下也不翻 \Seen。
8
+ // MOVE: 有 MOVE 能力直接 UID MOVE;否则 COPY + \Deleted + EXPUNGE 兜底。
9
+
10
+ import tls from "node:tls";
11
+ import { decodeHeaderWord, parseHeaders, parseMime } from "./mime.js";
12
+ import { decodeMutf7, encodeMutf7 } from "./mutf7.js";
13
+
14
+ export class ImapError extends Error {}
15
+
16
+ /** TLS 连接器:默认 `tls.connect`,测试里换成 `net.connect` 就能对**明文假服务器**
17
+ * 跑真实协议对话(R2,2026-11-29)。生产路径永远走默认值。 */
18
+ let tlsConnector = (opts, cb) => tls.connect(opts, cb);
19
+ export function setConnectorForTest(fn) {
20
+ tlsConnector = typeof fn === "function" ? fn : (opts, cb) => tls.connect(opts, cb);
21
+ }
22
+
23
+ const XOAUTH2_B64 = (user, token) =>
24
+ Buffer.from(`user=${user}\u0001auth=Bearer ${token}\u0001\u0001`).toString("base64");
25
+
26
+ class ImapConnection {
27
+ constructor() {
28
+ this.sock = null;
29
+ this.buf = Buffer.alloc(0);
30
+ this.tag = 0;
31
+ this.pending = new Map(); // tag → command 状态
32
+ this.current = null; // 正在等待完成的命令
33
+ this.litLeft = 0;
34
+ this.litChunks = [];
35
+ this.afterLiteral = false; // 字面量收尾后,下一行是同一响应的续行
36
+ this.destroyed = false;
37
+ }
38
+
39
+ /** 连接 + XOAUTH2 认证 + CAPABILITY。 */
40
+ connect(host, port, user, token) {
41
+ const self = this;
42
+ return new Promise((resolve, reject) => {
43
+ const sock = tlsConnector({ host, port: port || 993, servername: host }, () => {
44
+ self.sock = sock;
45
+ // 绝不调用 sock.setEncoding(...):哪怕传 null 也会把流切成「字符串模式」
46
+ // (底层 StringDecoder 默认按 utf8 解码),_onData 收到的就是 string 而非 Buffer,
47
+ // Buffer.concat 立刻抛 ERR_INVALID_ARG_TYPE;而这个异常发生在 socket 的 data
48
+ // 事件里、不在任何 Promise 链上,会直接打死 host 进程(GUI 随即 503)。
49
+ // 不设编码即拿到 Buffer —— IMAP 是二进制安全的,字面量必须按字节处理。
50
+ sock.on("data", (d) => self._onData(d));
51
+ sock.on("error", (e) => self._fatal(e));
52
+ sock.on("end", () => self._fatal(new ImapError("connection closed by server")));
53
+ sock.setTimeout(30_000, () => self._fatal(new ImapError("socket timeout")));
54
+ self.command("CAPABILITY").then((cap) => {
55
+ // 服务器的 greeting("* OK ... ready")可能与 CAPABILITY 响应同批到达并被
56
+ // 记进 lines,只取真正的 CAPABILITY 行,否则能力集会被 greeting 污染。
57
+ self.capabilities = cap.lines
58
+ .filter((l) => /^\* CAPABILITY\b/i.test(l))
59
+ .join("\n").toUpperCase();
60
+ return self.command(`AUTHENTICATE XOAUTH2 ${XOAUTH2_B64(user, token)}`);
61
+ }).then((auth) => {
62
+ void auth;
63
+ resolve(self);
64
+ }).catch(reject);
65
+ });
66
+ sock.on("error", (e) => { if (!self.sock) reject(e); }); // 握手前
67
+ });
68
+ }
69
+
70
+ _fatal(err) {
71
+ if (this.destroyed) return;
72
+ this.destroyed = true;
73
+ for (const p of this.pending.values()) p.reject(err);
74
+ this.pending.clear();
75
+ try { this.sock?.destroy(); } catch {}
76
+ }
77
+
78
+ command(raw) {
79
+ if (!this.sock) throw new ImapError("not connected");
80
+ const tag = `A${String(++this.tag).padStart(4, "0")}`;
81
+ const state = { tag, lines: [], literal: null, reject: null };
82
+ state.promise = new Promise((resolve, reject) => {
83
+ state.resolve = resolve;
84
+ state.reject = (e) => { this.pending.delete(tag); reject(e); };
85
+ });
86
+ this.pending.set(tag, state);
87
+ this.current = state;
88
+ this.sock.write(`${tag} ${raw}\r\n`);
89
+ return state.promise;
90
+ }
91
+
92
+ /** 带字面量的命令(APPEND 用)。
93
+ *
94
+ * IMAP 的 APPEND 是**同步字面量**:先发命令行 + `{N}`,服务器回 `+ `(续行请求)
95
+ * 之后才把 N 个字节写出去。所以不能复用 command():它一次就把整行写完。
96
+ * 服务器若直接回 tagged NO/BAD(文件夹不存在、超配额),那一步就 reject,
97
+ * 不会干等续行(等不到就会一直挂到 socket 超时)。
98
+ */
99
+ commandWithLiteral(rawHead, bytes) {
100
+ if (!this.sock) throw new ImapError("not connected");
101
+ const buf = Buffer.isBuffer(bytes) ? bytes : Buffer.from(String(bytes ?? ""), "utf8");
102
+ const tag = `A${String(++this.tag).padStart(4, "0")}`;
103
+ const state = { tag, lines: [], literal: null, reject: null, onContinue: null };
104
+ state.promise = new Promise((resolve, reject) => {
105
+ state.resolve = resolve;
106
+ state.reject = (e) => { this.pending.delete(tag); reject(e); };
107
+ });
108
+ this.pending.set(tag, state);
109
+ this.current = state;
110
+ state.onContinue = () => {
111
+ try {
112
+ this.sock.write(buf);
113
+ this.sock.write("\r\n"); // 字面量后的行尾(服务器要靠它知道命令结束)
114
+ } catch (e) {
115
+ state.reject(e instanceof Error ? e : new ImapError(String(e)));
116
+ }
117
+ };
118
+ this.sock.write(`${tag} ${rawHead} {${buf.length}}\r\n`);
119
+ return state.promise;
120
+ }
121
+
122
+ _onData(chunk) {
123
+ // 兜底:data 事件里抛出的任何异常必须就地转成「本次请求失败」。
124
+ // 宿主进程里一个未捕获异常 = 整个 DSH 崩溃,所以这里不容许漏出去。
125
+ try {
126
+ this._feed(chunk);
127
+ } catch (err) {
128
+ this._fatal(err instanceof Error ? err : new ImapError(String(err)));
129
+ }
130
+ }
131
+
132
+ /** 真正的解析状态机;异常统一由 _onData 兜住。 */
133
+ _feed(chunk) {
134
+ // 防御:万一 data 事件给了字符串(编码被意外设置),按 latin1 还原字节
135
+ if (typeof chunk === "string") chunk = Buffer.from(chunk, "latin1");
136
+ this.buf = Buffer.concat([this.buf, chunk]);
137
+ while (true) {
138
+ if (this.litLeft > 0) {
139
+ // 本批数据吃完但字面量还没收全 → 退出等下一批。
140
+ // 少了这一行,take 会恒为 0、litLeft 永不减少,while 变成死循环把
141
+ // host 进程卡死(比崩溃更难查),而字面量跨 chunk 是常态。
142
+ if (this.buf.length === 0) break;
143
+ const take = Math.min(this.litLeft, this.buf.length);
144
+ this.litChunks.push(this.buf.subarray(0, take));
145
+ this.buf = this.buf.subarray(take);
146
+ this.litLeft -= take;
147
+ if (this.litLeft > 0) continue;
148
+ // 字面量收尾后通常紧跟 \r\n(属于字面量后的行尾),剥掉
149
+ if (this.buf.length >= 2 && this.buf[0] === 0x0d && this.buf[1] === 0x0a) this.buf = this.buf.subarray(2);
150
+ if (this.current) this.current.literal = Buffer.concat(this.litChunks);
151
+ this.litChunks = [];
152
+ // 同一响应行的剩余部分(如 " FLAGS (\Seen))"、" UID 4512)")会在下一行
153
+ // 到达,它属于刚才那条 untagged 行,必须拼回去,否则 FLAGS/UID 丢失
154
+ // (mailbox_list 的已读/未读就全是错的)。
155
+ this.afterLiteral = true;
156
+ continue;
157
+ }
158
+ const nl = this.buf.indexOf(0x0a);
159
+ if (nl === -1) break;
160
+ let line = this.buf.subarray(0, nl).toString("latin1");
161
+ this.buf = this.buf.subarray(nl + 1);
162
+ if (line.endsWith("\r")) line = line.slice(0, -1);
163
+ if (this.afterLiteral) {
164
+ this.afterLiteral = false;
165
+ if (this.current && this.current.lines.length) {
166
+ this.current.lines[this.current.lines.length - 1] += line;
167
+ } else {
168
+ this._routeLine(line);
169
+ }
170
+ // 续行本身也可能再声明一个字面量(一个响应里多段 FETCH)
171
+ const mc = line.match(/(\{(\d+)\*?})\s*$/);
172
+ if (mc && this.current) {
173
+ this.litLeft = parseInt(mc[2], 10);
174
+ this.litChunks = [];
175
+ if (this.litLeft === 0) this.current.literal = Buffer.alloc(0);
176
+ }
177
+ continue;
178
+ }
179
+ // 行尾字面量声明。**必须带结尾的 \}** —— 少了它,真实的 "{22430}" 永远
180
+ // 匹配不上,FETCH 的正文与头部会全部丢失(实测踩过这个坑)。
181
+ const m = line.match(/(\{(\d+)\*?})\s*$/);
182
+ if (m && this.current) {
183
+ const head = line.slice(0, m.index).trimEnd();
184
+ if (head) this._routeLine(head);
185
+ this.litLeft = parseInt(m[2], 10);
186
+ this.litChunks = [];
187
+ if (this.litLeft === 0) {
188
+ this.current.literal = Buffer.alloc(0);
189
+ continue;
190
+ }
191
+ continue;
192
+ }
193
+ // 独立字面量行
194
+ const s = line.match(/^\{(\d+)\*?}$/);
195
+ if (s && this.current) {
196
+ this.litLeft = parseInt(s[1], 10);
197
+ this.litChunks = [];
198
+ if (this.litLeft === 0) this.current.literal = Buffer.alloc(0);
199
+ continue;
200
+ }
201
+ this._routeLine(line);
202
+ }
203
+ }
204
+
205
+ _routeLine(line) {
206
+ // 续行请求(`+ Ready for literal data`):带字面量的命令在这里才把正文写出去
207
+ if (line.startsWith("+")) {
208
+ const cur = this.current;
209
+ if (cur && typeof cur.onContinue === "function") {
210
+ const fn = cur.onContinue;
211
+ cur.onContinue = null;
212
+ fn();
213
+ }
214
+ return;
215
+ }
216
+ const tagM = line.match(/^([A-Z]\d+) (OK|NO|BAD)\s?([\s\S]*)$/);
217
+ if (tagM) {
218
+ const state = this.pending.get(tagM[1]);
219
+ this.pending.delete(tagM[1]);
220
+ if (this.current === state) this.current = null;
221
+ if (!state) return; // 迟到/未知 tag:忽略,不能把 data 事件炸成致命错误
222
+ state.onContinue = null; // 已经收尾,不再等续行
223
+ state.done = tagM[3]; // tagged 行的后半段(如 "APPEND completed (APPENDUID 1 2)")
224
+ if (tagM[2] === "OK") state.resolve({ lines: state.lines, literal: state.literal, done: state.done });
225
+ else state.reject(new ImapError(`${tagM[1]} ${tagM[2]}: ${tagM[3].trim()}`));
226
+ return;
227
+ }
228
+ if (line.startsWith("*") && this.current) this.current.lines.push(line);
229
+ // 无标签行路由到最近未完成的命令;乱序/迟到响应 v1 忽略
230
+ }
231
+
232
+ close() {
233
+ this.destroyed = true;
234
+ try { this.sock?.end(); } catch {}
235
+ try { this.sock?.destroy(); } catch {}
236
+ }
237
+ }
238
+
239
+ // ---- 高层客户端 ----------------------------------------------------------
240
+
241
+ const ENVELOPE_FIELDS = "FROM TO CC SUBJECT DATE MESSAGE-ID IN-REPLY-TO REFERENCES MIME-VERSION CONTENT-TYPE";
242
+
243
+ /** 非 ASCII(中文)检索走本地过滤时最多回扫多少封。
244
+ * 每封一次 FETCH(状态机不支持一个响应里多个字面量),所以不能设太大。
245
+ * R7(2026-11-30):中文检索只能走这条路,所以从 80 提到 200(每封一次 FETCH,
246
+ * 信封只有头部几百字节;实测 200 封约 2~4 秒,可接受)。 */
247
+ const LOCAL_SCAN_CAP = 200;
248
+ /** 正文条件(中文)时最多抓几封整封来比对:整封是大对象,别把 200 封都拖下来。 */
249
+ const LOCAL_BODY_CAP = 30;
250
+ /** 搜索条件的字符串归一(undefined/null → "")。 */
251
+ function strOf(v) {
252
+ return v === undefined || v === null ? "" : String(v).trim();
253
+ }
254
+
255
+ export class ImapClient {
256
+ constructor(account, token) {
257
+ this.account = account;
258
+ this.token = token;
259
+ this.conn = new ImapConnection();
260
+ this._folder = null;
261
+ }
262
+
263
+ async connect() {
264
+ await this.conn.connect(this.account.imapHost, this.account.imapPort, this.account.email, this.token);
265
+ return this;
266
+ }
267
+
268
+ close() { this.conn.close(); }
269
+
270
+ has(cap) { return (this.conn.capabilities ?? "").includes(cap); }
271
+
272
+ /** SELECT 指定文件夹(全部读操作用 PEEK,不翻 \Seen)。 */
273
+ async open(folder = this.account.defaultFolder) {
274
+ const r = await this.conn.command(`SELECT "${encodeMutf7(folder)}"`);
275
+ const info = { name: folder, messages: 0, uidValidity: null, uidNext: null };
276
+ for (const line of r.lines) {
277
+ // SELECT 回的是 "* 231 EXISTS"(不是 MESSAGES),两者都认
278
+ const mv = line.match(/^\* (\d+) (EXISTS|MESSAGES)$/i);
279
+ if (mv) info.messages = parseInt(mv[1], 10);
280
+ const uv = line.match(/UIDVALIDITY (\d+)/i);
281
+ if (uv) info.uidValidity = parseInt(uv[1], 10);
282
+ const un = line.match(/UIDNEXT (\d+)/i);
283
+ if (un) info.uidNext = parseInt(un[1], 10);
284
+ }
285
+ this._folder = folder;
286
+ return info;
287
+ }
288
+
289
+ /** LIST → [{name, flags[], separator?}]
290
+ * Microsoft 连分隔符都是带引号的(`"/"`),名字可能是带引号字符串或裸原子;
291
+ * 正则必须同时容忍这两种写法 —— 否则一条都匹配不上(mailbox_folders 返回空)。 */
292
+ async listFolders() {
293
+ const r = await this.conn.command('LIST "" "*"');
294
+ const folders = [];
295
+ for (const line of r.lines) {
296
+ const m = line.match(/^\* LIST \(([^)]*)\)\s+(?:"([^"]*)"|(\S+))\s+(.*)$/);
297
+ if (!m) continue;
298
+ const flags = (m[1].match(/[\\$A-Za-z0-9_-]+/g) ?? []).map((s) => s.replace(/^\\/, ""));
299
+ const sep = m[2] ?? m[3] ?? "/";
300
+ let name = (m[4] ?? "").trim();
301
+ if (name.startsWith('"') && name.endsWith('"')) {
302
+ name = name.slice(1, -1).replace(/\\(.)/g, "$1");
303
+ }
304
+ if (!name || /^\{\d+\}$/.test(name)) continue; // 字面量形式的名字取不到(极罕见),跳过
305
+ // 名字是 modified UTF-7:解码后给用户看/给工具用;发命令时再 encode 回去
306
+ folders.push({ name: decodeMutf7(name), flags, separator: sep });
307
+ }
308
+ return folders;
309
+ }
310
+
311
+ /** STATUS 指定文件夹。
312
+ * Microsoft 的名字多为**不带引号**的裸原子(仅含空格时才加引号),行尾还会多一个
313
+ * 空格 —— 两种写法都要认、尾空格也要容忍,否则解析结果恒为 {}。 */
314
+ async status(folder) {
315
+ const r = await this.conn.command(`STATUS "${encodeMutf7(folder)}" (MESSAGES UNSEEN UIDVALIDITY UIDNEXT)`);
316
+ const out = {};
317
+ for (const line of r.lines) {
318
+ const m = line.match(/^\* STATUS (?:"([^"]*)"|(\S+))\s+\(([^)]*)\)\s*$/);
319
+ if (!m) continue;
320
+ for (const tok of (m[3] ?? "").match(/[A-Z]+\s+\d+/g) ?? []) {
321
+ const [k, v] = tok.split(/\s+/);
322
+ out[k.toLowerCase()] = parseInt(v, 10);
323
+ }
324
+ break;
325
+ }
326
+ return out;
327
+ }
328
+
329
+ /** UID SEARCH(criteria) → uid[](升序)。
330
+ *
331
+ * criteria: { unseen, seen, since, until, from, to, subject, body(别名 text) }
332
+ *
333
+ * **非 ASCII 检索在 Exchange 上没有服务端解法**(2026-11-30 真机探针逐条实测):
334
+ * ① 裸 UTF-8 字符串 → `A0004 BAD: Command Error. 11`
335
+ * ② `CHARSET UTF-8` + 引号字符串 → `A0004 BAD: Command Error. 11`
336
+ * ③ `CHARSET UTF-8` + 字面量 → **连接被服务器直接断开**
337
+ * 所以这里**不**试 CHARSET:每次工具调用都是新连接、尝试必然失败,白付一次
338
+ * BAD 往返还多一条日志;真支持 CHARSET 的服务器(Gmail/dovecot)等 R5 多服务商
339
+ * 时再按 provider 打开。当前策略分两层:
340
+ * ① 纯 ASCII:服务端一把梭(含 FROM/TO/SUBJECT/TEXT,覆盖整个文件夹);
341
+ * ② 含非 ASCII:服务端只筛日期/未读,客户端按子串过滤最近 LOCAL_SCAN_CAP 封;
342
+ * 有正文条件时才抓正文(上限 LOCAL_BODY_CAP 封),没有就不抓。
343
+ * 代价写明在返回值里(`localScan: true`)—— 用户该知道"这次只翻了最近 N 封"。 */
344
+ async uidSearch(criteria = {}) {
345
+ const c = {
346
+ unseen: criteria.unseen === true,
347
+ seen: criteria.seen === true,
348
+ since: criteria.since,
349
+ until: criteria.until,
350
+ from: strOf(criteria.from),
351
+ to: strOf(criteria.to),
352
+ subject: strOf(criteria.subject),
353
+ body: strOf(criteria.body ?? criteria.text),
354
+ };
355
+ const textual = ["from", "to", "subject", "body"].filter((k) => c[k]);
356
+ const nonAscii = textual.some((k) => /[^\x00-\x7F]/.test(c[k]));
357
+
358
+ if (!textual.length || !nonAscii) {
359
+ try {
360
+ return await this._searchRaw(ImapClient.searchKeys(c));
361
+ } catch (e) {
362
+ // 纯 ASCII 也被拒(极少见):退回「只按日期/未读筛 + 本地过滤」,别让搜索整个失败
363
+ if (!textual.length) throw e;
364
+ const all = await this._searchRaw(ImapClient.searchKeys(c, { skipText: true }));
365
+ const r = await this._filterLocal(all, c);
366
+ r.localScan = true;
367
+ return r;
368
+ }
369
+ }
370
+ const all = await this._searchRaw(ImapClient.searchKeys(c, { skipText: true }));
371
+ const out = await this._filterLocal(all, c);
372
+ out.localScan = true;
373
+ return out;
374
+ }
375
+
376
+ /** 组装 SEARCH 键集(不做 IO)。skipText:只留日期/未读。 */
377
+ static searchKeys(c, { skipText = false } = {}) {
378
+ const parts = [];
379
+ if (c.unseen) parts.push("UNSEEN");
380
+ if (c.seen) parts.push("SEEN");
381
+ if (c.since) parts.push(`SINCE "${ImapClient.imapDate(new Date(c.since))}"`);
382
+ if (c.until) parts.push(`BEFORE "${ImapClient.imapDate(new Date(c.until))}"`);
383
+ if (!skipText) {
384
+ if (c.from) parts.push(`FROM "${escapeImap(c.from)}"`);
385
+ if (c.to) parts.push(`TO "${escapeImap(c.to)}"`);
386
+ if (c.subject) parts.push(`SUBJECT "${escapeImap(c.subject)}"`);
387
+ if (c.body) parts.push(`TEXT "${escapeImap(c.body)}"`);
388
+ }
389
+ return parts.length ? parts.join(" ") : "ALL";
390
+ }
391
+
392
+ async _searchRaw(keys) {
393
+ const r = await this.conn.command(`UID SEARCH ${keys}`);
394
+ for (const line of r.lines) {
395
+ const m = line.match(/^\* SEARCH (.*)$/);
396
+ if (m) return m[1].trim() ? m[1].trim().split(/\s+/).map(Number) : [];
397
+ }
398
+ return [];
399
+ }
400
+
401
+ /** 客户端过滤:信件头用信封,正文条件才抓整封(上限 LOCAL_BODY_CAP)。 */
402
+ async _filterLocal(uids, c) {
403
+ const need = ["from", "to", "subject", "body"].filter((k) => c[k]);
404
+ if (!need.length || !uids.length) return uids;
405
+ const window = uids.slice(-LOCAL_SCAN_CAP);
406
+ const envs = await this.fetchEnvelopes(window);
407
+ const ok = (hay, want) => String(hay ?? "").toLowerCase().includes(String(want).toLowerCase());
408
+ let hit = envs.filter((e) => {
409
+ if (c.from && !ok(e.from, c.from)) return false;
410
+ if (c.to && !(ok(e.to, c.to) || ok(e.cc, c.to))) return false;
411
+ if (c.subject && !ok(e.subject, c.subject)) return false;
412
+ return true;
413
+ });
414
+ if (c.body) {
415
+ const probe = hit.slice(-LOCAL_BODY_CAP);
416
+ const kept = [];
417
+ for (const e of probe) {
418
+ try {
419
+ const parsed = parseMime(await this.fetchFull(e.uid));
420
+ if (ok(parsed.bodyText, c.body)) kept.push(e);
421
+ } catch { /* 单封读不出来不该拖垮整次搜索 */ }
422
+ }
423
+ hit = kept;
424
+ }
425
+ return hit.map((e) => e.uid);
426
+ }
427
+
428
+ /** 水位检索:UID SEARCH UID <since+1>:* → 严格大于水位的 uid(升序,最多 limit 个)。
429
+ * 调用前必须已 open(folder) —— SEARCH 只在 SELECTED 态合法。
430
+ * ⚠️ Exchange 的坑:当 from 大于当前最大 UID 时,`UID n:*` 会**返回全部邮件**
431
+ * (而不是空),所以这里必须按 uid > sinceUid 再过滤一遍,否则水位会被打回起点。 */
432
+ async searchUidsSince(sinceUid, limit = 20) {
433
+ const since = Number(sinceUid) || 0;
434
+ const r = await this.conn.command(`UID SEARCH UID ${since + 1}:*`);
435
+ let uids = [];
436
+ for (const line of r.lines) {
437
+ const m = line.match(/^\* SEARCH (.*)$/);
438
+ if (m) { uids = m[1].trim() ? m[1].trim().split(/\s+/).map(Number) : []; break; }
439
+ }
440
+ return uids.filter((u) => Number.isFinite(u) && u > since).slice(0, Math.max(1, Number(limit) || 20));
441
+ }
442
+
443
+ /** 状态回同步(2026-10-31):批量取 FLAGS。返回 [{uid, flags, seen}](按 uid 升序);
444
+ * **服务器已不存在的 uid 不会出现在返回里** —— 调用方据此识别「已移走/删除」。
445
+ * 只取 FLAGS 不碰 BODY,一封几十字节,500 封一次往返也无压力。 */
446
+ async fetchFlags(uids) {
447
+ const list = [...new Set((uids ?? []).map(Number).filter(Number.isFinite))].sort((a, b) => a - b);
448
+ const out = new Map();
449
+ const CHUNK = 200;
450
+ for (let i = 0; i < list.length; i += CHUNK) {
451
+ const set = list.slice(i, i + CHUNK).join(",");
452
+ const r = await this.conn.command(`UID FETCH ${set} (FLAGS)`);
453
+ for (const line of r.lines) {
454
+ // 形如 `* 5 FETCH (FLAGS (\Seen) UID 42)`;UID 与 FLAGS 顺序服务端自定,都在括号里解析
455
+ const m = line.match(/\bFETCH \((.*)\)\s*$/);
456
+ if (!m) continue;
457
+ const um = m[1].match(/\bUID (\d+)/);
458
+ if (!um) continue;
459
+ const fm = m[1].match(/FLAGS \(([^)]*)\)/);
460
+ const flags = fm && fm[1].trim() ? fm[1].trim().split(/\s+/) : [];
461
+ out.set(Number(um[1]), { uid: Number(um[1]), flags, seen: flags.includes("\\Seen") });
462
+ }
463
+ }
464
+ return [...out.values()].sort((a, b) => a.uid - b.uid);
465
+ }
466
+
467
+ /** 取信封:逐 UID 取 HEADER.FIELDS(字面量即头部块)。
468
+ * 返回与 uids 等长的信封数组(顺序一致)。 */
469
+ async fetchEnvelopes(uids) {
470
+ const spec = `BODY.PEEK[HEADER.FIELDS (${ENVELOPE_FIELDS})]`;
471
+ const out = [];
472
+ for (const uid of uids) {
473
+ let literal = null;
474
+ let flags = [];
475
+ try {
476
+ const r = await this.conn.command(`UID FETCH ${uid} (${spec} FLAGS)`);
477
+ literal = r.literal;
478
+ for (const line of r.lines) {
479
+ const fm = line.match(/FLAGS \(([^)]*)\)/);
480
+ if (fm) flags = fm[1].trim() ? fm[1].trim().split(/\s+/) : [];
481
+ // 未置 \Seen 时 Microsoft 回 FLAGS ()
482
+ }
483
+ } catch (e) {
484
+ out.push({ uid, error: String(e.message), flags, seen: false });
485
+ continue;
486
+ }
487
+ // UID 空洞:Exchange/Outlook 的 UID 序列不连续(被删的信会留下空缺),服务端对
488
+ // 不存在的 UID 回的是 `OK` 但**不带任何 FETCH 数据**,于是 literal 为 null。
489
+ // 这种情况必须跳过 —— 否则会造出一个 subject/from 全 null 的"幽灵信封",
490
+ // 混进列表、搜索与 uid 计数里(2026-11-29 清理测试邮件时实测踩到)。
491
+ if (!literal) continue;
492
+ const h = parseHeaders(literal?.toString("latin1") ?? "");
493
+ out.push({
494
+ uid,
495
+ subject: h["subject"] ? decodeHeaderWord(h["subject"]) : null,
496
+ from: h["from"] ? decodeHeaderWord(h["from"]) : null,
497
+ to: h["to"] ? decodeHeaderWord(h["to"]) : null,
498
+ cc: h["cc"] ? decodeHeaderWord(h["cc"]) : null,
499
+ date: h["date"] || null,
500
+ message_id: h["message-id"] || null,
501
+ in_reply_to: h["in-reply-to"] || null,
502
+ references: h["references"] || null,
503
+ content_type: h["content-type"] || null,
504
+ flags,
505
+ seen: flags.includes("\\Seen"),
506
+ });
507
+ }
508
+ return out;
509
+ }
510
+
511
+ /** 取整封(BODY.PEEK[]) → 原始字节。 */
512
+ async fetchFull(uid) {
513
+ const r = await this.conn.command(`UID FETCH ${uid} (BODY.PEEK[])`);
514
+ if (!r.literal) throw new ImapError(`fetch uid ${uid} 无正文`);
515
+ return r.literal;
516
+ }
517
+
518
+ /** 标记已读/未读。 */
519
+ async setSeen(uid, seen) {
520
+ await this.conn.command(`UID STORE ${uid} ${seen ? "+" : "-"}FLAGS (\\Seen)`);
521
+ }
522
+
523
+ /** 批量标已读/未读(R1,2026-11-29):一条 `UID STORE` 打一串 uid。
524
+ *
525
+ * 整文件夹的未读可能有上千封,逐封 STORE 是上千次往返;IMAP 的集合语法
526
+ * (`1,2,3` / `1:5`)本身就是为这件事设计的。返回实际下发的 uid 个数。 */
527
+ async setSeenBulk(uids, seen) {
528
+ const list = (Array.isArray(uids) ? uids : [])
529
+ .map((u) => Number(u))
530
+ .filter((u) => Number.isFinite(u) && u > 0);
531
+ if (!list.length) return 0;
532
+ await this.conn.command(`UID STORE ${list.join(",")} ${seen ? "+" : "-"}FLAGS (\\Seen)`);
533
+ return list.length;
534
+ }
535
+
536
+ /** APPEND 一封邮件到指定文件夹(发信后写「已发送」用,B4/2026-11-29)。
537
+ *
538
+ * 必须与 SMTP 发出去的是**同一份原始字节** —— 抄送自己的方案会在收件箱里多一份
539
+ * 副本、还污染未读与通知,所以宁可在这里追加。
540
+ * flags 默认 `\Seen`:自己发的信不该在 Sent 里显示未读。
541
+ * 返回服务器给的 uid(UUIDPLUS 的 APPENDUID),拿不到就 null。
542
+ */
543
+ async append(folder, raw, { flags = ["\\Seen"] } = {}) {
544
+ const list = (Array.isArray(flags) ? flags : []).filter(Boolean);
545
+ const head = `APPEND "${encodeMutf7(folder)}"${list.length ? ` (${list.join(" ")})` : ""}`;
546
+ const r = await this.conn.commandWithLiteral(head, raw);
547
+ // UIDPLUS 的 APPENDUID 在 tagged 行里(不在 `* ` 开头的 untagged 行里)
548
+ const done = String(r.done ?? "");
549
+ const m = done.match(/APPENDUID\s+\d+\s+(\d+)/i);
550
+ if (m) return Number(m[1]);
551
+ for (const line of r.lines ?? []) {
552
+ const lm = line.match(/APPENDUID\s+\d+\s+(\d+)/i);
553
+ if (lm) return Number(lm[1]);
554
+ }
555
+ return null;
556
+ }
557
+
558
+ /** 找「已发送」文件夹:优先 SPECIAL-USE `\Sent`,再按常见名字回退。
559
+ * 找不到或 LIST 失败时回退 `Sent Items`(Exchange 的默认名)。 */
560
+ async findSentFolder() {
561
+ try {
562
+ const folders = await this.listFolders();
563
+ const byAttr = folders.find((f) => (f.flags ?? []).some((x) => /^sent$/i.test(String(x))));
564
+ if (byAttr) return byAttr.name;
565
+ for (const want of ["Sent Items", "Sent", "已发送", "已发送邮件", "已傳送郵件", "Sent Messages"]) {
566
+ const hit = folders.find((f) => String(f.name).toLowerCase() === want.toLowerCase());
567
+ if (hit) return hit.name;
568
+ }
569
+ } catch { /* LIST 失败(权限/超时)就用默认名兜底,由 APPEND 自己报错 */ }
570
+ return "Sent Items";
571
+ }
572
+
573
+ /** 这条 Message-ID 已经在该文件夹里了吗(APPEND 幂等用)→ uid 或 null。
574
+ * 重试/兜底路径会重复调用送出流程,靠它避免同一封信在 Sent 里出现两份。 */
575
+ async findUidByMessageId(folder, messageId) {
576
+ const id = String(messageId ?? "").trim();
577
+ if (!id || !folder) return null;
578
+ await this.open(folder);
579
+ const r = await this.conn.command(`UID SEARCH HEADER Message-ID "${escapeImap(id)}"`);
580
+ for (const line of r.lines ?? []) {
581
+ const m = line.match(/^\* SEARCH (.*)$/);
582
+ if (m && m[1].trim()) return Number(m[1].trim().split(/\s+/)[0]);
583
+ }
584
+ return null;
585
+ }
586
+
587
+ /** 「刚发出去的这封」是否已经在文件夹里了 —— 专治 Exchange/Outlook 的**自动存档**。
588
+ *
589
+ * 2026-11-29 真机实测:Outlook 在 SMTP 收下这封信后 1~2 秒会自己往 Sent 存一份
590
+ * (它重新生成 Message-ID,所以按 Message-ID 查重抓不到),此时再 APPEND 就会出现
591
+ * 两封一模一样的信。判据用「主题完全相同 + 时间在窗口内 + 收件人对得上」,
592
+ * 主题比较**在本地做**(中文主题没法走服务端 SEARCH)。
593
+ * 返回命中的 uid,没有则 null。
594
+ */
595
+ async findJustSent(folder, { subject = "", withinMs = 15 * 60_000, to = [], now = Date.now() } = {}) {
596
+ const want = String(subject ?? "").trim();
597
+ if (!folder || !want) return null;
598
+ const info = await this.open(folder);
599
+ const uidNext = Number(info?.uidNext ?? 0);
600
+ if (!(uidNext > 1)) return null;
601
+ const uids = await this.searchUidsSince(Math.max(0, uidNext - 12), 12);
602
+ const envs = uids.length ? await this.fetchEnvelopes(uids) : [];
603
+ const wantTo = (Array.isArray(to) ? to : []).map((s) => String(s ?? "").toLowerCase()).filter(Boolean);
604
+ for (const e of envs) {
605
+ if (String(e.subject ?? "").trim() !== want) continue;
606
+ const t = Date.parse(String(e.date ?? ""));
607
+ if (Number.isFinite(t) && Math.abs(Number(now) - t) > withinMs) continue;
608
+ const hay = `${e.to ?? ""}\n${e.cc ?? ""}`.toLowerCase();
609
+ if (wantTo.length && !wantTo.some((a) => hay.includes(a))) continue;
610
+ return e.uid;
611
+ }
612
+ return null;
613
+ }
614
+
615
+ /** 移动到目标文件夹。 */
616
+ async move(uid, toFolder) {
617
+ if (this.has("MOVE")) {
618
+ await this.conn.command(`UID MOVE ${uid} "${encodeMutf7(toFolder)}"`);
619
+ return "moved";
620
+ }
621
+ await this.conn.command(`UID COPY ${uid} "${encodeMutf7(toFolder)}"`);
622
+ await this.conn.command(`UID STORE ${uid} +FLAGS (\\Deleted)`);
623
+ await this.conn.command("EXPUNGE");
624
+ return "copied+deleted";
625
+ }
626
+
627
+ static imapDate(d) {
628
+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
629
+ return `${String(d.getUTCDate()).padStart(2, "0")}-${months[d.getUTCMonth()]}-${d.getUTCFullYear()}`;
630
+ }
631
+ }
632
+
633
+ function escapeImap(s) {
634
+ return String(s).replace(/(["\\])/g, "\\$1");
635
+ }