pi-tsgw 1.5.2 → 1.6.0

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.
@@ -0,0 +1,86 @@
1
+ import { ImapFlow, type ImapFlowOptions } from "imapflow";
2
+ import type { EmailConfig } from "./config.ts";
3
+ import { EmailError } from "./types.ts";
4
+
5
+ const IDLE_MS = 3 * 60_000;
6
+ interface Connection {
7
+ client?: ImapFlow;
8
+ queue: Promise<unknown>;
9
+ timer?: ReturnType<typeof setTimeout>;
10
+ }
11
+
12
+ /** 一个邮件会话持有;同账户排队,不同账户独立,失败不在本次调用中重试。 */
13
+ export class ImapSessions {
14
+ private readonly connections = new Map<string, Connection>();
15
+ private closed = false;
16
+
17
+ constructor(
18
+ private readonly config: EmailConfig,
19
+ private readonly createClient: (options: ImapFlowOptions) => ImapFlow = options => new ImapFlow(options),
20
+ ) {}
21
+
22
+ run<T>(account: string, mailbox: string | undefined, signal: AbortSignal | undefined, action: (client: ImapFlow) => Promise<T>): Promise<T> {
23
+ if (!Object.hasOwn(this.config.imap, account))
24
+ return Promise.reject(new EmailError("ACCOUNT_MISSING", "未配置指定的 IMAP 账户。"));
25
+ if (this.closed) return Promise.reject(new EmailError("SESSION_CLOSED", "邮件会话已经关闭。"));
26
+ let connection = this.connections.get(account);
27
+ if (!connection) {
28
+ connection = { queue: Promise.resolve() };
29
+ this.connections.set(account, connection);
30
+ }
31
+ const current = connection;
32
+ const task = current.queue.then(async () => {
33
+ if (this.closed) throw new EmailError("SESSION_CLOSED", "邮件会话已经关闭。");
34
+ signal?.throwIfAborted();
35
+ clearTimeout(current.timer);
36
+ const settings = this.config.imap[account]!;
37
+ let client = current.client;
38
+ if (!client?.usable) {
39
+ client?.close();
40
+ client = this.createClient({
41
+ host: settings.host, port: settings.port, secure: settings.tls === "implicit",
42
+ doSTARTTLS: settings.tls === "starttls", tls: { rejectUnauthorized: true },
43
+ auth: { user: settings.user, pass: settings.password },
44
+ logger: false, logRaw: false, emitLogs: false, disableAutoIdle: true,
45
+ connectionTimeout: 15_000, greetingTimeout: 15_000, socketTimeout: 60_000,
46
+ });
47
+ // 错误由正在执行的请求返回;不将服务端响应或凭据写入普通日志。
48
+ client.on("error", () => {});
49
+ current.client = client;
50
+ }
51
+ const active = client;
52
+ const abort = () => active.close();
53
+ signal?.addEventListener("abort", abort, { once: true });
54
+ try {
55
+ if (!active.usable) await active.connect();
56
+ signal?.throwIfAborted();
57
+ if (!mailbox) return await action(active);
58
+ const lock = await active.getMailboxLock(mailbox);
59
+ try {
60
+ signal?.throwIfAborted();
61
+ return await action(active);
62
+ } finally { lock.release(); }
63
+ } finally {
64
+ signal?.removeEventListener("abort", abort);
65
+ if (!this.closed) {
66
+ current.timer = setTimeout(() => {
67
+ current.client?.close();
68
+ current.client = undefined;
69
+ }, IDLE_MS);
70
+ current.timer.unref();
71
+ }
72
+ }
73
+ });
74
+ current.queue = task.then(() => undefined, () => undefined);
75
+ return task;
76
+ }
77
+
78
+ dispose(): void {
79
+ this.closed = true;
80
+ for (const connection of this.connections.values()) {
81
+ clearTimeout(connection.timer);
82
+ connection.client?.close();
83
+ }
84
+ this.connections.clear();
85
+ }
86
+ }
@@ -0,0 +1,23 @@
1
+ import { VERSION, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { readEmailConfig } from "./config.ts";
3
+
4
+ /** 邮件依赖宿主 codemode 暴露契约;1.2 为已核验基线,不提高整个插件的 peer 要求。 */
5
+ export function supportsEmailTools(version: string): boolean {
6
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:\+.*)?$/.exec(version);
7
+ return !!match && (Number(match[1]) > 1 || (Number(match[1]) === 1 && Number(match[2]) >= 2));
8
+ }
9
+
10
+ export async function registerEmail(pi: ExtensionAPI, options: { agentDir?: string; version?: string } = {}): Promise<void> {
11
+ const loaded = readEmailConfig(options.agentDir);
12
+ if (loaded.status === "disabled") return;
13
+ const error = loaded.status === "invalid" ? loaded.message
14
+ : !supportsEmailTools(options.version ?? VERSION) ? "邮件功能需要已验证的 Pi 1.2+ codemode 能力;其他插件功能不受影响。" : undefined;
15
+ if (error) {
16
+ pi.on("session_start", (_event, ctx) => { ctx.ui.notify(error, "warning"); });
17
+ return;
18
+ }
19
+ if (loaded.status === "ready") {
20
+ const { registerEmailTools } = await import("./tools.ts");
21
+ registerEmailTools(pi, loaded.config);
22
+ }
23
+ }
@@ -0,0 +1,18 @@
1
+ import type { FetchMessageObject, FetchQueryObject, ImapFlow } from "imapflow";
2
+ import { EmailError, type MessageRef } from "./types.ts";
3
+
4
+ export function assertMailbox(client: ImapFlow, ref: Omit<MessageRef, "uid">): void {
5
+ if (!client.mailbox || client.mailbox.uidValidity.toString() !== ref.uidValidity)
6
+ throw new EmailError("STALE_MAILBOX", "文件夹身份已变化,请重新查询邮件清单。");
7
+ }
8
+
9
+ export async function requireMessage(client: ImapFlow, ref: MessageRef, query: FetchQueryObject): Promise<FetchMessageObject> {
10
+ const message = await client.fetchOne(String(ref.uid), { ...query, uid: true }, { uid: true });
11
+ if (!message || message.uid !== ref.uid)
12
+ throw new EmailError("MESSAGE_MISSING", "指定邮件已不存在,请重新查询清单。");
13
+ return message;
14
+ }
15
+
16
+ export function messageCacheKey(ref: MessageRef, part: string): string {
17
+ return JSON.stringify([ref.account, ref.mailbox, ref.uidValidity, ref.uid, part]);
18
+ }
@@ -0,0 +1,307 @@
1
+ import type { FetchMessageObject, ImapFlow } from "imapflow";
2
+ import type { EmailCache } from "./cache.ts";
3
+ import type { EmailConfig, ImapAccountConfig } from "./config.ts";
4
+ import type { ImapSessions } from "./imap-session.ts";
5
+ import { assertMailbox } from "./message.ts";
6
+ import {
7
+ EmailError, type MarkInput, type MessageBatch, type MoveInput, type MutationAction,
8
+ type MutationInput, type MutationItem, type MutationResult, type OperationStatus, type TrashInput,
9
+ } from "./types.ts";
10
+
11
+ /** 明确 UID 清单只发固定次数的 UID FETCH/STORE/MOVE/EXPUNGE;不逐封往返、不 SEARCH 扩单、不用序号。 */
12
+ const SAFE = {
13
+ canceled: "操作已取消,未执行。",
14
+ missing: "指定邮件已不存在,未执行操作。",
15
+ notStarted: "连接已中断,未执行操作。",
16
+ rejected: "服务器拒绝执行该操作。",
17
+ partial: "部分步骤未完成,请重新查询确认。",
18
+ unknown: "连接中断或无法核对结果,请重新查询确认。",
19
+ startFailed: "邮件操作未能开始,请稍后重试。",
20
+ destinationMissing: "目标文件夹不存在或不可选择,未执行操作。",
21
+ destinationUnknown: "无法确认目标文件夹,未执行操作。",
22
+ } as const;
23
+
24
+ interface Change { action: string; flag: string; add: boolean }
25
+ interface Work { uid: number; present: boolean; item: MutationItem }
26
+ type Halt = "canceled" | "disconnected" | undefined;
27
+ /** 与 imapflow 2.9.1 的 hasCapability 一致:显式通告,或真实启用 rev2/服务器仅支持 rev2。 */
28
+ function supports(client: ImapFlow, capability: "MOVE" | "UIDPLUS"): boolean {
29
+ return client.capabilities.has(capability)
30
+ || client.enabled.has("IMAP4REV2")
31
+ || (client.capabilities.has("IMAP4rev2") && !client.capabilities.has("IMAP4rev1"));
32
+ }
33
+ /** tagged NO/BAD 在 imapflow 错误对象上带 responseStatus;NoConnection/BYE 不走该分支。 */
34
+ function refused(error: unknown): boolean {
35
+ const status = (error as { responseStatus?: unknown } | null)?.responseStatus;
36
+ return status === "NO" || status === "BAD";
37
+ }
38
+ /** BYE 先进入 LOGOUT,传输层延迟关闭时 usable 可能还未清除。 */
39
+ function connected(client: ImapFlow): boolean {
40
+ return client.usable && client.state !== client.states.LOGOUT;
41
+ }
42
+ /** STORE/MOVE/EXPUNGE 对命令异常也返回 false;连接已不可用或已取消时按 unknown。 */
43
+ function falseStatus(client: ImapFlow, signal: AbortSignal | undefined): OperationStatus {
44
+ return !connected(client) || signal?.aborted ? "unknown" : "failed";
45
+ }
46
+
47
+ /** 目标必须已存在且可选择;INBOX 由协议保证,其余用一次 LIST 精确匹配,不创建目录。 */
48
+ async function requireDestination(client: ImapFlow, destination: string): Promise<void> {
49
+ if (destination.toUpperCase() === "INBOX") return;
50
+ const entries = await client.list({ listOnly: true })
51
+ .catch(() => { throw new EmailError("DESTINATION_UNKNOWN", SAFE.destinationUnknown); });
52
+ const target = entries.find(entry => entry.path === destination);
53
+ if (!target) throw new EmailError("DESTINATION_MISSING", SAFE.destinationMissing);
54
+ // \Noselect 不能选择;\NonExistent 只是子目录占位名,本身不存在。
55
+ if ([...target.flags].some(flag => ["\\NOSELECT", "\\NONEXISTENT"].includes(flag.toUpperCase())))
56
+ throw new EmailError("DESTINATION_MISSING", SAFE.destinationMissing);
57
+ }
58
+
59
+ function planFor(action: MutationAction, input: MutationInput, settings: ImapAccountConfig): { destination?: string; changes: Change[] } {
60
+ const changes: Change[] = [];
61
+ const mark = input as MarkInput;
62
+ if (action === "mark") {
63
+ if (mark.read !== undefined) changes.push({ action: "read", flag: "\\Seen", add: mark.read });
64
+ if (mark.flagged !== undefined) changes.push({ action: "flagged", flag: "\\Flagged", add: mark.flagged });
65
+ } else if (action === "trash" && (input as TrashInput).markRead === true) {
66
+ changes.push({ action: "read", flag: "\\Seen", add: true });
67
+ }
68
+ const destinations: Partial<Record<MutationAction, string>> = {
69
+ move: (input as MoveInput).targetMailbox,
70
+ trash: settings.trashMailbox,
71
+ junk: settings.junkMailbox,
72
+ not_junk: "INBOX",
73
+ };
74
+ const destination = destinations[action];
75
+ // 未知 action 或缺失移动目标都不应静默变成空操作。
76
+ if (action !== "mark" && action !== "purge" && !destination)
77
+ throw new EmailError("INVALID_ACTION", "不支持的邮件操作。");
78
+ return { destination, changes };
79
+ }
80
+ async function fetchAll(client: ImapFlow, uids: number[], flags = false): Promise<FetchMessageObject[]> {
81
+ return client.fetchAll(uids, flags ? { uid: true, flags: true } : { uid: true }, { uid: true });
82
+ }
83
+
84
+ async function fetchUids(client: ImapFlow, uids: number[]): Promise<Set<number>> {
85
+ return new Set((await fetchAll(client, uids)).map(row => row.uid));
86
+ }
87
+ function hasFlag(flags: Set<string> | undefined, flag: string): boolean | undefined {
88
+ if (!flags) return undefined;
89
+ for (const value of flags) if (value.toUpperCase() === flag.toUpperCase()) return true;
90
+ return false;
91
+ }
92
+
93
+ function markStep(work: Work[], index: number, status: OperationStatus): void {
94
+ for (const w of work) w.item.steps[index]!.status = status;
95
+ }
96
+ /** 批量 STORE 后用一次 FETCH flags 逐项核对;返回是否因断线/取消中止后续阶段。 */
97
+ async function flagBatch(client: ImapFlow, signal: AbortSignal | undefined, uids: number[], changes: Change[], work: Work[], clear: () => void): Promise<boolean> {
98
+ const pending: number[] = [];
99
+ let halted = false;
100
+ for (let index = 0; index < changes.length; index += 1) {
101
+ const change = changes[index]!;
102
+ if (signal?.aborted || !connected(client)) {
103
+ halted = true;
104
+ break;
105
+ }
106
+ clear();
107
+ let status: OperationStatus;
108
+ try {
109
+ const ok = change.add
110
+ ? await client.messageFlagsAdd(uids, [change.flag], { uid: true })
111
+ : await client.messageFlagsRemove(uids, [change.flag], { uid: true });
112
+ status = ok ? "success" : falseStatus(client, signal);
113
+ } catch (error) {
114
+ status = refused(error) ? "failed" : "unknown";
115
+ }
116
+ if (status === "success") { pending.push(index); continue; }
117
+ markStep(work, index, status);
118
+ if (status === "unknown") { halted = true; break; }
119
+ }
120
+
121
+ if (pending.length > 0 && !halted && !signal?.aborted && connected(client)) {
122
+ let rows: FetchMessageObject[] | undefined;
123
+ try { rows = await fetchAll(client, uids, true); } catch { rows = undefined; }
124
+ const flags = new Map((rows ?? []).map(row => [row.uid, row.flags]));
125
+ for (const index of pending) for (const w of work) {
126
+ const actual = hasFlag(flags.get(w.uid), changes[index]!.flag);
127
+ w.item.steps[index]!.status = actual === undefined ? "unknown" : actual === changes[index]!.add ? "success" : "failed";
128
+ }
129
+ // 核对请求本身断线/取消时,后续阶段不能再发。
130
+ if (!rows && (!connected(client) || signal?.aborted)) halted = true;
131
+ } else if (pending.length > 0) {
132
+ for (const index of pending) markStep(work, index, "unknown");
133
+ }
134
+ return halted || signal?.aborted === true || !connected(client);
135
+ }
136
+ /** 一次批量 UID MOVE;缺 uidMap 时用一次源 FETCH 核对,不能证明就保留 unknown。 */
137
+ async function moveBatch(client: ImapFlow, signal: AbortSignal | undefined, uids: number[], destination: string, work: Work[], step: number, clear: () => void): Promise<void> {
138
+ clear();
139
+ let response: Awaited<ReturnType<ImapFlow["messageMove"]>>;
140
+ try {
141
+ response = await client.messageMove(uids, destination, { uid: true });
142
+ } catch (error) {
143
+ return markStep(work, step, refused(error) ? "failed" : "unknown");
144
+ }
145
+ if (!response) return markStep(work, step, falseStatus(client, signal));
146
+ const info = (uid?: number): NonNullable<MutationItem["destination"]> => ({
147
+ mailbox: response.destination || destination,
148
+ ...(response.uidValidity === undefined ? {} : { uidValidity: response.uidValidity.toString() }),
149
+ ...(uid === undefined ? {} : { uid }),
150
+ });
151
+ const targets = new Map(work.map(w => [w.uid, response.uidMap?.get(w.uid)]));
152
+ const unresolved = work.filter(w => targets.get(w.uid) === undefined).map(w => w.uid);
153
+ let present: Set<number> | undefined;
154
+ if (unresolved.length > 0 && !signal?.aborted && connected(client)) {
155
+ try { present = await fetchUids(client, unresolved); } catch { present = undefined; }
156
+ }
157
+ for (const w of work) {
158
+ const target = targets.get(w.uid);
159
+ if (target !== undefined) {
160
+ w.item.steps[step]!.status = "success";
161
+ w.item.destination = info(target);
162
+ } else if (!present) {
163
+ w.item.steps[step]!.status = "unknown";
164
+ } else if (present.has(w.uid)) {
165
+ w.item.steps[step]!.status = "failed";
166
+ } else {
167
+ w.item.steps[step]!.status = "success";
168
+ w.item.destination = info();
169
+ }
170
+ }
171
+ }
172
+ /** 一次批量 UID EXPUNGE,再用一次 FETCH 核对:已不在=成功,仍在=failed。 */
173
+ async function purgeBatch(client: ImapFlow, signal: AbortSignal | undefined, uids: number[], work: Work[], clear: () => void): Promise<void> {
174
+ clear();
175
+ try {
176
+ if (!(await client.messageDelete(uids, { uid: true }))) {
177
+ markStep(work, 0, falseStatus(client, signal));
178
+ return;
179
+ }
180
+ } catch (error) {
181
+ markStep(work, 0, refused(error) ? "failed" : "unknown");
182
+ return;
183
+ }
184
+ if (signal?.aborted || !connected(client)) {
185
+ markStep(work, 0, "unknown");
186
+ return;
187
+ }
188
+ let present: Set<number> | undefined;
189
+ try { present = await fetchUids(client, uids); } catch { present = undefined; }
190
+ for (const w of work)
191
+ w.item.steps[0]!.status = !present ? "unknown" : present.has(w.uid) ? "failed" : "success";
192
+ }
193
+
194
+ function finalize(work: Work[], halt: Halt): void {
195
+ for (const w of work) {
196
+ if (!w.present) continue;
197
+ const item = w.item;
198
+ const statuses = item.steps.map(step => step.status);
199
+ if (statuses.includes("unknown")) { item.status = "unknown"; item.message = SAFE.unknown; continue; }
200
+ if (!statuses.includes("failed")) { item.status = "success"; delete item.message; continue; }
201
+ item.status = "failed";
202
+ item.message = statuses.includes("success") ? SAFE.partial
203
+ : halt === "canceled" ? SAFE.canceled
204
+ : halt === "disconnected" ? SAFE.notStarted : SAFE.rejected;
205
+ }
206
+ }
207
+
208
+ function aggregate(items: MutationItem[]): MutationResult["status"] {
209
+ const statuses = items.flatMap(item => [item.status, ...item.steps.map(step => step.status)]);
210
+ const success = statuses.includes("success");
211
+ const failed = statuses.includes("failed");
212
+ const unknown = statuses.includes("unknown");
213
+ if (unknown) return success ? "partial" : "unknown";
214
+ return success && failed ? "partial" : failed ? "failed" : "success";
215
+ }
216
+
217
+ function canceled(batch: MessageBatch): MutationResult {
218
+ return {
219
+ status: "failed", account: batch.account, mailbox: batch.mailbox, uidValidity: batch.uidValidity,
220
+ items: batch.uids.map(uid => ({ uid, status: "failed", steps: [], message: SAFE.canceled })),
221
+ };
222
+ }
223
+
224
+ export async function mutateEmail(
225
+ action: MutationAction, input: MutationInput, config: EmailConfig,
226
+ sessions: ImapSessions, cache: EmailCache, signal?: AbortSignal,
227
+ ): Promise<MutationResult> {
228
+ const batch = input as MessageBatch;
229
+ // 空清单绝不发 UID 集合;入口 schema 有 minItems,这里是网络层兜底。
230
+ if (batch.uids.length === 0) throw new EmailError("NO_MESSAGES", "未指定要操作的邮件。");
231
+ const settings = config.imap[batch.account];
232
+ if (!settings) throw new EmailError("ACCOUNT_MISSING", "未配置指定的 IMAP 账户。");
233
+ // purge 只允许该账户配置的回收站,严格逐字符比较,不猜、不做大小写归一。
234
+ if (action === "purge" && batch.mailbox !== settings.trashMailbox)
235
+ throw new EmailError("PURGE_SOURCE_INVALID", "只能永久删除该账户回收站文件夹中的邮件。");
236
+ const { destination, changes } = planFor(action, input, settings);
237
+ if (signal?.aborted) return canceled(batch);
238
+
239
+ const work: Work[] = batch.uids.map(uid => ({ uid, present: false, item: { uid, status: "failed", steps: [] } }));
240
+ let wrote = false;
241
+ // 第一次真实写入前清空缓存;写入后的成功、失败或未知都不能再信旧状态。
242
+ const clear = (): void => {
243
+ if (wrote) return;
244
+ wrote = true;
245
+ cache.clear();
246
+ };
247
+ let halt: Halt = undefined;
248
+
249
+ try {
250
+ await sessions.run(batch.account, batch.mailbox, signal, async client => {
251
+ assertMailbox(client, batch);
252
+ // 能力只预检一次;不足时整批拒绝,不进入库的 COPY+EXPUNGE 降级路径。
253
+ if (destination && !supports(client, "MOVE"))
254
+ throw new EmailError("MOVE_UNSUPPORTED", "服务器不支持原生移动命令,已取消操作,未修改邮件。");
255
+ if (action === "purge" && !supports(client, "UIDPLUS"))
256
+ throw new EmailError("UID_EXPUNGE_UNSUPPORTED", "服务器不支持按 UID 永久删除,已取消操作,未修改邮件。");
257
+ if (destination) await requireDestination(client, destination);
258
+
259
+ // 一次批量 FETCH 同时确认存在性;缺失 UID 不进入任何写命令。
260
+ const rows = await fetchAll(client, batch.uids, true);
261
+ const existing = new Set(rows.map(row => row.uid));
262
+ for (const w of work) if (!existing.has(w.uid)) w.item.message = SAFE.missing;
263
+ const active = work.filter(w => existing.has(w.uid));
264
+ if (active.length === 0) return;
265
+ for (const w of active) {
266
+ w.present = true;
267
+ for (const change of changes) w.item.steps.push({ action: change.action, status: "failed" });
268
+ if (action === "purge") w.item.steps.push({ action: "purge", status: "failed" });
269
+ else if (destination) w.item.steps.push({ action: "move", status: "failed" });
270
+ }
271
+ const uids = active.map(w => w.uid);
272
+
273
+ if (signal?.aborted || !connected(client)) {
274
+ halt = signal?.aborted ? "canceled" : "disconnected";
275
+ return;
276
+ }
277
+ if (action === "purge") {
278
+ await purgeBatch(client, signal, uids, active, clear);
279
+ return;
280
+ }
281
+ if (changes.length > 0) {
282
+ const halted = await flagBatch(client, signal, uids, changes, active, clear);
283
+ if (halted) halt = signal?.aborted ? "canceled" : "disconnected";
284
+ if (action === "mark" || halted) return;
285
+ }
286
+ if (signal?.aborted || !connected(client)) {
287
+ halt = signal?.aborted ? "canceled" : "disconnected";
288
+ return;
289
+ }
290
+ if (destination) await moveBatch(client, signal, uids, destination, active, changes.length, clear);
291
+ });
292
+ } catch (error) {
293
+ // 写入开始前的失败直接拒绝;开始后保留逐项结果,不抹掉已完成的步骤。
294
+ if (!wrote) {
295
+ if (error instanceof EmailError) throw error;
296
+ if (signal?.aborted) throw new EmailError("ABORTED", SAFE.canceled);
297
+ throw new EmailError("MUTATION_FAILED", SAFE.startFailed);
298
+ }
299
+ }
300
+
301
+ finalize(work, halt);
302
+ const items = work.map(w => w.item);
303
+ return {
304
+ status: aggregate(items), account: batch.account, mailbox: batch.mailbox,
305
+ uidValidity: batch.uidValidity, items,
306
+ };
307
+ }
@@ -0,0 +1,68 @@
1
+ import type { FetchMessageObject, ImapFlow, MessageStructureObject, SearchObject } from "imapflow";
2
+ import { EmailError, type ListInput, type SearchInput } from "./types.ts";
3
+
4
+ export function summary(message: FetchMessageObject): Record<string, unknown> {
5
+ const envelope = message.envelope;
6
+ return {
7
+ uid: message.uid, subject: envelope?.subject, messageId: envelope?.messageId,
8
+ date: dateValue(envelope?.date), internalDate: dateValue(message.internalDate),
9
+ from: envelope?.from, to: envelope?.to, cc: envelope?.cc, replyTo: envelope?.replyTo,
10
+ flags: [...(message.flags ?? [])], size: message.size,
11
+ };
12
+ }
13
+
14
+ function dateValue(value: Date | string | undefined): string | undefined {
15
+ return value instanceof Date ? (Number.isNaN(value.getTime()) ? undefined : value.toISOString()) : value;
16
+ }
17
+
18
+ export function serverQuery(input: SearchInput): SearchObject {
19
+ const { headers, unread, ...fields } = input.query;
20
+ return { ...fields, ...(headers ? { header: headers } : {}), ...(unread === undefined ? {} : { seen: !unread }) };
21
+ }
22
+
23
+ /** 先取服务器 UID,再仅请求这一页的摘要;序号不能作为跨调用引用。 */
24
+ export async function queryPage(client: ImapFlow, input: ListInput, query: SearchObject): Promise<Record<string, unknown>> {
25
+ if (!client.mailbox) throw new EmailError("MAILBOX_MISSING", "未打开指定文件夹。");
26
+ const limit = input.limit ?? 50;
27
+ const found = await client.search(query, { uid: true });
28
+ if (!Array.isArray(found)) throw new EmailError("SEARCH_FAILED", "服务器未完成邮件查询,请稍后重试。");
29
+ const uids = [...new Set(found)]
30
+ .filter(uid => input.beforeUid === undefined || uid < input.beforeUid)
31
+ .sort((a, b) => b - a);
32
+ const page = uids.slice(0, limit);
33
+ const messages: FetchMessageObject[] = [];
34
+ if (page.length) {
35
+ for await (const message of client.fetch(page, { uid: true, envelope: true, flags: true, size: true, internalDate: true }, { uid: true })) {
36
+ if (page.includes(message.uid)) messages.push(message);
37
+ }
38
+ }
39
+ messages.sort((a, b) => b.uid - a.uid);
40
+ return {
41
+ account: input.account, mailbox: input.mailbox ?? "INBOX", uidValidity: client.mailbox.uidValidity.toString(),
42
+ messages: messages.map(summary), nextBeforeUid: uids.length > limit ? page.at(-1) : null,
43
+ };
44
+ }
45
+
46
+ export interface MimePart {
47
+ part: string; name?: string; type: string; size?: number; attachment: boolean;
48
+ charset?: string; disposition?: string; format?: string;
49
+ }
50
+
51
+ /** 附件内嵌邮件不作为外层正文;单节点正文的标准下载编号为 1。 */
52
+ export function mimeParts(root: MessageStructureObject | undefined): MimePart[] {
53
+ const result: MimePart[] = [];
54
+ function visit(node: MessageStructureObject, inheritedAttachment = false, isRoot = false): void {
55
+ const name = node.dispositionParameters?.filename ?? node.parameters?.name;
56
+ const type = node.type.toLowerCase().trim();
57
+ const disposition = node.disposition?.toLowerCase().trim();
58
+ const attachment = inheritedAttachment || disposition === "attachment" || !!name ||
59
+ (!type.startsWith("multipart/") && !["text/plain", "text/html"].includes(type));
60
+ const part = node.part || (isRoot && !node.childNodes?.length ? "1" : undefined);
61
+ if (part && /^\d+(?:\.\d+)*$/.test(part)) result.push({ part, name, type, size: node.size, attachment,
62
+ charset: node.parameters?.charset?.toLowerCase().trim(), disposition,
63
+ format: node.parameters?.format?.toLowerCase().trim() });
64
+ for (const child of node.childNodes ?? []) visit(child, attachment);
65
+ }
66
+ if (root) visit(root, false, true);
67
+ return result;
68
+ }
@@ -0,0 +1,150 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { open, unlink } from "node:fs/promises";
3
+ import { Transform } from "node:stream";
4
+ import { pipeline } from "node:stream/promises";
5
+ import { TextDecoder } from "node:util";
6
+ import { EmailCache, EMAIL_CACHE_MAX_ENTRY_BYTES } from "./cache.ts";
7
+ import { readMessageBody } from "./body.ts";
8
+ import type { ImapSessions } from "./imap-session.ts";
9
+ import { assertMailbox, messageCacheKey, requireMessage } from "./message.ts";
10
+ import { mimeParts, queryPage, serverQuery, summary } from "./query.ts";
11
+ import { EmailError, type AttachmentInput, type ListInput, type MessageRef, type ReadInput, type SearchInput, type ThreadHeaders } from "./types.ts";
12
+
13
+ const HEADER_BUDGET = 1024 * 1024;
14
+
15
+ function validMessageId(value: string | undefined): value is string {
16
+ return !!value && /^<[^<>\s@]+@[^<>\s@]+>$/.test(value) && /^[\x21-\x7e]+$/.test(value);
17
+ }
18
+
19
+ function missingPart(): EmailError { return new EmailError("PART_MISSING", "指定 MIME 部分不存在,请重新读取邮件结构。"); }
20
+ function identity(ref: MessageRef): Record<string, unknown> {
21
+ return { account: ref.account, mailbox: ref.mailbox, uidValidity: ref.uidValidity, uid: ref.uid };
22
+ }
23
+
24
+ export class EmailReader {
25
+ constructor(private readonly sessions: ImapSessions, private readonly cache: EmailCache) {}
26
+
27
+ mailboxes(account: string, signal?: AbortSignal): Promise<Record<string, unknown>> {
28
+ return this.sessions.run(account, undefined, signal, async client => ({
29
+ account, mailboxes: (await client.list()).map(box => ({
30
+ path: box.path, name: box.name, delimiter: box.delimiter,
31
+ flags: [...box.flags], specialUse: box.specialUse, listed: box.listed, subscribed: box.subscribed,
32
+ })),
33
+ }));
34
+ }
35
+
36
+ list(input: ListInput, signal?: AbortSignal): Promise<Record<string, unknown>> {
37
+ return this.sessions.run(input.account, input.mailbox ?? "INBOX", signal, client => queryPage(client, input, { all: true }));
38
+ }
39
+
40
+ search(input: SearchInput, signal?: AbortSignal): Promise<Record<string, unknown>> {
41
+ return this.sessions.run(input.account, input.mailbox ?? "INBOX", signal, client => queryPage(client, input, serverQuery(input)));
42
+ }
43
+
44
+ read(input: ReadInput, signal?: AbortSignal): Promise<Record<string, unknown>> {
45
+ return this.sessions.run(input.account, input.mailbox, signal, async client => {
46
+ assertMailbox(client, input);
47
+ const message = await requireMessage(client, input, { envelope: true, bodyStructure: true });
48
+ return { ...identity(input), ...summary(message),
49
+ attachments: mimeParts(message.bodyStructure).filter(part => part.attachment),
50
+ ...await readMessageBody(client, input, message.bodyStructure, this.cache, signal) };
51
+ });
52
+ }
53
+
54
+ headers(input: ReadInput, signal?: AbortSignal): Promise<Record<string, unknown>> {
55
+ return this.sessions.run(input.account, input.mailbox, signal, async client => {
56
+ assertMailbox(client, input);
57
+ const key = messageCacheKey(input, "headers");
58
+ if (input.refresh) this.cache.delete(key);
59
+ const hit = this.cache.get(key);
60
+ let raw = typeof hit === "string" ? hit : undefined;
61
+ if (raw === undefined) {
62
+ const message = await requireMessage(client, input, { headers: true });
63
+ if (!message.headers) throw new EmailError("HEADERS_MISSING", "服务器未返回邮件原始头部。");
64
+ if (message.headers.length > HEADER_BUDGET)
65
+ throw new EmailError("HEADERS_TOO_LARGE", "原始头部超过读取预算,未返回截断头部。");
66
+ try {
67
+ // ignoreBOM 保留原始 BOM;严格拒绝损坏字节,而非以替换字符声称完整。
68
+ raw = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(message.headers);
69
+ } catch {
70
+ throw new EmailError("HEADERS_ENCODING_UNSUPPORTED", "原始头部不是合法 UTF-8,无法无损返回,未输出损坏或截断内容。");
71
+ }
72
+ this.cache.set(key, raw, "content");
73
+ }
74
+ return { ...identity(input), headers: raw, complete: true, cacheHit: typeof hit === "string" };
75
+ });
76
+ }
77
+
78
+ attachment(input: AttachmentInput, signal?: AbortSignal): Promise<Record<string, unknown>> {
79
+ return this.sessions.run(input.account, input.mailbox, signal, async client => {
80
+ assertMailbox(client, input);
81
+ const key = messageCacheKey(input, `attachment:${input.part}`);
82
+ if (input.refresh) this.cache.delete(key);
83
+ const message = await requireMessage(client, input, { bodyStructure: true });
84
+ const part = mimeParts(message.bodyStructure).find(part => part.part === input.part);
85
+ if (!part) throw missingPart();
86
+ const textConversion = (!part.disposition || part.disposition === "inline") &&
87
+ ["text/plain", "text/html", "text/x-amp-html"].includes(part.type) &&
88
+ (part.format === "flowed" || (part.charset && !["ascii", "usascii", "utf8"].includes(part.charset.replace(/[^a-z0-9]+/g, ""))));
89
+ if (textConversion)
90
+ throw new EmailError("ATTACHMENT_TRANSFORM_UNSUPPORTED", "该文本 MIME 部分会被下载库转换字符集或 flowed 格式,首版暂不支持无损导出;未创建文件。");
91
+ const cached = this.cache.get(key);
92
+ // 先独占创建,只有成功创建后本次调用才拥有清理权限。
93
+ const file = await open(input.path, "wx", 0o600);
94
+ let complete = false;
95
+ try {
96
+ signal?.throwIfAborted();
97
+ let size = 0;
98
+ if (Buffer.isBuffer(cached)) {
99
+ await file.writeFile(cached, { signal });
100
+ size = cached.length;
101
+ } else {
102
+ const download = await client.download(String(input.uid), part.part, { uid: true });
103
+ if (!download.content) throw missingPart();
104
+ let chunks: Buffer[] | undefined = [];
105
+ const meter = new Transform({ transform(chunk: Buffer, _encoding, callback) {
106
+ size += chunk.length;
107
+ if (size > EMAIL_CACHE_MAX_ENTRY_BYTES) chunks = undefined;
108
+ else chunks?.push(Buffer.from(chunk));
109
+ callback(null, chunk);
110
+ } });
111
+ await pipeline(download.content, meter, file.createWriteStream(), { signal });
112
+ if (chunks) this.cache.set(key, Buffer.concat(chunks, size), "content");
113
+ }
114
+ signal?.throwIfAborted();
115
+ await file.close();
116
+ complete = true;
117
+ return { ...identity(input), path: input.path, part: part.part, name: part.name, type: part.type, size, cacheHit: Buffer.isBuffer(cached) };
118
+ } finally {
119
+ if (!complete) {
120
+ await file.close().catch(() => {});
121
+ await unlink(input.path).catch(() => {});
122
+ }
123
+ }
124
+ });
125
+ }
126
+
127
+ thread(ref: MessageRef, signal?: AbortSignal): Promise<ThreadHeaders> {
128
+ return this.sessions.run(ref.account, ref.mailbox, signal, async client => {
129
+ assertMailbox(client, ref);
130
+ const message = await requireMessage(client, ref, { envelope: true, headers: ["References"] });
131
+ const id = message.envelope?.messageId;
132
+ if (!validMessageId(id))
133
+ throw new EmailError("MESSAGE_ID_MISSING", "原邮件没有合法 Message-ID,无法安全关联回复。");
134
+ if ((message.headers?.length ?? 0) > HEADER_BUDGET)
135
+ throw new EmailError("HEADERS_TOO_LARGE", "线程引用头部超过读取预算。");
136
+ // 仅展开库已筛选出的 References 字段,不解析 MIME 或替换原始头部接口。
137
+ const unfolded = (message.headers?.toString("utf8") ?? "").replace(/\r?\n[ \t]+/g, " ");
138
+ const references: string[] = [];
139
+ for (const line of unfolded.split(/\r?\n/)) {
140
+ if (!/^references:/i.test(line)) continue;
141
+ for (const match of line.slice(line.indexOf(":") + 1).matchAll(/<[^<>\s@]+@[^<>\s@]+>/g)) {
142
+ if (validMessageId(match[0])) references.push(match[0]);
143
+ }
144
+ }
145
+ if (!references.length && validMessageId(message.envelope?.inReplyTo))
146
+ references.push(message.envelope.inReplyTo);
147
+ return { inReplyTo: id, references: [...new Set([...references, id])] };
148
+ });
149
+ }
150
+ }