dsh-mobile-plugin 0.5.81 → 0.5.83

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 (67) hide show
  1. package/README.md +4 -0
  2. package/dsh-mobile-credentials/lib/credentials.js +5 -0
  3. package/lib/client.js +171 -5
  4. package/lib/frpc/provision.cjs +21 -17
  5. package/lib/frpc/runner.cjs +231 -168
  6. package/lib/impl.js +77 -107
  7. package/lib/index.js +1 -1
  8. package/lib/mirror/pusher.cjs +60 -10
  9. package/lib/mobile/approval-memory.js +2 -55
  10. package/lib/mobile/approvals.js +6 -82
  11. package/lib/mobile/events.js +2 -1
  12. package/lib/mobile/feedback.js +6 -5
  13. package/lib/mobile/file-read.js +4 -2
  14. package/lib/mobile/host-bridge.js +12 -1
  15. package/lib/mobile/mux.js +148 -21
  16. package/lib/mobile/paired-devices.js +2 -1
  17. package/lib/mobile/pairing.js +8 -7
  18. package/lib/mobile/relay-control.js +33 -38
  19. package/lib/mobile/session-changes.js +8 -2
  20. package/lib/mobile/session-delivery.js +5 -1
  21. package/lib/mobile/session-file.js +46 -25
  22. package/lib/mobile/session-head.js +7 -3
  23. package/lib/mobile/session-snapshot.js +5 -1
  24. package/lib/mobile/session-step.js +13 -7
  25. package/lib/mobile/session-stop-summary.js +6 -1
  26. package/lib/mobile/stream-registry.js +48 -53
  27. package/lib/mobile/stream.js +17 -2
  28. package/lib/mobile/uploads.js +190 -163
  29. package/lib/p2p/session.cjs +169 -70
  30. package/lib/p2p/wiring.cjs +4 -2
  31. package/lib/panel/index.html +44 -24
  32. package/lib/relay/blob-upload.cjs +103 -0
  33. package/lib/relay/config-store.js +79 -0
  34. package/lib/relay/control.js +131 -52
  35. package/lib/relay/core.js +55 -17
  36. package/lib/relay/lan-discovery.cjs +22 -14
  37. package/lib/relay/lan-port-policy.cjs +8 -2
  38. package/lib/relay/lan-proxy.js +47 -12
  39. package/lib/relay/pairing-payload.cjs +14 -5
  40. package/lib/relay/preview-webapp.cjs +150 -0
  41. package/lib/relay/preview.js +35 -8
  42. package/lib/relay/protocol.js +6 -4
  43. package/lib/relay/relay-probe.js +112 -21
  44. package/lib/relay/status.js +4 -7
  45. package/lib/relay/tunnel-forwarder.cjs +4 -2
  46. package/lib/relay/tunnel.js +39 -8
  47. package/lib/remote/controller.cjs +33 -3
  48. package/lib/remote/host-control.cjs +11 -2
  49. package/lib/remote/router.cjs +83 -33
  50. package/lib/remote/transport.cjs +32 -5
  51. package/lib/remote/tunnel-helper.cjs +51 -25
  52. package/lib/remote/tunnels.cjs +27 -3
  53. package/lib/routes/control-plane.js +41 -53
  54. package/lib/routes/mobile-api.js +21 -31
  55. package/lib/shared/fresh-request.js +32 -1
  56. package/lib/shared/route-order.cjs +118 -132
  57. package/lib/shared/sse-write.js +29 -10
  58. package/lib/shared/via-header.js +5 -12
  59. package/lib/shell/transport-host.js +9 -1
  60. package/lib/shell/updater.js +18 -6
  61. package/lib/sidecar-facade-worker.cjs +165 -118
  62. package/lib/sidecar-facade.cjs +6 -1
  63. package/lib/sidecar-lifecycle.cjs +6 -2
  64. package/lib/tailcat/host-process.cjs +32 -8
  65. package/lib/tailcat/session.cjs +27 -10
  66. package/package.json +6 -6
  67. package/lib/mobile/auto-review.js +0 -178
@@ -11,10 +11,6 @@
11
11
  * 一节才有得对账(理由当时只在卡上闪一下,卡一结算就没了)。这份记录只给人看,不参与任何
12
12
  * 判定,所以只留最近若干条、超了挤掉最老的。
13
13
  *
14
- * 第三段是**自动审阅档的判定流水**(`autoReview`):这一档会替人放行,每次判定都要留凭据。
15
- * 这条记录**不写会话日志** —— 宿主读盘时认不出的事件类型会让整份会话打不开,账本才是它该在
16
- * 的地方(见 auto-review.js 的 `record`)。
17
- *
18
14
  * 落盘位置 `<DSH_HOME>/storages/mobile-plugin/approval-rules.json`,照移动端那几份账本的
19
15
  * 同一套「原子写 + 读坏当空」的边界:账本读不动不能把审批拦在门外,写失败也只影响「重启后
20
16
  * 还在不在」。`DSH_MOBILE_APPROVAL_RULES` 只给测试注入路径用。
@@ -34,8 +30,6 @@ const VERSION = 1;
34
30
  const MAX_RULES = 500;
35
31
  /** 拒绝记录上限:只是给人对账用的流水,留最近这些就够了。 */
36
32
  const MAX_DECISIONS = 50;
37
- /** 自动审阅判定上限:同上,只是流水。 */
38
- const MAX_AUTO_REVIEW = 200;
39
33
 
