dsh-mobile-plugin 0.5.35 → 0.5.36

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.
Files changed (34) hide show
  1. package/lib/impl.js +0 -7
  2. package/lib/mobile/answer-sources.js +223 -0
  3. package/lib/mobile/approval-memory.js +1 -1
  4. package/lib/mobile/events.js +0 -20
  5. package/lib/mobile/extension-data.js +105 -5
  6. package/lib/mobile/history-derive.js +54 -1
  7. package/lib/mobile/notification-prefs.js +2 -2
  8. package/lib/mobile/permissions.js +8 -5
  9. package/lib/mobile/plugin-market.js +103 -4
  10. package/lib/mobile/run-timeline.js +317 -0
  11. package/lib/mobile/session-stop-summary.js +122 -0
  12. package/lib/mobile/stats-ledger.cjs +45 -0
  13. package/lib/mobile/stop-summary.js +146 -0
  14. package/lib/mobile/third-party-extensions.js +86 -0
  15. package/lib/mobile/tool-result-cache.js +30 -2
  16. package/lib/panel/index.html +15 -15
  17. package/lib/relay/lan-proxy.js +20 -11
  18. package/lib/relay/tunnel.js +28 -12
  19. package/lib/routes/mobile-api.js +25 -19
  20. package/lib/shared/derived-cache.js +121 -0
  21. package/lib/shared/http-util.js +55 -18
  22. package/package.json +1 -2
  23. package/config/agent-presets/supervisor/agent.cordis.yml +0 -237
  24. package/config/agent-presets/supervisor/preset.yml +0 -3
  25. package/lib/mobile/auto-review-log.js +0 -160
  26. package/lib/mobile/knowledge-base.js +0 -481
  27. package/lib/mobile/mail.js +0 -621
  28. package/lib/mobile/supervisor-broadcast.js +0 -503
  29. package/lib/mobile/supervisor-memory/index.js +0 -305
  30. package/lib/mobile/supervisor-runtime/index.js +0 -54
  31. package/lib/mobile/supervisor-runtime/inject.js +0 -218
  32. package/lib/mobile/supervisor-runtime/judgment.js +0 -113
  33. package/lib/mobile/supervisor-tools.js +0 -419
  34. package/lib/mobile/task-ledger.js +0 -381
