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/bridge.js ADDED
@@ -0,0 +1,940 @@
1
+ // lib/bridge.js — M6.3:回环(loopback)HTTP 桥。
2
+ //
3
+ // 为什么需要它:设置卡片走的是官方 apiproxy 的 settings.describe/mutate RPC,
4
+ // 但**页面里要显示运行时状态**(已经抓了多少、上次什么时候、有多少未读、有什么新邮件)
5
+ // 和**要触发动作**(立刻检查一次)时,官方 RPC 没有对应的服务面 —— 只能自己开两条路由。
6
+ //
7
+ // 信任模型(与 dsh-llm-proxy / opencode2dsh 的 ip-pool 桥一致,已在 DSH 0.2.0-rc.2 真机验证):
8
+ // ① socket 对端必须是字面回环地址(127.0.0.1 / ::1 / ::ffff:127.0.0.1);
9
+ // ② Host 头必须是**规范化**的回环权威(不接受 `localhost:19387.`、`127.0.0.1:0x50` 这类花活);
10
+ // ③ 浏览器同源(Origin 存在时必须与 Host 相同,sec-fetch-site 不能是 cross-site);
11
+ // ④ 一律 POST(避免被 <img>/<script> 之类的 GET 触达),JSON 体积上限 16KB。
12
+ // **任何一条不满足 → 403**,不给任何回显(不泄漏存在性)。
13
+ //
14
+ // 边界:这不是"认证"。它只挡 CSRF 与局域网访问;真正的信任来自"回环 socket"本身。
15
+ // 所以路由里**只**允许暴露运行状态与幂等的"立刻检查",不允许改配置、不允许读正文。
16
+ //
17
+ // 本文件零依赖(纯函数 + node:http 形状的对象),可离线测试。
18
+
19
+ /** 桥的路由前缀(与客户端 client.js 里的常量必须一致)。 */
20
+ export const MAILBOX_BRIDGE_PREFIX = "/api/mailbox";
21
+
22
+ /** JSON 请求体上限(触发一次检查的 body 只有几十字节,16KB 足够)。 */
23
+ export const MAX_JSON_BODY_BYTES = 16 * 1024;
24
+
25
+ /** 浮动栏默认/上限取几封"最近邮件"。 */
26
+ export const RECENT_DEFAULT = 5;
27
+ export const RECENT_MAX = 50;
28
+
29
+ // ------------------------------------------------------------------ 信任判定
30
+
31
+ /** socket 对端是否是字面回环地址。 */
32
+ export function isLoopbackAddress(address) {
33
+ return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
34
+ }
35
+
36
+ /** 主机名是否是字面回环权威(localhost / [::1] / 127.x.x.x)。 */
37
+ export function isLoopbackHostname(hostname) {
38
+ if (hostname === "localhost" || hostname === "[::1]") return true;
39
+ const parts = String(hostname).split(".");
40
+ return parts.length === 4
41
+ && parts[0] === "127"
42
+ && parts.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255);
43
+ }
44
+
45
+ /** 解析一个裸 Host 权威;非规范形态返回 undefined。 */
46
+ export function parseAuthority(authority) {
47
+ if (typeof authority !== "string" || authority.trim() !== authority || authority === "") return undefined;
48
+ const match = authority.startsWith("[")
49
+ ? /^\[[^\]]+\](?::([0-9]+))?$/.exec(authority)
50
+ : /^[^:@/?#\s]+(?::([0-9]+))?$/.exec(authority);
51
+ if (match === null) return undefined;
52
+ try {
53
+ const url = new URL("http://" + authority);
54
+ if (url.username !== "" || url.password !== "" || url.pathname !== "/" || url.search !== "" || url.hash !== "") return undefined;
55
+ const rawPort = match[1];
56
+ // "080" 这类前导零、超范围端口一律拒绝(消除同源判定的歧义面)
57
+ if (rawPort !== undefined && (String(Number(rawPort)) !== rawPort || Number(rawPort) > 65535)) return undefined;
58
+ return { url };
59
+ } catch { return undefined; }
60
+ }
61
+
62
+ /** 浏览器同源标记(回环主机之间一律视为同源)。 */
63
+ export function isSameOriginRequest(request, hostUrl) {
64
+ const headers = request?.headers ?? {};
65
+ if (headers["sec-fetch-site"] === "cross-site") return false;
66
+ const origin = headers.origin;
67
+ if (origin === undefined) return true; // 非浏览器(如我们自己的测试/CLI)
68
+ try { return new URL(String(origin)).host === hostUrl.host; } catch { return false; }
69
+ }
70
+
71
+ /** 热路径信任判定:回环 socket + 规范化 Host + 同源。全部满足才 true。 */
72
+ export function isTrustedBridgeRequest(request) {
73
+ if (!isLoopbackAddress(request?.socket?.remoteAddress)) return false;
74
+ const host = request?.headers?.host;
75
+ if (typeof host !== "string") return false;
76
+ const parsed = parseAuthority(host);
77
+ if (parsed === undefined) return false;
78
+ if (parsed.url.host.toLowerCase() !== host.toLowerCase()) return false; // 大小写/编码花活全部出局
79
+ if (!isSameOriginRequest(request, parsed.url)) return false;
80
+ return isLoopbackHostname(parsed.url.hostname);
81
+ }
82
+
83
+ /** 部署层账号集合(cordis.patch.yml 的 accounts)。取不到就当空集 —— 宁可多显示为
84
+ * runtime(可删),也不能因为取不到配置就把可删的账号误标成不可删。 */
85
+ function deployedSetOf(deps) {
86
+ try {
87
+ const s = deps.deployedEmails?.();
88
+ return s instanceof Set ? s : new Set(Array.isArray(s) ? s : []);
89
+ } catch { return new Set(); }
90
+ }
91
+
92
+ // ------------------------------------------------------------------ HTTP 管线
93
+
94
+ /** 写一个 JSON 响应。 */
95
+ export function writeJson(res, status, body) {
96
+ res.writeHead(status, {
97
+ "content-type": "application/json; charset=utf-8",
98
+ "referrer-policy": "no-referrer",
99
+ "cache-control": "no-store",
100
+ });
101
+ res.end(JSON.stringify(body));
102
+ }
103
+
104
+ /** 读 JSON 请求体;超限或解析失败 → undefined(调用方给 400)。 */
105
+ export async function readJsonBody(req, maxBytes = MAX_JSON_BODY_BYTES) {
106
+ const chunks = [];
107
+ let size = 0;
108
+ for await (const chunk of req) {
109
+ size += chunk.length;
110
+ if (size > maxBytes) return undefined;
111
+ chunks.push(Buffer.from(chunk));
112
+ }
113
+ try {
114
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
115
+ } catch {
116
+ return undefined;
117
+ }
118
+ }
119
+
120
+ // ------------------------------------------------------------------ 状态视图
121
+
122
+ const num = (v, d = 0) => (Number.isFinite(Number(v)) ? Number(v) : d);
123
+
124
+ /** 桥只认 `{ok:false, code, message}`:错误对象自带 code(如 no-such-attachment)就透传,否则用兜底码。 */
125
+ const apiMessage = (e) => String(e?.message ?? e);
126
+ const kindCode = (e, fallback) => (typeof e?.code === "string" && e.code ? e.code : fallback);
127
+
128
+ /**
129
+ * 组装浮动栏/卡片要的那一份状态。
130
+ * **纯函数**:所有活数据都由 deps 现取(绝不在闭包里缓存快照 —— 那样刷新按钮就失效了)。
131
+ *
132
+ * @param {object} deps
133
+ * now() → 毫秒时间戳
134
+ * top() → 生效的设置(notify/watcher/archive/pollIntervalSeconds…)
135
+ * watcher() → Watcher 实例或 null
136
+ * watcherState() → { running, locked, reason }
137
+ * store() → store 实例或 null
138
+ * imReady() → IM 通道是否就绪
139
+ * settingsTarget() → 'host' | 'file' | 'none'
140
+ * @param {object} [opts]
141
+ * recentLimit → 最近邮件条数(0 = 不取)
142
+ * account → 账户过滤(非空字符串时 recent 只含该账户;空/缺省 = 全局列表)
143
+ */
144
+ export function buildStatusView(deps, { recentLimit = RECENT_DEFAULT, account = "" } = {}) {
145
+ const now = num(deps.now?.() ?? Date.now(), 0);
146
+ const top = deps.top?.() ?? {};
147
+ const watcher = deps.watcher?.() ?? null;
148
+ const ws = deps.watcherState?.() ?? {};
149
+ const store = deps.store?.() ?? null;
150
+ const limit = Math.min(RECENT_MAX, Math.max(0, num(recentLimit, RECENT_DEFAULT)));
151
+ // 账户过滤(客户端"账号切换"用):只认字符串;去掉首尾空白后为空 ⇒ 等同于不过滤
152
+ const acct = typeof account === "string" ? account.trim() : "";
153
+ const warnings = [];
154
+
155
+ const view = {
156
+ at: now,
157
+ artifact: "mailbox",
158
+ watcher: {
159
+ enabled: top?.watcher?.enabled !== false,
160
+ running: ws.running === true,
161
+ locked: ws.locked !== false,
162
+ reason: ws.reason ?? null,
163
+ pollIntervalSeconds: num(top?.pollIntervalSeconds, 0),
164
+ folders: ws.folders ?? 0,
165
+ },
166
+ lastCheck: null,
167
+ counts: { messages: 0, unread: 0, notices: 0, noticesUnseen: 0, digestQueued: 0, tags: 0, facts: 0 },
168
+ folders: [],
169
+ accounts: [],
170
+ recent: [],
171
+ // 回显本次的账户过滤(客户端据此确认"现在看的是哪个账号");null = 全局列表
172
+ recentAccount: acct ? acct : null,
173
+ notify: {
174
+ enabled: top?.notify?.enabled !== false,
175
+ channel: top?.notify?.channel ?? "auto",
176
+ botId: top?.notify?.botId ?? "",
177
+ targetId: top?.notify?.targetId ?? "",
178
+ targetReady: deps.imReady?.() === true,
179
+ },
180
+ settingsTarget: deps.settingsTarget?.() ?? "none",
181
+ archiveMode: top?.archive?.mode ?? "metadata",
182
+ // 2026-11-30 需求「连接状态搬进配置页」:每个「账户/文件夹」的同步健康 + 上次成功 + 最近错误。
183
+ // 数据源是归档库的 sync_state(watcher 每轮写),配置卡据此显示"哪条链路正常/需要重新授权"。
184
+ health: [],
185
+ // 收发与内容的当前有效值(配置卡里显示"默认/已改"用;改值仍走运行层设置)
186
+ mail: {
187
+ bodyLimit: Number(top?.bodyLimit ?? 0),
188
+ attachMaxBytes: Number(top?.attachMaxBytes ?? 0),
189
+ },
190
+ // 只在部署层生效的开关,配置卡只读回显(write.enabled=工具注册期读,LLM=worker 快照)
191
+ readonly: {
192
+ writeEnabled: top?.write?.enabled === true,
193
+ llmSummary: top?.llm?.digest?.enabled === true,
194
+ llmSemantic: top?.llm?.semantic?.enabled === true,
195
+ updateSource: String(top?.update?.source ?? ""),
196
+ },
197
+ warnings,
198
+ };
199
+
200
+ // 多账户显示(2026-10-23):按账户聚合;配置里的账户**即使还没有归档邮件也要出现**(显示 0/0),
201
+ // 否则"新加了邮箱"这件事在浮动栏/面板里完全不可见。冷启动(store 未就绪)也带着这份骨架。
202
+ const accountRows = new Map();
203
+ for (const a of (Array.isArray(top?.accounts) ? top.accounts : [])) {
204
+ if (a?.email) accountRows.set(a.email, { account: a.email, alias: a.alias || a.email, messages: 0, unread: 0 });
205
+ }
206
+
207
+ // M6.7(2026-10-30):**服务器实时计数**。来源 = 最近一轮 watcher 的 runFolder 结果
208
+ // (open 后同连接 STATUS:MESSAGES/UNSEEN)。尤其 online 模式(不落库)下本地归档
209
+ // 永远停旧,这是唯一可信的数字源。有实时数的账户行直接覆盖(number+source:"live"),
210
+ // 归档聚合只给**没有**实时数的账户兜底。冷启动/首轮未跑时 live.at=null,浮动栏退回报归档数。
211
+ const liveByAccount = new Map();
212
+ const liveFolders = [];
213
+ const ltResults = Array.isArray(watcher?.lastTick?.results) ? watcher.lastTick.results : [];
214
+ for (const r of ltResults) {
215
+ if (!r || typeof r !== "object" || !r.live || !r.account) continue;
216
+ const entry = {
217
+ account: String(r.account),
218
+ folder: String(r.folder ?? ""),
219
+ total: num(r.live.total, 0),
220
+ unread: r.live.unread == null ? null : num(r.live.unread, 0),
221
+ at: num(r.live.at, 0),
222
+ };
223
+ liveFolders.push(entry);
224
+ const acc = liveByAccount.get(entry.account) ?? { account: entry.account, messages: 0, unread: 0, unreadKnown: true, at: 0 };
225
+ acc.messages += entry.total;
226
+ if (entry.unread == null) acc.unreadKnown = false;
227
+ else acc.unread += entry.unread;
228
+ acc.at = Math.max(acc.at, entry.at);
229
+ liveByAccount.set(entry.account, acc);
230
+ }
231
+ for (const live of liveByAccount.values()) {
232
+ const prev = accountRows.get(live.account);
233
+ // 分文件夹明细(2026-10-30 监控文件夹选项):给浮动栏画「INBOX 230/1 · Projects 78/18」用。
234
+ // 只列**本轮真实轮询到**的文件夹(配置里配了但本轮失败/未跑的不掺进来)。
235
+ const folders = liveFolders
236
+ .filter((f) => f.account === live.account)
237
+ .map((f) => ({ folder: f.folder, total: f.total, unread: f.unread, at: f.at }));
238
+ accountRows.set(live.account, {
239
+ account: live.account,
240
+ alias: prev?.alias || live.account,
241
+ messages: live.messages,
242
+ unread: live.unread,
243
+ source: "live",
244
+ at: live.at || null,
245
+ unreadKnown: live.unreadKnown !== false,
246
+ folders,
247
+ });
248
+ }
249
+ view.accounts = [...accountRows.values()];
250
+
251
+ const liveKnown = liveFolders.length > 0 && liveFolders.every((f) => f.unread != null);
252
+ view.live = {
253
+ at: liveFolders.length ? Math.max(...liveFolders.map((f) => f.at)) : null,
254
+ folders: liveFolders,
255
+ counts: {
256
+ messages: liveFolders.reduce((n, f) => n + f.total, 0),
257
+ unread: liveFolders.reduce((n, f) => n + (f.unread ?? 0), 0),
258
+ known: liveKnown,
259
+ },
260
+ };
261
+
262
+ // 最近一轮(给"上次检查:xx 前"用;null 表示还没跑过)
263
+ const lt = watcher?.lastTick ?? null;
264
+ if (lt) {
265
+ const results = Array.isArray(lt.results) ? lt.results : [];
266
+ view.lastCheck = {
267
+ at: num(lt.now, 0),
268
+ agoSeconds: Math.max(0, Math.round((now - num(lt.now, now)) / 1000)),
269
+ fetched: results.reduce((n, r) => n + num(r?.fetched, 0), 0),
270
+ failures: num(lt.failures, 0),
271
+ folders: num(lt.total, results.length),
272
+ paused: lt.paused === true,
273
+ nextDelaySeconds: Math.round(num(lt.nextDelayMs, 0) / 1000),
274
+ error: results.find((r) => r?.error)?.error ?? null,
275
+ };
276
+ }
277
+
278
+ if (!store) {
279
+ if (top?.watcher?.enabled !== false && !ws.reason) warnings.push("归档库尚未就绪(首轮抓取还没开始?)");
280
+ else if (ws.reason) warnings.push(`watcher 未运行:${ws.reason}`);
281
+ return view;
282
+ }
283
+
284
+ try {
285
+ const rows = store.stats();
286
+ view.folders = rows.map((r) => ({
287
+ account: r.account, folder: r.folder, total: r.total, unread: r.unread, newestTs: r.newestTs ?? null,
288
+ }));
289
+ view.counts.messages = rows.reduce((n, r) => n + num(r.total, 0), 0);
290
+ view.counts.unread = rows.reduce((n, r) => n + num(r.unread, 0), 0);
291
+ view.counts.notices = store.countNotices?.() ?? 0;
292
+ view.counts.noticesUnseen = store.countNotices?.({ unseenOnly: true }) ?? 0;
293
+ view.counts.digestQueued = store.digestQueueSize?.() ?? 0;
294
+ view.counts.tags = store.countTags?.() ?? 0;
295
+ view.counts.facts = store.countFacts?.() ?? 0;
296
+ // 按账户聚合(多账户显示):归档行 → 账户级合计;不在配置里的账户照样保留。
297
+ // ⚠️ 已有服务器实时数的账户(source:"live")**不叠加**归档数 —— 实时数就是
298
+ // 服务器真相,叠上归档数(online 模式下是旧档)只会得到错误的合计。
299
+ for (const r of rows) {
300
+ const key = String(r.account ?? "");
301
+ if (!key) continue;
302
+ const row = accountRows.get(key) ?? { account: key, alias: key, messages: 0, unread: 0 };
303
+ if (row.source !== "live") {
304
+ row.messages += num(r.total, 0);
305
+ row.unread += num(r.unread, 0);
306
+ }
307
+ accountRows.set(key, row);
308
+ }
309
+ view.accounts = [...accountRows.values()];
310
+ // 同步健康:sync_state 里 watcher 每轮写的 health/last_ok_at/last_error(B5/R3/R4 的产物)
311
+ try {
312
+ view.health = (store.listSyncState?.() ?? []).map((s) => ({
313
+ account: String(s.account ?? ""),
314
+ alias: accountRows.get(String(s.account ?? ""))?.alias ?? String(s.account ?? ""),
315
+ folder: String(s.folder ?? ""),
316
+ health: String(s.health ?? "unknown"),
317
+ lastOkAt: num(s.last_ok_at, 0),
318
+ lastError: s.last_error ? String(s.last_error) : "",
319
+ lastUid: num(s.last_uid, 0),
320
+ }));
321
+ } catch { view.health = []; }
322
+ } catch (e) {
323
+ warnings.push(`归档库统计失败:${e?.message ?? e}`);
324
+ }
325
+
326
+ if (limit > 0) {
327
+ // M6.7:online 模式不落库 → 本地 messages 表是切换前遗留的旧档,列出来只会误导
328
+ // (2026-10-30 用户反馈"数据标签是旧档"的另一半)。跳过列表并说明原因。
329
+ if (String(view.archiveMode) === "online") {
330
+ view.recentUnavailable = true;
331
+ warnings.push("online 模式不落库:最近邮件列表不可用(计数为服务器实时)");
332
+ } else try {
333
+ // 过滤路径:store 按账户过滤(查不到就是空数组,不报错);不过滤路径保持原样(全局列表)
334
+ const listArgs = acct ? { account: acct, limit, unreadOnly: false } : { limit, unreadOnly: false };
335
+ view.recent = store.listMessages(listArgs).map((m) => ({
336
+ account: m.account, alias: accountRows.get(String(m.account ?? ""))?.alias ?? m.account,
337
+ folder: m.folder, uid: num(m.uid, 0),
338
+ subject: m.subject ?? "(无主题)", from: m.from_addr ?? "", dateTs: m.date_ts ?? null,
339
+ seen: m.seen === 1 || m.seen === true, hasAttachment: m.has_attachment === 1,
340
+ importance: m.importance ?? null, snippet: m.snippet ?? null,
341
+ }));
342
+ } catch (e) {
343
+ warnings.push(`最近邮件读取失败:${e?.message ?? e}`);
344
+ }
345
+ }
346
+
347
+ // 未看通知留痕(2026-10-30):浮动栏徽标「📬 N 新」的 N 就是它,但 online 模式下
348
+ // recent 列表不可用,用户展开面板看不到那 N 封是什么 —— 把留痕原文列出来。
349
+ // 留痕在任何归档模式下都会写(notify 先 record 再 deliver),所以 online 也有数据。
350
+ // 2026-10-30 二番改造:留痕带 items([{uid,subject,from}])时**按封展开**成行 ——
351
+ // 用户要"选中邮件、看得见 subject/发件人、能继续追问";旧留痕没有 items 就退回单行(标题+正文)。
352
+ try {
353
+ if (store && typeof store.listNotices === "function") {
354
+ const noticeRows = (store.listNotices({ limit: 10, unseenOnly: true }) ?? []);
355
+ const expanded = [];
356
+ for (const n of noticeRows) {
357
+ const mails = Array.isArray(n.items) ? n.items : [];
358
+ if (mails.length) {
359
+ for (const m of mails.slice(0, 8)) { // 单条留痕最多展开 8 封,别把面板撑爆
360
+ expanded.push({
361
+ id: Number(n.id), uid: Number(m?.uid) || null,
362
+ subject: String(m?.subject ?? "") || String(n.title ?? ""),
363
+ from: String(m?.from ?? "") || null,
364
+ account: n.account ?? "", folder: n.folder ?? "",
365
+ at: Number(n.created_at ?? 0), noticeTitle: String(n.title ?? ""),
366
+ });
367
+ }
368
+ } else {
369
+ expanded.push({
370
+ id: Number(n.id), uid: null,
371
+ subject: String(n.title ?? ""), from: null,
372
+ account: n.account ?? "", folder: n.folder ?? "",
373
+ at: Number(n.created_at ?? 0), noticeTitle: String(n.title ?? ""), body: String(n.body ?? ""),
374
+ });
375
+ }
376
+ if (expanded.length >= 14) break; // 总行数同样封顶
377
+ }
378
+ view.notices = expanded.slice(0, 14);
379
+ }
380
+ } catch { /* 留痕列表拿不到就空着,不影响计数 */ }
381
+
382
+ return view;
383
+ }
384
+
385
+ // ------------------------------------------------------------------ 处理器
386
+
387
+ /**
388
+ * 组装两个动作的处理器。
389
+ * @param {object} deps 见 buildStatusView,外加:
390
+ * check() → Promise<{fetched,failures,folders,directories}>:立刻跑一轮(由 index.js 提供,带并发闸门)
391
+ */
392
+ /**
393
+ * 组装两个动作的处理器。
394
+ * @param {object} deps 见 buildStatusView,外加:
395
+ * check() → Promise<{fetched,failures,folders,directories}>:立刻跑一轮(由 index.js 提供,带并发闸门)
396
+ * persistAccounts(account) → Promise<{ok,via,reason?}>:配置页免重启添加/更新账号
397
+ * authDevice(email) → Promise<{ok,userCode,verificationUri,expires,reason?}>:发起设备码流
398
+ * authComplete(email) → Promise<{ok,email,reason?}>:完成设备码流,写入 token
399
+ */
400
+ export function makeBridgeHandlers(deps) {
401
+ let inFlight = null; // 并发闸门:两次"立刻检查"合并成一次(IMAP 会话很贵)
402
+
403
+ return {
404
+ async status(body = {}) {
405
+ const limit = Number(body?.limit);
406
+ // 账户过滤(客户端"账号切换"用):只认字符串,去掉首尾空白;非字符串/空白 ⇒ 不过滤
407
+ const rawAccount = body?.account;
408
+ const account = typeof rawAccount === "string" ? rawAccount.trim() : "";
409
+ return { ok: true, value: buildStatusView(deps, { recentLimit: Number.isFinite(limit) ? limit : RECENT_DEFAULT, account }) };
410
+ },
411
+
412
+ /** 立刻检查一次(用户点浮动栏的"检查")。**幂等**:正在跑就复用同一次。 */
413
+ async check(body = {}) {
414
+ const ws = deps.watcherState?.() ?? {};
415
+ const w = deps.watcher?.() ?? null;
416
+ if (w == null) {
417
+ return { ok: false, code: "watcher-not-running", message: ws.reason ?? "watcher 未运行(可能是没有 timer 服务、未取到单实例锁,或已关闭)" };
418
+ }
419
+ // 暂停态下 tick() 会直接短路(不抓邮件),所以直接如实拒绝,别让用户以为检查过了
420
+ if (ws.paused === true || deps.top?.()?.watcher?.enabled === false) {
421
+ return { ok: false, code: "watcher-paused", message: ws.reason ?? "watcher 已暂停(watcher.enabled=false):先打开再检查" };
422
+ }
423
+ if (inFlight) return { ok: true, value: { ...(await inFlight), deduplicated: true } };
424
+ try {
425
+ inFlight = Promise.resolve().then(() => deps.check?.() ?? {});
426
+ const r = await inFlight;
427
+ // ⚠️ 2026-10-27 修:`status` 此前用 `recentLimit: 0` 构建 ⇒ 返回的 recent 是**空数组**,
428
+ // 客户端拿它覆盖视图时会先把列表清空再重拉一次(界面"闪一下"、且看不到本轮抓到了什么)。
429
+ // 这里改成带上真实的最近邮件(默认条数),并显式回传本轮结果(tick 的 fetched/failures),
430
+ // 让"立刻检查"能被用户看出**真的同步了**。
431
+ const ws = deps.watcherState?.() ?? {};
432
+ return {
433
+ ok: true,
434
+ value: {
435
+ ...r,
436
+ deduplicated: false,
437
+ status: buildStatusView(deps, { recentLimit: RECENT_DEFAULT }),
438
+ after: {
439
+ at: r?.at ?? Date.now(),
440
+ fetched: Number(r?.fetched ?? 0),
441
+ failures: Number(r?.failures ?? 0),
442
+ folders: Number(r?.folders ?? 0),
443
+ watcherRunning: ws.running !== false,
444
+ },
445
+ },
446
+ };
447
+ } catch (e) {
448
+ return { ok: false, code: "check-failed", message: String(e?.message ?? e) };
449
+ } finally {
450
+ inFlight = null;
451
+ }
452
+ },
453
+
454
+ /** dsh-im 的**真实**候选(机器人 + 投递目标),给配置卡做下拉用。 */
455
+ async targets() {
456
+ const im = deps.im?.() ?? null;
457
+ if (!im || typeof im.listBots !== "function") {
458
+ return { ok: false, code: "im-not-ready", message: "dsh-im 服务未就绪(dshIm 还没提供或未安装)" };
459
+ }
460
+ let list = [];
461
+ try { list = (await im.listBots()) ?? []; }
462
+ catch (e) { return { ok: false, code: "list-bots-failed", message: String(e?.message ?? e) }; }
463
+ const bots = [];
464
+ const targets = [];
465
+ for (const b of list) {
466
+ const botId = typeof b === "string" ? b : (b?.botId ?? b?.id);
467
+ if (!botId) continue;
468
+ const name = typeof b === "string" ? "" : (b?.name ?? "");
469
+ const username = typeof b === "string" ? "" : (b?.username ?? "");
470
+ bots.push({ botId, name, username });
471
+ let rows = [];
472
+ try { rows = (await im.listTargets(botId)) ?? []; } catch { continue; }
473
+ for (const t of rows) {
474
+ const targetId = t?.targetId ?? t?.id;
475
+ if (targetId) targets.push({ botId, targetId, name: t?.name ?? "", kind: t?.kind ?? "", botName: name });
476
+ }
477
+ }
478
+ const botsWithoutTargets = bots.filter((b) => !targets.some((t) => t.botId === b.botId)).map((b) => b.botId);
479
+ return { ok: true, value: { bots, targets, botsWithoutTargets } };
480
+ },
481
+
482
+ /** 标记留痕为已看(浮动栏的"标为已看")。body.ids 缺省 = 全部;给了 ids = 只标这几条。 */
483
+ async ack(body = {}) {
484
+ const st = deps.store?.();
485
+ if (!st || typeof st.markNotices !== "function") {
486
+ return { ok: false, code: "store-not-ready", message: "存储未就绪" };
487
+ }
488
+ // ids=[] 在 markNotices 里会退化成"全部"(where 拼接语义),这里显式拦下,别误标
489
+ let ids = null;
490
+ if (Array.isArray(body?.ids)) {
491
+ ids = body.ids.map(Number).filter((n) => Number.isFinite(n));
492
+ if (ids.length === 0) return { ok: true, value: { marked: 0, ids: [] } };
493
+ }
494
+ const marked = st.markNotices({ ids, seenAt: Date.now() });
495
+ return { ok: true, value: { marked, ids } };
496
+ },
497
+
498
+ /**
499
+ * 标已读/未读(2026-11-29 需求):面板里直接改**服务器**状态。
500
+ * body = { account, folder?, uid?, seen? } —— 给 uid = 只改这一封;不给 uid = 改整个文件夹的未读。
501
+ * 客户端**不替用户做决定**:seen 缺省 true(标已读),显式 false 才是标未读。
502
+ */
503
+ async markSeen(body = {}) {
504
+ const account = String(body?.account ?? "").trim();
505
+ if (!account) return { ok: false, code: "missing-account", message: "缺少 account(邮箱地址或别名)" };
506
+ if (typeof deps.markSeen !== "function") {
507
+ return { ok: false, code: "not-supported", message: "本插件未暴露标已读能力" };
508
+ }
509
+ const uid = body?.uid == null ? null : Number(body.uid);
510
+ if (uid != null && !Number.isFinite(uid)) return { ok: false, code: "bad-uid", message: "uid 不是数字" };
511
+ const seen = body?.seen !== false;
512
+ try {
513
+ const value = await deps.markSeen({ account, folder: String(body?.folder ?? "").trim(), uid, seen });
514
+ return { ok: true, value };
515
+ } catch (e) {
516
+ return { ok: false, code: "mark-seen-failed", message: String(e?.message ?? e) };
517
+ }
518
+ },
519
+
520
+ /** 配置卡「监控文件夹」多选框的数据源:真连 IMAP LIST 拿该账号的文件夹名。 */
521
+ async folders(body = {}) {
522
+ const account = String(body?.account ?? "").trim();
523
+ if (!account) return { ok: false, code: "missing-account", message: "缺少 account(邮箱地址或别名)" };
524
+ if (typeof deps.foldersList !== "function") {
525
+ return { ok: false, code: "not-supported", message: "本插件未暴露文件夹列表能力" };
526
+ }
527
+ try {
528
+ return { ok: true, value: { folders: await deps.foldersList(account) } };
529
+ } catch (e) {
530
+ return { ok: false, code: "folders-list-failed", message: String(e?.message ?? e) };
531
+ }
532
+ },
533
+
534
+ /** 重置水位回填历史(2026-10-31):本地库与邮箱内容对齐的入口。body={account, folder?}。 */
535
+ async resync(body = {}) {
536
+ const account = String(body?.account ?? "").trim();
537
+ if (!account) return { ok: false, code: "missing-account", message: "缺少 account(邮箱地址或别名)" };
538
+ if (typeof deps.resync !== "function") {
539
+ return { ok: false, code: "not-supported", message: "本插件未暴露重置水位能力" };
540
+ }
541
+ try {
542
+ return { ok: true, value: await deps.resync({ account, folder: body?.folder }) };
543
+ } catch (e) {
544
+ return { ok: false, code: "resync-failed", message: String(e?.message ?? e) };
545
+ }
546
+ },
547
+
548
+ /** 配置页:列出当前生效的账号(不含敏感信息,如 clientId/scopes 不回显)。 */
549
+ async accounts(body = {}) {
550
+ const top = deps.top?.() ?? {};
551
+ const list = Array.isArray(top.accounts) ? top.accounts : [];
552
+ const tokenStatus = deps.accountTokenStatus?.() ?? [];
553
+ const statusMap = new Map(tokenStatus.map((s) => [s.email, s]));
554
+ const deployed = deployedSetOf(deps);
555
+ return { ok: true, value: { accounts: list.map((a) => {
556
+ const st = statusMap.get(a.email);
557
+ return {
558
+ email: a.email, alias: a.alias, imapHost: a.imapHost, imapPort: a.imapPort,
559
+ smtpHost: a.smtpHost, smtpPort: a.smtpPort, defaultFolder: a.defaultFolder,
560
+ // 监控文件夹(2026-10-30):卡片要展示当前监控范围,并在「编辑」时预填
561
+ folders: Array.isArray(a.folders) ? a.folders : [],
562
+ authorized: st?.authorized ?? false,
563
+ remainSeconds: st?.remainSeconds ?? 0,
564
+ // 来源:deploy = cordis.patch.yml(配置页**删不掉**,只能改文件 + 重启 DSH);
565
+ // runtime = 运行时层(配置页可增删)。卡片据此显示来源并禁用「删除」。
566
+ source: deployed.has(a.email) ? "deploy" : "runtime",
567
+ };
568
+ }) } };
569
+ },
570
+
571
+ /** 配置页:免重启添加/更新一个账号。body = { email, alias, imapHost, imapPort, smtpHost, smtpPort, defaultFolder, folders? }
572
+ * folders(2026-10-30):字符串数组,要监控的文件夹;**不传/空 = 沿用该账号已配置的监控范围**(没有则默认 INBOX)。 */
573
+ async accountsPut(body = {}) {
574
+ if (!deps.persistAccounts) {
575
+ return { ok: false, code: "not-supported", message: "本插件未暴露账号写入能力(需宿主支持 runtime 配置)" };
576
+ }
577
+ try {
578
+ const r = await deps.persistAccounts(body);
579
+ if (!r.ok) return { ok: false, code: r.reason || "write-failed", message: r.error || r.reason };
580
+ return { ok: true, via: r.via };
581
+ } catch (e) {
582
+ return { ok: false, code: "accounts-put-failed", message: String(e?.message ?? e) };
583
+ }
584
+ },
585
+
586
+ /** 配置页:删除一个账号 —— **只能删运行时层账号**。
587
+ *
588
+ * 生效账号是「部署层 ∪ 运行时层」的并集(index.js 的 runtimeRawOf),所以对部署层
589
+ * 账号写一份"少了它"的运行时列表是删不掉的:2026-10-17 实测传 accounts:[] 之后,
590
+ * 生效账号依旧是 peer@example.org。旧实现因此假成功(提示已保存、刷新后账号
591
+ * 又回来,且没有任何解释);现在明确拒绝,并说清该去改哪。 */
592
+ async accountsDelete(body = {}) {
593
+ const email = String(body?.email ?? "").trim();
594
+ if (!email) return { ok: false, code: "missing-email", message: "缺少 email" };
595
+ const top = deps.top?.() ?? {};
596
+ const current = Array.isArray(top.accounts) ? top.accounts : [];
597
+ if (!current.some((a) => a.email === email)) {
598
+ return { ok: false, code: "not-found", message: `账号 ${email} 不在账号列表中` };
599
+ }
600
+ if (deployedSetOf(deps).has(email)) {
601
+ return {
602
+ ok: false,
603
+ code: "deployed-account",
604
+ message: `账号 ${email} 来自部署层(cordis.patch.yml 的 accounts),配置页删不掉;`
605
+ + "请编辑该文件里的 accounts 后重启 DSH。",
606
+ };
607
+ }
608
+ if (typeof deps.replaceRuntimeAccounts !== "function") {
609
+ return { ok: false, code: "delete-not-supported", message: "删除账号需要宿主支持 runtime.accounts 覆盖写入" };
610
+ }
611
+ // 只过滤**运行时层**那一份:若拿生效列表去写,会把部署层账号复制进运行时层,
612
+ // 变成两份同名账号(覆盖语义上无害,但会让来源显示变得没法解释)。
613
+ let runtimeList = current;
614
+ try { if (typeof deps.runtimeAccounts === "function") runtimeList = deps.runtimeAccounts() ?? []; }
615
+ catch { /* 取不到运行时层 → 退回生效列表(等价于旧行为) */ }
616
+ const next = runtimeList.filter((a) => a.email !== email);
617
+ if (next.length === runtimeList.length) {
618
+ return { ok: false, code: "not-found", message: `账号 ${email} 不是运行时层账号,无需删除` };
619
+ }
620
+ try {
621
+ const r = await deps.replaceRuntimeAccounts(next);
622
+ if (!r.ok) return { ok: false, code: r.reason || "write-failed", message: r.error || r.reason };
623
+ return { ok: true, via: r.via };
624
+ } catch (e) {
625
+ return { ok: false, code: "accounts-delete-failed", message: String(e?.message ?? e) };
626
+ }
627
+ },
628
+
629
+ /** 浮动栏:列某封邮件的附件清单(不落盘、不读正文,只回名字/大小/类型)。 */
630
+ async listAttachments(body = {}) {
631
+ const account = String(body?.account ?? "").trim();
632
+ const folder = String(body?.folder ?? "").trim();
633
+ const uid = Number(body?.uid);
634
+ if (!account) return { ok: false, code: "missing-account", message: "缺少 account" };
635
+ if (!Number.isFinite(uid) || uid <= 0) return { ok: false, code: "bad-uid", message: "uid 必须是正整数" };
636
+ if (typeof deps.listAttachments !== "function") {
637
+ return { ok: false, code: "not-supported", message: "宿主未暴露附件读取能力(重启 DSH 后可用)" };
638
+ }
639
+ try {
640
+ const r = await deps.listAttachments({ account, folder, uid });
641
+ return { ok: true, value: r };
642
+ } catch (e) {
643
+ return { ok: false, code: kindCode(e, "attachments-failed"), message: apiMessage(e) };
644
+ }
645
+ },
646
+
647
+ /** 浮动栏:取某一个附件的字节(base64)。只给面板"点开就看",不做落盘。 */
648
+ async getAttachment(body = {}) {
649
+ const account = String(body?.account ?? "").trim();
650
+ const folder = String(body?.folder ?? "").trim();
651
+ const uid = Number(body?.uid);
652
+ const index = Number(body?.index);
653
+ if (!account) return { ok: false, code: "missing-account", message: "缺少 account" };
654
+ if (!Number.isFinite(uid) || uid <= 0) return { ok: false, code: "bad-uid", message: "uid 必须是正整数" };
655
+ if (!Number.isInteger(index) || index < 1) return { ok: false, code: "bad-index", message: "index 必须是 ≥1 的整数(附件序号从 1 开始)" };
656
+ if (typeof deps.getAttachment !== "function") {
657
+ return { ok: false, code: "not-supported", message: "宿主未暴露附件读取能力(重启 DSH 后可用)" };
658
+ }
659
+ try {
660
+ const r = await deps.getAttachment({ account, folder, uid, index });
661
+ return { ok: true, value: r };
662
+ } catch (e) {
663
+ return { ok: false, code: kindCode(e, "attachment-failed"), message: apiMessage(e) };
664
+ }
665
+ },
666
+
667
+ /** 配置页:发一条测试消息,验证 IM 通道真能发出去(与工具 action=test 同一条路径)。 */
668
+ async notifyTest(body = {}) {
669
+ if (typeof deps.notifyTest !== "function") {
670
+ return { ok: false, code: "not-supported", message: "宿主未暴露通道自测能力(重启 DSH 后可用)" };
671
+ }
672
+ try {
673
+ const r = await deps.notifyTest(body ?? {});
674
+ return { ok: true, value: r };
675
+ } catch (e) {
676
+ return { ok: false, code: kindCode(e, "notify-test-failed"), message: apiMessage(e) };
677
+ }
678
+ },
679
+
680
+ /** 配置页:为指定账号发起 OAuth2 设备码流。 */
681
+ async authDevice(body = {}) {
682
+ const email = String(body?.email ?? "").trim();
683
+ if (!email) return { ok: false, code: "missing-email", message: "缺少 email" };
684
+ if (!deps.authDevice) {
685
+ return { ok: false, code: "not-supported", message: "本插件未暴露设备码发起能力" };
686
+ }
687
+ try {
688
+ return await deps.authDevice(email);
689
+ } catch (e) {
690
+ return { ok: false, code: "auth-device-failed", message: String(e?.message ?? e) };
691
+ }
692
+ },
693
+
694
+ /** 配置页:完成 OAuth2 设备码流,写入本地 token。 */
695
+ async authComplete(body = {}) {
696
+ const email = String(body?.email ?? "").trim();
697
+ if (!email) return { ok: false, code: "missing-email", message: "缺少 email" };
698
+ if (!deps.authComplete) {
699
+ return { ok: false, code: "not-supported", message: "本插件未暴露设备码完成能力" };
700
+ }
701
+ try {
702
+ return await deps.authComplete(email);
703
+ } catch (e) {
704
+ return { ok: false, code: "auth-complete-failed", message: String(e?.message ?? e) };
705
+ }
706
+ },
707
+ };
708
+ }
709
+
710
+ // ------------------------------------------------------------------ 路由
711
+
712
+ /** 组装 webServer.register 要的精确路由(全部 POST + 回环守卫)。 */
713
+ export function makeBridgeRoutes(handlers, { guard = isTrustedBridgeRequest } = {}) {
714
+ /** 仅守卫(回环+同源),不检查方法(方法由 postOnly/accountsMethods 做)。 */
715
+ const admit = (req, res) => {
716
+ if (!guard(req)) { writeJson(res, 403, { ok: false, code: "forbidden" }); return false; }
717
+ return true;
718
+ };
719
+ /** 守卫 + 方法闸门;不通过时自己写完响应并返回 false。 */
720
+ // /status /check /targets /auth/* 只允许 POST(防 CSRF / 被 <form> GET 触达)
721
+ // /accounts 允许 GET(列表) / POST(增改) / DELETE(删除)
722
+ const methodAllowed = (method, allowed) => allowed.includes(method ?? "");
723
+ const requireMethod = (allowed) => (req, res) => {
724
+ if (!methodAllowed(req.method, allowed)) {
725
+ writeJson(res, 405, { ok: false, code: "method-not-allowed", message: `method not allowed: ${req.method ?? ""}` });
726
+ return false;
727
+ }
728
+ return true;
729
+ };
730
+ const postOnly = requireMethod(["POST"]);
731
+ const accountsMethods = requireMethod(["GET", "POST", "DELETE"]);
732
+ const bodyOf = async (req, res) => {
733
+ let body;
734
+ try { body = await readJsonBody(req); } catch { body = undefined; }
735
+ if (body === undefined) {
736
+ // GET 请求通常没有 body,视为空对象
737
+ if (req.method === "GET") return {};
738
+ writeJson(res, 400, { ok: false, code: "body-unreadable", message: `请求体必须是 ≤${MAX_JSON_BODY_BYTES} 字节的 JSON 对象` });
739
+ return undefined;
740
+ }
741
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
742
+ writeJson(res, 400, { ok: false, code: "body-unreadable", message: "请求体必须是 JSON 对象" });
743
+ return undefined;
744
+ }
745
+ return body;
746
+ };
747
+
748
+ return [
749
+ {
750
+ kind: "exact",
751
+ path: `${MAILBOX_BRIDGE_PREFIX}/status`,
752
+ handler: async (req, res) => {
753
+ if (!admit(req, res)) return;
754
+ if (!postOnly(req, res)) return;
755
+ const body = await bodyOf(req, res);
756
+ if (body === undefined) return;
757
+ try { writeJson(res, 200, await handlers.status(body)); }
758
+ catch (e) { writeJson(res, 500, { ok: false, code: "status-failed", message: String(e?.message ?? e) }); }
759
+ },
760
+ },
761
+ {
762
+ kind: "exact",
763
+ path: `${MAILBOX_BRIDGE_PREFIX}/check`,
764
+ handler: async (req, res) => {
765
+ if (!admit(req, res)) return;
766
+ if (!postOnly(req, res)) return;
767
+ const body = await bodyOf(req, res);
768
+ if (body === undefined) return;
769
+ try { writeJson(res, 200, await handlers.check(body)); }
770
+ catch (e) { writeJson(res, 500, { ok: false, code: "check-failed", message: String(e?.message ?? e) }); }
771
+ },
772
+ },
773
+ {
774
+ // 配置卡「监控文件夹」多选框:列某账号的 IMAP 文件夹(只读)
775
+ kind: "exact",
776
+ path: `${MAILBOX_BRIDGE_PREFIX}/folders`,
777
+ handler: async (req, res) => {
778
+ if (!admit(req, res)) return;
779
+ if (!postOnly(req, res)) return;
780
+ const body = await bodyOf(req, res);
781
+ if (body === undefined) return;
782
+ try { writeJson(res, 200, await handlers.folders(body)); }
783
+ catch (e) { writeJson(res, 500, { ok: false, code: "folders-failed", message: String(e?.message ?? e) }); }
784
+ },
785
+ },
786
+ {
787
+ // 重置水位回填历史(写水位,不碰邮件;幂等)
788
+ kind: "exact",
789
+ path: `${MAILBOX_BRIDGE_PREFIX}/resync`,
790
+ handler: async (req, res) => {
791
+ if (!admit(req, res)) return;
792
+ if (!postOnly(req, res)) return;
793
+ const body = await bodyOf(req, res);
794
+ if (body === undefined) return;
795
+ try { writeJson(res, 200, await handlers.resync(body)); }
796
+ catch (e) { writeJson(res, 500, { ok: false, code: "resync-failed", message: String(e?.message ?? e) }); }
797
+ },
798
+ },
799
+ {
800
+ // 配置卡的候选下拉数据源(只读)
801
+ kind: "exact",
802
+ path: `${MAILBOX_BRIDGE_PREFIX}/targets`,
803
+ handler: async (req, res) => {
804
+ if (!admit(req, res)) return;
805
+ if (!postOnly(req, res)) return;
806
+ const body = await bodyOf(req, res);
807
+ if (body === undefined) return;
808
+ try { writeJson(res, 200, await handlers.targets(body)); }
809
+ catch (e) { writeJson(res, 500, { ok: false, code: "targets-failed", message: String(e?.message ?? e) }); }
810
+ },
811
+ },
812
+ {
813
+ // 配置页账号管理:GET 列出,POST(action=put) 添加/更新,DELETE(action=delete 或 DELETE 方法) 删除
814
+ kind: "exact",
815
+ path: `${MAILBOX_BRIDGE_PREFIX}/accounts`,
816
+ handler: async (req, res) => {
817
+ if (!admit(req, res)) return;
818
+ if (!accountsMethods(req, res)) return;
819
+ const body = await bodyOf(req, res);
820
+ if (body === undefined) return;
821
+ const method = req.method ?? "";
822
+ if (method === "GET") {
823
+ try { writeJson(res, 200, await handlers.accounts(body)); }
824
+ catch (e) { writeJson(res, 500, { ok: false, code: "accounts-failed", message: String(e?.message ?? e) }); }
825
+ } else if (method === "POST") {
826
+ if (body.action === "put") {
827
+ try { writeJson(res, 200, await handlers.accountsPut(body)); }
828
+ catch (e) { writeJson(res, 500, { ok: false, code: "accounts-put-failed", message: String(e?.message ?? e) }); }
829
+ } else if (body.action === "delete") {
830
+ try { writeJson(res, 200, await handlers.accountsDelete(body)); }
831
+ catch (e) { writeJson(res, 500, { ok: false, code: "accounts-delete-failed", message: String(e?.message ?? e) }); }
832
+ } else {
833
+ // 默认当作 list
834
+ try { writeJson(res, 200, await handlers.accounts(body)); }
835
+ catch (e) { writeJson(res, 500, { ok: false, code: "accounts-failed", message: String(e?.message ?? e) }); }
836
+ }
837
+ } else if (method === "DELETE") {
838
+ try { writeJson(res, 200, await handlers.accountsDelete(body)); }
839
+ catch (e) { writeJson(res, 500, { ok: false, code: "accounts-delete-failed", message: String(e?.message ?? e) }); }
840
+ } else {
841
+ writeJson(res, 405, { ok: false, code: "method-not-allowed", message: `method not allowed: ${method}` });
842
+ }
843
+ },
844
+ },
845
+ {
846
+ // 配置页:发起 OAuth2 设备码流
847
+ kind: "exact",
848
+ path: `${MAILBOX_BRIDGE_PREFIX}/auth/device`,
849
+ handler: async (req, res) => {
850
+ if (!admit(req, res)) return;
851
+ if (!postOnly(req, res)) return;
852
+ const body = await bodyOf(req, res);
853
+ if (body === undefined) return;
854
+ try { writeJson(res, 200, await handlers.authDevice(body)); }
855
+ catch (e) { writeJson(res, 500, { ok: false, code: "auth-device-failed", message: String(e?.message ?? e) }); }
856
+ },
857
+ },
858
+ {
859
+ // 配置页:完成 OAuth2 设备码流,写入 token
860
+ kind: "exact",
861
+ path: `${MAILBOX_BRIDGE_PREFIX}/auth/complete`,
862
+ handler: async (req, res) => {
863
+ if (!admit(req, res)) return;
864
+ if (!postOnly(req, res)) return;
865
+ const body = await bodyOf(req, res);
866
+ if (body === undefined) return;
867
+ try { writeJson(res, 200, await handlers.authComplete(body)); }
868
+ catch (e) { writeJson(res, 500, { ok: false, code: "auth-complete-failed", message: String(e?.message ?? e) }); }
869
+ },
870
+ },
871
+ {
872
+ // 浮动栏:把所有留痕标为已看(让"📬 N 新"徽标归零)
873
+ kind: "exact",
874
+ path: `${MAILBOX_BRIDGE_PREFIX}/ack`,
875
+ handler: async (req, res) => {
876
+ if (!admit(req, res)) return;
877
+ if (!postOnly(req, res)) return;
878
+ const body = await bodyOf(req, res);
879
+ if (body === undefined) return;
880
+ try { writeJson(res, 200, await handlers.ack(body)); }
881
+ catch (e) { writeJson(res, 500, { ok: false, code: "ack-failed", message: String(e?.message ?? e) }); }
882
+ },
883
+ },
884
+ {
885
+ // 浮动栏:把某封(或某文件夹的全部未读)在**服务器上**标为已读/未读。
886
+ // 2026-11-29 需求:面板里不点进详情也能把已读状态写回服务器,并同步到其他客户端。
887
+ kind: "exact",
888
+ path: `${MAILBOX_BRIDGE_PREFIX}/mark-seen`,
889
+ handler: async (req, res) => {
890
+ if (!admit(req, res)) return;
891
+ if (!postOnly(req, res)) return;
892
+ const body = await bodyOf(req, res);
893
+ if (body === undefined) return;
894
+ try { writeJson(res, 200, await handlers.markSeen(body)); }
895
+ catch (e) { writeJson(res, 500, { ok: false, code: "mark-seen-failed", message: apiMessage(e) }); }
896
+ },
897
+ },
898
+ {
899
+ // 浮动栏:列某封邮件的附件清单(只回名字/大小/类型,不落盘、不读正文)。
900
+ // 2026-11-29 需求:邮件行上的 📎 徽标点一下就要能看有哪些附件。
901
+ kind: "exact",
902
+ path: `${MAILBOX_BRIDGE_PREFIX}/attachments`,
903
+ handler: async (req, res) => {
904
+ if (!admit(req, res)) return;
905
+ if (!postOnly(req, res)) return;
906
+ const body = await bodyOf(req, res);
907
+ if (body === undefined) return;
908
+ try { writeJson(res, 200, await handlers.listAttachments(body)); }
909
+ catch (e) { writeJson(res, 500, { ok: false, code: "attachments-failed", message: apiMessage(e) }); }
910
+ },
911
+ },
912
+ {
913
+ // 浮动栏:取单个附件的字节(base64),由浏览器自己解码打开 —— 不写磁盘。
914
+ kind: "exact",
915
+ path: `${MAILBOX_BRIDGE_PREFIX}/attachment`,
916
+ handler: async (req, res) => {
917
+ if (!admit(req, res)) return;
918
+ if (!postOnly(req, res)) return;
919
+ const body = await bodyOf(req, res);
920
+ if (body === undefined) return;
921
+ try { writeJson(res, 200, await handlers.getAttachment(body)); }
922
+ catch (e) { writeJson(res, 500, { ok: false, code: "attachment-failed", message: apiMessage(e) }); }
923
+ },
924
+ },
925
+ {
926
+ // 配置页:发一条测试消息(与 mailbox_notify action=test 共用 notifyTestCore)。
927
+ // 以前这条只能靠对话让 agent 代跑,用户在配置页里没法自证"通道到底通不通"。
928
+ kind: "exact",
929
+ path: `${MAILBOX_BRIDGE_PREFIX}/notify-test`,
930
+ handler: async (req, res) => {
931
+ if (!admit(req, res)) return;
932
+ if (!postOnly(req, res)) return;
933
+ const body = await bodyOf(req, res);
934
+ if (body === undefined) return;
935
+ try { writeJson(res, 200, await handlers.notifyTest(body)); }
936
+ catch (e) { writeJson(res, 500, { ok: false, code: "notify-test-failed", message: apiMessage(e) }); }
937
+ },
938
+ },
939
+ ];
940
+ }