dsh-mobile-plugin 0.5.48 → 0.5.50

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/client.js CHANGED
@@ -596,15 +596,51 @@ window.__ModuleLoader__.load({
596
596
  *
597
597
  * 内容由调用方按这一轮的现场拼好交进来;这里只管画与收,不做任何请求。
598
598
  */
599
+ /**
600
+ * 嵌在窗里的那一页对父窗口说的两句话:我还能不能继续轮询。
601
+ *
602
+ * **关窗必须让它真的停下来**:这一窗改成「收起不销毁」之后(见 `createDiagnosisDialog`
603
+ * 的 `keep`),那一页仍然挂在 DOM 上,页内那几个 3 秒轮询不会自己停 —— 用户说的
604
+ * 「关掉窗口就恢复正常」正是靠这一条维持的。iframe 跨源还好、跨源也被挡,所以这里按
605
+ * 同源 `postMessage` 通知,页面那边听不到就照常按 `document.hidden` 判。
606
+ */
607
+ const PANEL_VISIBILITY = 'dsh-mobile-plugin:panel-visibility';
608
+
609
+ /** 通知嵌着的那一页:现在看得见 / 看不见。拿不到窗口就静默跳过。 */
610
+ function tellFrame(overlay, visible) {
611
+ try {
612
+ const frame = overlay && typeof overlay.querySelector === 'function'
613
+ ? overlay.querySelector('iframe')
614
+ : null;
615
+ const win = frame && frame.contentWindow;
616
+ if (!win || typeof win.postMessage !== 'function') return;
617
+ win.postMessage({ type: PANEL_VISIBILITY, visible: Boolean(visible) }, '*');
618
+ } catch {
619
+ // 跨源(理论上不该发生:这一窗嵌的就是同源面板页)—— 页面自己按 document.hidden 判。
620
+ }
621
+ }
622
+
599
623
  function createDiagnosisDialog(doc) {
600
624
  let overlay = null;
601
625
  /** 底下那一句说明(复制结果就地改它,不重画整窗)。 */
602
626
  let noteEl = null;
603
627
  let escapeListener = null;
604
628
  const hide = () => {
605
- if (overlay && typeof overlay.remove === 'function' && overlay.parentElement) overlay.remove();
606
- overlay = null;
607
- noteEl = null;
629
+ // **`keep` 的窗只收起、不销毁**:那一页是一份 1.4MB 的单文件产物,销毁掉下次
630
+ // 打开就得整份重新下载 + 重新挂载,实测每次多花七百来毫秒 —— 而用户点一下手机图标
631
+ // 只是想看一眼。留着它、隐藏起来,再打开是热的(实测 866ms → 123ms)。
632
+ // 代价是那一页还占着内存、页内轮询也还在跑,所以下面必须通知它「看不见了」,
633
+ // 让它自己把轮询停掉 —— 否则「关掉窗口就恢复正常」这条就不成立了。
634
+ if (overlay && overlay.__dshmKeep) {
635
+ if (typeof overlay.style === 'object') overlay.style.display = 'none';
636
+ tellFrame(overlay, false);
637
+ // 说明那一行**不清**:下次复用这一窗时还要往上写一句「已复制」之类。
638
+ } else if (overlay) {
639
+ if (typeof overlay.remove === 'function' && overlay.parentElement) overlay.remove();
640
+ // 不保留的那种收起就是彻底不留:引用一并清掉,下次是全新一窗(Esc / 遮罩也重新挂)。
641
+ overlay = null;
642
+ }
643
+ if (!(overlay && overlay.__dshmKeep)) noteEl = null;
608
644
  if (escapeListener && typeof doc.removeEventListener === 'function') {
609
645
  doc.removeEventListener('keydown', escapeListener);
610
646
  }
@@ -619,6 +655,23 @@ window.__ModuleLoader__.load({
619
655
  const open = (model) => {
620
656
  if (!doc || typeof doc.createElement !== 'function' || !doc.body) return null;
621
657
  const spec = model && typeof model === 'object' ? model : {};
658
+ const frameSrc = spec.frame && spec.frame.src ? String(spec.frame.src) : '';
659
+ // **同一页再开一次,直接把上一次那一窗亮出来**(见 `hide` 里的说明):那一页还活着,
660
+ // 重建等于把整份产物重新解析、React 重新挂载一遍。地址变了(换了页)才重建。
661
+ if (overlay && overlay.__dshmKeep && overlay.__dshmSrc === frameSrc) {
662
+ if (typeof overlay.style === 'object') overlay.style.display = '';
663
+ if (spec.title) overlay.setAttribute('aria-label', spec.title);
664
+ tellFrame(overlay, true);
665
+ // 底下那句说明仍然按这一轮重置(`noteEl` 是上一轮那个节点,还挂着)。
666
+ if (noteEl) noteEl.textContent = spec.note || '';
667
+ if (typeof doc.addEventListener === 'function' && !escapeListener) {
668
+ escapeListener = (event) => {
669
+ if (event && (event.key === 'Escape' || event.key === 'Esc')) hide();
670
+ };
671
+ doc.addEventListener('keydown', escapeListener);
672
+ }
673
+ return overlay;
674
+ }
622
675
  if (!overlay) {
623
676
  overlay = make('div', 'dshm_overlay');
624
677
  overlay.setAttribute(DIAG_MARK, '');
@@ -637,6 +690,10 @@ window.__ModuleLoader__.load({
637
690
  }
638
691
  }
639
692
  if (spec.title) overlay.setAttribute('aria-label', spec.title);
693
+ // 「这一窗收起时不销毁」的记号(见 `hide`)。只有带整页 iframe 的那一窗需要它:
694
+ // 那一页重建一次要重新解析一整份产物,而诊断窗那几行读数是现拼的,重建几乎不要钱。
695
+ overlay.__dshmKeep = Boolean(spec.keep);
696
+ overlay.__dshmSrc = frameSrc;
640
697
  // 每次重画:读数与按钮都是这一轮的现场,别留上一轮的字。
641
698
  // **`children` 是 HTMLCollection,没有 `slice()`**(假元素是数组,测试覆盖不到);
642
699
  // 先摊成数组再边删边走。
@@ -707,11 +764,26 @@ window.__ModuleLoader__.load({
707
764
  noteEl = note;
708
765
  return overlay;
709
766
  };
767
+ /**
768
+ * 彻底销毁这一窗(连同嵌着的那一页)。
769
+ *
770
+ * `hide` 对带整页的窗是「收起、留着复用」,但**离开这一窗去浏览器**那一支不该留:
771
+ * 用户已经不在这里看了,把那一页和一整份产物继续占着内存没有道理。
772
+ */
773
+ const dispose = () => {
774
+ if (overlay && typeof overlay.remove === 'function' && overlay.parentElement) overlay.remove();
775
+ overlay = null;
776
+ noteEl = null;
777
+ if (escapeListener && typeof doc.removeEventListener === 'function') {
778
+ doc.removeEventListener('keydown', escapeListener);
779
+ }
780
+ escapeListener = null;
781
+ };
710
782
  /** 就地更新底下那一句说明(不重画整窗)。 */
711
783
  const note = (text) => {
712
784
  if (noteEl) noteEl.textContent = text === undefined ? '' : String(text);
713
785
  };
714
- return { open, hide, note };
786
+ return { open, hide, note, dispose };
715
787
  }
716
788
 
717
789
  /** 复制一段文字:先走剪贴板 API,不行退回 textarea + execCommand。 */
@@ -1307,13 +1379,16 @@ window.__ModuleLoader__.load({
1307
1379
  const openBrowser = (page) => {
1308
1380
  if (typeof window === 'undefined' || typeof window.open !== 'function') return;
1309
1381
  const opened = window.open(page || consolePage, '_blank', 'noreferrer');
1310
- if (opened) dialog.hide();
1382
+ // 开出去了就彻底销毁:用户已经不在这一窗里看了,没必要继续留着一整页。
1383
+ if (opened) dialog.dispose();
1311
1384
  else dialog.note(t('consolePopupBlocked'));
1312
1385
  };
1313
1386
 
1314
1387
  dialog.open({
1315
1388
  title: t('consoleTitle'),
1316
1389
  wide: true,
1390
+ // 收起时不销毁(见 `hide`):再点一次图标就是热的,省掉一次整页重载。
1391
+ keep: true,
1317
1392
  frame: {
1318
1393
  src: consolePage,
1319
1394
  title: t('consoleTitle'),
package/lib/impl.js CHANGED
@@ -13,7 +13,7 @@ import z from '@deepseek-ai/schemastery'
13
13
  const require = createRequire(import.meta.url)
14
14
  const core = require('./relay/core.js')
15
15
  const pairingApproval = require('./relay/pairing-policy.js')
16
- const { sendJson, sendHtml } = require('./shared/http-util.js')
16
+ const { sendJson, sendHtml, htmlEtag } = require('./shared/http-util.js')
17
17
  // 控制面守卫(localOnly)与移动端守卫(guarded)都住在这里;两套守卫并排放,
18
18
  // 「控制面多挡跨站与 method、移动端只挡 token」这个不对称一眼可见。
19
19
  const { localOnly, trustedLocalUi, readJson, createGuarded } = require('./http/routing.js')
@@ -454,6 +454,7 @@ function apply(ctx) {
454
454
  sendJson,
455
455
  // 面板页(lib/panel/index.html)整页吐给浏览器用;与控制面其它响应一样按注入传,不在这里 require,路由表才保持「只依赖注入项」。
456
456
  sendHtml,
457
+ htmlEtag,
457
458
  state,
458
459
  sidecarToken,
459
460
  status,
@@ -555,6 +556,10 @@ function apply(ctx) {
555
556
  hostMetadata,
556
557
  // iOS 推送令牌上报(/push-token)的登记 / 删除出口;不传时路由只回 ok。
557
558
  pushNotify,
559
+ // 「这台电脑上还连着哪些手机」的两条路由(见 mobile/paired-devices.js):凭据库真源 +
560
+ // 吊销时收掉被踢设备在途的 SSE。
561
+ credentials,
562
+ dropDeviceStreams: (deviceId) => streamRegistry.drop(deviceId),
558
563
  // 取值器而非快照对象:snapshot 会被 applySidecarConfig 整体替换,闭包捕获对象会让
559
564
  // 连接信息永远停在进程启动那一刻。
560
565
  getSidecarSnapshot: sidecarLifecycle.getSnapshot,
@@ -11,6 +11,10 @@
11
11
  * 一节才有得对账(理由当时只在卡上闪一下,卡一结算就没了)。这份记录只给人看,不参与任何
12
12
  * 判定,所以只留最近若干条、超了挤掉最老的。
13
13
  *
14
+ * 第三段是**自动审阅档的判定流水**(`autoReview`):这一档会替人放行,每次判定都要留凭据。
15
+ * 这条记录**不写会话日志** —— 宿主读盘时认不出的事件类型会让整份会话打不开,账本才是它该在
16
+ * 的地方(见 auto-review.js 的 `record`)。
17
+ *
14
18
  * 落盘位置 `<DSH_HOME>/storages/mobile-plugin/approval-rules.json`,照移动端那几份账本的
15
19
  * 同一套「原子写 + 读坏当空」的边界:账本读不动不能把审批拦在门外,写失败也只影响「重启后
16
20
  * 还在不在」。`DSH_MOBILE_APPROVAL_RULES` 只给测试注入路径用。
@@ -28,6 +32,8 @@ const VERSION = 1;
28
32
  const MAX_RULES = 500;
29
33
  /** 拒绝记录上限:只是给人对账用的流水,留最近这些就够了。 */
30
34
  const MAX_DECISIONS = 50;
35
+ /** 自动审阅判定上限:同上,只是流水。 */
36
+ const MAX_AUTO_REVIEW = 200;
31
37
 
32
38
  function rulesFile() {
33
39
  return process.env.DSH_MOBILE_APPROVAL_RULES
@@ -59,7 +65,25 @@ function normalizeRule(entry) {
59
65
  }
60
66
 
61
67
  function emptyStore() {
62
- return { version: VERSION, updatedAt: 0, rules: [], decisions: [] };
68
+ return { version: VERSION, updatedAt: 0, rules: [], decisions: [], autoReview: [] };
69
+ }
70
+
71
+ /** 自动审阅档的三种结论;其余取值当坏记录丢掉。 */
72
+ const AUTO_REVIEW_ACTIONS = new Set(['allow', 'reject', 'card']);
73
+
74
+ /** 一条自动审阅判定:形状不对的丢掉,读坏的文件不能把页面撑炸。 */
75
+ function normalizeAutoReview(entry) {
76
+ if (!isRecord(entry) || !AUTO_REVIEW_ACTIONS.has(entry.action)) return null;
77
+ return {
78
+ sessionId: textOf(entry.sessionId, 200) || null,
79
+ action: entry.action,
80
+ verdict: textOf(entry.verdict, 40) || null,
81
+ decidedBy: textOf(entry.decidedBy, 40) || null,
82
+ targetMode: textOf(entry.targetMode, 40) || null,
83
+ toolName: textOf(entry.toolName, 120) || null,
84
+ callId: textOf(entry.callId, 200) || null,
85
+ at: Number.isFinite(entry.at) ? entry.at : Date.now(),
86
+ };
63
87
  }
64
88
 
65
89
  /** 一条拒绝记录:形状不对的丢掉,读坏的文件不能把页面撑炸。 */
@@ -94,11 +118,17 @@ function readStore() {
94
118
  const decision = normalizeDecision(entry);
95
119
  if (decision) decisions.push(decision);
96
120
  }
121
+ const autoReview = [];
122
+ for (const entry of Array.isArray(raw.autoReview) ? raw.autoReview : []) {
123
+ const decision = normalizeAutoReview(entry);
124
+ if (decision) autoReview.push(decision);
125
+ }
97
126
  return {
98
127
  version: VERSION,
99
128
  updatedAt: Number.isFinite(raw.updatedAt) ? raw.updatedAt : 0,
100
129
  rules,
101
130
  decisions,
131
+ autoReview,
102
132
  };
103
133
  }
104
134
 
@@ -111,7 +141,9 @@ function saveStore(store) {
111
141
  }
112
142
  let decisions = (store.decisions || []).slice();
113
143
  if (decisions.length > MAX_DECISIONS) decisions = decisions.slice(decisions.length - MAX_DECISIONS);
114
- const next = { ...store, version: VERSION, updatedAt: Date.now(), rules, decisions };
144
+ let autoReview = (store.autoReview || []).slice();
145
+ if (autoReview.length > MAX_AUTO_REVIEW) autoReview = autoReview.slice(autoReview.length - MAX_AUTO_REVIEW);
146
+ const next = { ...store, version: VERSION, updatedAt: Date.now(), rules, decisions, autoReview };
115
147
  try {
116
148
  fs.mkdirSync(path.dirname(file), { recursive: true });
117
149
  const tmp = `${file}.${process.pid}.tmp`;
@@ -189,6 +221,25 @@ function recordDecision({ classKey, reason } = {}) {
189
221
  return saveStore(store);
190
222
  }
191
223
 
224
+ /**
225
+ * 记一条自动审阅判定。只给人和脚本对账用,不参与任何判定;没有合法 action 的不记,
226
+ * 落盘失败也只影响这一条留不留得下来。
227
+ */
228
+ function recordAutoReview(entry = {}) {
229
+ const record = normalizeAutoReview({ ...entry, at: Date.now() });
230
+ if (!record) return false;
231
+ const store = readStore();
232
+ store.autoReview.push(record);
233
+ return saveStore(store);
234
+ }
235
+
236
+ /** 最近的自动审阅判定(新的在前),给对账用。 */
237
+ function listAutoReview() {
238
+ return readStore().autoReview
239
+ .slice()
240
+ .sort((a, b) => b.at - a.at);
241
+ }
242
+
192
243
  module.exports = {
193
244
  listRules,
194
245
  hasRule,
@@ -196,4 +247,6 @@ module.exports = {
196
247
  removeRule,
197
248
  listDecisions,
198
249
  recordDecision,
250
+ listAutoReview,
251
+ recordAutoReview,
199
252
  };
@@ -33,6 +33,7 @@ const { randomUUID } = require('node:crypto');
33
33
  const { sendJson, readJsonBody } = require('../shared/http-util');
34
34
  const { cancelForwardedRequests } = require('./host-bridge/transport.js');
35
35
  const autoReview = require('./auto-review.js');
36
+ const { sessionIdOf } = require('./session-id.js');
36
37
  const facts = require('./approval-facts.js');
37
38
  const approvalMemory = require('./approval-memory.js');
38
39
 
@@ -347,14 +348,6 @@ function resetForTest() {
347
348
  autoReviewConfig = null;
348
349
  }
349
350
 
350
- function sessionIdOf(session) {
351
- if (!session || typeof session !== 'object') return null;
352
- if (typeof session.id === 'string' && session.id) return session.id;
353
- // 宿主自己的两处写法不一致(`dsh-api-session-controller` 用 `session.id`,
354
- // `dsh-acp` 用 `session.header.id`);认不出会话 id 就等于这条审批没人能答,所以两种都认。
355
- const header = session.header;
356
- return header && typeof header.id === 'string' && header.id ? header.id : null;
357
- }
358
351
 
359
352
  function sessionIdOfRequest(request) {
360
353
  const agent = request && request.agent;
@@ -239,6 +239,19 @@ function reset() {
239
239
  SESSIONS.clear();
240
240
  }
241
241
 
242
+ /**
243
+ * 只从盘上那份对象文件头量宽高,**不问宿主、不搬字节**(批量那一档用)。
244
+ *
245
+ * 量不出来(对象文件不在 / 不是位图)回 null,调用方退回问宿主那条路。这条比 `refFor`
246
+ * 便宜的地方在于:它连「和盘上字节对得上的引用」都不拼 —— 宿主那条校验只在真要取字节
247
+ * 或要宿主自己量的时候才用得上。
248
+ */
249
+ function localDims(attachmentId) {
250
+ const probed = probeObject(attachmentId);
251
+ if (!probed) return null;
252
+ return { width: probed.width, height: probed.height };
253
+ }
254
+
242
255
  module.exports = {
243
256
  MAX_IDS_PER_SESSION,
244
257
  MAX_SESSIONS,
@@ -247,6 +260,7 @@ module.exports = {
247
260
  remember,
248
261
  lookup,
249
262
  refFor,
263
+ localDims,
250
264
  openObject,
251
265
  streamIfRemembered,
252
266
  reset,
@@ -30,6 +30,9 @@
30
30
  * 不另设一份模型配置:换模型跟着会话走,不会和用户在手机上选的模型打架。
31
31
  */
32
32
 
33
+ const approvalMemory = require('./approval-memory.js');
34
+ const { sessionIdOf } = require('./session-id.js');
35
+
33
36
  /** 沙箱升档的两个目标(见 @deepseek-ai/dsh-sandbox 的 approveEscalation:审批只可能来自这两档)。 */
34
37
  const TARGET_WORKSPACE = 'workspace-write';
35
38
  const TARGET_DANGER = 'danger-full-access';
@@ -153,20 +156,23 @@ async function decide(ctx, request, session, watching) {
153
156
  }
154
157
 
155
158
  /**
156
- * 在会话日志里留一条可查的判定记录。**旁路**:写不进也不能影响这次判定,异常一律吞掉。
157
- * 事件类型是本插件自己的,不进模型可见面(不是 surface 事件),历史派生认不出会忽略。
159
+ * 在插件自己的审批账本里留一条可查的判定记录。**旁路**:写不进也不能影响这次判定,异常一律吞掉。
160
+ * **不写会话日志**:宿主读盘时认不出的事件类型会让整份会话打不开(`ignorable` 只有宿主内部的
161
+ * plugin record 才带得上,外部插件没有这条通道),判定流水放 `approval-memory` 的 `autoReview`。
158
162
  */
159
163
  function record(session, decision, request) {
160
- if (!session || typeof session.append !== 'function' || !decision) return;
161
- const data = {
162
- action: decision.action,
163
- verdict: decision.verdict,
164
- decidedBy: decision.by,
165
- targetMode: decision.targetMode || null,
166
- toolName: typeof request.toolName === 'string' ? request.toolName : null,
167
- callId: typeof request.callId === 'string' ? request.callId : null,
168
- };
169
- try { session.append('approval/auto-review', data); } catch { /* 记账是旁路,坏了不该改判定 */ }
164
+ if (!decision) return;
165
+ try {
166
+ approvalMemory.recordAutoReview({
167
+ sessionId: sessionIdOf(session),
168
+ action: decision.action,
169
+ verdict: decision.verdict,
170
+ decidedBy: decision.by,
171
+ targetMode: decision.targetMode || null,
172
+ toolName: request && typeof request.toolName === 'string' ? request.toolName : null,
173
+ callId: request && typeof request.callId === 'string' ? request.callId : null,
174
+ });
175
+ } catch { /* 记账是旁路,坏了不该改判定 */ }
170
176
  }
171
177
 
172
178
  module.exports = { targetModeOf, decide, record, TARGET_WORKSPACE, TARGET_DANGER };
@@ -109,20 +109,23 @@ function sendFailure(res, error) {
109
109
  }
110
110
 
111
111
  /**
112
- * POST /api/mobile/v1/file/create
113
- * body { path(绝对), sessionId?, content?, overwrite? }
112
+ * 一段正文落到**已校验的落点**上:`file/create` 与 `session/write-body` 共用这一段。
113
+ *
114
+ * 两处共用是因为这里只有一份正确顺序 —— 按项目排队 → 判重 / 拒符号链接与目录 →
115
+ * 落盘 → 出包。抄第二份迟早会出现「一条路由拒软链、另一条顺着写」这类只在一边成立的
116
+ * 边界,而两条路由的落点判定本来就是同一份 `preparePath`。
117
+ *
118
+ * @param {{ target: string, roots: string[] }} prepared `preparePath` 的结果
119
+ * @param {object} body 请求体(只读 `overwrite`)
120
+ * @param {string} content 正文
121
+ * @param {object} res node:http ServerResponse
122
+ * @param {Record<string, unknown>} [extra] 回包里额外带的格子(写路由自己的字段)
114
123
  */
115
- async function handleFileCreate(ctx, req, res) {
116
- const body = (await readJsonBody(req)) || {};
117
- const prepared = await preparePath(ctx, body, res);
118
- if (!prepared) return;
124
+ async function writeContentAt(prepared, body, content, res, extra) {
119
125
  const { target, roots } = prepared;
120
-
121
- const content = typeof body.content === 'string' ? body.content : (body.content == null ? '' : null);
122
- if (content === null) return sendError(res, 400, 'invalid-content', 'content 必须是字符串');
123
126
  const bytes = Buffer.byteLength(content, 'utf8');
124
127
  if (bytes > FILE_MAX_CONTENT_BYTES) {
125
- return sendError(res, 413, 'too-large', '文件太大,手机这边不支持一次性新建这么大的文件');
128
+ return sendError(res, 413, 'too-large', '文件太大,手机这边不支持一次性写这么大的文件');
126
129
  }
127
130
 
128
131
  // 落盘这一段按项目串行:判重与写入必须在同一个独占窗口里,否则两条并发请求会都判「不存在」。
@@ -152,10 +155,25 @@ async function handleFileCreate(ctx, req, res) {
152
155
  created: !existing,
153
156
  overwritten: !!existing,
154
157
  bytes,
158
+ ...extra,
155
159
  });
156
160
  });
157
161
  }
158
162
 
163
+ /**
164
+ * POST /api/mobile/v1/file/create
165
+ * body { path(绝对), sessionId?, content?, overwrite? }
166
+ */
167
+ async function handleFileCreate(ctx, req, res) {
168
+ const body = (await readJsonBody(req)) || {};
169
+ const prepared = await preparePath(ctx, body, res);
170
+ if (!prepared) return;
171
+
172
+ const content = typeof body.content === 'string' ? body.content : (body.content == null ? '' : null);
173
+ if (content === null) return sendError(res, 400, 'invalid-content', 'content 必须是字符串');
174
+ await writeContentAt(prepared, body, content, res);
175
+ }
176
+
159
177
  /**
160
178
  * POST /api/mobile/v1/file/delete
161
179
  * body { path(绝对), sessionId? }
@@ -259,6 +277,11 @@ module.exports = {
259
277
  FILE_NAME_MAX,
260
278
  FILE_MAX_CONTENT_BYTES,
261
279
  validSegment,
280
+ // 「一段正文落成文件」那条路由(`session-write-body.js`)与 `file/create` 共用这三份:
281
+ // 落点判定、错误体、带内容写入。抄第二份就等于让两条路各有一套允许区判据。
282
+ preparePath,
283
+ sendError,
284
+ writeContentAt,
262
285
  handleFileCreate,
263
286
  handleFileDelete,
264
287
  handleFileRename,
@@ -9,7 +9,8 @@
9
9
  *
10
10
  * 三条边界:
11
11
  * 1. `path` 必须是绝对路径 —— 这条路由没有可信的解析基准,相对路径直接 400,不去猜谁当基准。
12
- * 判定用的是 resolve 之后的落点,`..` 爬出允许区一律不认(403 `outside-allowed`)。
12
+ * 判定用的是 resolve 之后的落点,并对 `realpath` 之后的物理落点再判一次(堵软链逃逸),
13
+ * `..` 爬出允许区一律不认(403 `outside-allowed`)。
13
14
  * 2. 认出允许区之后的失败分开报:盘上没有 404 `missing`、不是普通文件 400 `not-a-file`、
14
15
  * 超过 512MB 413 `too-large`。码与文案跟 `/session/file` 同一套,App 那边一套分支就够。
15
16
  * 3. 字节流式回写,不在插件进程里缓冲。响应那一半(明文的整份 / 206 一段、协议 v2 的分块
@@ -17,13 +18,19 @@
17
18
  * 必然漂,而漂了的症状是「手机上永远下载中」或「取回来的那段解不开」,没有报错。
18
19
  */
19
20
 
20
- const { stat } = require('node:fs/promises');
21
+ const { stat, realpath } = require('node:fs/promises');
21
22
  const path = require('node:path');
22
23
 
23
24
  const { sendJson, readJsonBody } = require('../shared/http-util');
24
25
  const { allowedRoots, inAllowedZone } = require('./allowed-zone.js');
25
26
  const { sendFileBytes, SESSION_FILE_MAX_BYTES } = require('./session-file.js');
26
27
 
28
+ /** 允许区每个根 realpath 之后的样子;解析不了的根直接跳过(跳过是缩小范围)。 */
29
+ async function realRootsOf(roots) {
30
+ const resolved = await Promise.all(roots.map((root) => realpath(root).catch(() => null)));
31
+ return resolved.filter((root) => typeof root === 'string');
32
+ }
33
+
27
34
  /**
28
35
  * 扩展名 → 内容类型。与 `session-file.js` 那张表逐条相同:两条路给同一个文件必须给出同一个
29
36
  * `content-type`,否则 App 那边「按类型决定怎么预览」的分支会看端点选,等于多一种行为。
@@ -114,9 +121,23 @@ async function handleFileRead(ctx, req, res) {
114
121
  });
115
122
  }
116
123
 
124
+ // 字符串落点在允许区里还不够:工作区里的软链可能指到区外。与写侧(`file-ops.js` 的
125
+ // `preparePath`)同一条判据 —— 按 `realpath` 之后的物理落点再判一次。
126
+ const realTarget = await realpath(target).catch(() => null);
127
+ if (!realTarget) {
128
+ // realpath 失败 = 盘上没有了(或断了):与 stat 失败同一个 404 口子。
129
+ return sendJson(res, 404, { ok: false, error: { code: 'missing', message: '文件已经不在这台电脑上了' } });
130
+ }
131
+ if (!inAllowedZone(await realRootsOf(roots), realTarget)) {
132
+ return sendJson(res, 403, {
133
+ ok: false,
134
+ error: { code: 'outside-allowed', message: '这个文件的物理位置不在能看的范围里(可能经过了符号链接)' },
135
+ });
136
+ }
137
+
117
138
  let info;
118
139
  try {
119
- info = await stat(target);
140
+ info = await stat(realTarget);
120
141
  } catch {
121
142
  return sendJson(res, 404, { ok: false, error: { code: 'missing', message: '文件已经不在这台电脑上了' } });
122
143
  }
@@ -131,15 +152,15 @@ async function handleFileRead(ctx, req, res) {
131
152
  }
132
153
 
133
154
  const header = {
134
- 'content-type': mediaTypeOf(target),
135
- 'content-disposition': dispositionOf(path.basename(target)),
155
+ 'content-type': mediaTypeOf(realTarget),
156
+ 'content-disposition': dispositionOf(path.basename(realTarget)),
136
157
  'cache-control': 'no-store',
137
158
  };
138
159
 
139
160
  // 响应那一半(明文的整份 / 206 一段、协议 v2 的分块信封)与 `/session/file` 是**同一份**
140
161
  // 实现:两条路给同一个文件必须给出同一组头、同一种块形状、同一个起始序号口径。
141
162
  await sendFileBytes(req, res, {
142
- target,
163
+ target: realTarget,
143
164
  size: info.size,
144
165
  header,
145
166
  rawOffset: body && body.offset,
@@ -98,6 +98,11 @@ function toolResultParts(msg) {
98
98
  *
99
99
  * 宽高两格见 `imageDimsOf`:那是「手机能不能在挂载那一帧就占好位置」的前提。
100
100
  *
101
+ * `bytes` 来自宿主附件记账(`attachment.bytes`,宿主 `ImageAttachmentRef` 本来就有这一格):
102
+ * App 的事实条靠它写体积,没有它就只能对内联形状按 base64 长度估。`mediaIds` 是宿主在图片
103
+ * 块上标的「这次生成的批编号」:有就原样透传,手机侧据此把同一次生成的几张认成一组候选;
104
+ * 老宿主不给这一格,手机侧按「这一轮的图算一批」兜底,插件不另造编号。
105
+ *
101
106
  * 两条都要求 mediaType 可读(块上没有就退到 attachment 上的),否则 App 认不出来、
102
107
  * 也没有可显示的动作,返回 null 让调用方丢掉它。
103
108
  */
@@ -113,11 +118,45 @@ function imageEntryOf(block) {
113
118
  ? block.name
114
119
  : (typeof attachment.name === 'string' ? attachment.name : undefined);
115
120
  const dims = imageDimsOf(block, attachment);
116
- if (attachmentId) return { mediaType, ...(name !== undefined ? { name } : {}), ...dims, attachmentId };
117
- if (typeof block.data === 'string' && block.data) return { mediaType, data: block.data, ...(name !== undefined ? { name } : {}), ...dims };
121
+ const bytes = imageBytesOf(block, attachment);
122
+ const mediaIds = imageMediaIdsOf(block, attachment);
123
+ const extra = {
124
+ ...(name !== undefined ? { name } : {}),
125
+ ...dims,
126
+ ...(bytes === undefined ? {} : { bytes }),
127
+ ...(mediaIds.length === 0 ? {} : { mediaIds }),
128
+ };
129
+ if (attachmentId) return { mediaType, ...extra, attachmentId };
130
+ if (typeof block.data === 'string' && block.data) return { mediaType, data: block.data, ...extra };
118
131
  return null;
119
132
  }
120
133
 
134
+ /**
135
+ * 图片的字节数:宿主附件记账里的 `bytes`(块上或 attachment 上都认)。
136
+ *
137
+ * 不是正数的当没有:体积那一格宁可整截不写,也不摆一个「0 B」。
138
+ */
139
+ function imageBytesOf(block, attachment) {
140
+ const pick = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined);
141
+ return pick(block.bytes) ?? pick(attachment.bytes);
142
+ }
143
+
144
+ /**
145
+ * 这次生成的批编号(宿主在图片块上标的 `mediaIds`):去重后升序,没有就回空数组。
146
+ *
147
+ * **不新造编号**:手机侧对没有批号的图按「这一轮算一批」归组,插件补一个跨轮唯一号只会
148
+ * 让同一轮里的图被拆成多组。
149
+ */
150
+ function imageMediaIdsOf(block, attachment) {
151
+ const source = Array.isArray(block.mediaIds) ? block.mediaIds
152
+ : (Array.isArray(attachment.mediaIds) ? attachment.mediaIds : []);
153
+ const ids = new Set();
154
+ for (const value of source) {
155
+ if (typeof value === 'number' && Number.isFinite(value)) ids.add(value);
156
+ }
157
+ return [...ids].sort((left, right) => left - right);
158
+ }
159
+
121
160
  /**
122
161
  * 图片的原始宽高 —— 宿主的附件里本来就有(`attachment.width` / `attachment.height`)。
123
162
  *
@@ -709,10 +748,12 @@ function deriveMessages(events, sessionId, lookbackEvents) {
709
748
  const images = [
710
749
  ...blocks.filter((b) => b.type === 'image'),
711
750
  ...toolImages,
712
- ].map(({ mediaType, data, name, attachmentId, width, height }) => ({
751
+ ].map(({ mediaType, data, name, attachmentId, width, height, bytes, mediaIds }) => ({
713
752
  mediaType,
714
753
  ...(typeof name === 'string' ? { name } : {}),
715
754
  ...(Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0 ? { width, height } : {}),
755
+ ...(typeof bytes === 'number' && Number.isFinite(bytes) && bytes > 0 ? { bytes } : {}),
756
+ ...(Array.isArray(mediaIds) && mediaIds.length > 0 ? { mediaIds } : {}),
716
757
  ...(typeof attachmentId === 'string' && attachmentId ? { attachmentId } : {}),
717
758
  ...(typeof attachmentId === 'string' && attachmentId ? {} : { data }),
718
759
  }));