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.
@@ -0,0 +1,395 @@
1
+ // lib/settings.js — 插件自己的「运行时设置层」(M3.3 / ROADMAP §2.3 阶段一)。
2
+ //
3
+ // 为什么要有这一层:此前 notify.botId/targetId、阈值、静音、日报时间全部写在
4
+ // cordis.patch.yml 里 → 用户每改一个字都要重启 DSH(这个会话就是卡在这里)。
5
+ //
6
+ // 学自 dsh-im 的做法:配置分两层:
7
+ // · cordis config(patch.yml)= 管理员/部署层默认值:accounts、tokenDir、host/port 等**结构性**字段
8
+ // · 本文件 = 用户运行时层:`<dataDir>/settings.json`,改完**下一轮(≤60s)生效,不用重启**
9
+ //
10
+ // 三条硬约束(全部来自 dsh-im 踩过的坑,它的 4.39.0 release notes 专门修过):
11
+ // 1. **逐字段校验 + 持久化** —— 它曾把 7 个设置字段存丢了,重载后全变 undefined。
12
+ // 这里每个字段都有校验器和 round-trip 测试(test/settings.test.mjs)。
13
+ // 2. **未知键绝不静默忽略** —— update() 走严格模式,写错字段名立刻报错并列出可用键;
14
+ // 否则用户以为设上了,其实什么都没发生。
15
+ // 3. **原子写** —— tmp + rename,绝不留下半个 JSON。
16
+ //
17
+ // 优先级:`settings.json` > cordis config > DEFAULTS(见 applySettings 返回的 sources)。
18
+
19
+ import fs from "node:fs";
20
+ import path from "node:path";
21
+ import { ARCHIVE_MODES, CHANNELS } from "./config.js";
22
+
23
+ const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
24
+
25
+ /** 可配置项清单 —— 单一事实来源,normalizeSettings / applySettings / diffLive / 文档都从这里派生。 */
26
+ export const SETTINGS_FIELDS = [
27
+ // ---- 通知(M3):这一批是用户最常改的,所以必须免重启 ----
28
+ { path: "notify.enabled", kind: "bool", live: true },
29
+ // 通知方式(2026-10-15 用户诉求):auto = 有 IM 通道就走 IM、否则只留痕(等价旧行为);
30
+ // im = 必须走 dsh-im(没配目标时**只留痕并提示**,绝不卡水位);
31
+ // local= 明确"不进 IM",只在 DSH 内留痕(浮动栏 M6.4 展示)。
32
+ { path: "notify.channel", kind: "enum", live: true, unset: "auto", options: CHANNELS },
33
+ { path: "notify.botId", kind: "str", live: true, unset: "" },
34
+ { path: "notify.targetId", kind: "str", live: true, unset: "" },
35
+ { path: "notify.importanceThreshold", kind: "int", live: true, min: 0, max: 100, unset: 60 },
36
+ { path: "notify.batch", kind: "int", live: true, min: 1, unset: 5 },
37
+ // 验证码是否明文出现在推送里(2026-11-30 用户诉求「加开关,默认给、可关掉」)。
38
+ // 只影响「是否显示」,不影响分级:含验证码的邮件照样即时推,只是不显示那行 🔑。
39
+ { path: "notify.includeCodes", kind: "bool", live: true, unset: true },
40
+ { path: "notify.quietHours", kind: "quiet", live: true, unset: null },
41
+ { path: "notify.dailyDigest.enabled", kind: "bool", live: true },
42
+ { path: "notify.dailyDigest.at", kind: "hhmm", live: true, unset: "08:00" },
43
+ { path: "notify.filter.skip", kind: "list", live: true, unset: [] },
44
+ { path: "notify.filter.only", kind: "list", live: true, unset: [] },
45
+ // ---- watcher / 归档:读的都是「每轮现取」的字段,所以也能免重启 ----
46
+ { path: "watcher.enabled", kind: "bool", live: true, cfg: "watcher.enabled" },
47
+ // ⚠️ top 上的键名与配置路径不一致:settings.json 里写 watcher.pollIntervalSeconds,
48
+ // resolveTop() 出来的是顶层 top.pollIntervalSeconds(历史原因)。所以必须显式给 top 路径,
49
+ // 否则改间隔会写进一个没人读的角落,用户以为设了其实没生效。
50
+ { path: "watcher.pollIntervalSeconds",kind: "int", live: true, min: 5, unset: 60, cfg: "pollIntervalSeconds", top: "pollIntervalSeconds" },
51
+ { path: "archive.mode", kind: "mode", live: true, unset: "metadata" },
52
+ { path: "archive.snippet", kind: "bool", live: true, unset: true },
53
+ { path: "archive.retentionDays", kind: "int", live: true, min: 0, unset: 0 },
54
+ { path: "archive.maxBytes", kind: "int", live: true, min: 0, unset: 0 },
55
+ // B7:元数据维护窗口(天)。0 = 不维护;默认 180 天。清的是「服务器上早就没有的邮件行
56
+ // + 陈年通知 + 它们的倒排词条」,不动 .eml(那是 retentionDays 的事)。
57
+ { path: "archive.maintenanceDays", kind: "int", live: true, min: 0, unset: 180 },
58
+ // 2026-11-30 需求「可配置参数搬进配置页」:正文截断与附件上限原来只能在 cordis.patch.yml
59
+ // 或工具参数里调,用户没法按自己习惯改。两者都在调用时从 top 现取,所以放运行层即可热生效。
60
+ { path: "mail.bodyLimit", kind: "int", live: true, min: 200, max: 20000, unset: 4000, top: "bodyLimit" },
61
+ { path: "mail.attachMaxBytes", kind: "int", live: true, min: 0, unset: 26214400, top: "attachMaxBytes" },
62
+ ];
63
+
64
+ /** 字段在 resolveTop() 结果里的实际路径(默认与配置路径相同)。 */
65
+ export function topPathOf(field) {
66
+ return field.top ?? field.path;
67
+ }
68
+
69
+ /** 不在清单里的字段 = 结构性配置,只能写 cordis.patch.yml,改完必须重启。 */
70
+ export const STRUCTURAL_FIELDS = [
71
+ "accounts", "dataDir", "tokenDir", "attachDir", "storeDir",
72
+ "accounts[].clientId/authority/scopes", "accounts[].imapHost/imapPort/smtpHost/smtpPort",
73
+ "maxBackoffSeconds", "maxMessagesPerCycle",
74
+ "archive.backfill", "archive.attachments",
75
+ "tags.rules", "knownDomains",
76
+ ];
77
+
78
+ export class SettingsError extends Error {
79
+ constructor(message) { super(message); this.name = "SettingsError"; this.code = "SETTINGS_INVALID"; }
80
+ }
81
+
82
+ // ---------------------------------------------------------------- 字段树
83
+ function buildTree(fields) {
84
+ const root = { children: new Map(), field: null };
85
+ for (const f of fields) {
86
+ let node = root;
87
+ for (const part of f.path.split(".")) {
88
+ if (!node.children.has(part)) node.children.set(part, { children: new Map(), field: null });
89
+ node = node.children.get(part);
90
+ }
91
+ node.field = f;
92
+ }
93
+ return root;
94
+ }
95
+ const TREE = buildTree(SETTINGS_FIELDS);
96
+
97
+ // ---------------------------------------------------------------- 单字段校验
98
+ const HHMM_RE = /^([01]?\d|2[0-3]):([0-5]\d)$/;
99
+ const QUIET_RE = /^\s*([01]?\d|2[0-3]):([0-5]\d)\s*-\s*([01]?\d|2[0-3]):([0-5]\d)\s*$/;
100
+
101
+ export function normalizeHhmm(value) {
102
+ const s = String(value ?? "").trim();
103
+ if (!HHMM_RE.test(s)) throw new SettingsError(`时间格式应为 HH:MM(如 "08:00"),收到 ${JSON.stringify(value)}`);
104
+ return s;
105
+ }
106
+
107
+ function normalizeLeaf(field, value, at) {
108
+ switch (field.kind) {
109
+ case "bool":
110
+ if (typeof value !== "boolean") throw new SettingsError(`${at} 应为 true/false,收到 ${typeof value}`);
111
+ return value;
112
+ case "str": {
113
+ if (typeof value !== "string") throw new SettingsError(`${at} 应为字符串,收到 ${typeof value}`);
114
+ const s = value.trim();
115
+ return s;
116
+ }
117
+ case "int": {
118
+ const n = Number(value);
119
+ if (!Number.isFinite(n) || !Number.isInteger(n)) throw new SettingsError(`${at} 应为整数,收到 ${JSON.stringify(value)}`);
120
+ if (field.min !== undefined && n < field.min) throw new SettingsError(`${at} 不能小于 ${field.min}(收到 ${n})`);
121
+ if (field.max !== undefined && n > field.max) throw new SettingsError(`${at} 不能大于 ${field.max}(收到 ${n})`);
122
+ return n;
123
+ }
124
+ case "list": {
125
+ if (!Array.isArray(value)) throw new SettingsError(`${at} 应为字符串数组`);
126
+ const out = [];
127
+ for (const x of value) {
128
+ if (typeof x !== "string") throw new SettingsError(`${at} 数组元素应为字符串`);
129
+ const s = x.trim();
130
+ if (s && !out.includes(s)) out.push(s);
131
+ }
132
+ return out;
133
+ }
134
+ case "quiet": {
135
+ if (value === null || value === "") return null;
136
+ if (typeof value !== "string" || !QUIET_RE.test(value)) {
137
+ throw new SettingsError(`${at} 应为 "HH:MM-HH:MM"(如 "23:00-08:00")或 null,收到 ${JSON.stringify(value)}`);
138
+ }
139
+ return value.trim();
140
+ }
141
+ case "hhmm":
142
+ return normalizeHhmm(value);
143
+ case "mode": {
144
+ const s = String(value ?? "").toLowerCase();
145
+ if (!ARCHIVE_MODES.includes(s)) throw new SettingsError(`${at} 只能是 ${ARCHIVE_MODES.join(" / ")},收到 ${JSON.stringify(value)}`);
146
+ return s;
147
+ }
148
+ case "enum": {
149
+ const s = String(value ?? "");
150
+ const options = field.options ?? [];
151
+ if (!options.includes(s)) throw new SettingsError(`${at} 只能是 ${options.join(" / ")},收到 ${JSON.stringify(value)}`);
152
+ return s;
153
+ }
154
+ default:
155
+ throw new SettingsError(`${at} 有未知的校验类型 "${field.kind}"`);
156
+ }
157
+ }
158
+
159
+ /** 递归校验;lenient=true 时**跳过**未知键与不合法值(用于读盘,容忍手滑写错的字段),
160
+ * false 时一律报错(用于写入,绝不静默丢字段)。 */
161
+ function walk(node, input, at, out, lenient) {
162
+ if (!isPlainObject(input)) throw new SettingsError(`${at || "(root)"} 应为对象`);
163
+ for (const key of Object.keys(input)) {
164
+ const child = node.children.get(key);
165
+ const keyAt = at ? `${at}.${key}` : key;
166
+ if (!child) {
167
+ if (lenient) continue;
168
+ const known = [...node.children.keys()].join(", ");
169
+ throw new SettingsError(`${keyAt} 不是可配置项(可用:${known || "无"})`);
170
+ }
171
+ const v = input[key];
172
+ if (child.field) {
173
+ if (v === undefined) continue;
174
+ let norm;
175
+ try { norm = normalizeLeaf(child.field, v, keyAt); }
176
+ catch (e) {
177
+ if (lenient) continue; // 读盘时坏值只丢这一项,别让整份设置失效
178
+ throw e;
179
+ }
180
+ out[key] = norm;
181
+ } else {
182
+ if (!isPlainObject(out[key])) out[key] = {};
183
+ walk(child, v, keyAt, out[key], lenient);
184
+ if (!Object.keys(out[key]).length) delete out[key];
185
+ }
186
+ }
187
+ return out;
188
+ }
189
+
190
+ /** 把「扁平点号键」的补丁摊成嵌套对象。
191
+ * `{"notify.botId":"x"}` 与 `{"notify":{"botId":"x"}}` 都接受 ——
192
+ * 后者是规范写法,前者是给 LLM/命令行少打几个字符的便利形态。
193
+ * 两者混用时以规范写法为先(点号键不会覆盖已显式声明的分支)。 */
194
+ export function expandPatch(patch = {}) {
195
+ const out = {};
196
+ for (const key of Object.keys(patch ?? {})) {
197
+ if (!key.includes(".")) {
198
+ if (isPlainObject(patch[key])) out[key] = expandPatch(patch[key]);
199
+ else out[key] = patch[key];
200
+ continue;
201
+ }
202
+ const parts = key.split(".");
203
+ let cur = out;
204
+ for (const p of parts.slice(0, -1)) {
205
+ if (!isPlainObject(cur[p])) cur[p] = {};
206
+ cur = cur[p];
207
+ }
208
+ cur[parts[parts.length - 1]] = patch[key];
209
+ }
210
+ return out;
211
+ }
212
+
213
+ /** 只做校验与形状规整;**不读盘不写盘**。
214
+ * @returns {{ok:true,value:object}|{ok:false,error:string}} */
215
+ export function normalizeSettings(raw = {}, { lenient = false, expand = false } = {}) {
216
+ try {
217
+ const input = expand ? expandPatch(raw) : raw;
218
+ const value = walk(TREE, input ?? {}, "", {}, lenient);
219
+ // 清掉空分支,保证「只设置了一个字段」不会凭空多出空对象
220
+ return { ok: true, value };
221
+ } catch (e) {
222
+ return { ok: false, error: String(e?.message ?? e) };
223
+ }
224
+ }
225
+
226
+ function mergeDeep(dst, src) {
227
+ for (const k of Object.keys(src)) {
228
+ const v = src[k];
229
+ if (isPlainObject(v)) { if (!isPlainObject(dst[k])) dst[k] = {}; mergeDeep(dst[k], v); }
230
+ else dst[k] = v;
231
+ }
232
+ return dst;
233
+ }
234
+
235
+ // ---------------------------------------------------------------- 存取
236
+ export class SettingsStore {
237
+ /** @param file `<dataDir>/settings.json` */
238
+ constructor(file, { now = () => Date.now() } = {}) {
239
+ this.file = String(file ?? "");
240
+ this.value = {};
241
+ this.rev = 0; // 每次成功写入 +1;调用方据此判断缓存是否失效
242
+ this.loaded = false;
243
+ this.lastError = null;
244
+ this.now = now;
245
+ /** M6.1:非空 = 本文件已一次性迁移进宿主配置页(见 markImported)。 */
246
+ this.importedTo = null;
247
+ }
248
+
249
+ /** M6.1:settings.json 已迁移进宿主配置页。
250
+ * ① **立刻清空内存层** —— 否则本进程内旧文件仍压住宿主同名字段,
251
+ * "迁移成功但值还是旧的"(真机会表现成:配置页改了,工具 status 不变);
252
+ * ② 之后**拒绝再写这个文件** —— 迁移后真相在宿主,再写私有文件就是重新制造第二份真相。 */
253
+ markImported(renamedTo = null) {
254
+ this.value = {};
255
+ this.importedTo = renamedTo ?? this.file;
256
+ this.rev += 1;
257
+ return this;
258
+ }
259
+
260
+ /** 迁移后禁用私有写入(调用方会回落到宿主 / 明确报错,而不是静默分叉)。 */
261
+ importedError() {
262
+ return new SettingsError(
263
+ `settings.json 已迁移到宿主配置页(${this.importedTo ?? this.file});请用宿主配置页或 mailbox_notify 修改`
264
+ );
265
+ }
266
+
267
+ /** 读盘。文件不存在 / 损坏 / 含未知键 → 都当作空设置(绝不让插件起不来)。 */
268
+ load() {
269
+ this.loaded = true;
270
+ this.lastError = null;
271
+ let text = null;
272
+ try { text = fs.readFileSync(this.file, "utf8"); }
273
+ catch { return this.value; } // 没有文件:首次运行
274
+ let parsed = null;
275
+ try { parsed = JSON.parse(text); } catch (e) { this.lastError = `settings.json 解析失败(已忽略): ${e?.message ?? e}`; return this.value; }
276
+ const r = normalizeSettings(parsed, { lenient: true });
277
+ if (!r.ok) { this.lastError = `settings.json 含非法字段(已忽略): ${r.error}`; return this.value; }
278
+ this.value = r.value;
279
+ return this.value;
280
+ }
281
+
282
+ get() { return this.value; }
283
+
284
+ /** 合并写入。严格校验:写错字段名/类型立刻失败并说明,绝不静默丢字段。
285
+ * 落盘失败(只读目录、磁盘满、EACCES)一律转成 `{ok:false,error}` ——
286
+ * 调用方(persistSettings)只判断 r.ok,抛出去会变成"配置页保存时崩一片"。 */
287
+ update(patch = {}) {
288
+ if (this.importedTo) return { ok: false, error: this.importedError().message };
289
+ const r = normalizeSettings(patch, { lenient: false, expand: true });
290
+ if (!r.ok) return { ok: false, error: r.error };
291
+ if (!Object.keys(r.value).length) return { ok: false, error: "没有提供任何可配置项" };
292
+ const next = mergeDeep(mergeDeep({}, this.value), r.value);
293
+ try {
294
+ this.write(next);
295
+ } catch (e) {
296
+ return { ok: false, error: String(e?.message ?? e) };
297
+ }
298
+ this.value = next;
299
+ this.rev += 1;
300
+ return { ok: true, value: this.value, rev: this.rev, file: this.file };
301
+ }
302
+
303
+ /** 清空(回到完全由 cordis config 决定)。 */
304
+ reset() {
305
+ if (this.importedTo) return { ok: false, error: this.importedError().message };
306
+ const before = JSON.stringify(this.value);
307
+ try {
308
+ this.write({});
309
+ } catch (e) {
310
+ return { ok: false, error: String(e?.message ?? e) };
311
+ }
312
+ this.value = {};
313
+ this.rev += 1;
314
+ return { ok: true, changed: before !== "{}", rev: this.rev, file: this.file };
315
+ }
316
+
317
+ /** 原子写:tmp + rename。失败抛错(调用方决定怎么提示)。 */
318
+ write(value) {
319
+ const tmp = `${this.file}.tmp`;
320
+ try {
321
+ fs.mkdirSync(path.dirname(this.file), { recursive: true });
322
+ fs.writeFileSync(tmp, `${JSON.stringify({ version: 1, ...value }, null, 2)}\n`, { mode: 0o600 });
323
+ fs.renameSync(tmp, this.file);
324
+ } catch (e) {
325
+ try { fs.rmSync(tmp, { force: true }); } catch { /* 已丢 */ }
326
+ throw new SettingsError(`写入 ${this.file} 失败: ${e?.message ?? e}`);
327
+ }
328
+ }
329
+ }
330
+
331
+ // ---------------------------------------------------------------- 分层叠加
332
+ function readPath(obj, dotted) {
333
+ let cur = obj;
334
+ for (const part of dotted.split(".")) {
335
+ if (!isPlainObject(cur)) return undefined;
336
+ cur = cur[part];
337
+ }
338
+ return cur;
339
+ }
340
+
341
+ /** 浅拷贝 top,只替换会被叠加的子树 —— 绝不在原对象上改(调用方还要拿旧值做 diff)。 */
342
+ function cloneTop(top) {
343
+ const out = { ...top };
344
+ out.watcher = { ...top.watcher };
345
+ out.archive = { ...top.archive };
346
+ out.notify = { ...top.notify, dailyDigest: { ...top.notify.dailyDigest }, filter: { ...top.notify.filter } };
347
+ return out;
348
+ }
349
+
350
+ /**
351
+ * 把 settings 叠加到 resolveTop() 的结果上,并报告**每个值是谁说了算**。
352
+ * @returns {{ top, sources: Object<string,"settings"|"config"|"default"> }}
353
+ */
354
+ export function applySettings(top, settings = {}, rawConfig = {}) {
355
+ const norm = normalizeSettings(settings, { lenient: true });
356
+ const out = cloneTop(top);
357
+ const sources = {};
358
+ for (const f of SETTINGS_FIELDS) {
359
+ const cfgPath = f.cfg ?? f.path;
360
+ const fromSettings = readPath(norm.ok ? norm.value : {}, f.path);
361
+ const fromConfig = readPath(rawConfig, cfgPath);
362
+ if (fromSettings !== undefined) {
363
+ writePath(out, topPathOf(f), fromSettings);
364
+ sources[f.path] = "settings";
365
+ } else if (fromConfig !== undefined) {
366
+ sources[f.path] = "config";
367
+ } else {
368
+ sources[f.path] = "default";
369
+ }
370
+ }
371
+ return { top: out, sources };
372
+ }
373
+
374
+ function writePath(obj, dotted, value) {
375
+ const parts = dotted.split(".");
376
+ let cur = obj;
377
+ for (const p of parts.slice(0, -1)) {
378
+ // 中间节点不存在就建:topPathOf() 可能指向新的分组(2026-11-30 加 mail 组时踩过)
379
+ if (!cur[p] || typeof cur[p] !== "object") cur[p] = {};
380
+ cur = cur[p];
381
+ }
382
+ cur[parts[parts.length - 1]] = value;
383
+ }
384
+
385
+ /** 哪些「可免重启生效」的字段变了。@returns {{path:string,value:any}[]}
386
+ * path 用**配置路径**(settings.json 里的写法),value 取叠加后的实际值。 */
387
+ export function diffLive(oldTop, newTop) {
388
+ const out = [];
389
+ for (const f of SETTINGS_FIELDS) {
390
+ if (!f.live) continue;
391
+ const a = readPath(oldTop, topPathOf(f)), b = readPath(newTop, topPathOf(f));
392
+ if (JSON.stringify(a) !== JSON.stringify(b)) out.push({ path: f.path, value: b });
393
+ }
394
+ return out;
395
+ }
package/lib/smtp.js ADDED
@@ -0,0 +1,153 @@
1
+ // lib/smtp.js — 纯 Node SMTP:587 端口 STARTTLS + AUTH XOAUTH2。
2
+ // 主服务器连上/认证失败时由调用方换备服务器重试。
3
+
4
+ import net from "node:net";
5
+ import tls from "node:tls";
6
+
7
+ const XOAUTH2_B64 = (user, token) =>
8
+ Buffer.from(`user=${user}\u0001auth=Bearer ${token}\u0001\u0001`).toString("base64");
9
+
10
+ /** STARTTLS 用的 TLS 连接器:默认 `tls.connect`,测试里换成「复用明文 socket」就能对
11
+ * 进程内**明文假服务器**跑完整的 EHLO/AUTH/MAIL/DATA 对话(R2,2026-11-29)。 */
12
+ let tlsConnector = (opts, cb) => tls.connect(opts, cb);
13
+ export function setTlsConnectorForTest(fn) {
14
+ tlsConnector = typeof fn === "function" ? fn : (opts, cb) => tls.connect(opts, cb);
15
+ }
16
+
17
+ /** 状态机:逐行缓冲,识别多行响应(码+连字符 → 继续;空格 → 终止)。 */
18
+ function createReader() {
19
+ let pending = []; // 未完成的多行响应 { code, lines }
20
+ let queue = []; // 已完成响应
21
+ let notify = null; // resolve 等待者
22
+
23
+ return {
24
+ feed(chunk) {
25
+ pending = pending.concat(String(chunk).split(/\r?\n/));
26
+ let acc = null;
27
+ while (pending.length) {
28
+ const line = pending.shift();
29
+ if (!line.trim()) continue;
30
+ const m = line.match(/^(\d{3})([ -])([\s\S]*)$/);
31
+ if (!m) continue;
32
+ const [ , code, sep, rest ] = m;
33
+ if (sep === "-") {
34
+ acc = acc ? acc : { code, lines: [] };
35
+ acc.lines.push(rest);
36
+ continue;
37
+ }
38
+ if (acc) {
39
+ acc.lines.push(rest);
40
+ queue.push(acc); acc = null;
41
+ } else {
42
+ queue.push({ code, lines: [rest] });
43
+ }
44
+ }
45
+ while (notify && queue.length) {
46
+ const r = notify; notify = null;
47
+ r(queue.shift());
48
+ }
49
+ },
50
+ next() {
51
+ if (queue.length) return Promise.resolve(queue.shift());
52
+ return new Promise((res) => { notify = res; });
53
+ },
54
+ };
55
+ }
56
+
57
+ class SmtpClient {
58
+ constructor(host, port = 587) {
59
+ this.host = host;
60
+ this.port = port;
61
+ this.sock = null;
62
+ this.reader = createReader();
63
+ }
64
+
65
+ connect() {
66
+ return new Promise((resolve, reject) => {
67
+ this.sock = net.connect({ host: this.host, port: this.port });
68
+ this.sock.setEncoding("utf8");
69
+ this.sock.setTimeout(30_000, () => this.sock.destroy(new Error("smtp socket timeout")));
70
+ this.sock.on("data", (d) => this.reader.feed(d));
71
+ this.sock.on("error", reject);
72
+ this.sock.on("connect", async () => {
73
+ try {
74
+ const greeting = await this.reader.next();
75
+ if (greeting.code !== "220") reject(new Error(`smtp greeting ${greeting.code}: ${greeting.lines[0]}`));
76
+ else resolve();
77
+ } catch (e) { reject(e); }
78
+ });
79
+ });
80
+ }
81
+
82
+ /** 发一条命令,等一个响应;期望码(百位)。 */
83
+ cmd(line, expectCode) {
84
+ this.sock.write(line + "\r\n");
85
+ return this.reader.next().then((resp) => {
86
+ if (expectCode && !resp.code.startsWith(expectCode)) {
87
+ throw new Error(`smtp ${resp.code} (expect ${expectCode}xx): ${resp.lines.join(" | ")}`);
88
+ }
89
+ return resp;
90
+ });
91
+ }
92
+
93
+ starttls() {
94
+ return new Promise((resolve, reject) => {
95
+ const plain = this.sock;
96
+ const secure = tlsConnector({ socket: plain, servername: this.host });
97
+ secure.setTimeout(30_000, () => secure.destroy(new Error("smtp tls timeout")));
98
+ secure.on("error", reject);
99
+ secure.on("secureConnect", () => {
100
+ this.sock = secure;
101
+ this.reader = createReader();
102
+ secure.setEncoding("utf8");
103
+ secure.on("data", (d) => this.reader.feed(d));
104
+ resolve();
105
+ });
106
+ });
107
+ }
108
+
109
+ close() {
110
+ try { this.sock?.end(); } catch {}
111
+ try { this.sock?.destroy(); } catch {}
112
+ }
113
+ }
114
+
115
+ /**
116
+ * 发一封。options: { host, port, user, token, to, cc, bcc, rawMime }
117
+ * 握手: EHLO → STARTTLS → EHLO → AUTH XOAUTH2(334 → base64 凭证 → 235)。
118
+ * DATA 段: CRLF 归一化 + 句点转义(行首 "."→"..")+ "\r\n.\r\n"。
119
+ * 返回 { server, accepted }。认证/连接失败时调用方换备服务器重试。
120
+ */
121
+ export async function sendMail({ user, token, host, port, to = [], cc = [], bcc = [], rawMime }) {
122
+ const rcpts = [...new Set([...to, ...cc, ...(bcc || [])])];
123
+ if (!rcpts.length) throw new Error("sendMail: 收件人为空(to/cc/bcc)");
124
+ const client = new SmtpClient(host, port);
125
+ try {
126
+ await client.connect();
127
+ await client.cmd("EHLO mail.local", "2");
128
+ await client.cmd("STARTTLS", "2");
129
+ await client.starttls();
130
+ await client.cmd("EHLO mail.local", "2");
131
+ // AUTH 的初始响应有两条合法路子:留空走 334 挑战(这里),或内联
132
+ // AUTH XOAUTH2 <base64>(SASL-IR)。**绝不能写成 "AUTH XOAUTH2 *"** ——
133
+ // "*" 是 SMTP 的「取消认证」记号,服务器会直接回
134
+ // 501 5.5.4 Authentication cancelled(实测踩过这个坑)。
135
+ await client.cmd("AUTH XOAUTH2", "3");
136
+ await client.cmd(XOAUTH2_B64(user, token), "2");
137
+ await client.cmd(`MAIL FROM:<${user}>`, "2");
138
+ for (const addr of rcpts) await client.cmd(`RCPT TO:<${addr}>`, "2");
139
+ await client.cmd("DATA", "3");
140
+ // 点填充(dot-stuffing)只对「行首」的 "." 生效(/^\./gm)。
141
+ // 之前写成 /(?<!\.)\./ 会把正文里所有句点都翻倍 —— "example.com" 变成
142
+ // "example..com",整封信内容损坏(URL、域名、小数全中招)。
143
+ await client.cmd(rawMime.replace(/\r?\n/g, "\r\n").replace(/^\./gm, "..") + "\r\n.\r\n", "2");
144
+ // QUIT 的响应不可信:实测 Exchange 在收下整封信(250)之后,会对 QUIT 回
145
+ // "500 5.3.3 Unrecognized command 'unknown'"。此时邮件**已经投递成功**,
146
+ // 绝不能因此报错 —— 否则调用方会换备用服务器重发,造成重复投递(实测重复了两封)。
147
+ try { await client.cmd("QUIT", "2"); } catch { /* 邮件已投递,忽略收尾错误 */ }
148
+ return { server: host, accepted: rcpts.length };
149
+ } catch (err) {
150
+ client.close();
151
+ throw err;
152
+ }
153
+ }