dsh-mobile-plugin 0.5.91 → 0.5.92

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.
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ // 控制面不再按跨站来源拒绝:反代、公网域名、桌面壳自定义协议下都放行,只留转发与 method 守卫。
2
3
  // 移动请求异常通过插件日志记录方法、无查询串路径和堆栈,日志失败不影响原有 500 响应。
3
4
  // 设备能力和入口恢复只在请求信封验过之后记账。
4
5
 
@@ -54,36 +55,9 @@ const remoteRelayRequest = (req) => Boolean(
54
55
  || /(?:^|;\s*)dsh_(?:pair|lan)=/.test(String(req.headers.cookie || '')),
55
56
  )
56
57
 
57
- // Cross-site guard for the control plane.
58
- //
59
- // `localOnly` alone only rejected requests that carried relay routing
60
- // credentials, so a plain cross-site `GET /api/relay/revoke-all` from any page
61
- // the user had open still executed (the routes had no method check either).
62
- // Rejecting cross-site fetches and pinning each route to one method closes
63
- // that: a control-plane call now has to be a same-origin top-level/`same-origin`
64
- // request, and it has to use the documented verb.
65
- //
66
- // 只读页面(面板页)是唯一的例外,而且只放开「人点开的一页」这一种形态:社区桌面壳
67
- // 会把自己接住的链接原地打开,从自定义协议页跳到 `http://127.0.0.1:<端口>/api/relay/panel`
68
- // 时 Chromium 一定给 `sec-fetch-site: cross-site`(自定义协议与 http 不同源),
69
- // 按攻击挡掉,用户看到的就是整屏一句 403 JSON。判据换成 Fetch 元数据里的
70
- // `mode: navigate` + `dest: document`:别的网页最多能把用户带到这一页(只读 HTML),
71
- // 页面里偷偷发的 fetch/XHR 仍然 403。
72
- const documentNavigation = (req) => {
73
- const headers = req?.headers && typeof req.headers === 'object' ? req.headers : {}
74
- return String(headers['sec-fetch-mode'] || '').toLowerCase() === 'navigate'
75
- && String(headers['sec-fetch-dest'] || '').toLowerCase() === 'document'
76
- }
77
-
78
- const crossSiteRequest = (req, allowDocumentNavigation = false) => {
79
- if (allowDocumentNavigation === true && documentNavigation(req)) return false
80
- if (String(req.headers['sec-fetch-site'] || '').toLowerCase() === 'cross-site') return true
81
- const origin = req.headers.origin
82
- if (typeof origin !== 'string' || !origin) return false
83
- const host = req.headers.host
84
- if (typeof host !== 'string' || !host) return true
85
- try { return new URL(origin).host !== host } catch { return true }
86
- }
58
+ // 控制面不按「来源」拦截:跨站、反代改写了 Host、桌面壳自定义协议下都一样放行。
59
+ // 不管这台机器部署在哪儿(本机、局域网、公网域名、反代后面),控制面只认「谁转发的」
60
+ // 这一条,并钉住每个路由的 method —— 经中转 / 局域网代理转发来的仍按远程处理。
87
61
 
88
62
  // 本机界面与局域网界面各有来源范围;两者都要求 socket 与 Host 同属可信网络,
89
63
  // 并拒绝代理转发标记,不以客户端自带的来源头扩大信任。
