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/notify.js ADDED
@@ -0,0 +1,328 @@
1
+ // lib/notify.js — 通知组装与投递(M3)。
2
+ //
3
+ // 关键语义:
4
+ // * 高分(≥ 阈值)立即推;低分合并成一条「日报」式摘要(不刷屏)
5
+ // * 静音时段只压低分,高分照推
6
+ // * **投递失败必须让调用方知道**(ok:false)→ sync 据此**不推进水位**,下轮重发
7
+ // (宁可重复提醒,不可漏提醒)
8
+ // * 投递通道由外部注入(deliver),本模块不依赖任何宿主服务,便于离线测试
9
+
10
+ import { scoreMessage } from "./importance.js";
11
+ import { summarizeMessage, dailyDigest, codeLine, codeOf } from "./digest.js";
12
+
13
+ /** 过滤器:{ skip: [], only: [] },命中判定用 from+subject+snippet 拼成的全文。 */
14
+ export function normalizeFilter(filter = {}) {
15
+ const arr = (v) => (Array.isArray(v) ? v.map((x) => String(x).toLowerCase()).filter(Boolean) : []);
16
+ return { skip: arr(filter.skip), only: arr(filter.only) };
17
+ }
18
+
19
+ const hayOf = (m) => `${m.from ?? ""}\n${m.subject ?? ""}\n${m.snippet ?? ""}`.toLowerCase();
20
+
21
+ export function pickItems(items = [], filter = {}) {
22
+ const f = normalizeFilter(filter);
23
+ return items.filter((it) => {
24
+ const hay = hayOf(it.row ?? it);
25
+ if (f.skip.some((p) => hay.includes(p))) return false;
26
+ if (f.only.length && !f.only.some((p) => hay.includes(p))) return false;
27
+ return true;
28
+ });
29
+ }
30
+
31
+ /** "23:00-08:00" 这类跨午夜区间;非法/空 → 永远不在静音。 */
32
+ export function inQuietHours(quietHours, ts = Date.now()) {
33
+ const m = /^\s*(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})\s*$/.exec(String(quietHours ?? ""));
34
+ if (!m) return false;
35
+ const cur = new Date(ts).getHours() * 60 + new Date(ts).getMinutes();
36
+ const start = Number(m[1]) * 60 + Number(m[2]);
37
+ const end = Number(m[3]) * 60 + Number(m[4]);
38
+ return start <= end ? (cur >= start && cur < end) : (cur >= start || cur < end);
39
+ }
40
+
41
+ const shortFrom = (from) => String(from ?? "").replace(/<[^>]*>/g, "").replace(/"/g, "").trim().slice(0, 28) || "未知发件人";
42
+
43
+ /** 组装通知文本。
44
+ * includeCodes(默认 true):是否在推送里显示验证码。有些人不希望验证码明文出现在
45
+ * IM 会话里(手机锁屏预览也会露出来),所以做成开关 —— 由 notify.includeCodes 控制。
46
+ * 注意:关掉只影响「显示」,不影响分级(含码的邮件仍然即时推,不会因此掉进日报)。 */
47
+ export function formatNotification({ account, immediate = [], batched = [], batchLimit = 5, includeCodes = true } = {}) {
48
+ const total = immediate.length + batched.length;
49
+ if (!total) return "";
50
+ const lines = [`📬 新邮件 ${total} 封 · ${account}`];
51
+ immediate.forEach((x, i) => {
52
+ const m = x.item.row ?? x.item;
53
+ lines.push(`${i + 1}. ${String(m.subject ?? "(无主题)").slice(0, 80)} — ${shortFrom(m.from)}`);
54
+ // 验证码单列一行、紧跟标题:2FA 邮件的正文摘要常被客套话占满,码藏在几百字之后。
55
+ // 用户 2026-11-26 反馈「推送里看不到验证码」,这里给最显眼的位置。
56
+ const code = includeCodes ? codeLine(m) : "";
57
+ if (code) lines.push(` ${code}`);
58
+ // 关掉开关时,正文摘要里可能还带着那串数字(2FA 邮件就是「code: 184408」)——
59
+ // 只隐掉 🔑 行不够,摘要里的同一串也要打码,否则开关等于没关。
60
+ let summary = summarizeMessage(m);
61
+ if (!includeCodes) {
62
+ const hit = codeOf(m);
63
+ if (hit?.code) summary = summary.split(String(hit.code)).join("••••");
64
+ }
65
+ lines.push(` ${x.score >= 60 ? "⚡" : "·"} ${summary}`);
66
+ if (x.tags?.length) lines.push(` 🏷 ${x.tags.join(" / ")}`);
67
+ });
68
+ if (batched.length) {
69
+ lines.push("———");
70
+ lines.push(`低优先 ${batched.length} 封:`);
71
+ lines.push(dailyDigest(batched, { limit: batchLimit, includeCodes }));
72
+ }
73
+ return lines.join("\n");
74
+ }
75
+
76
+ /** 自动发现投递目标(用户没手填 botId/targetId 时用)。
77
+ * 优先级:显式配置 → 名称像邮箱的候选 → 唯一候选;多个候选则报 ambiguous 交人决定。
78
+ * @param requireExisting 为 true 时,**即使 botId/targetId 都填了也要去 dsh-im 的真实列表里核对**
79
+ * (2026-10-16:有人把 Telegram bot token 填进 botId,而"填了就 configured"让状态显示成健康,
80
+ * 实际 dsh-im 里根本没有这个机器人 ⇒ 必须能识破)。
81
+ * @returns {ok, botId?, targetId?, source?, reason?, candidates?} */
82
+ export async function resolveImTarget(im, { botId = "", targetId = "", prefer = null, requireExisting = false } = {}) {
83
+ if (!im || typeof im.listBots !== "function") return { ok: false, reason: "no-service" };
84
+ if (botId && targetId && !requireExisting) return { ok: true, botId, targetId, source: "config" };
85
+
86
+ const bots = (await im.listBots().catch(() => [])) ?? [];
87
+ const cands = [];
88
+ for (const b of bots) {
89
+ const id = typeof b === "string" ? b : (b?.botId ?? b?.id);
90
+ if (!id || (botId && id !== botId)) continue;
91
+ let targets = [];
92
+ try { targets = (await im.listTargets(id)) ?? []; } catch { continue; }
93
+ for (const t of targets) {
94
+ const tid = t?.targetId ?? t?.id;
95
+ if (tid) cands.push({ botId: id, targetId: tid, name: t?.name ?? "", kind: t?.kind ?? "", botName: b?.name ?? "" });
96
+ }
97
+ }
98
+ if (!cands.length) {
99
+ // 填了 botId 却在列表里找不到 → 明确区分"这个 bot 不存在"和"dsh-im 里一个都没有"
100
+ if (botId) return { ok: false, reason: "bot-not-found", candidates: [] };
101
+ return { ok: false, reason: "no-targets" };
102
+ }
103
+
104
+ if (targetId) {
105
+ const hit = cands.find((c) => c.targetId === targetId);
106
+ if (hit) return { ok: true, ...hit, source: "config-target" };
107
+ // 允许只填 botId:此时按"该 bot 的唯一候选"收窄(但绝不把它当成 targetId 用)
108
+ if (botId) {
109
+ const sameBot = cands.filter((c) => c.botId === botId);
110
+ if (sameBot.length === 1) return { ok: true, ...sameBot[0], source: "config-bot-single" };
111
+ return { ok: false, reason: "target-not-found", candidates: sameBot.length ? sameBot : cands };
112
+ }
113
+ return { ok: false, reason: "target-not-found", candidates: cands };
114
+ }
115
+ const re = prefer ?? /mail|邮箱|郵箱|邮件|郵件|inbox|outlook|default|默认|默認/i;
116
+ const preferred = cands.filter((c) => re.test(`${c.targetId} ${c.name} ${c.kind}`));
117
+ if (preferred.length === 1) return { ok: true, ...preferred[0], source: "auto-preferred" };
118
+ if (cands.length === 1) return { ok: true, ...cands[0], source: "auto-single" };
119
+ return { ok: false, reason: "ambiguous", candidates: cands };
120
+ }
121
+
122
+ /** 日报文本(低优先邮件的每日汇总)。多账户时按账户分组(2026-10-23:双账户混排
123
+ * 会分不清哪封来自哪个邮箱);单账户保持原样,不加分组噪音。 */
124
+ export function buildDailyDigestText(items = [], { limit = 40 } = {}) {
125
+ if (!items.length) return "";
126
+ const day = new Date().toISOString().slice(0, 10);
127
+ const lines = [`📮 邮件日报 ${day} · 低优先 ${items.length} 封`];
128
+ const accountOf = (m) => m?.account ?? m?.row?.account ?? "";
129
+ const emit = (m) => lines.push(`· ${String(m.subject ?? m.row?.subject ?? "(无主题)").slice(0, 70)} — ${shortFrom(m.from_addr ?? m.from)}`);
130
+ const accounts = [...new Set(items.map(accountOf).filter(Boolean))];
131
+ if (accounts.length > 1) {
132
+ let remaining = limit;
133
+ for (const acc of accounts) {
134
+ if (remaining <= 0) break;
135
+ const accItems = items.filter((m) => accountOf(m) === acc);
136
+ const shown = accItems.slice(0, remaining);
137
+ remaining -= shown.length;
138
+ lines.push(`—— ${acc}(${accItems.length} 封)`);
139
+ shown.forEach(emit);
140
+ }
141
+ } else {
142
+ items.slice(0, limit).forEach(emit);
143
+ }
144
+ if (items.length > limit) lines.push(`…另有 ${items.length - limit} 封`);
145
+ return lines.join("\n");
146
+ }
147
+
148
+ export class Notifier {
149
+ constructor({
150
+ deliver = null, threshold = 60, batch = 5, filter = {}, quietHours = null,
151
+ rules = [], knownDomains = [], log = () => {}, now = Date.now,
152
+ queueBatched = null, record = null, channel = "auto",
153
+ filterUnnotified = null, markNotified = null, includeCodes = true,
154
+ } = {}) {
155
+ this.deliver = deliver; // 可空:没有 IM 通道时只留痕(浮动栏兜底)
156
+ // 通知方式(2026-10-15 用户诉求):字符串,**或**返回字符串的函数
157
+ // (让"卡片里改了通知方式"能立刻生效,不必重建 Notifier)。
158
+ this.channel = channel;
159
+ // ⚠️ 阈值 **0 是合法值**(=所有邮件都即时推):`Number(0) || 60` 会把它换成 60。
160
+ // 2026-10-16 真机第二次踩:配置层已修,但通知器自己还有一份同样的写法 ⇒
161
+ // 阈值改 0、状态也显示 0,score 10 的邮件仍被判"低优先"进日报。
162
+ this.threshold = Number.isFinite(Number(threshold)) ? Number(threshold) : 60;
163
+ this.batch = Math.max(1, Number(batch) || 5);
164
+ this.filter = normalizeFilter(filter);
165
+ this.quietHours = quietHours;
166
+ this.rules = rules;
167
+ this.knownDomains = knownDomains;
168
+ this.log = log;
169
+ this.now = now;
170
+ this.queueBatched = queueBatched; // 提供时:低优先进「日报缓冲」,不进本条消息
171
+ this.record = record; // 提供时:每条通知留痕(供输入框浮动栏展示)
172
+ // B3(2026-11-29):通知幂等。投递失败时水位不推进 ⇒ watcher 下一轮重抓同一批,
173
+ // 没有账本就会重复推送同一封邮件。两个钩子都由 index.js 接到 store。
174
+ this.filterUnnotified = filterUnnotified; // ({account,folder,uids}) => 已推过的 uid[]
175
+ this.markNotified = markNotified; // ({account,folder,uids,noticeId}) => n
176
+ // 验证码是否明文出现在推送里(2026-11-30 用户诉求):布尔,或返回布尔的函数,
177
+ // 这样卡片里开关一改,下一条推送就生效,不必重启。
178
+ this.includeCodes = includeCodes;
179
+ }
180
+
181
+ /** @returns {ok, total, filtered, immediate, batched, delivered, quiet, recorded, queued, text, error?}
182
+ * ok:false 表示**投递失败**,调用方不得推进水位。 */
183
+ async notify({ account, folder, items = [] } = {}) {
184
+ const uidOf = (it) => Number(it?.row?.uid ?? it?.uid);
185
+ // B3:先剔除「已经推过」的邮件(账本在 store 里,按 account/folder/uid 唯一)。
186
+ let incoming = items;
187
+ let skipped = 0;
188
+ if (typeof this.filterUnnotified === "function" && items.length) {
189
+ try {
190
+ const uids = items.map(uidOf).filter(Number.isFinite);
191
+ if (uids.length) {
192
+ const done = new Set((await this.filterUnnotified({ account, folder, uids })) ?? []);
193
+ if (done.size) {
194
+ incoming = items.filter((it) => !done.has(uidOf(it)));
195
+ skipped = items.length - incoming.length;
196
+ if (skipped) this.log("info", `[${account}/${folder}] ${skipped} 封已在通知账本里,跳过重复推送`);
197
+ }
198
+ }
199
+ } catch (e) {
200
+ this.log("warn", `[${account}/${folder}] 通知账本查询失败(按未推送处理): ${e?.message ?? e}`);
201
+ }
202
+ }
203
+ const total = incoming.length;
204
+ const kept = pickItems(incoming, this.filter);
205
+ const filtered = total - kept.length;
206
+
207
+ const scored = kept.map((it) => ({ item: it, ...scoreMessage(it.row ?? it, { rules: this.rules, knownDomains: this.knownDomains }) }));
208
+ // 有验证码的邮件**永远**立即推:哪怕用户把阈值调高了、哪怕它长得像营销邮件。
209
+ // 验证码十分钟就失效,进日报等于没推(2026-11-26 用户诉求)。
210
+ const hasCode = (x) => Boolean(codeLine(x.item.row ?? x.item));
211
+ const immediate = scored.filter((x) => x.score >= this.threshold || hasCode(x));
212
+ let batched = scored.filter((x) => !(x.score >= this.threshold || hasCode(x)));
213
+
214
+ const base = { total, filtered, skipped, immediate: immediate.length, batched: batched.length, delivered: false, quiet: false, recorded: false, queued: 0 };
215
+ if (!kept.length) return { ...base, ok: true, text: "" };
216
+
217
+ // 这些 uid 一旦「真的让用户看见了」(IM 送达 / 仅留痕 / local / 进日报缓冲)就记账。
218
+ // 静音抑制与投递失败**不**记账 —— 前者是被规则挡下的,后者下一轮要重试。
219
+ const settle = async () => {
220
+ if (typeof this.markNotified !== "function") return;
221
+ const uids = kept.map(uidOf).filter(Number.isFinite);
222
+ if (!uids.length) return;
223
+ try { await this.markNotified({ account, folder, uids, noticeId: base.noticeId ?? null }); }
224
+ catch (e) { this.log("warn", `[${account}/${folder}] 通知账本记账失败(可能导致重复推送): ${e?.message ?? e}`); }
225
+ };
226
+
227
+ // 低优先:进日报缓冲(决策 B),本条消息里就不再逐条列
228
+ let queued = 0;
229
+ let queuedSubjects = [];
230
+ if (batched.length && this.queueBatched) {
231
+ const r = await this.queueBatched(batched.map((x) => ({ account, folder, uid: x.item.row?.uid ?? x.item.uid, score: x.score, row: x.item.row ?? x.item })));
232
+ if (r) { // 缓冲成功才从本条消息里移除
233
+ queued = batched.length;
234
+ queuedSubjects = batched.map((x) => x.item.row?.subject ?? "(无主题)");
235
+ batched = [];
236
+ }
237
+ }
238
+
239
+ if (immediate.length === 0 && batched.length === 0) {
240
+ // 全部进了日报缓冲:不算投递(但也没失败)。
241
+ // ⚠️ 2026-10-16 修复:这条分支过去**连留痕都不写** ⇒ 没有 IM 通道时,用户对"来了新邮件"
242
+ // 完全零感知(实测:抓到 4 封,notices=0)。现在补一条摘要留痕(浮动栏/状态可查)。
243
+ if (this.record && queued > 0) {
244
+ const body = `低优先 ${queued} 封已进日报缓冲(到点汇总一次)\n`
245
+ + queuedSubjects.map((s) => `· ${s}`).join("\n");
246
+ // 逐封结构化数据同上:日报缓冲里的邮件在面板里同样要能选中/追问
247
+ const qItems = batched.map((x) => {
248
+ const m = x.item?.row ?? x.item ?? {};
249
+ return { uid: Number(m.uid) || null, subject: String(m.subject ?? "").slice(0, 120), from: String(m.from ?? "").slice(0, 120) };
250
+ });
251
+ try {
252
+ await this.record({ kind: "digest-queued", account, folder, title: `新邮件 ${total} 封(低优先)`, body, count: queued, items: qItems });
253
+ base.recorded = true;
254
+ } catch (e) {
255
+ this.log("warn", `[${account}/${folder}] 日报入队留痕失败: ${e?.message ?? e}`);
256
+ }
257
+ this.log("info", `[${account}/${folder}] ${queued} 封低优先已进日报缓冲(已留痕,浮动栏可见)`);
258
+ }
259
+ await settle(); // 进日报缓冲 = 已被系统接收,记账防重复
260
+ return { ...base, ok: true, queued, text: "" };
261
+ }
262
+
263
+ if (immediate.length === 0 && inQuietHours(this.quietHours, this.now())) {
264
+ this.log("info", `[${account}/${folder}] 静音时段,${kept.length} 封低优先通知已抑制`);
265
+ return { ...base, ok: true, quiet: true, queued, text: "" };
266
+ }
267
+
268
+ const text = formatNotification({
269
+ account, immediate, batched, batchLimit: this.batch,
270
+ includeCodes: typeof this.includeCodes === "function" ? this.includeCodes() !== false : this.includeCodes !== false,
271
+ });
272
+
273
+ // 先留痕:即使 IM 通道挂了,浮动栏也能看到"有什么新邮件"
274
+ // (M6.7:记住 notice id,投递成功后由 markDelivered 回写 delivered_at)
275
+ // 2026-10-30:再加**逐封邮件结构化数据**(uid/subject/from)——
276
+ // 面板要把每封渲染成"可选中(插入坐标)/看得见 subject+发件人"的行,只有 body 文本做不到。
277
+ if (this.record && text) {
278
+ const mailItems = [...immediate, ...batched].map((x) => {
279
+ const m = x.item?.row ?? x.item ?? {};
280
+ return {
281
+ uid: Number(m.uid) || null,
282
+ subject: String(m.subject ?? "").slice(0, 120),
283
+ from: String(m.from ?? "").slice(0, 120),
284
+ };
285
+ });
286
+ try { base.noticeId = Number(await this.record({ kind: immediate.length ? "immediate" : "batch", account, folder, title: `新邮件 ${total} 封`, body: text, count: kept.length, items: mailItems })) || null; base.recorded = true; }
287
+ catch (e) { this.log("warn", `[${account}/${folder}] 通知留痕失败: ${e?.message ?? e}`); }
288
+ }
289
+
290
+ if (typeof this.deliver !== "function") {
291
+ // 没有投递通道:留痕即成功(不卡水位,浮动栏负责展示)
292
+ this.log("info", `[${account}/${folder}] 无 IM 投递通道,已仅留痕(${kept.length} 封,浮动栏可见)`);
293
+ await settle(); // 留痕即"已让用户看见"(浮动栏)
294
+ return { ...base, ok: true, text };
295
+ }
296
+
297
+ // 通知方式 = local:用户明确"不要 IM",只留痕(留痕在上面已经做过)
298
+ const channel = typeof this.channel === "function" ? this.channel() : this.channel;
299
+ if (channel === "local") {
300
+ this.log("info", `[${account}/${folder}] 通知方式=local:仅留痕(${kept.length} 封,浮动栏可见)`);
301
+ await settle(); // 用户明确只要留痕 → 也算已推过
302
+ return { ...base, ok: true, delivered: false, queued, text, localOnly: true };
303
+ }
304
+
305
+ try {
306
+ await this.deliver({ text, account, folder, immediate, batched });
307
+ // M6.7:投递成功 → 回写留痕的 delivered_at(以前投递成功只打日志,
308
+ // delivered_at 永远 null,状态里"待推通知"永远虚高 —— 2026-10-30 实锤)
309
+ if (base.noticeId != null && typeof this.markDelivered === "function") {
310
+ try { this.markDelivered(base.noticeId); }
311
+ catch (e) { this.log("warn", `[${account}/${folder}] 通知已送达标记失败(不影响功能): ${e?.message ?? e}`); }
312
+ }
313
+ if (this.record) this.log("info", `[${account}/${folder}] 已通知:高优先 ${immediate.length} 封,低优先 ${queued || batched.length} 封,过滤 ${filtered} 封`);
314
+ await settle(); // 真正送达才记账
315
+ return { ...base, ok: true, delivered: true, queued, text };
316
+ } catch (e) {
317
+ // "没有通道"不是投递失败:只留痕即可,**绝不能因此卡住水位**
318
+ if (e?.code === "NO_CHANNEL") {
319
+ this.log("info", `[${account}/${folder}] 没有 IM 投递通道:仅留痕(浮动栏可见)`);
320
+ await settle();
321
+ return { ...base, ok: true, delivered: false, queued, text, noChannel: true };
322
+ }
323
+ const error = String(e?.message ?? e);
324
+ this.log("error", `[${account}/${folder}] 通知投递失败(水位不推进,下轮重发): ${error}`);
325
+ return { ...base, ok: false, delivered: false, queued, text, error };
326
+ }
327
+ }
328
+ }
package/lib/oauth.js ADDED
@@ -0,0 +1,275 @@
1
+ // lib/oauth.js — OAuth2 设备码流 + 刷新 + token 存取。
2
+ //
3
+ // 协议参考(与本仓库 Python 版 outlook_agent/oauth.py 等价):
4
+ // authority: https://login.microsoftonline.com/consumers/oauth2/v2.0
5
+ // POST /devicecode {client_id, scope} → {device_code, user_code,
6
+ // verification_uri, verification_uri_complete, expires_in, interval}
7
+ // POST /token {client_id, grant_type: urn:ietf:params:oauth:grant-type:device_code,
8
+ // device_code} → 轮询至 token / authorization_pending / slow_down /
9
+ // expired_token / authorization_declined
10
+ // refresh: POST /token {client_id, grant_type: refresh_token, refresh_token, scope}
11
+ // — Microsoft 可能在响应里省略 refresh_token,此时保留旧值。
12
+ //
13
+ // token 文件: <tokenDir>/<tokenSlug(email)>.json,原子写(.tmp + rename),
14
+ // 字段: {email, client_id, access_token, refresh_token, expires_at(epoch), scope}。
15
+ // 与 Python 版共享同一目录时文件名/字段一致,可直接复用。
16
+
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import crypto from "node:crypto";
20
+ import { execFileSync } from "node:child_process";
21
+ import { tokenSlug } from "./config.js";
22
+
23
+ /** 测试注入点:默认走全局 fetch。只给离线测试用,生产路径不调用。 */
24
+ let fetchImpl = (...args) => globalThis.fetch(...args);
25
+ export function setFetchForTest(fn) {
26
+ fetchImpl = typeof fn === "function" ? fn : (...args) => globalThis.fetch(...args);
27
+ }
28
+
29
+ async function postForm(url, form) {
30
+ const res = await fetchImpl(url, {
31
+ method: "POST",
32
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
33
+ body: new URLSearchParams(form).toString(),
34
+ });
35
+ const text = await res.text();
36
+ let data;
37
+ try { data = JSON.parse(text); } catch { data = { raw: text }; }
38
+ return { status: res.status, data };
39
+ }
40
+
41
+ /** 开始设备码流。返回 { userCode, verificationUri, expires, interval, state }。
42
+ * state 由调用方(工具层)持久化到 pendingDir,供 complete 阶段使用。 */
43
+ export async function deviceCodeStart(account) {
44
+ const form = { client_id: account.clientId, scope: account.scopes.join(" ") };
45
+ const { status, data } = await postForm(account.authority + "/devicecode", form);
46
+ if (status !== 200) throw new Error(`devicecode ${status}: ${JSON.stringify(data)}`);
47
+ return {
48
+ userCode: data.user_code,
49
+ verificationUri: data.verification_uri_complete ?? data.verification_uri,
50
+ expires: data.expires_in,
51
+ interval: data.interval,
52
+ state: { deviceCode: data.device_code, account: account.email },
53
+ };
54
+ }
55
+
56
+ /** 轮询一次 /token(device_code)。成功时返回 token 载荷;未授权返回 pending 状态。
57
+ * 参数: { email, clientId, authority, scopes, deviceCode }(state 由工具层持久化)。 */
58
+ export async function deviceCodePoll(st) {
59
+ const form = {
60
+ client_id: st.clientId,
61
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
62
+ device_code: st.deviceCode,
63
+ scope: st.scopes.join(" "),
64
+ };
65
+ const { status, data } = await postForm(st.authority + "/token", form);
66
+ if (data.access_token) {
67
+ return {
68
+ ok: true,
69
+ access_token: data.access_token,
70
+ refresh_token: data.refresh_token,
71
+ expires_in: data.expires_in,
72
+ scope: data.scope,
73
+ };
74
+ }
75
+ if (status === 200) return { ok: false, reason: "pending" }; // 罕见但合法
76
+ switch (data.error) {
77
+ case "authorization_pending": return { ok: false, reason: "pending" };
78
+ case "slow_down": return { ok: false, reason: "slow_down" };
79
+ case "expired_token": return { ok: false, reason: "expired" };
80
+ case "authorization_declined": return { ok: false, reason: "declined" };
81
+ default: return { ok: false, reason: data.error ?? `http ${status}`, detail: data };
82
+ }
83
+ }
84
+
85
+ /** 用 refresh_token 换新 access_token。响应缺 refresh_token 时保留旧值。 */
86
+ export async function refreshAccessToken(account, refreshToken) {
87
+ const form = {
88
+ client_id: account.clientId,
89
+ grant_type: "refresh_token",
90
+ refresh_token: refreshToken,
91
+ scope: account.scopes.join(" "),
92
+ };
93
+ const { status, data } = await postForm(account.authority + "/token", form);
94
+ if (!data.access_token) {
95
+ throw new Error(`refresh 失败 ${status}: ${JSON.stringify(data)}`);
96
+ }
97
+ return {
98
+ access_token: data.access_token,
99
+ refresh_token: data.refresh_token ?? refreshToken,
100
+ expires_in: data.expires_in,
101
+ scope: data.scope ?? account.scopes.join(" "),
102
+ };
103
+ }
104
+
105
+ // ---- token 文件读写 ------------------------------------------------------
106
+
107
+ export function tokenPath(top, account) {
108
+ return path.join(top.tokenDir, tokenSlug(account.email));
109
+ }
110
+
111
+ export function readToken(top, account) {
112
+ const p = tokenPath(top, account);
113
+ if (!fs.existsSync(p)) return null;
114
+ try {
115
+ const t = JSON.parse(fs.readFileSync(p, "utf8"));
116
+ hardenFileMode(p); // 老库里可能是 0644,读到就顺手收紧
117
+ // 老装的 token 目录可能还是继承 ACL(实测 icacls 里一片 `(I)`),读到就顺手收紧一次
118
+ hardenWindowsAcl(path.dirname(p));
119
+ return t;
120
+ } catch { return null; }
121
+ }
122
+
123
+ // 权限收紧(2026-11-29 B2):token 含 refresh_token,等同邮箱密码。
124
+ // POSIX 用 0600/0700;Windows 的 chmod 基本无效,额外用 icacls 断继承 + 只授本人,
125
+ // 每目录只做一次;失败只 warn(不阻断发信/收信)。
126
+ const aclDone = new Set();
127
+ const modeDone = new Set();
128
+
129
+ // icacls 的实际执行函数(测试可注入,便于验证「收紧失败要回滚」这条安全网)
130
+ let aclRunner = (args) => execFileSync("icacls", args, { stdio: "ignore", windowsHide: true, timeout: 5000 });
131
+ export function setAclRunnerForTest(fn) {
132
+ aclRunner = typeof fn === "function"
133
+ ? fn
134
+ : (args) => execFileSync("icacls", args, { stdio: "ignore", windowsHide: true, timeout: 5000 });
135
+ }
136
+
137
+ function hardenDirMode(dir) {
138
+ if (process.platform === "win32") return;
139
+ if (modeDone.has(dir)) return;
140
+ try { fs.chmodSync(dir, 0o700); modeDone.add(dir); } catch { /* best effort */ }
141
+ }
142
+
143
+ function hardenFileMode(p) {
144
+ if (process.platform === "win32") return;
145
+ if (modeDone.has(p)) return;
146
+ try { fs.chmodSync(p, 0o600); modeDone.add(p); } catch { /* best effort */ }
147
+ }
148
+
149
+ export function hardenWindowsAcl(dir) {
150
+ if (process.platform !== "win32") return;
151
+ // 逃生阀:测试用 MAILBOX_SKIP_ACL=1;真机可用 MAILBOX_TOKEN_ACL=inherit 关掉收紧。
152
+ if (process.env.MAILBOX_SKIP_ACL === "1") return;
153
+ if (process.env.MAILBOX_TOKEN_ACL === "inherit") return;
154
+ if (aclDone.has(dir)) return;
155
+ aclDone.add(dir); // 无论成败只尝试一次:失败时不刷日志,也不每次写 token 都重跑
156
+ const user = process.env.USERNAME;
157
+ if (!user) return;
158
+ const who = process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${user}` : user;
159
+ const run = (args) => aclRunner(args);
160
+
161
+ // 默认只**补一条本人显式授权**(幂等),不动继承链。
162
+ // 2026-11-29 真机事故:`/inheritance:r` 会把**组** ACE 一起摘掉,而宿主进程恰恰是靠
163
+ // Dev\CodexSandboxUsers 这类组拿到权限的 —— 收紧之后自己反而读不到 token,
164
+ // 表现成「账户未授权」、账号被停泊 auth-error。断继承收益有限(目录本来就在用户
165
+ // profile 下),风险却是整插件不可用,所以改成显式 opt-in。
166
+ const strict = String(process.env.MAILBOX_TOKEN_ACL ?? "").toLowerCase() === "strict";
167
+ try {
168
+ run([dir, "/grant", `${who}:(OI)(CI)F`]);
169
+ if (!strict) return;
170
+ run([dir, "/inheritance:r"]);
171
+ verifyDirReadable(dir); // strict 下必须立刻验证:读不到就说明摘掉了自己的权限
172
+ } catch (e) {
173
+ try { run([dir, "/inheritance:e"]); } catch { /* 回滚也失败就只能靠环境变量关掉 */ }
174
+ console.warn(`[mailbox] token 目录 ACL 收紧已回滚(收紧后读不到,保持可用):${e?.code ?? e?.message ?? e}`);
175
+ }
176
+ }
177
+
178
+ /** 收紧之后必须还能读 —— 读不到说明把宿主自己的权限也摘掉了。 */
179
+ function verifyDirReadable(dir) {
180
+ fs.readdirSync(dir);
181
+ const one = fs.readdirSync(dir).find((f) => f.endsWith(".json"));
182
+ if (one) fs.readFileSync(path.join(dir, one), "utf8");
183
+ }
184
+
185
+ function ensurePrivateDir(dir) {
186
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
187
+ hardenDirMode(dir);
188
+ hardenWindowsAcl(dir);
189
+ }
190
+
191
+ export function writeToken(top, account, token) {
192
+ const p = tokenPath(top, account);
193
+ ensurePrivateDir(top.tokenDir);
194
+ const payload = JSON.stringify({
195
+ email: account.email,
196
+ client_id: account.clientId,
197
+ access_token: token.access_token,
198
+ refresh_token: token.refresh_token,
199
+ expires_at: Math.floor(Date.now() / 1000) + (token.expires_in ?? 3599),
200
+ scope: token.scope ?? account.scopes.join(" "),
201
+ }, null, 2);
202
+ // 2026-11-29 B1:临时名必须唯一。原来的固定 `<file>.tmp` 在并发刷新时
203
+ // 会互相覆盖/抢先 rename,另一个 rename 拿不到源文件直接 ENOENT。
204
+ const tmp = `${p}.${process.pid}.${crypto.randomUUID()}.tmp`;
205
+ try {
206
+ fs.writeFileSync(tmp, payload, { mode: 0o600 });
207
+ hardenFileMode(tmp);
208
+ fs.renameSync(tmp, p); // 原子替换(同盘)
209
+ hardenFileMode(p);
210
+ // 写后回读:磁盘上读不回自己刚写的 access_token 就说明被截断/被抢写
211
+ const back = JSON.parse(fs.readFileSync(p, "utf8"));
212
+ if (back?.access_token !== token.access_token) throw new Error("token 写入校验失败(回读不一致)");
213
+ } catch (e) {
214
+ try { fs.unlinkSync(tmp); } catch { /* 已被 rename 或本就不存在 */ }
215
+ throw e;
216
+ }
217
+ return p;
218
+ }
219
+
220
+ export function deleteToken(top, account) {
221
+ const p = tokenPath(top, account);
222
+ if (fs.existsSync(p)) fs.unlinkSync(p);
223
+ return p;
224
+ }
225
+
226
+ /** 取一个可用 access_token:本地未过期直接给;过期/将过期(120s 余量)则刷新。
227
+ * 刷新成功后用绝对 expires_at 写回(token record 的 expires_in 字段不可靠,
228
+ * 避免二次写文件时把余量当全量再累加)。
229
+ *
230
+ * 2026-11-29 B1:同一账户的并发刷新必须合并成一个在途请求 —— 否则 watcher
231
+ * 的多个文件夹 + 工具调用会同时拿着同一个 refresh_token 去换,既浪费配额,
232
+ * 又因为 refresh_token 轮换(RFC 6749 §6 / Microsoft)而互相作废,表现为
233
+ * 随机的 「A0002 NO: User is authenticated but not connected.」。 */
234
+ const inflight = new Map();
235
+
236
+ export function resetInflightForTest() {
237
+ inflight.clear();
238
+ }
239
+
240
+ export async function getAccessToken(top, account) {
241
+ const key = String(account?.email ?? account?.alias ?? "default");
242
+ const running = inflight.get(key);
243
+ if (running) return running;
244
+ const task = (async () => {
245
+ let t = readToken(top, account);
246
+ if (!t?.access_token) throw new Error(`账户 ${account.alias} 未授权;先调用 mailbox_auth action=device`);
247
+ const now = Math.floor(Date.now() / 1000);
248
+ if (t.expires_at < now + 120) {
249
+ const fresh = await refreshAccessToken(account, t.refresh_token);
250
+ t = { ...t, ...fresh, expires_at: now + (fresh.expires_in ?? 3599) };
251
+ writeToken(top, account, t);
252
+ }
253
+ return t.access_token;
254
+ })().finally(() => { if (inflight.get(key) === task) inflight.delete(key); });
255
+ inflight.set(key, task);
256
+ return task;
257
+ }
258
+
259
+ /** 状态一览:每个账户的 token 新鲜度。 */
260
+ export function tokenStatus(top) {
261
+ const now = Math.floor(Date.now() / 1000);
262
+ return top.accounts.map((a) => {
263
+ const t = readToken(top, a);
264
+ if (!t?.access_token) return { alias: a.alias, email: a.email, authorized: false };
265
+ const remain = Math.round(t.expires_at - now);
266
+ return {
267
+ alias: a.alias,
268
+ email: a.email,
269
+ authorized: true,
270
+ expired: remain <= 0,
271
+ remainSeconds: Math.max(0, remain),
272
+ hasRefresh: !!t.refresh_token,
273
+ };
274
+ });
275
+ }