40
34
  function rulesFile() {
41
35
  return process.env.DSH_MOBILE_APPROVAL_RULES
@@ -67,25 +61,7 @@ function normalizeRule(entry) {
67
61
  }
68
62
 
69
63
  function emptyStore() {
70
- return { version: VERSION, updatedAt: 0, rules: [], decisions: [], autoReview: [] };
71
- }
72
-
73
- /** 自动审阅档的三种结论;其余取值当坏记录丢掉。 */
74
- const AUTO_REVIEW_ACTIONS = new Set(['allow', 'reject', 'card']);
75
-
76
- /** 一条自动审阅判定:形状不对的丢掉,读坏的文件不能把页面撑炸。 */
77
- function normalizeAutoReview(entry) {
78
- if (!isRecord(entry) || !AUTO_REVIEW_ACTIONS.has(entry.action)) return null;
79
- return {
80
- sessionId: textOf(entry.sessionId, 200) || null,
81
- action: entry.action,
82
- verdict: textOf(entry.verdict, 40) || null,
83
- decidedBy: textOf(entry.decidedBy, 40) || null,
84
- targetMode: textOf(entry.targetMode, 40) || null,
85
- toolName: textOf(entry.toolName, 120) || null,
86
- callId: textOf(entry.callId, 200) || null,
87
- at: Number.isFinite(entry.at) ? entry.at : Date.now(),
88
- };
64
+ return { version: VERSION, updatedAt: 0, rules: [], decisions: [] };
89
65
  }
90
66
 
91
67
  /** 一条拒绝记录:形状不对的丢掉,读坏的文件不能把页面撑炸。 */
@@ -120,17 +96,11 @@ function readStore() {
120
96
  const decision = normalizeDecision(entry);
121
97
  if (decision) decisions.push(decision);
122
98
  }
123
- const autoReview = [];
124
- for (const entry of Array.isArray(raw.autoReview) ? raw.autoReview : []) {
125
- const decision = normalizeAutoReview(entry);
126
- if (decision) autoReview.push(decision);
127
- }
128
99
  return {
129
100
  version: VERSION,
130
101
  updatedAt: Number.isFinite(raw.updatedAt) ? raw.updatedAt : 0,
131
102
  rules,
132
103
  decisions,
133
- autoReview,
134
104
  };
135
105
  }
136
106
 
@@ -143,9 +113,7 @@ function saveStore(store) {
143
113
  }
144
114
  let decisions = (store.decisions || []).slice();
145
115
  if (decisions.length > MAX_DECISIONS) decisions = decisions.slice(decisions.length - MAX_DECISIONS);