@@ -1,621 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * 手机邮箱页那三条通道的宿主侧:问「装没装」、读写邮件、写/发草稿。
5
- *
6
- * ## 为什么要在宿主绕一圈
7
- *
8
- * 电脑上那个 `dsh-email` 插件把三个接口开在宿主自己的 web 端口上,靠 `x-dsh-email-mailbox`
9
- * 这类专用头 + 同源 + JSON 认身份。手机是另一台设备:它既不是同源,也不该拿到那套接口的整张脸
10
- * (设置口返回里就有明文授权码)。所以手机打的是我们自己的 `/api/mobile/v1/mail/*`,由宿主
11
- * **以自己人身份**在 `127.0.0.1:<宿主端口>` 环回再去问它 —— 与 `mobile/extension-data.js`
12
- * 那套 `host.data` 同一类事。区别在于邮件只有这一个来源,不必做成可登记的通用转发表,
13
- * 于是单独一份实现,`SERVICES` 那张表一行不动。
14
- *
15
- * ## 收口口径
16
- *
17
- * 形状与 `mobile/supervisor-memory` 那两条同一套:坏字段整条丢、超长截断、不掺文案(文案在
18
- * App 的字典里)。请求体与响应体都有限长,超时也卡死 —— 目标都是本机服务,慢到这份上就是它
19
- * 自己卡住了,没有理由让一条移动端请求无限等着。凭据永不出宿主:设置口只用它的账号卡片,
20
- * 明文授权码那些字段连读都读不进来,更不会拼进回包。
21
- *
22
- * 纯 Node(http),无 cordis 依赖;测试把 `http.request` 指到本机假服务上跑,不碰真网。
23
- */
24
-
25
- const http = require('node:http');
26
-
27
- const { sendJson, readJsonBody } = require('../shared/http-util');
28
-
29
- /** 请求体上限:手机上发来的就是一条 JSON 命令,草稿正文最大 200KB,2MB 已经很宽松。 */
30
- const MAX_REQUEST_BYTES = 2 * 1024 * 1024;
31
- /** 响应体上限:邮件正文与文件夹清单几百 KB 是常态,16MB 兜住异常大包。 */
32
- const MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
33
- /** 一条环回请求的总时限。目标都是本机插件,慢到这份上就是它自己卡住了。 */
34
- const REQUEST_TIMEOUT_MS = 20000;
35
- /** 草稿正文上限:超过就整条拒,**不静默截断** —— 截断后发出去的信没人会发现少了后半截。 */
36
- const DRAFT_TEXT_MAX_BYTES = 200 * 1024;
37
-
38
- /** 邮件插件那三个口(与它自己注册的路径一致)。 */
39
- const SETTINGS_PATH = '/api/dsh-email/settings';
40
- const MAILBOX_PATH = '/api/dsh-email/mailbox';
41
- const DRAFT_PATH = '/api/dsh-email/drafts';
42
-
43
- /** `mailbox` 口允许的邮件动作。附件/内嵌图不走这条(见 docs/mail-app.md §1.2)。 */
44
- const MAIL_ACTIONS = new Set(['list', 'read', 'folders', 'mark', 'search', 'attachment']);
45
- /** `drafts` 口的草稿动作。 */
46
- const DRAFT_ACTIONS = new Set(['save', 'list', 'get', 'send']);
47
- /** `mailbox` 能接受的标记动作。 */
48
- const MARK_VERBS = new Set(['read', 'unread', 'star', 'unstar', 'move']);
49
-
50
- /** 宿主 web 服务真正在听的端口。与 `mobile/host-web.js` 同一口径:取实绑值,不取配置首选值。 */
51
- function hostPortOf(ctx) {
52
- try {
53
- const port = ctx?.webServer?.port;
54
- return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
55
- } catch {
56
- return null;
57
- }
58
- }
59
-
60
- /**
61
- * 取 DSH 浏览器会话的 launch token。与 `mobile/host-web.js` 同一来源:连接服务的
62
- * `browserAuth.launchToken`。用 `ctx.get` 而不是 inject,宿主没这个服务时拿到 null 就好,
63
- * 不会把整行 inject 挂住。
64
- */
65
- function launchTokenOf(ctx) {
66
- try {
67
- const connection = typeof ctx?.get === 'function' ? ctx.get('connection') : null;
68
- const token = connection && connection.browserAuth ? connection.browserAuth.launchToken : null;
69
- return typeof token === 'string' && token.length > 0 ? token : null;
70
- } catch {
71
- return null;
72
- }
73
- }
74
-
75
- /**
76
- * 用 launch token 换一张浏览器会话 cookie。
77
- *
78
- * **这一跳不是可省的**:宿主把 `/api/*`(邮件插件那三个口就注册在它下面)交给连接服务
79
- * 的 `admit()` 鉴权 —— 没有浏览器会话 cookie 的请求一律 401,哪怕它来自环回地址。
80
- * 所以插件必须先在 `/connect?token=…` 上把自己换成一个「已登录的浏览器」,再拿回来的
81
- * `set-cookie` 去打邮件接口。不这么做,`status` 会一直判成「没装」——症状是用户明明装好了、
82
- * 手机上却永远看不到邮件。
83
- *
84
- * 换到的 cookie 按端口 + token 缓存:同一进程里 token 不变、cookie 长(默认 30 天),
85
- * 每次请求都重换一遍纯属浪费。`/connect` 是一次 GET + 302,本身也很轻。
86
- */
87
- const cookieCache = new Map();
88
- const COOKIE_TTL_MS = 5 * 60 * 1000;
89
-
90
- function browserCookie(port, token) {
91
- const cacheKey = `${port}:${token}`;
92
- const hit = cookieCache.get(cacheKey);
93
- if (hit && Date.now() - hit.at < COOKIE_TTL_MS) return Promise.resolve(hit.cookie);
94
- return new Promise((resolve) => {
95
- let done = false;
96
- const finish = (cookie) => {
97
- if (done) return;
98
- done = true;
99
- try { req.destroy(); } catch { /* 已经断了 */ }
100
- if (cookie) cookieCache.set(cacheKey, { cookie, at: Date.now() });
101
- resolve(cookie);
102
- };
103
- let req;
104
- try {
105
- req = http.request({
106
- host: '127.0.0.1',
107
- port,
108
- path: `/connect?token=${encodeURIComponent(token)}`,
109
- method: 'GET',
110
- headers: { accept: 'text/html, */*' },
111
- timeout: 5000,
112
- }, (res) => {
113
- const raw = res.headers['set-cookie'];
114
- res.resume();
115
- if (!raw || !raw.length) return finish('');
116
- // 只取 `name=value` 那一段,属性(Path/HttpOnly/…)不进请求头。
117
- finish(String(raw[0]).split(';')[0]);
118
- });
119
- } catch {
120
- return finish('');
121
- }
122
- req.on('timeout', () => finish(''));
123
- req.on('error', () => finish(''));
124
- req.end();
125
- });
126
- }
127
-
128
- /**
129
- * 一次带会话的环回请求:先确保拿到 cookie,再把它附在请求上。
130
- *
131
- * cookie 拿不到时仍照发(不带 cookie)—— 那种情况网关会回 401,`status` 据此判
132
- * `forbidden`,比直接判「没装」更接近事实(服务在,只是我们没认上)。
133
- */
134
- async function authedRequest(ctx, port, options) {
135
- const token = launchTokenOf(ctx);
136
- const cookie = token ? await browserCookie(port, token) : '';
137
- const headers = cookie ? { ...(options.headers || {}), cookie } : (options.headers || {});
138
- return request(port, { ...options, headers });
139
- }
140
-
141
- function isObject(value) {
142
- return typeof value === 'object' && value !== null && !Array.isArray(value);
143
- }
144
-
145
- /** 一个非空字符串最多 max 字节;不满条件的字段整格丢掉(不硬塞空串顶位)。 */
146
- function narrowString(value, max) {
147
- if (typeof value !== 'string') return undefined;
148
- const text = value.trim();
149
- if (text === '' || Buffer.byteLength(text) > max) return undefined;
150
- return text;
151
- }
152
-
153
- /** 一个落在 [min,max] 的整数;不是安全整数就当没给。 */
154
- function narrowInt(value, min, max) {
155
- if (!Number.isSafeInteger(value)) return undefined;
156
- return value >= min && value <= max ? value : undefined;
157
- }
158
-
159
- /**
160
- * 一封信的 uid 只是句柄:IMAP 是正整数,AgentMail 那类是字符串 id。
161
- * 数字收成原值(插件两种都收),字符串卡长度并拒绝换行/控制字符 —— 它会拼进 IMAP 命令。
162
- */
163
- function narrowUid(value) {
164
- if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return value;
165
- if (typeof value === 'string') {
166
- const text = value.trim();
167
- if (text !== '' && text.length <= 998 && !/[\r\n\0]/.test(text)) return text;
168
- }
169
- return undefined;
170
- }
171
-
172
- /**
173
- * 把一条环回请求发到 `127.0.0.1:<port>`,收状态码与正文(utf8)。
174
- *
175
- * 失败统一回 `status: 0`:连不上 / 超时 / 响应过大都是「这次没问到」,调用方再按档归类,
176
- * 不把「连不上」伪装成一个 HTTP 状态。
177
- */
178
- function request(port, { method, path, headers, body }) {
179
- return new Promise((resolve) => {
180
- const finalHeaders = { accept: 'application/json, */*', ...headers };
181
- const hasBody = typeof body === 'string' && body.length > 0;
182
- if (hasBody) {
183
- finalHeaders['content-type'] = 'application/json';
184
- finalHeaders['content-length'] = Buffer.byteLength(body);
185
- }
186
- let done = false;
187
- const finish = (result) => {
188
- if (done) return;
189
- done = true;
190
- resolve(result);
191
- };
192
- let req;
193
- try {
194
- req = http.request({
195
- host: '127.0.0.1',
196
- port,
197
- path,
198
- method,
199
- headers: finalHeaders,
200
- timeout: REQUEST_TIMEOUT_MS,
201
- }, (res) => {
202
- const chunks = [];
203
- let total = 0;
204
- res.on('data', (chunk) => {
205
- total += chunk.length;
206
- if (total > MAX_RESPONSE_BYTES) {
207
- req.destroy();
208
- finish({ status: 0, json: null, text: '' });
209
- return;
210
- }
211
- chunks.push(chunk);
212
- });
213
- res.on('end', () => {
214
- const text = Buffer.concat(chunks).toString('utf8');
215
- let json = null;
216
- try { json = text ? JSON.parse(text) : null; } catch { json = null; }
217
- finish({ status: res.statusCode || 0, json, text });
218
- });
219
- res.on('error', () => finish({ status: 0, json: null, text: '' }));
220
- });
221
- } catch {
222
- return finish({ status: 0, json: null, text: '' });
223
- }
224
- req.on('timeout', () => {
225
- req.destroy();
226
- finish({ status: 0, json: null, text: '' });
227
- });
228
- req.on('error', () => finish({ status: 0, json: null, text: '' }));
229
- if (hasBody) req.write(body);
230
- req.end();
231
- });
232
- }
233
-
234
- /** 从一次环回结果里挑一句给用户看的话(插件自己的口径优先)。 */
235
- function messageOfResult(result) {
236
- const json = result && result.json;
237
- if (isObject(json)) {
238
- if (isObject(json.error) && typeof json.error.message === 'string') return json.error.message;
239
- if (typeof json.message === 'string') return json.message;
240
- }
241
- return '';
242
- }
243
-
244
- /**
245
- * 设置口的账号卡片 → 只留账号名与地址、默认标记。
246
- *
247
- * 设置口回的是整份快照,`value.settings.value` 里就躺着明文授权码。这里**只**从
248
- * `accountsDetail.list` 里取 name / user / isDefault 三格,别的一概不读 —— 凭据不是
249
- * 「转发前再删一遍」,而是压根没进过这个函数。
250
- */
251
- function accountsFromSettings(result) {
252
- if (result.status !== 200 || !isObject(result.json) || result.json.ok !== true) return null;
253
- const value = result.json.value;
254
- if (!isObject(value)) return null;
255
- const detail = isObject(value.accountsDetail) ? value.accountsDetail : null;
256
- const list = detail && Array.isArray(detail.list) ? detail.list : null;
257
- // 有 accountsDetail 或至少 writable/accounts 这两格之一,才认它是邮件插件的设置快照。
258
- if (!detail && !Array.isArray(value.accounts) && typeof value.writable !== 'boolean') return null;
259
- const accounts = [];
260
- for (const card of list || []) {
261
- if (!isObject(card)) continue;
262
- const name = narrowString(card.name, 200);
263
- if (!name) continue;
264
- accounts.push({
265
- name,
266
- address: typeof card.user === 'string' ? card.user.trim() : '',
267
- default: card.isDefault === true,
268
- });
269
- }
270
- const declared = detail && typeof detail.defaultAccount === 'string' ? detail.defaultAccount.trim() : '';
271
- const defaultAccount = declared || (accounts.find((entry) => entry.default)?.name ?? '');
272
- for (const entry of accounts) entry.default = entry.name === defaultAccount;
273
- const out = { accounts, defaultAccount };
274
- if (typeof value.version === 'string' && value.version.trim()) out.version = value.version.trim();
275
- return out;
276
- }
277
-
278
- /** mailbox 的 `accounts` 动作 → 同一份账号形状。这条根本不返回凭据,天然干净。 */
279
- function accountsFromMailbox(result) {
280
- if (result.status !== 200 || !isObject(result.json) || result.json.ok !== true) return null;
281
- const value = result.json.value;
282
- if (!isObject(value) || !Array.isArray(value.accounts)) return null;
283
- const defaultAccount = typeof value.defaultAccount === 'string' ? value.defaultAccount.trim() : '';
284
- const accounts = [];
285
- for (const row of value.accounts) {
286
- if (!isObject(row)) continue;
287
- const name = narrowString(row.name, 200);
288
- if (!name) continue;
289
- accounts.push({
290
- name,
291
- address: typeof row.user === 'string' ? row.user.trim() : '',
292
- default: name === defaultAccount,
293
- });
294
- }
295
- return { accounts, defaultAccount };
296
- }
297
-
298
- /**
299
- * 探活:先问设置口拿账号与默认账号,问不到再问 mailbox 的 accounts 动作。
300
- *
301
- * 两条都试过才有资格判「没装」:设置口在某些宿主版本上可能没挂、或者版本不认这套头,
302
- * 但 mailbox 口照样在。档位按 docs/mail-app.md §1.1:打不通 / 404 → missing,403 → forbidden,
303
- * 其它 → error。
304
- */
305
- async function probeStatus(ctx, port) {
306
- const settings = await authedRequest(ctx, port, {
307
- method: 'GET',
308
- path: SETTINGS_PATH,
309
- headers: { 'x-dsh-email-settings': '1', 'sec-fetch-site': 'none' },
310
- });
311
- const fromSettings = accountsFromSettings(settings);
312
- if (fromSettings) return { ok: true, installed: true, ...fromSettings };
313
-
314
- const mailbox = await authedRequest(ctx, port, {
315
- method: 'POST',
316
- path: MAILBOX_PATH,
317
- headers: { 'x-dsh-email-mailbox': '1', 'sec-fetch-site': 'none' },
318
- body: JSON.stringify({ action: 'accounts' }),
319
- });
320
- const fromMailbox = accountsFromMailbox(mailbox);
321
- if (fromMailbox) return { ok: true, installed: true, ...fromMailbox };
322
-
323
- const results = [settings, mailbox];
324
- if (results.some((result) => result.status === 403)) {
325
- return { ok: true, installed: false, reason: 'forbidden' };
326
- }
327
- const errored = results.find((result) => result.status !== 0 && result.status !== 404);
328
- if (errored) {
329
- const message = messageOfResult(errored) || '邮件插件没有正常应答。';
330
- return { ok: true, installed: false, reason: 'error', message };
331
- }
332
- return { ok: true, installed: false, reason: 'missing' };
333
- }
334
-
335
- /** 一条失败但形状正常的回包:App 侧永远读 `{ ok:false, error:{ code, message } }`。 */
336
- function fail(res, code, message) {
337
- return sendJson(res, 200, { ok: false, error: { code, message } });
338
- }
339
-
340
- /**
341
- * POST /api/mobile/v1/mail/status
342
- *
343
- * 插件没装是一等公民:这条**永远**回 200,用 `installed:false` + `reason` 说清楚,页面据此
344
- * 摆一句平静的说明,而不是红框 + 重试。只有手机连不上这台电脑本身才是传输层错误。
345
- */
346
- async function handleMailStatus(ctx, req, res) {
347
- // 空对象请求体也读掉,别让连接挂在那里。
348
- await readJsonBody(req, MAX_REQUEST_BYTES);
349
- const port = hostPortOf(ctx);
350
- if (port === null) return sendJson(res, 200, { ok: true, installed: false, reason: 'missing' });
351
- let result;
352
- try {
353
- result = await probeStatus(ctx, port);
354
- } catch {
355
- result = { ok: true, installed: false, reason: 'error', message: '邮件插件探活失败。' };
356
- }
357
- sendJson(res, 200, result);
358
- }
359
-
360
- /**
361
- * 把外部那一条邮件命令收窄成要发给 mailbox 的形状。
362
- *
363
- * 只留这个动作用得上的字段,坏字段整格丢、超长截断。`mark` 那一格的内部动作在插件里叫
364
- * `mark`(契约里称它「内层 action」,但外层已经是 `action`,那两格会撞名,插件实际读的是
365
- * `mark`),所以外层的 `markAction` 落回上游的 `mark`。`search` 在插件里就是「带 query 的
366
- * list」,转发时并回 `list` 才走得到它的搜索分支。
367
- *
368
- * @returns {object|null} 收窄后的上游请求体;参数不成立回 null(调用方回 bad-request)。
369
- */
370
- function narrowMailBody(action, body) {
371
- const out = { action };
372
- const account = narrowString(body.account, 200);
373
- if (account !== undefined) out.account = account;
374
- const folder = narrowString(body.folder, 1024);
375
- if (folder !== undefined) out.folder = folder;
376
-
377
- if (action === 'list' || action === 'search') {
378
- if (action === 'search') {
379
- const query = narrowString(body.query, 500);
380
- if (query === undefined) return null;
381
- out.action = 'list';
382
- out.query = query;
383
- }
384
- const limit = narrowInt(body.limit, 1, 100);
385
- if (limit !== undefined) out.limit = limit;
386
- const offset = narrowInt(body.offset, 0, 10000);
387
- if (offset !== undefined) out.offset = offset;
388
- if (body.unreadOnly === true) out.unreadOnly = true;
389
- const since = narrowString(body.since, 40);
390
- if (since !== undefined) out.since = since;
391
- const until = narrowString(body.until, 40);
392
- if (until !== undefined) out.until = until;
393
- return out;
394
- }
395
-
396
- if (action === 'folders') return out;
397
-
398
- if (action === 'read' || action === 'attachment') {
399
- const uid = narrowUid(body.uid);
400
- if (uid === undefined) return null;
401
- out.uid = uid;
402
- if (action === 'attachment') {
403
- const index = narrowInt(body.index, 0, 999);
404
- if (index !== undefined) out.index = index;
405
- }
406
- return out;
407
- }
408
-
409
- if (action === 'mark') {
410
- const uid = narrowUid(body.uid);
411
- if (uid === undefined) return null;
412
- const verb = narrowString(body.markAction, 20);
413
- if (!verb || !MARK_VERBS.has(verb)) return null;
414
- out.uid = uid;
415
- out.mark = verb;
416
- const toFolder = narrowString(body.toFolder, 1024);
417
- if (toFolder !== undefined) out.toFolder = toFolder;
418
- return out;
419
- }
420
-
421
- return null;
422
- }
423
-
424
- /**
425
- * 把 mailbox 的成功结果收窄成 App 要的那份形状(App 在 api/domains/mail.ts 里读这些格)。
426
- *
427
- * **`hasMore` 是宿主自己算的**:邮件插件 0.24 的 list / search 回包只给 `count`(当前文件夹
428
- * 或匹配集的总数)与本页 `messages`,没有 `hasMore`。手机要据它决定「还能不能再往下翻」,
429
- * 所以这里按 `offset + 本页条数 < count` 补一格 —— 少了它,列表滑到底也拉不出第二页,
430
- * 用户会以为只有 20 封。
431
- */
432
- function shapeMailResult(action, value, offset) {
433
- if (action === 'folders') {
434
- const folders = Array.isArray(value) ? value : (isObject(value) && Array.isArray(value.folders) ? value.folders : []);
435
- return { ok: true, folders };
436
- }
437
- if (action === 'read') {
438
- return { ok: true, message: isObject(value) ? value : null };
439
- }
440
- if (isObject(value)) {
441
- const out = { ok: true, ...value };
442
- if ((action === 'list' || action === 'search') && Array.isArray(value.messages)) {
443
- const count = Number.isSafeInteger(value.count) ? value.count : value.messages.length;
444
- out.hasMore = (Number.isSafeInteger(offset) ? offset : 0) + value.messages.length < count;
445
- }
446
- return out;
447
- }
448
- return { ok: true };
449
- }
450
-
451
- /** 一次 mailbox 环回结果 → 移动端的统一回包(失败折成封闭几档 code,不抛)。 */
452
- function shapeMailFailure(result) {
453
- if (result.status === 0 || result.status === 404) {
454
- return { ok: false, error: { code: 'not-installed', message: '这台电脑上没有邮件插件。' } };
455
- }
456
- if (!isObject(result.json)) {
457
- return { ok: false, error: { code: 'mail-failed', message: '邮件插件没有返回可读的结果。' } };
458
- }
459
- if (result.json.ok !== true) {
460
- const message = messageOfResult(result) || '邮件操作失败。';
461
- return { ok: false, error: { code: 'mail-failed', message } };
462
- }
463
- return null;
464
- }
465
-
466
- /**
467
- * POST /api/mobile/v1/mail —— list / read / folders / mark / search / attachment。
468
- *
469
- * 与 mailbox 口同名同参,宿主只做「转发 + 收窄」,不做翻译层;唯一要改的是 `markAction`
470
- * 落回上游的 `mark`,以及 `search` 并回带 query 的 `list`(插件没有独立的 search 分支)。
471
- */
472
- async function handleMailRoute(ctx, req, res) {
473
- const body = await readJsonBody(req, MAX_REQUEST_BYTES);
474
- if (!isObject(body)) return fail(res, 'bad-request', '请求体必须是一个对象。');
475
- const action = typeof body.action === 'string' ? body.action.trim() : '';
476
- if (!MAIL_ACTIONS.has(action)) return fail(res, 'bad-request', '不支持的邮件动作。');
477
-
478
- const upstream = narrowMailBody(action, body);
479
- if (!upstream) return fail(res, 'bad-request', '这个动作的参数不完整。');
480
-
481
- const port = hostPortOf(ctx);
482
- if (port === null) return fail(res, 'not-installed', '这台电脑上没有邮件插件。');
483
-
484
- const result = await authedRequest(ctx, port, {
485
- method: 'POST',
486
- path: MAILBOX_PATH,
487
- headers: { 'x-dsh-email-mailbox': '1', 'sec-fetch-site': 'none' },
488
- body: JSON.stringify(upstream),
489
- });
490
- const failed = shapeMailFailure(result);
491
- if (failed) return sendJson(res, 200, failed);
492
- sendJson(res, 200, shapeMailResult(action, result.json.value, upstream.offset));
493
- }
494
-
495
- /** 往草稿口打一发,返回原始环回结果;调用方自己读 `.json.value`。 */
496
- function draftCall(ctx, port, payload) {
497
- return authedRequest(ctx, port, {
498
- method: 'POST',
499
- path: DRAFT_PATH,
500
- headers: { 'x-dsh-email-draft': '1', 'sec-fetch-site': 'none' },
501
- body: JSON.stringify(payload),
502
- });
503
- }
504
-
505
- /**
506
- * POST /api/mobile/v1/mail/draft —— save / list / get / send。
507
- *
508
- * 草稿口的动作名和契约不完全同名:新建是 `create`、改已有是 `update`(要带 revision)、
509
- * 发送要先 `preview` 拿到一张一次性 plan 再 `send` 并带上确认位。这里替手机把这几步走完,
510
- * 手机只看到 save / list / get / send 四个动词。发送的「点一下就发出去」在 App 侧已经被
511
- * 一次确认挡住,这里只负责把确认之后的那条路走完,不自己替用户按下去。
512
- */
513
- async function handleMailDraft(ctx, req, res) {
514
- const body = await readJsonBody(req, MAX_REQUEST_BYTES);
515
- if (!isObject(body)) return fail(res, 'bad-request', '请求体必须是一个对象。');
516
- const action = typeof body.action === 'string' ? body.action.trim() : '';
517
- if (!DRAFT_ACTIONS.has(action)) return fail(res, 'bad-request', '不支持的草稿动作。');
518
-
519
- const port = hostPortOf(ctx);
520
- if (port === null) return fail(res, 'not-installed', '这台电脑上没有邮件插件。');
521
-
522
- if (action === 'save') {
523
- const text = typeof body.text === 'string' ? body.text : '';
524
- if (Buffer.byteLength(text, 'utf8') > DRAFT_TEXT_MAX_BYTES) {
525
- return fail(res, 'bad-request', '草稿正文超过 200KB,请精简后再保存。');
526
- }
527
- const id = narrowString(body.id, 200);
528
- const fields = {
529
- account: narrowString(body.account, 200),
530
- to: typeof body.to === 'string' ? body.to : '',
531
- subject: typeof body.subject === 'string' ? body.subject : '',
532
- text,
533
- };
534
- const payload = { ...fields };
535
- if (id !== undefined) {
536
- // 改已有草稿要带乐观并发用的 revision:先读一份拿到它,再 update。
537
- const got = await draftCall(ctx, port, { action: 'get', id });
538
- const failed = shapeDraftFailure(got);
539
- if (failed) return sendJson(res, 200, failed);
540
- const revision = isObject(got.json.value) ? got.json.value.revision : undefined;
541
- const result = await draftCall(ctx, port, { action: 'update', id, revision, ...fields });
542
- return respondDraft(res, 'save', result);
543
- }
544
- const result = await draftCall(ctx, port, { action: 'create', ...fields });
545
- return respondDraft(res, 'save', result);
546
- }
547
-
548
- if (action === 'list') {
549
- const payload = { action: 'list' };
550
- const account = narrowString(body.account, 200);
551
- if (account !== undefined) payload.account = account;
552
- const result = await draftCall(ctx, port, payload);
553
- return respondDraft(res, 'list', result);
554
- }
555
-
556
- // get / send 都要一个 id。
557
- const id = narrowString(body.id, 200);
558
- if (id === undefined) return fail(res, 'bad-request', '这一条需要草稿 id。');
559
-
560
- if (action === 'get') {
561
- const result = await draftCall(ctx, port, { action: 'get', id });
562
- return respondDraft(res, 'get', result);
563
- }
564
-
565
- // send:先取 revision → preview 拿 plan id → 带确认位 send。
566
- const got = await draftCall(ctx, port, { action: 'get', id });
567
- const gotFailed = shapeDraftFailure(got);
568
- if (gotFailed) return sendJson(res, 200, gotFailed);
569
- const revision = isObject(got.json.value) ? got.json.value.revision : undefined;
570
- const preview = await draftCall(ctx, port, { action: 'preview', id, revision });
571
- const previewFailed = shapeDraftFailure(preview);
572
- if (previewFailed) return sendJson(res, 200, previewFailed);
573
- const plan = isObject(preview.json.value) ? preview.json.value.id : undefined;
574
- if (typeof plan !== 'string') return fail(res, 'mail-failed', '邮件插件没有给出可用的发送预览。');
575
- const result = await draftCall(ctx, port, { action: 'send', id, preview: plan, confirmed: true });
576
- return respondDraft(res, 'send', result);
577
- }
578
-
579
- /** 草稿一次环回失败 → 移动端统一回包(与邮件那条同一档 code)。 */
580
- function shapeDraftFailure(result) {
581
- if (result.status === 0 || result.status === 404) {
582
- return { ok: false, error: { code: 'not-installed', message: '这台电脑上没有邮件插件。' } };
583
- }
584
- if (!isObject(result.json)) {
585
- return { ok: false, error: { code: 'mail-failed', message: '邮件插件没有返回可读的结果。' } };
586
- }
587
- if (result.json.ok !== true) {
588
- const message = messageOfResult(result) || '草稿操作失败。';
589
- return { ok: false, error: { code: 'mail-failed', message } };
590
- }
591
- return null;
592
- }
593
-
594
- /** 草稿动作的成功结果 → App 要的形状:list 给 drafts,其余给单个 draft。 */
595
- function respondDraft(res, action, result) {
596
- const failed = shapeDraftFailure(result);
597
- if (failed) return sendJson(res, 200, failed);
598
- const value = result.json.value;
599
- if (action === 'list') {
600
- const drafts = isObject(value) && Array.isArray(value.drafts) ? value.drafts : [];
601
- return sendJson(res, 200, { ok: true, drafts });
602
- }
603
- if (action === 'send') {
604
- const draft = isObject(value) && isObject(value.draft) ? value.draft : null;
605
- return sendJson(res, 200, { ok: true, draft });
606
- }
607
- sendJson(res, 200, { ok: true, draft: isObject(value) ? value : null });
608
- }
609
-
610
- module.exports = {
611
- handleMailStatus,
612
- handleMailRoute,
613
- handleMailDraft,
614
- // 测试与装配用得到的那几格常量/纯函数。
615
- MAX_REQUEST_BYTES,
616
- MAX_RESPONSE_BYTES,
617
- REQUEST_TIMEOUT_MS,
618
- DRAFT_TEXT_MAX_BYTES,
619
- hostPortOf,
620
- narrowMailBody,
621
- };