@@ -132,12 +106,8 @@ const trustedLocalNetworkUi = (req) => trustedNetworkUi(req, isLocalNetworkAddre
132
106
 
133
107
  // `method` 可以是单个方法名,也可以是方法名数组(同一个路径上挂 GET+POST)。
134
108
  // 单方法时的 405 文案保持不变。
135
- //
136
- // `options.allowDocumentNavigation` 只给那几条「本来就是给人点开看」的只读页面用,
137
- // 其余路由不传,跨站照旧一律拒。
138
- const localOnly = (method, handler, options = {}) => async (req, res) => {
109
+ const localOnly = (method, handler) => async (req, res) => {
139
110
  if (remoteRelayRequest(req)) return sendJson(res, 403, { ok: false, error: { code: 'local_only', message: '控制面仅允许本机访问' } })
140
- if (crossSiteRequest(req, options.allowDocumentNavigation === true)) return sendJson(res, 403, { ok: false, error: { code: 'cross_site', message: '控制面拒绝跨站请求' } })
141
111
  const allowed = Array.isArray(method) ? method : [method]
142
112
  const actual = String(req.method || 'GET').toUpperCase()
143
113
  if (!allowed.includes(actual)) {
@@ -313,7 +283,6 @@ module.exports = {
313
283
  remoteRelayRequest,
314
284
  proxiedRequest,
315
285
  VIA_HEADER,
316
- crossSiteRequest,
317
286
  isLoopbackAddress,
318
287
  isLocalNetworkAddress,
319
288
  trustedLocalUi,
package/lib/impl.js CHANGED
@@ -370,6 +370,10 @@ function apply(ctx) {
370
370
  // getPort 依赖上面刚就位的 sidecar/advertisedLanPort,所以放在这里建。
371
371
  let controlHost = null
372
372
  try { controlHost = typeof ctx.get === 'function' ? ctx.get('dshMobileTransportControl') || null : null } catch { controlHost = null }
373
+ // 总控转达的「请自检」要回的那份诊断:实例在移动端路由表里造(同一份内容,不另算一套),
374
+ // 这里先留一个取值器,路由装好之后才接上。
375
+ let relayDiagnosticsOf = null
376
+ const controlDiagnostics = () => (typeof relayDiagnosticsOf === 'function' ? relayDiagnosticsOf() : null)
373
377
  const control = controlHost && controlHost.client ? controlHost.client : createControlClient({
374
378
  state,
375
379
  persist: () => core.saveState(state),
@@ -377,6 +381,7 @@ function apply(ctx) {
377
381
  getHistoryKey: () => core.ensureHistoryKey(state),
378
382
  getRelayConnected: () => relayConnectedOf(),
379
383
  getConnectedRelay: () => { const tunnel = sidecarLifecycle.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
384
+ getDiagnostics: controlDiagnostics,
380
385
  log: warn,
381
386
  onIdentityConflict: rotateNow,
382
387
  })
@@ -388,6 +393,7 @@ function apply(ctx) {
388
393
  getHistoryKey: () => core.ensureHistoryKey(state),
389
394
  getRelayConnected: () => relayConnectedOf(),
390
395
  getConnectedRelay: () => { const tunnel = sidecarLifecycle.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
396
+ getDiagnostics: controlDiagnostics,
391
397
  onIdentityConflict: rotateNow,
392
398
  })
393
399
  }
@@ -681,6 +687,8 @@ function apply(ctx) {
681
687
  // 核对的「路径 → handler」表,不用在 1000 行装配代码里翻。
682
688
  mount('移动端路由', () => registerMobileRoutes({
683
689
  registerRoute,
690
+ // 同一份诊断的第二个出口(总控转达的「请自检」):拿到实例就接到上面那个取值器上。
691
+ bindRelayControl: (handlers) => { relayDiagnosticsOf = handlers && typeof handlers.diagnostics === 'function' ? handlers.diagnostics : null },
684
692
  remoteComputers,
685
693
  // 直连隧道:已配对的手机走这条拿到自己的入口地址,不用重新扫码。
686
694
  tailcat,
@@ -798,7 +798,9 @@ function createRelayControlHandlers(deps) {
798
798
  }
799
799
 
800
800
  /**
801
- * `GET /api/mobile/v1/relay/diagnostics` —— 只读诊断:故障台账 + 地址候选的端口细节。
801
+ * 只读诊断:故障台账 + 地址候选的端口细节。两张嘴共用这一份 —— 手机上那条链路还通时走
802
+ * `GET /api/mobile/v1/relay/diagnostics`,连不上时由总控转达、经 `lib/relay/control.js`
803
+ * 的 `diagnostics` 出口回给手机。
802
804
  *
803
805
  * 隧道为什么断、局域网为什么没起来,答案在故障台账与端口自检这两处;两条一起给,
804
806
  * 手机上一页就能回答「这台到底怎么了」。
@@ -814,11 +816,10 @@ function createRelayControlHandlers(deps) {
814
816
  * 答不了「插件是哪一版、后台服务重启过几回、镜像还推不推得动」。
815
817
  * **仍然只读、仍然只进不出**:注册密钥、配对码、`lanSecret`、访问 token 一格都不出现。
816
818
  */
817
- async function handleRelayDiagnostics(_ctx, _req, res) {
818
- if (!wired) return unavailable(res);
819
+ function buildDiagnostics() {
819
820
  const snapshot = typeof status === 'function' ? status() : {};
820
821
  const text = (value) => (typeof value === 'string' ? value : '');
821
- sendJson(res, 200, {
822
+ return {
822
823
  ok: true,
823
824
  faults: faultsView(),
824
825
  /** 最近一次「按新配置重建隧道失败」的错误与时间(见上方说明)。 */
@@ -854,7 +855,12 @@ function createRelayControlHandlers(deps) {
854
855
  ok: snapshot?.mirror?.ok === undefined ? null : snapshot.mirror.ok === true,
855
856
  error: text(snapshot?.mirror?.error) || null,
856
857
  },
857
- });
858
+ };
859
+ }
860
+
861
+ async function handleRelayDiagnostics(_ctx, _req, res) {
862
+ if (!wired) return unavailable(res);
863
+ sendJson(res, 200, buildDiagnostics());
858
864
  }
859
865
 
860
866
  return {
@@ -869,6 +875,8 @@ function createRelayControlHandlers(deps) {
869
875
  handleRelayCheckPort,
870
876
  handleRelayProbe,
871
877
  handleRelayDiagnostics,
878
+ // 同一份诊断的第二个出口:总控转达的「请自检」(见 lib/relay/control.js)。
879
+ diagnostics: buildDiagnostics,
872
880
  };
873
881
  }
874
882
 
@@ -1,6 +1,7 @@
1
1
  // 首次入口就绪补连总控,更新收到回执后才标记已发布。
2
2
  // 加密上报真实可用地址,并用握手期限与协议心跳维护总控连接。
3
3
  // 2026-11-21:对外多给一份「此刻会报上去的明文清单」,供手机「立即同步」与总控那份逐条比对。
4
+ // 2026-11-22:收到总控转达的「请自检」就回一份诊断(同一份内容,见 mobile/relay-control.js)。
4
5
  'use strict';
5
6
 
6
7
  /**
@@ -17,6 +18,9 @@
17
18
  *
18
19
  * 地址没变就不发——链路平时是静的,只在地址变化时推一次。
19
20
  * 总控地址是内置常量,可用 `DSH_CONTROL_URL` 覆盖(本地联调用)。
21
+ *
22
+ * 另一件事:手机连不上插件时会请总控转一句「请自检」。插件收到就地把「这台电脑此刻怎么样」
23
+ * 封成答案回过去(scope `diagnose`,与地址那份分开)。总控只转达,不知道是谁问的。
20
24
  */
21
25
 
22
26
  const WebSocket = require('ws');
@@ -36,6 +40,8 @@ const CONTROL_BASE_URL = (process.env.DSH_CONTROL_URL || 'https://ai-hub.wnluo.c
36
40
  const HANDSHAKE_TIMEOUT_MS = 10_000;
37
41
  const HEARTBEAT_INTERVAL_MS = 15_000;
38
42
  const PONG_TIMEOUT_MS = 45_000;
43
+ /** 连着两次「请自检」的最小间隔:手机上连点两下别把同一份诊断翻两遍。 */
44
+ const DIAGNOSE_COOLDOWN_MS = 2_000;
39
45
 
40
46
  /** https→wss、http→ws。总控的 WebSocket 端点挂在同一前缀下。 */
41
47
  function controlWsUrl(base = CONTROL_BASE_URL) {
@@ -123,7 +129,7 @@ function controlMeta(state, connected = false, connectedRelay) {
123
129
  * @param {(msg: string, ...rest: any[]) => void} [deps.log]
124
130
  */
125
131
  function createControlClient(options = {}) {
126
- const { persist, getPort, getHistoryKey, getAddresses, getRelayConnected, getConnectedRelay, log = () => {}, onIdentityConflict = null } = options
132
+ const { persist, getPort, getHistoryKey, getAddresses, getRelayConnected, getConnectedRelay, getDiagnostics = null, log = () => {}, onIdentityConflict = null } = options
127
133
  // `getState` 让控制客户端读到**当前这一代**的状态(换代后状态对象会换一份):老的直接传
128
134
  // `state` 的用法保留为兜底,测试与旧调用方行为不变。
129
135
  const getState = typeof options.getState === 'function' ? options.getState : () => options.state
@@ -154,6 +160,8 @@ function createControlClient(options = {}) {
154
160
  let identityConflictStreak = 0;
155
161
  let lastIdentityConflictAt = 0;
156
162
  let identityConflictCooldownUntil = 0;
163
+ // 上一次回答「请自检」的时刻(见 DIAGNOSE_COOLDOWN_MS)。
164
+ let lastDiagnoseAt = 0;
157
165
  const IDENTITY_CONFLICT_THRESHOLD = 3;
158
166
  const IDENTITY_CONFLICT_WINDOW_MS = 60_000;
159
167
  const IDENTITY_CONFLICT_COOLDOWN_MS = 10 * 60_000;
@@ -231,6 +239,47 @@ function createControlClient(options = {}) {
231
239
  tick();
232
240
  }
233
241
 
242
+ /**
243
+ * 收到总控转达的「请自检」:把「这台电脑此刻怎么样」封成答案回过去。
244
+ *
245
+ * 内容与 `/relay/diagnostics` 是**同一份**(`getDiagnostics` 就是那个 handler 的实现),
246
+ * 另加两格只有这条路上才有意义的东西:总控这条腿自己(连着、发布过没有),以及此刻**会**
247
+ * 报上去的明文地址清单 —— 手机手上那份是不是旧的,一比对就知道。
248
+ *
249
+ * 封在 `diagnose` 这个 scope 下(地址那份是 `control`):总控解不开,也没法拿它去冒充地址。
250
+ */
251
+ function answerDiagnose() {
252
+ const now = Date.now();
253
+ if (now - lastDiagnoseAt < DIAGNOSE_COOLDOWN_MS) return;
254
+ lastDiagnoseAt = now;
255
+ const key = hk();
256
+ if (!key) return;
257
+ let diagnostics = null;
258
+ try {
259
+ diagnostics = typeof getDiagnostics === 'function' ? getDiagnostics() : null;
260
+ } catch (error) {
261
+ log('control: diagnostics failed', error && error.message);
262
+ }
263
+ const current = snapshot();
264
+ const plain = {
265
+ kind: 'diagnose',
266
+ at: now,
267
+ instanceId: getState().instanceId || '',
268
+ // 总控这条腿:手机能问进来,说明它此刻是通的。
269
+ control: { connected: current.connected, published: current.published },
270
+ reported: addresses(),
271
+ diagnostics: diagnostics || null,
272
+ };
273
+ let payload = '';
274
+ try {
275
+ payload = sealHistoryBlob(key, 'diagnose', getState().instanceId || '', plain);
276
+ } catch (error) {
277
+ log('control: diagnose seal failed', error && error.message);
278
+ return;
279
+ }
280
+ send({ type: 'answer', payload });
281
+ }
282
+
234
283
  function scheduleReconnect() {
235
284
  if (!running) return;
236
285
  attempt += 1;
@@ -350,6 +399,9 @@ function createControlClient(options = {}) {
350
399
  acknowledge();
351
400
  } else if (msg && msg.type === 'updated') {
352
401
  acknowledge();
402
+ } else if (msg && msg.type === 'ask') {
403
+ // 总控只转达,不说是谁问的;回一份诊断就够了,不回执、不重发。
404
+ answerDiagnose();
353
405
  } else if (msg && msg.type === 'error') {
354
406
  // 包括 unauthorized(同一 instanceId 被别处占了令牌、或令牌对不上):断开后按指数退避重连,
355
407
  // 不在 open 时清零,所以最多退到 30 秒一次,不会再每秒硬撞。
@@ -1,4 +1,5 @@
1
1
  'use strict';
2
+ // 2026-11-21:控制面不再按跨站来源拒绝,远程电脑管理只留 trustedLocalUi 这一条。
2
3
  // 远程电脑管理仅接受本机可信界面;电脑配对和加密升级由各自协议独立认证。
3
4
  // 桌面壳入口带专属标记,本机代理据此只给壳会话启用桌面端排版。
4
5
  // 2026-11-19:spawn 的异步失败(没有 pid 或收到 error)和 900ms 内闪退同等处理,回 shellOpened:false;
@@ -6,7 +7,7 @@
6
7
  // 2026-11-19:/mode 删掉静态档位白名单,存在性只由 controller.setMode → router.setMode 校验
7
8
  // (静态那份冗余且先过期,会把新通道挡在门外)。
8
9
  const { sendJson, readJsonBody } = require('../shared/http-util.js');
9
- const { trustedLocalUi, crossSiteRequest } = require('../http/routing.js');
10
+ const { trustedLocalUi } = require('../http/routing.js');
10
11
  const { launchShell, spawnFailed } = require('./shell.cjs');
11
12
  const { REMOTE_ERROR_TEXT, REMOTE_ERROR_FALLBACK } = require('./controller.cjs');
12
13
  const PREFIX = '/api/relay/remote-computers';
@@ -38,7 +39,7 @@ function createRemoteRoutes({ controller, host, credentials, instanceId, now = D
38
39
  function handler(suffix) {
39
40
  return async (req, res) => {
40
41
  res.setHeader('cache-control', 'no-store');
41
- if (!trustedLocalUi(req) || crossSiteRequest(req)) return sendJson(res, 403, {
42
+ if (!trustedLocalUi(req)) return sendJson(res, 403, {
42
43
  ok: false, error: { code: 'local_only', message: '请从本机 DSH 插件打开远程电脑管理' },
43
44
  });
44
45
  if (req.method !== METHODS[suffix]) return sendJson(res, 405, {
@@ -1,3 +1,4 @@
1
+ // 2026-11-21:控制面去掉跨站与只读来源拦截,按用户要求不再限制部署位置和访问来源。
1
2
  // 配对二维码在隧道窗口就绪后取当前状态,渲染完成前复核票据与身份。
2
3
  // 网络动作区分配置受理与真实连接,主动重连使用独立动作并保留探测总期限。
3
4
  // 注册本机控制面,并在吊销回执完成后关闭本实例在途连接。
@@ -7,11 +8,11 @@
7
8
  /**
8
9
  * 控制面路由(`/api/relay/*`):桌面设置页与宿主本机运维动作走这里。
9
10
  *
10
- * 控制面校验浏览器来源与网络范围,移动端校验 token;中转与移动端代理不能调用控制面。
11
+ * 控制面不校验来源(跨站也放行),只拦经中转 / 局域网代理转发来的请求与错误 method;移动端校验 token。
11
12
  * 依赖以取值器 / 函数注入、不捕获对象:闭包里那些 let(sidecar 等)会被整体替换,`getSidecar` 拿到实例就等于拿到旧 facade 快照。
12
13
  * 改中转地址与手机端写同一份配置、走同一条下发路径;「先登记迁移、再重建隧道」在 worker 的 configure 里(见 ../relay/migrate.js),这里只把失败原因如实带回面板。
13
14
  * 设备清单一条路径回两份内容(活着的设备 / 已解绑的历史),按 query 分叉:路径进了白名单与路由清单,为一次多带的内容再开一条要两处跟着动。
14
- * 配对与管理允许本机及标准局域网直连;公网两小时窗口仅放行只读面板。
15
+ * 配对与管理仍只允许本机及标准局域网直连;只读管理面不再限制来源,从哪儿打开都能进。
15
16
  * 桌面侧边栏两颗图标的显示开关写进同一份配置,只认布尔值;手机端配置口不收这两格。
16
17
  */
17
18
 
@@ -105,25 +106,21 @@ function createWebAccessWindow({ now = Date.now, monotonicNow = () => performanc
105
106
  };
106
107
  }
107
108
 
108
- function createWebAccessLocalOnly({ localOnly, trustedLocalUi, webAccessWindow, sendJson }) {
109
- return (method, handler, options) => localOnly(method, async (req, res) => {
109
+ function createWebAccessLocalOnly({ localOnly, trustedLocalUi, sendJson }) {
110
+ return (method, handler) => localOnly(method, async (req, res) => {
110
111
  const route = String(req?.url || '').split('?', 1)[0];
112
+ // 会改动本机状态 / 吐密钥的动作(配对、改配置、解绑、更新、重载实现等)仍只允许本机或
113
+ // 标准局域网直连。只读管理面(状态、地址、设备清单、面板页、faults 等)不再看来源:
114
+ // 不管用户从本机、局域网、公网域名还是反代后面打开,都能正常进入。
111
115
  const trusted = trustedLocalUi(req) || trustedLocalNetworkUi(req);
112
- // 本机与局域网直连都可配对和配置;公网窗口不扩大这些操作的来源范围。
113
116
  if (LOCAL_OPERATOR_ROUTES.has(route) && !trusted) {
114
117
  return sendJson(res, 403, {
115
118
  ok: false,
116
119
  error: { code: 'local_operator_only', message: '该操作会改动配对、中转、设备授权或插件更新,只允许从本机或局域网直连 DSH 执行' },
117
120
  });
118
121
  }
119
- if (WEB_ACCESS_ROUTES.has(route) && !trusted && !webAccessWindow.isOpen()) {
120
- return sendJson(res, 423, {
121
- ok: false,
122
- error: { code: 'web_access_closed', message: '网页管理暂未开放,请从 DSH 本机设置页开启 2 小时窗口' },
123
- });
124
- }
125
122
  return handler(req, res);
126
- }, options);
123
+ });
127
124
  }
128
125
 
129
126
  /**
@@ -386,7 +383,6 @@ function registerControlPlaneRoutes(deps) {
386
383
  const localOnly = createWebAccessLocalOnly({
387
384
  localOnly: baseLocalOnly,
388
385
  trustedLocalUi: typeof trustedLocalUi === 'function' ? trustedLocalUi : () => false,
389
- webAccessWindow,
390
386
  sendJson,
391
387
  });
392
388
 
@@ -702,18 +698,15 @@ function registerControlPlaneRoutes(deps) {
702
698
  process.stderr.write(`[dsh-mobile-plugin] panel unavailable (${diagnosis.reason}) ${PANEL_FILE}: ${diagnosis.message}\n`);
703
699
  return sendJson(res, 500, { ok: false, error: { code: 'panel_missing', reason: diagnosis.reason, message: diagnosis.message, path: PANEL_FILE } });
704
700
  };
705
- // 三条面板页是「人点开的一页」:社区桌面壳会把自己接住的链接原地打开,从自定义协议
706
- // 页跳过来必带 `sec-fetch-site: cross-site`,不放开这一种形态,用户看到的就是整屏
707
- // 一句 403 JSON(见 `lib/http/routing.js` 的 `documentNavigation`)。
708
- registerRoute({ kind: 'exact', path: '/api/relay/panel', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
709
- registerRoute({ kind: 'exact', path: '/api/relay/panel/setup', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
710
- registerRoute({ kind: 'exact', path: '/api/relay/panel/settings', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
701
+ // 几条面板页与别的控制面路由同一套守卫:只拦经中转 / 局域网代理转发来的请求、钉住 method;
702
+ // 不管页面是从本机、局域网、公网域名还是桌面壳自定义协议打开的,都照常出这一页。
703
+ registerRoute({ kind: 'exact', path: '/api/relay/panel', handler: localOnly('GET', async (req, res) => servePanel(req, res)) })
704
+ registerRoute({ kind: 'exact', path: '/api/relay/panel/setup', handler: localOnly('GET', async (req, res) => servePanel(req, res)) })
705
+ registerRoute({ kind: 'exact', path: '/api/relay/panel/settings', handler: localOnly('GET', async (req, res) => servePanel(req, res)) })
711
706
  // 控制台那一窗(点手机图标进来的第一屏)与上面几条吐同一份 HTML,分流同样在 React 侧。
712
- // 它同样放开 `allowDocumentNavigation`:入口就是桌面端弹的那一窗(同源 iframe)。
713
- registerRoute({ kind: 'exact', path: '/api/relay/panel/console', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
707
+ registerRoute({ kind: 'exact', path: '/api/relay/panel/console', handler: localOnly('GET', async (req, res) => servePanel(req, res)) })
714
708
  // 远程电脑独立页与上面几条吐同一份 HTML,分流在 React 侧(`Root.tsx` 认 `/remote`)。
715
- // 入口是桌面侧边栏那颗电脑图标弹的窗(同源 iframe),与控制台同一条 `allowDocumentNavigation` 理由。
716
- registerRoute({ kind: 'exact', path: '/api/relay/panel/remote', handler: localOnly('GET', async (req, res) => servePanel(req, res), { allowDocumentNavigation: true }) })
709
+ registerRoute({ kind: 'exact', path: '/api/relay/panel/remote', handler: localOnly('GET', async (req, res) => servePanel(req, res)) })
717
710
  // 手机端「已读回执」的下发口:客户端半边每 2s GET 一次,拿 sessionId → readAt 水位,
718
711
  // 对水位前进过的会话在桌面页面里就地清掉 completionUnread(见 lib/client.js)。
719
712
  // 台账由 /api/mobile/v1/session/read 写(lib/mobile/session-send.js)。
@@ -1335,6 +1328,7 @@ function registerControlPlaneRoutes(deps) {
1335
1328
  // 路由字符串清单放在注册区之后,避免被按路由源码切片的契约测试误认为是真正的 handler。
1336
1329
  /** 网页管理的固定开放窗口;按单调时钟计时,系统校时不会把窗口意外延长。 */
1337
1330
  const WEB_ACCESS_WINDOW_MS = 2 * 60 * 60 * 1000;
1331
+ // 只读管理面路由清单:来源限制已放开(从哪儿打开都能进),清单保留用于路由盘点与契约测试。
1338
1332
  const WEB_ACCESS_ROUTES = new Set([
1339
1333
  '/api/relay/addresses',
1340
1334
  '/api/relay/probe-relays',
@@ -173,6 +173,8 @@ function registerMobileRoutes(deps) {
173
173
  // 中转配置那一组要**装配期已有的实例**(config store、sidecar 生命周期),不能靠模块级
174
174
  // 单例去拿:同一进程里两份 relay.json 的真值只会打架。所以这里按装配层给的依赖建一次。
175
175
  const relayControl = createRelayControlHandlers(deps.relayControl || {})
176
+ // 总控那条「请自检」要读的是同一份诊断,所以把实例交回装配层,别在那边另算一套。
177
+ if (typeof deps.bindRelayControl === 'function') deps.bindRelayControl(relayControl)
176
178
 
177
179
  // 设备批量同步的两份状态:一次性券表只活在内存(进程重启即清),收件箱按实例落 `$DSH_HOME`。
178
180
  // 页面能挂几次本函数就建几份;配对那条要用同一份券表,所以在这里建好、同时交给下面两处。
@@ -61,6 +61,8 @@ export function installTransportHosts(ctx) {
61
61
  getConnectedRelay: () => { const tunnel = sidecarHost.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
62
62
  // 身份冲突时触发换身份的动作,由当前这一代注入(换代换它即可)。缺省不启用。
63
63
  onIdentityConflict: null,
64
+ // 总控转达的「请自检」要回的那份诊断,由当前这一代注入(同一份内容,见 relay-control)。
65
+ getDiagnostics: null,
64
66
  }
65
67
  const controlClient = createControlClient({
66
68
  getState: () => controlProviders.getState(),
@@ -69,6 +71,7 @@ export function installTransportHosts(ctx) {
69
71
  getHistoryKey: () => controlProviders.getHistoryKey(),
70
72
  getRelayConnected: () => controlProviders.getRelayConnected(),
71
73
  getConnectedRelay: () => controlProviders.getConnectedRelay(),
74
+ getDiagnostics: () => controlProviders.getDiagnostics(),
72
75
  log: warn,
73
76
  onIdentityConflict: (...args) => {
74
77
  const fn = controlProviders.onIdentityConflict
@@ -31,6 +31,67 @@ const HOIST_DIFF = /ERR_PNPM_PUBLIC_HOIST_PATTERN_DIFF|ERR_PNPM_VIRTUAL_STORE_DI
31
31
  /** 命令输出留多少字符(日志与错误信息里给个人看得懂的尾巴)。 */
32
32
  const OUTPUT_TAIL = 4000;
33
33
 
34
+ /** 等 profile 写锁的上限:DSH 的插件管理自己最长等 120 秒,这里不跟它比耐心,超时就让出这一轮。 */
35
+ const PROFILE_LOCK_WAIT_MS = 30 * 1000;
36
+
37
+ /** 锁记录里那个 `pid\n` 进程还在不在;认不出来的一律当「活着」,不抢。 */
38
+ function holderProcessExited(record) {
39
+ if (!/^\d+\n$/.test(record)) return false;
40
+ const pid = Number(record.trim());
41
+ if (pid === 0 || pid > 0x7fffffff) return false;
42
+ if (pid === process.pid) return false;
43
+ try {
44
+ process.kill(pid, 0);
45
+ return false;
46
+ } catch (error) {
47
+ return error.code === 'ESRCH';
48
+ }
49
+ }
50
+
51
+ /**
52
+ * 拿 profile 的包写锁再干活,和 DSH 插件管理抢**同一个锁文件**(`<profile>/package.json.lock`)。
53
+ *
54
+ * 本插件自己会跑 `pnpm add` 换包,DSH 的插件管理在更新/卸载时也会跑。两边同时改同一个 profile,
55
+ * 轻则锁文件、依赖目录装坏,重则插件起不来、手机断连。DSH 那边已经用这个 `<package.json>.lock`
56
+ * 串行化它所有的包操作;我们抢同一把锁就自然和它排上队 —— 不用它配合,也不用它知道我们。
57
+ * 抢不到就认输(抛 `PROFILE_BUSY`),绝不硬装。
58
+ *
59
+ * 锁的格式和 @deepseek-ai/dsh-atomic-write 的 withFileLock 一致:`wx` 建同名 `.lock`、写入持有者
60
+ * pid;持有者进程没了(`ESRCH`)就清掉残留锁重来,免得一次崩溃把自动更新永久卡死。pid 只在本机
61
+ * 可比,跨机共享同一个 profile 不在支持范围。
62
+ */
63
+ async function withProfileLock(profileDir, operation, { waitMs = PROFILE_LOCK_WAIT_MS } = {}) {
64
+ const lockPath = path.join(profileDir, 'package.json.lock');
65
+ const deadline = Date.now() + waitMs;
66
+ let delay = 20;
67
+ for (;;) {
68
+ try {
69
+ fs.writeFileSync(lockPath, `${process.pid}\n`, { flag: 'wx', mode: 0o600 });
70
+ break;
71
+ } catch (error) {
72
+ if (!error || (error.code !== 'EEXIST' && error.code !== 'EPERM')) throw error;
73
+ let record = null;
74
+ try { record = fs.readFileSync(lockPath, 'utf8'); } catch { /* 刚被释放,下一轮再抢 */ }
75
+ if (record !== null && holderProcessExited(record)) {
76
+ try { fs.rmSync(lockPath, { force: true }); } catch { /* 别人也在清,下一轮再抢 */ }
77
+ continue;
78
+ }
79
+ if (Date.now() >= deadline) {
80
+ const busy = new Error('profile 的包目录正被另一个安装/卸载操作占用(可能 DSH 正在装别的插件),这次先不动盘,稍后再试。');
81
+ busy.code = 'PROFILE_BUSY';
82
+ throw busy;
83
+ }
84
+ await new Promise(resolve => setTimeout(resolve, delay));
85
+ delay = Math.min(delay * 2, 200);
86
+ }
87
+ }
88
+ try {
89
+ return await operation();
90
+ } finally {
91
+ try { fs.rmSync(lockPath, { force: true }); } catch { /* 释放失败不掩盖真正的结果 */ }
92
+ }
93
+ }
94
+
34
95
  /**
35
96
  * 去哪儿找包管理器。
36
97
  *
@@ -702,6 +763,9 @@ async function installLatest({
702
763
  );
703
764
  }
704
765
 
766
+ // 真正会改盘的一段(备份 → pnpm add → 核对/回滚 → 登记排除清单)整体在 profile 写锁里跑,
767
+ // 和 DSH 插件管理的装卸操作排同一队,避免两边同时改坏同一份依赖树。
768
+ const performInstall = async () => {
705
769
  const previousComplete = beforeVersion !== null && installationProblem(profileNodeModules, name, beforeVersion) === null;
706
770
  // 备份正在跑的那一代:包的活就落在下面那一行 spawn 上,它一跑旧目录就没了。
707
771
  // 备份失败不该挡住更新(那是多一层保险),所以这里吞掉它的异常,由调用方记日志。
@@ -827,6 +891,28 @@ async function installLatest({
827
891
  message: withReason(`${command} 跑完了,但盘上还是 ${after ?? '读不到版本'},这一次不算数`, output),
828
892
  },
829
893
  };
894
+ };
895
+
896
+ try {
897
+ return await withProfileLock(profileDir, performInstall);
898
+ } catch (error) {
899
+ if (error && error.code === 'PROFILE_BUSY') {
900
+ // 「现在不行」,不是坏了:DSH 的插件管理正握着锁在装/卸别的插件。一行都不写盘,下个 tick 再来。
901
+ return {
902
+ installed: false,
903
+ skipped: true,
904
+ retryable: true,
905
+ beforeVersion,
906
+ installedVersion: beforeVersion,
907
+ source: declaredSource(profileDir, name),
908
+ command: null,
909
+ output: '',
910
+ detail: error.message,
911
+ failure: null,
912
+ };
913
+ }
914
+ throw error;
915
+ }
830
916
  }
831
917
 
832
918
  /**
@@ -967,4 +1053,6 @@ module.exports = {
967
1053
  DEFAULT_NAME,
968
1054
  INSTALL_TIMEOUT_MS,
969
1055
  OUTPUT_TAIL,
1056
+ // profile 写锁单测直接打它:验「拿不到锁就让路、拿到就串行」,比隔着整条安装链路更快更稳。
1057
+ withProfileLock,
970
1058
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.91",
3
+ "version": "0.5.92",
4
4
  "description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
5
5
  "license": "MIT",
6
6
  "icon": "./icon.png",