146
- let autoReview = (store.autoReview || []).slice();
147
- if (autoReview.length > MAX_AUTO_REVIEW) autoReview = autoReview.slice(autoReview.length - MAX_AUTO_REVIEW);
148
- const next = { ...store, version: VERSION, updatedAt: Date.now(), rules, decisions, autoReview };
116
+ const next = { ...store, version: VERSION, updatedAt: Date.now(), rules, decisions };
149
117
  try {
150
118
  fs.mkdirSync(path.dirname(file), { recursive: true });
151
119
  const tmp = `${file}.${process.pid}.tmp`;
@@ -228,25 +196,6 @@ function recordDecision({ classKey, reason } = {}) {
228
196
  return saveStore(store);
229
197
  }
230
198
 
231
- /**
232
- * 记一条自动审阅判定。只给人和脚本对账用,不参与任何判定;没有合法 action 的不记,
233
- * 落盘失败也只影响这一条留不留得下来。
234
- */
235
- function recordAutoReview(entry = {}) {
236
- const record = normalizeAutoReview({ ...entry, at: Date.now() });
237
- if (!record) return false;
238
- const store = readStore();
239
- store.autoReview.push(record);
240
- return saveStore(store);
241
- }
242
-
243
- /** 最近的自动审阅判定(新的在前),给对账用。 */
244
- function listAutoReview() {
245
- return readStore().autoReview
246
- .slice()
247
- .sort((a, b) => b.at - a.at);
248
- }
249
-
250
199
  module.exports = {
251
200
  listRules,
252
201
  hasRule,
@@ -254,6 +203,4 @@ module.exports = {
254
203
  removeRule,
255
204
  listDecisions,
256
205
  recordDecision,
257
- listAutoReview,
258
- recordAutoReview,
259
206
  };
@@ -25,8 +25,7 @@
25
25
  * 带沙箱档位(`<base>@<tier>`):同一条命令在「工作区内」与「完全访问」下不是同一类授权。
26
26
  * - **拒绝理由**:手机上写的理由随结算帧下发一份,同时记进 `approval-memory.js` 的最近拒绝
27
27
  * 记录 —— 只写在挂起项上会随结算一起消失,用户事后无从回看。
28
- * 另有「同一轮里相同请求再次出现直接 auto-reject」(`turnState` 记本轮签名)。这套逻辑整体
29
- * 叠在可关的自动审阅档(`auto-review.js`)之后,两者互不影响。
28
+ * 另有「同一轮里相同请求再次出现直接 auto-reject」(`turnState` 记本轮签名)。
30
29
  *
31
30
  * `classLabel`(类别人话)在推卡时随卡下发,供第三颗按钮旁那行说明;撤销接口在写盘失败时
32
31
  * 回非 ok,手机据此保留那一行并提示重试,不把没删成的规则当成已撤销。
@@ -35,7 +34,6 @@
35
34
  const { randomUUID } = require('node:crypto');
36
35
  const { sendJson, readJsonBody } = require('../shared/http-util');
37
36
  const { cancelForwardedRequests } = require('./host-bridge/transport.js');
38
- const autoReview = require('./auto-review.js');
39
37
  const { sessionIdOf } = require('./session-id.js');
40
38
  const facts = require('./approval-facts.js');
41
39
  const approvalMemory = require('./approval-memory.js');
@@ -71,13 +69,6 @@ const bySession = new Map();
71
69
  * 都不带轮次,所以轮次要本桥自己从 `session/event` 的 turn 事件维护。
72
70
  */
73
71
  const turnState = new Map();
74
- /**
75
- * `sessionId\u0000<callId|approvalId>`:这些审批**正在自动判定**(`auto-review.js` 最长要等
76
- * 十几秒)。判定期间 `approval/asked` 已经先建了一条 `bound:false` 的挂起项 —— 它答不动
77
- * (`pendingCardOf` 返回 undefined,点进去没有卡),却会让列表页亮一颗点不开的黄点。所以
78
- * `hasPending` 要把它们摘出去,判定结束(无论结论)在 finally 里清掉。
79
- */
80
- const judging = new Set();
81
72
  /**
82
73
  * 推送出口(`mobile/push-notify.js` 的 `notifyInteraction`)。由装配层经
83
74
  * `installApprovalBridge(ctx, pushNotify)` 或 `setPushNotifier` 注入;没注入就不推。
@@ -87,17 +78,6 @@ let pushNotifier = null;
87
78
  function setPushNotifier(fn) {
88
79
  pushNotifier = typeof fn === 'function' ? fn : null;
89
80
  }
90
- /**
91
- * 自动审阅档开关的取值器(装配层注入)。钩子每次现读 —— 开关是 live 的,改完下一次请求即生效;
92
- * 没注入就当关,行为与没有这一档时逐字节一致。
93
- */
94
- let autoReviewConfig = null;
95
- function setAutoReviewConfig(fn) {
96
- autoReviewConfig = typeof fn === 'function' ? fn : null;
97
- }
98
- function autoReviewEnabled() {
99
- return !!(autoReviewConfig && autoReviewConfig().approvalAutoReview);
100
- }
101
81
 
102
82
  function watcherCount(sessionId) {
103
83
  const set = watchers.get(sessionId);
@@ -287,43 +267,15 @@ function attachSession(sessionId, sink) {
287
267
  };
288
268
  }
289
269
 
290
- /**
291
- * 标上「这一条正在自动判定」,返回要在判定结束的 finally 里撤掉的键。
292
- *
293
- * 键按 `sessionId + callId(或 approvalId)` 铸:`approval/asked` 建的那条挂起项与钩子上的
294
- * request 共用同一个 callId,两边认得出是同一条。
295
- */
296
- function markJudging(sessionId, request) {
297
- const keys = [];
298
- for (const id of [request && request.callId, request && request.approvalId]) {
299
- if (typeof id !== 'string' || !id) continue;
300
- const key = `${sessionId}\u0000${id}`;
301
- judging.add(key);
302
- keys.push(key);
303
- }
304
- return keys;
305
- }
306
-
307
- /** 这条挂起项是不是还在自动判定里(按它会带的两种 id 认)。 */
308
- function isJudging(sessionId, entry) {
309
- if (judging.size === 0) return false;
310
- for (const id of [entry.callId, entry.approvalId]) {
311
- if (typeof id === 'string' && id && judging.has(`${sessionId}\u0000${id}`)) return true;
312
- }
313
- return false;
314
- }
315
-
316
270
  /**
317
271
  * 会话摘要里的待处理标记(0.2.x 的宿主不会再下发这个字段,见 sessions.js 的用法)。
318
272
  *
319
- * 口径:**全都在自动判定中就不算挂起**。判定最长要等十几秒,这期间 `approval/asked` 建的那条
320
- * `bound:false` 项答不动(`pendingCardOf` 给不出卡),算成挂起就只剩一颗点不开的黄点。已绑的
321
- * 待答卡、以及任何不在判定里的项一律照旧算 pending —— 它们是真在等人。
273
+ * 口径:还有没结算的挂起项就算挂起。
322
274
  */
323
275
  function hasPending(sessionId) {
324
276
  const open = openEntries(sessionId);
325
277
  if (open.length === 0) return false;
326
- return open.some((entry) => !isJudging(sessionId, entry));
278
+ return open.length > 0;
327
279
  }
328
280
 
329
281
  /**
@@ -346,9 +298,7 @@ function resetForTest() {
346
298
  entries.clear();
347
299
  bySession.clear();
348
300
  turnState.clear();
349
- judging.clear();
350
301
  pushNotifier = null;
351
- autoReviewConfig = null;
352
302
  }
353
303
 
354
304
 
@@ -766,34 +716,9 @@ async function onApprovalRequest(ctx, request, next) {
766
716
  const sessionId = sessionIdOfRequest(request);
767
717
  if (!sessionId) return next();
768
718
  const session = request.agent && request.agent.session ? request.agent.session : null;
769
- // 事实行与动作类别:在钩子这侧从日志原始参数算(手机线路已裁参数)。自动判定要用它,下半段
770
- // 的「已同意 / 本轮重复」也用同一份,所以在这里算一次。
771
- let prepared = null;
772
- // 自动审阅档(默认关):先做一次受限只读判定。能直接放行 / 拒绝就不建卡;越界才落到推卡。
773
- // 开关关着时这一步整段跳过,行为与没有这一档时一字不差(见 test/approval-bridge.test.cjs)。
774
- if (autoReviewEnabled()) {
775
- prepared = prepareFacts(session, request);
776
- // 判定期间先把这一条标出来:`approval/asked` 早于判定建的那条 `bound:false` 项答不动,
777
- // 不让它在列表页亮一颗点不开的黄点(见 hasPending)。
778
- const judgingKeys = markJudging(sessionId, request);
779
- let decision;
780
- try {
781
- // 「人在不在」只按**这条会话**的订阅算:进程级「最近有没有手机请求」既会误判在场,
782
- // 也会把「手机放着不动」误判成离开(见 auto-review.js 文件头)。
783
- decision = await autoReview.decide(ctx, request, session, isSessionWatched(sessionId), prepared);
784
- autoReview.record(session, decision, request, prepared);
785
- } finally {
786
- for (const key of judgingKeys) judging.delete(key);
787
- }
788
- if (decision.action === 'allow') {
789
- // 自动放行的类别也要记进「本轮已见过」:`approval/asked` 那侧靠它判断「这条会不会被钩子
790
- // 静默放行」,不记就还会建一条永远没人结算的挂起项。
791
- rememberDuplicate(sessionId, prepared);
792
- return 'allowed-once';
793
- }
794
- if (decision.action === 'reject') return 'rejected';
795
- }
796
- if (!prepared) prepared = prepareFacts(session, request);
719
+ // 事实行与动作类别:在钩子这侧从日志原始参数算(手机线路已裁参数)。下半段的
720
+ // 「已同意 / 本轮重复」要用同一份,所以在这里算一次。
721
+ const prepared = prepareFacts(session, request);
797
722
  // 「这一类以后都同意」:同类动作之前被用户放行过,这次直接静默放行,不弹卡也不转发。
798
723
  if (classAlreadyAllowed(prepared)) {
799
724
  rememberDuplicate(sessionId, prepared);
@@ -979,6 +904,5 @@ module.exports = {
979
904
  pendingCardOf,
980
905
  isSessionWatched,
981
906
  setPushNotifier,
982
- setAutoReviewConfig,
983
907
  resetForTest,
984
908
  };
@@ -1,3 +1,4 @@
1
+ // 转发设备事件,并按已鉴权实例登记可吊销的 SSE 连接。
1
2
  /**
2
3
  * 设备流响应声明心跳周期,供客户端检测首帧缺失。
3
4
  * 设备级事件流(GET /api/mobile/v1/events/stream):手机上侧栏那条 SSE。
@@ -137,7 +138,7 @@ async function handleDeviceStream(ctx, req, res) {
137
138
  res.write(': connected\n\n');
138
139
  const ac = new AbortController();
139
140
  // 按设备登记这条流:吊销时宿主主动断它(§3.3)。设备级流同样是「开着就一直收」。
140
- const untrack = streamRegistry.track(req.__dshRecord && req.__dshRecord.deviceId, res);
141
+ const untrack = streamRegistry.track(req.__dshRecord && req.__dshRecord.deviceId, res, req.__dshRecord?.instanceId);
141
142
  // 听**响应**的关闭,不是请求的:`req` 那条 'close' 在 IncomingMessage 上表示「入站请求已经
142
143
  // 读完」,一次普通 GET 走完就会触发,而这条 SSE 连接此刻还好好的 —— 听它会当场把自己掐掉。
143
144
  // 真正的「手机那头走了」落在 `res` 上;与 `/session/stream` 同一个口径。
@@ -1,5 +1,5 @@
1
1
  'use strict';
2
- // AI 查清问题后直接把反馈提交到分发平台;GitHub PR 这条只写进说明(2026-11-18)。
2
+ // AI 查清问题后直接把反馈提交到分发平台;官方回复在维护者反馈队列跟进,AI 代提的不进 App 反馈列表(2026-11-20)。
3
3
 
4
4
  /**
5
5
  * 给模型的「反馈」能力:用户在用插件 / App 时遇到问题,AI 先排查;真查出原因后,由 AI
@@ -8,7 +8,8 @@
8
8
  * ## 两条途径
9
9
  *
10
10
  * - **分发平台**:公开反馈接口,与 App 里的反馈页同一个(`/api/sdk/feedback`)。插件把
11
- * 当前连接的设备身份一并带上,提交后能收到官方回复。这条本模块能真的替用户提交。
11
+ * 当前连接的设备身份一并带上。官方回复在维护者反馈队列里跟进(`npm run feedback` 查看),
12
+ * 这条由 AI 代提的反馈不会出现在 App 的反馈列表里。这条本模块能真的替用户提交。
12
13
  * - **GitHub**:插件代码本身的 bug 可以直接提 PR。这条路依赖用户自己登录 GitHub,
13
14
  * 插件无法代提,所以只把仓库与前提写进说明,由 AI 自己判断走不走。
14
15
  *
@@ -44,7 +45,7 @@ function feedbackChannels() {
44
45
  {
45
46
  kind: 'distribution',
46
47
  name: 'APP 分发系统反馈',
47
- description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。插件会自动带上当前连接的设备身份;提交后能在 App 里收到官方回复。',
48
+ description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。插件会自动带上当前连接的设备身份;官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条由 AI 代提的反馈不会出现在 App 的反馈列表里。',
48
49
  endpoint: `${PLATFORM_ORIGIN}${FEEDBACK_PATH}`,
49
50
  requiresLogin: false,
50
51
  },
@@ -150,7 +151,7 @@ async function submitFeedback(deps, content, threadKey, deviceId) {
150
151
  return {
151
152
  threadKey: key,
152
153
  message: key
153
- ? `已提交到分发平台,反馈线程 ${key}。之后 App 里能收到官方回复。`
154
+ ? `已提交到分发平台,反馈线程 ${key}。官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条由 AI 代提的反馈不会出现在 App 的反馈列表里。`
154
155
  : '已提交到分发平台。',
155
156
  };
156
157
  }
@@ -165,7 +166,7 @@ function registerFeedbackTool(ctx, deps) {
165
166
  ctx.tools.register(defineTool({
166
167
  name: 'dsh_feedback',
167
168
  description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
168
- + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it, and the plugin fills in the connected device identity automatically; the user gets official replies in the app. '
169
+ + 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it, and the plugin fills in the connected device identity automatically; official replies are followed up in the maintainer feedback queue (run `npm run feedback`), and this AI-submitted feedback will not appear in the in-app feedback list. '
169
170
  + '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
170
171
  + 'Use `channels` to list both routes. Only submit after you have actually found the cause: describe the problem, what you checked, and the reproduction or suggested fix.',
171
172
  parameters: {
@@ -1,3 +1,4 @@
1
+ // 按既有允许区读取文件,并将字节范围交给统一响应实现。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -14,7 +15,7 @@
14
15
  * 2. 认出允许区之后的失败分开报:盘上没有 404 `missing`、不是普通文件 400 `not-a-file`、
15
16
  * 超过 512MB 413 `too-large`。码与文案跟 `/session/file` 同一套,App 那边一套分支就够。
16
17
  * 3. 字节流式回写,不在插件进程里缓冲。响应那一半(明文的整份 / 206 一段、协议 v2 的分块
17
- * 信封,含 `offset` 的校验与起始块序号)**直接调 `/session/file` 那一份**:两边抄一份形状
18
+ * 信封,含 `offset` / `length` 校验与起始块序号)**直接调 `/session/file` 那一份**:两边抄一份形状
18
19
  * 必然漂,而漂了的症状是「手机上永远下载中」或「取回来的那段解不开」,没有报错。
19
20
  */
20
21
 
@@ -124,7 +125,7 @@ async function resolveReadableFile(ctx, declared, sessionId) {
124
125
  }
125
126
 
126
127
  /**
127
- * POST { path(绝对), sessionId? } → 该文件的原始字节。
128
+ * POST { path(绝对), sessionId?, offset?, length? } → 该文件范围的原始字节。
128
129
  *
129
130
  * @param {object} ctx 插件上下文
130
131
  * @param {object} req node:http IncomingMessage
@@ -168,6 +169,7 @@ async function handleFileRead(ctx, req, res) {
168
169
  size: info.size,
169
170
  header,
170
171
  rawOffset: body && body.offset,
172
+ rawLength: body && body.length,
171
173
  });
172
174
  }
173
175
 
@@ -1,3 +1,4 @@
1
+ // 宿主能力检测与协议兼容桥共用入口,兼容服务由每代的独立上下文持有。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -56,4 +57,14 @@ function createApiProxy(ctx) {
56
57
  };
57
58
  }
58
59
 
59
- module.exports = { createApiProxy, UNAVAILABLE };
60
+ /** 包存在时先等宿主提供旧协议服务,包缺席时直接使用网关兼容桥。 */
61
+ function runtimeProvidesApiProxy() {
62
+ try {
63
+ require.resolve('@deepseek-ai/dsh-host-apiproxy/package.json');
64
+ return true;
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ module.exports = { createApiProxy, runtimeProvidesApiProxy, UNAVAILABLE };
package/lib/mobile/mux.js CHANGED
@@ -1,3 +1,4 @@
1
+ // 将已鉴权设备的多路请求限制在移动 API,并管理心跳、响应头期限与上游生命周期。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -20,8 +21,17 @@
20
21
  */
21
22
 
22
23
  const http = require('node:http');
24
+ const { performance } = require('node:perf_hooks');
23
25
  const { StringDecoder } = require('node:string_decoder');
24
26
  const { WebSocketServer } = require('ws');
27
+ const { withViaHeader } = require('../shared/via-header');
28
+
29
+ const MOBILE_PATH = /^\/api\/mobile\/v1\/[a-zA-Z0-9/_-]+(?:\?[^\r\n#]*)?$/;
30
+ const CONNECTION_HEADERS = new Set([
31
+ 'authorization', 'cookie', 'x-dsh-device-credential', 'x-dsh-device', 'x-dsh-instance',
32
+ 'x-dsh-device-name', 'x-dsh-device-model', 'x-dsh-platform', 'x-dsh-os-version',
33
+ 'x-dsh-app-version', 'x-dsh-package-id', 'x-dsh-build-number', 'x-dsh-channel', 'x-dsh-lan-discovery',
34
+ ]);
25
35
 
26
36
  /** 单帧上限:与中转 `MAX_WS_MESSAGE_BYTES` / 宿主预览管道对齐(8 MiB)。 */
27
37
  const MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
@@ -35,6 +45,9 @@ const MAX_CONNECTIONS = 32;
35
45
  const SEND_HIGH_WATER_BYTES = 4 * 1024 * 1024;
36
46
  const SEND_LOW_WATER_BYTES = 1 * 1024 * 1024;
37
47
  const SEND_RESUME_POLL_MS = 20;
48
+ const REVOKE_DRAIN_TIMEOUT_MS = 5000;
49
+ const HEARTBEAT_INTERVAL_MS = 15_000;
50
+ const PONG_TIMEOUT_MS = 45_000;
38
51
 
39
52
  /** 上游拨号超时:只覆盖「还没拿到响应头」这一段,之后是长连接,不能有读超时。 */
40
53
  const UPSTREAM_HEADER_TIMEOUT_MS = 30_000;
@@ -42,7 +55,7 @@ const UPSTREAM_HEADER_TIMEOUT_MS = 30_000;
42
55
  /** 不往上游转发的逐跳头(与隧道/预览同一口径)。 */
43
56
  const HOP_BY_HOP = new Set([
44
57
  'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
45
- 'te', 'trailer', 'transfer-encoding', 'upgrade', 'host',
58
+ 'te', 'trailer', 'transfer-encoding', 'upgrade', 'host', 'content-length',
46
59
  ]);
47
60
 
48
61
  function safeJson(text) {
@@ -53,7 +66,7 @@ function safeJson(text) {
53
66
  * 建一个 mux 服务。
54
67
  *
55
68
  * @param {object} opts
56
- * @param {{host?:string, port:number}} opts.upstream 本地移动 API 地址(一般 `127.0.0.1:<webPort>`)。
69
+ * @param {{host?:string, port:number, agent?:import('node:http').Agent}} opts.upstream 本地移动 API 地址(一般 `127.0.0.1:<webPort>`)。
57
70
  * @param {(req: import('node:http').IncomingMessage) => boolean} opts.authorize 握手鉴权。
58
71
  * @param {(msg: string) => void} [opts.onLog]
59
72
  */
@@ -65,6 +78,7 @@ function createMuxService(opts = {}) {
65
78
 
66
79
  const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE_BYTES });
67
80
  let connectionCount = 0;
81
+ const deviceConnections = new Map();
68
82
 
69
83
  /**
70
84
  * 宿主 webServer 的升级处理器(`ctx.webServer.registerUpgrade`)。
@@ -85,28 +99,60 @@ function createMuxService(opts = {}) {
85
99
  try { socket.destroy(); } catch { /* ignore */ }
86
100
  return;
87
101
  }
88
- wss.handleUpgrade(req, socket, head, (ws) => openConnection(ws));
102
+ const trustedHeaders = {};
103
+ for (const [name, value] of Object.entries(req.headers || {})) {
104
+ const key = name.toLowerCase();
105
+ if (CONNECTION_HEADERS.has(key)) trustedHeaders[key] = value;
106
+ }
107
+ wss.handleUpgrade(req, socket, head, (ws) => openConnection(ws, req, trustedHeaders));
89
108
  }
90
109
 
91
- function openConnection(ws) {
110
+ function openConnection(ws, upgradeReq, trustedHeaders) {
92
111
  connectionCount += 1;
112
+ const identity = { deviceId: upgradeReq.__dshRecord?.deviceId || '', instanceId: upgradeReq.__dshRecord?.instanceId || '' };
113
+ deviceConnections.set(ws, identity);
93
114
  /** id → 一条在飞的本地请求。 */
94
115
  const streams = new Map();
95
116
  let closed = false;
117
+ let revoking = false;
118
+ let gracefulId = null;
119
+ let closeTimer = null;
120
+ let drainPoll = null;
121
+ let finishDrain = null;
122
+ let lastPong = performance.now();
123
+ let heartbeatTimer = null;
96
124
 
97
- const send = (obj) => {
98
- if (closed || ws.readyState !== 1 /* OPEN */) return;
99
- try { ws.send(JSON.stringify(obj)); } catch { /* 断了,close 会收尾 */ }
125
+ const send = (obj, callback) => {
126
+ if (closed || ws.readyState !== 1 /* OPEN */) { callback?.(new Error('mux closed')); return; }
127
+ try { ws.send(JSON.stringify(obj), callback); } catch (error) { callback?.(error); }
128
+ };
129
+ const closeAfterDrain = () => {
130
+ if (closed) return;
131
+ if (ws.bufferedAmount > 0) { drainPoll = setTimeout(closeAfterDrain, SEND_RESUME_POLL_MS); return; }
132
+ try { ws.close(1000, 'device revoked'); } catch { ws.terminate(); }
100
133
  };
101
134
  const fail = (id, message) => send({ t: 'err', id, message: String(message || 'error') });
102
135
 
136
+ const releaseUpstreamSocket = (entry) => {
137
+ if (entry.activeUpstreamSocket && entry.onUpstreamSocketClose) entry.activeUpstreamSocket.off('close', entry.onUpstreamSocketClose);
138
+ entry.activeUpstreamSocket = null;
139
+ entry.onUpstreamSocketClose = null;
140
+ };
141
+
142
+ const clearHeaderTimer = (entry) => {
143
+ clearTimeout(entry.headerTimer);
144
+ entry.headerTimer = null;
145
+ };
146
+
103
147
  /** 收掉一条逻辑流:销毁上游请求、释放槽位。 */
104
148
  const dropStream = (id, reason) => {
105
149
  const entry = streams.get(id);
106
150
  if (!entry) return;
107
151
  streams.delete(id);
152
+ clearHeaderTimer(entry);
108
153
  if (entry.resumeTimer) clearTimeout(entry.resumeTimer);
109
- try { entry.req && entry.req.destroy(); } catch { /* ignore */ }
154
+ releaseUpstreamSocket(entry);
155
+ try { if (!entry.responseEnded) entry.req?.destroy(); } catch { /* ignore */ }
110
156
  if (reason) fail(id, reason);
111
157
  };
112
158
 
@@ -123,24 +169,34 @@ function createMuxService(opts = {}) {
123
169
 
124
170
  const startRequest = (frame) => {
125
171
  const id = frame.id;
126
- if (typeof id !== 'number') return;
172
+ if (typeof id !== 'number' || revoking) return;
127
173
  if (streams.has(id)) { fail(id, 'duplicate id'); return; }
128
174
  if (streams.size >= MAX_STREAMS_PER_CONNECTION) { fail(id, 'too many streams'); return; }
129
175
  const method = String(frame.method || 'GET').toUpperCase();
130
- const path = typeof frame.path === 'string' && frame.path ? frame.path : '/';
131
- const headers = {};
176
+ const path = typeof frame.path === 'string' ? frame.path : '';
177
+ if (!MOBILE_PATH.test(path)) { fail(id, 'mobile API path required'); return; }
178
+ const forwarded = {};
132
179
  if (frame.headers && typeof frame.headers === 'object') {
133
180
  for (const [k, v] of Object.entries(frame.headers)) {
134
- if (!k || HOP_BY_HOP.has(k.toLowerCase())) continue;
135
- headers[k] = v;
181
+ if (!k || HOP_BY_HOP.has(k.toLowerCase()) || CONNECTION_HEADERS.has(k.toLowerCase())) continue;
182
+ forwarded[k.toLowerCase()] = v;
136
183
  }
137
184
  }
138
- const entry = { req: null, res: null, paused: false, resumeTimer: null, decoder: new StringDecoder('utf8') };
185
+ const headers = withViaHeader({ ...forwarded, ...trustedHeaders }, 'mux', `${upstreamHost}:${upstreamPort}`);
186
+ // 正文由bodyEnd结束,所有方法都交给Node分块,GET/HEAD也不能退化成裸字节追加。
187
+ headers['transfer-encoding'] = 'chunked';
188
+ const entry = { req: null, res: null, activeUpstreamSocket: null, onUpstreamSocketClose: null, responseEnded: false, paused: false, resumeTimer: null, headerTimer: null, decoder: new StringDecoder('utf8') };
139
189
  streams.set(id, entry);
190
+ const headerTimer = setTimeout(() => {
191
+ if (entry.headerTimer === headerTimer && !closed && streams.get(id) === entry && !entry.res) dropStream(id, 'upstream header timeout');
192
+ }, UPSTREAM_HEADER_TIMEOUT_MS);
193
+ entry.headerTimer = headerTimer;
194
+ headerTimer.unref?.();
140
195
 
141
196
  let req;
142
197
  try {
143
- req = http.request({ host: upstreamHost, port: upstreamPort, method, path, headers }, (res) => {
198
+ req = http.request({ host: upstreamHost, port: upstreamPort, method, path, headers, ...(opts.upstream?.agent ? { agent: opts.upstream.agent } : {}) }, (res) => {
199
+ clearHeaderTimer(entry);
144
200
  if (closed || streams.get(id) !== entry) { res.destroy(); return; }
145
201
  entry.res = res;
146
202
  const respHeaders = {};
@@ -162,10 +218,18 @@ function createMuxService(opts = {}) {
162
218
  });
163
219
  res.on('end', () => {
164
220
  if (streams.get(id) !== entry) return;
165
- streams.delete(id);
221
+ entry.responseEnded = true;
222
+ releaseUpstreamSocket(entry);
223
+ entry.req = null;
166
224
  const rest = entry.decoder.end();
167
225
  if (rest) send({ t: 'chunk', id, text: rest });
168
- send({ t: 'end', id });
226
+ send({ t: 'end', id }, (error) => {
227
+ if (streams.get(id) === entry) streams.delete(id);
228
+ if (revoking && gracefulId === id) {
229
+ if (error) ws.terminate();
230
+ else closeAfterDrain();
231
+ }
232
+ });
169
233
  });
170
234
  res.on('error', () => { if (streams.get(id) === entry) dropStream(id, 'upstream response error'); });
171
235
  });
@@ -174,7 +238,13 @@ function createMuxService(opts = {}) {
174
238
  return;
175
239
  }
176
240
  entry.req = req;
177
- req.setTimeout(UPSTREAM_HEADER_TIMEOUT_MS, () => dropStream(id, 'upstream header timeout'));
241
+ req.on('socket', (socket) => {
242
+ if (closed || streams.get(id) !== entry || entry.responseEnded || req.destroyed || socket.destroyed) return;
243
+ releaseUpstreamSocket(entry);
244
+ entry.activeUpstreamSocket = socket;
245
+ entry.onUpstreamSocketClose = () => releaseUpstreamSocket(entry);
246
+ socket.once('close', entry.onUpstreamSocketClose);
247
+ });
178
248
  req.on('error', (error) => { if (streams.get(id) === entry) dropStream(id, error && error.message ? error.message : 'upstream error'); });
179
249
  if (frame.body !== undefined && frame.body !== null) {
180
250
  if (typeof frame.body !== 'string') { dropStream(id, 'bad body'); return; }
@@ -184,6 +254,7 @@ function createMuxService(opts = {}) {
184
254
 
185
255
  const onFrame = (frame) => {
186
256
  if (!frame || typeof frame !== 'object') return;
257
+ if (revoking && (frame.id !== gracefulId || !['body', 'bodyEnd'].includes(frame.t))) return;
187
258
  switch (frame.t) {
188
259
  case 'req': startRequest(frame); break;
189
260
  case 'body': {
@@ -207,16 +278,58 @@ function createMuxService(opts = {}) {
207
278
  const cleanup = () => {
208
279
  if (closed) return;
209
280
  closed = true;
281
+ clearInterval(heartbeatTimer);
282
+ heartbeatTimer = null;
283
+ clearTimeout(closeTimer);
284
+ clearTimeout(drainPoll);
285
+ finishDrain?.();
286
+ deviceConnections.delete(ws);
210
287
  connectionCount -= 1;
211
288
  for (const entry of streams.values()) {
289
+ clearHeaderTimer(entry);
212
290
  if (entry.resumeTimer) clearTimeout(entry.resumeTimer);
291
+ releaseUpstreamSocket(entry);
213
292
  try { entry.req && entry.req.destroy(); } catch { /* ignore */ }
214
293
  }
215
294
  streams.clear();
216
295
  };
217
296
 
297
+ heartbeatTimer = setInterval(() => {
298
+ if (closed || revoking) return;
299
+ if (ws.readyState !== 1 || performance.now() - lastPong >= PONG_TIMEOUT_MS) {
300
+ cleanup();
301
+ try { ws.terminate(); } catch { /* 已关闭 */ }
302
+ return;
303
+ }
304
+ try { ws.ping(); } catch {
305
+ cleanup();
306
+ try { ws.terminate(); } catch { /* 已关闭 */ }
307
+ }
308
+ }, HEARTBEAT_INTERVAL_MS);
309
+ heartbeatTimer.unref?.();
310
+ ws.on('pong', () => { if (!closed) lastPong = performance.now(); });
311
+
312
+ identity.revoke = (response) => {
313
+ const socket = response?.socket;
314
+ const owner = socket && !socket.destroyed && [...streams].find(([, entry]) => {
315
+ const upstream = entry.activeUpstreamSocket;
316
+ return !entry.responseEnded && entry.req && !entry.req.destroyed && upstream && !upstream.destroyed
317
+ && upstream.localPort === socket.remotePort && upstream.remotePort === socket.localPort;
318
+ });
319
+ if (!owner) { ws.terminate(); return; }
320
+ revoking = true;
321
+ clearInterval(heartbeatTimer);
322
+ heartbeatTimer = null;
323
+ clearHeaderTimer(owner[1]);
324
+ gracefulId = owner[0];
325
+ response.__dshMuxDrained = new Promise(resolve => { finishDrain = resolve; });
326
+ closeTimer = setTimeout(() => { try { ws.terminate(); } catch { /* 已关闭 */ } }, REVOKE_DRAIN_TIMEOUT_MS);
327
+ closeTimer.unref?.();
328
+ for (const id of [...streams.keys()]) if (id !== gracefulId) dropStream(id);
329
+ };
330
+
218
331
  ws.on('message', (data, isBinary) => {
219
- if (isBinary) return; // 契约只走 JSON 文本帧
332
+ if (closed || isBinary) return; // 契约只走 JSON 文本帧
220
333
  const frame = safeJson(data.toString('utf8'));
221
334
  if (!frame) { onLog('mux: bad json frame'); return; }
222
335
  onFrame(frame);
@@ -225,7 +338,21 @@ function createMuxService(opts = {}) {
225
338
  ws.on('error', cleanup);
226
339
  }
227
340
 
228
- return { handleUpgrade, MAX_MESSAGE_BYTES };
341
+ const dropConnections = (deviceId, instanceId, response) => {
342
+ let count = 0;
343
+ for (const [ws, identity] of deviceConnections) {
344
+ if (instanceId !== undefined && identity.instanceId !== String(instanceId || '')) continue;
345
+ if (deviceId !== undefined && identity.deviceId !== deviceId) continue;
346
+ deviceConnections.delete(ws);
347
+ if (ws.readyState === 3) continue;
348
+ count += 1;
349
+ try { identity.revoke(response); } catch { ws.terminate(); }
350
+ }
351
+ return count;
352
+ };
353
+ const dropDevice = (deviceId, instanceId, response) => dropConnections(deviceId, instanceId, response);
354
+ const dropAll = (instanceId, response) => dropConnections(undefined, instanceId, response);
355
+ return { handleUpgrade, dropDevice, dropAll, MAX_MESSAGE_BYTES };
229
356
  }
230
357
 
231
- module.exports = { createMuxService, MAX_MESSAGE_BYTES, MAX_STREAMS_PER_CONNECTION, MAX_CONNECTIONS };
358
+ module.exports = { createMuxService, MAX_MESSAGE_BYTES, MAX_STREAMS_PER_CONNECTION, MAX_CONNECTIONS, REVOKE_DRAIN_TIMEOUT_MS };