dsh-mobile-plugin 0.5.54 → 0.5.55

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,4 @@
1
- /** 远程网页的只读租期提示与主文档流式脚本注入。 */
1
+ /** 远程网页的只读租期提示、桌面壳的排版适配与主文档流式脚本注入。 */
2
2
  'use strict';
3
3
 
4
4
  const { Transform } = require('node:stream');
@@ -82,8 +82,112 @@ function browserNotice(text) {
82
82
  void poll();
83
83
  }
84
84
 
85
- function noticeScript() {
86
- return `(${browserNotice.toString()})(${JSON.stringify(TEXT)});`;
85
+ /**
86
+ * Mac 桌面壳的排版样式。官方把长相挂在 [data-platform='darwin'] 这个祖先记号上,
87
+ * 把「这是桌面端、去找宿主键盘桥」挂在根元素上的同名记号上。壳的记号只打在页面
88
+ * 主体,根元素保持网页版,服务照常按网页运行时启动。这里按官方原值补齐少数几条
89
+ * 只认根元素的规则,并给侧栏首行留出红黄绿按钮的位置:网页版不渲染官方那条
90
+ * 52px 让位带,折抵成 40px 上边距。全屏时按钮隐藏,让位跟着收掉。
91
+ */
92
+ const SHELL_CSS = `
93
+ html[data-dshm-shell] {
94
+ --dsh-frame-top-clearance: 48px;
95
+ --dsh-frame-overlay-top: calc(var(--dsh-frame-top-clearance) + 20px);
96
+ }
97
+ html[data-dshm-shell][data-fullscreen] {
98
+ --dsh-frame-overlay-top: 20px;
99
+ --dsh-frame-chrome-top: 0px;
100
+ }
101
+ html[data-dshm-shell], html[data-dshm-shell] body { background: transparent; }
102
+ html[data-dshm-shell] body { isolation: isolate; }
103
+ /* 官方侧栏底色是半透明、靠系统毛玻璃透出桌面;Tauri 这层毛玻璃没生效,透明下会直接
104
+ 透出壁纸,空着的顶部让位就成了一道浅带。这里把侧栏底色改成实色,整块和顶栏一致。 */
105
+ html[data-dshm-shell] body[data-platform='darwin'] {
106
+ --dsw-specific-menu: rgba(248, 249, 250, 0.94);
107
+ --dsw-specific-sidebar-glass-collapsed-fill: transparent;
108
+ --dsw-specific-sidebar-glass-collapsed-hover: var(--dsw-alias-interactive-bg-hover);
109
+ --dsw-specific-sidebar-glass-fill: rgb(255 255 255 / 0.55);
110
+ --dsw-specific-sidebar-glass-hover: rgb(255 255 255 / 0.3);
111
+ --dsw-specific-sidebar-tint: var(--dsw-specific-sidebar-fill);
112
+ --dsw-specific-sidebar-wash-bottom: transparent;
113
+ --dsw-specific-sidebar-wash-bottom-clear: transparent;
114
+ --dsw-specific-sidebar-wash-top: transparent;
115
+ --dsw-specific-sidebar-wash-top-clear: transparent;
116
+ }
117
+ html[data-dshm-shell] body[data-platform='darwin'][data-ds-dark-theme] {
118
+ --dsw-specific-menu: rgba(48, 49, 54, 0.94);
119
+ --dsw-specific-sidebar-glass-collapsed-fill: var(--dsw-specific-sidebar-glass-fill);
120
+ --dsw-specific-sidebar-glass-collapsed-hover: var(--dsw-specific-sidebar-glass-hover);
121
+ --dsw-specific-sidebar-glass-fill: rgb(255 255 255 / 0.15);
122
+ --dsw-specific-sidebar-glass-hover: rgb(255 255 255 / 0.2);
123
+ --dsw-specific-sidebar-tint: var(--dsw-specific-sidebar-fill);
124
+ }
125
+ /* 顶栏:把红黄绿让位做进侧栏顶部实底里,按钮嵌进侧栏、折叠键回到按钮同一行。 */
126
+ html[data-dshm-shell] [data-window-drag]:has([data-sidebar-toggle]) {
127
+ position: relative;
128
+ margin: -6px -8px 0;
129
+ padding: 44px 12px 8px;
130
+ height: auto;
131
+ overflow: visible;
132
+ box-sizing: border-box;
133
+ }
134
+ html[data-dshm-shell] [data-window-drag]:has([data-sidebar-toggle]) > [data-sidebar-toggle] {
135
+ position: absolute;
136
+ top: 10px;
137
+ right: 12px;
138
+ }
139
+ html[data-dshm-shell][data-fullscreen] [data-window-drag]:has([data-sidebar-toggle]) {
140
+ padding-top: 8px;
141
+ }
142
+ html[data-dshm-shell] body[data-platform='darwin'] [data-sidebar-collapsed]:not([data-sidebar-drawer]) {
143
+ --dsh-frame-leading-clearance: 0px;
144
+ }
145
+ `;
146
+
147
+ /**
148
+ * 桌面壳会话:只在页面主体打开官方的 Mac 排版,把网页自带的拖动标记翻成 Tauri 认的说法。
149
+ * Tauri 的 deep 覆盖整块子树、自动放过按钮,官方标了不许拖的那一支用 false 挡住;
150
+ * 页面切换时会增删这些元素,跟着同步。
151
+ */
152
+ function browserShell(css) {
153
+ const root = document.documentElement;
154
+ if (root.dataset.dshmShell === '1') return;
155
+ root.dataset.dshmShell = '1';
156
+ document.body.dataset.platform = 'darwin';
157
+ const style = document.createElement('style');
158
+ style.textContent = css;
159
+ document.head.appendChild(style);
160
+ const MARK = 'data-tauri-drag-region';
161
+ let scheduled = false;
162
+ const observer = new MutationObserver(() => {
163
+ if (scheduled) return;
164
+ scheduled = true;
165
+ const frame = window.requestAnimationFrame || window.setTimeout;
166
+ frame.call(window, () => {
167
+ scheduled = false;
168
+ observer.disconnect();
169
+ sync();
170
+ observer.observe(document.body, { subtree: true, childList: true, attributes: true });
171
+ });
172
+ });
173
+ function sync() {
174
+ for (const row of document.querySelectorAll('[data-window-drag]')) {
175
+ if (row.getAttribute(MARK) !== 'deep') row.setAttribute(MARK, 'deep');
176
+ }
177
+ for (const blocked of document.querySelectorAll('[data-window-drag-exclude],[data-window-drag-recall]')) {
178
+ if (blocked.getAttribute(MARK) !== 'false') blocked.setAttribute(MARK, 'false');
179
+ }
180
+ }
181
+ sync();
182
+ observer.observe(document.body, { subtree: true, childList: true, attributes: true });
183
+ }
184
+
185
+ function shellScript(platform) {
186
+ return platform === 'darwin' ? `(${browserShell.toString()})(${JSON.stringify(SHELL_CSS)});` : '';
187
+ }
188
+
189
+ function noticeScript({ shell = false, platform = '' } = {}) {
190
+ return `${shell ? shellScript(platform) : ''}(${browserNotice.toString()})(${JSON.stringify(TEXT)});`;
87
191
  }
88
192
 
89
193
  /** 仅保留开头少量字节定位 head;剩余文档直接透传,保留字节与背压。 */
@@ -115,4 +219,4 @@ function createNoticeTransform() {
115
219
  });
116
220
  }
117
221
 
118
- module.exports = { noticeScript, createNoticeTransform };
222
+ module.exports = { noticeScript, shellScript, createNoticeTransform };
@@ -1,5 +1,6 @@
1
1
  // 只监听本机的远程网页入口:一次性打开链接、访问租期与按窗口自动续期。
2
2
  // 每台网关各管各的租期;续期只延长期限,不重发入口地址、不动已建立的连接。
3
+ // 壳会话另发一枚只读标记:只给桌面窗口启用官方自带的让位与拖动排版。
3
4
  'use strict';
4
5
 
5
6
  const http = require('node:http');
@@ -17,9 +18,10 @@ const RENEW_CHECK_MS = 30 * 1000;
17
18
  const ATTACH_GRACE_MS = 4 * 1000;
18
19
  const OPEN_PATH = '/__dsh_remote_open';
19
20
 
20
- function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = () => {}, onError, onRenew = () => {} }) {
21
+ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = () => {}, onError, onRenew = () => {}, platform = process.platform }) {
21
22
  const live = new Set();
22
23
  const cookieName = `dsh_remote_${crypto.randomBytes(12).toString('hex')}`;
24
+ const shellCookie = `${cookieName}_shell`;
23
25
  const session = crypto.randomBytes(32).toString('base64url');
24
26
  let ticket = crypto.randomBytes(32).toString('base64url');
25
27
  let ticketExpiresAt = now() + OPEN_MS;
@@ -72,8 +74,11 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
72
74
  const value = url.searchParams.get('ticket');
73
75
  if (req.method !== 'GET' || !ticket || now() >= ticketExpiresAt || value !== ticket) return reply(res, 403, '打开链接已失效,请在本机面板重新打开。');
74
76
  ticket = '';
77
+ const cookies = [`${cookieName}=${session}; Path=/; HttpOnly; SameSite=Strict`];
78
+ // 只有从桌面壳打开的那一次入口带它;同一个入口用普通浏览器打开时保持网页版。
79
+ if (url.searchParams.get('shell') === '1') cookies.push(`${shellCookie}=1; Path=/; HttpOnly; SameSite=Strict`);
75
80
  res.writeHead(303, {
76
- location: '/', 'set-cookie': `${cookieName}=${session}; Path=/; HttpOnly; SameSite=Strict`,
81
+ location: '/', 'set-cookie': cookies,
77
82
  'cache-control': 'no-store', 'referrer-policy': 'no-referrer',
78
83
  });
79
84
  res.end(); return;
@@ -84,7 +89,9 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
84
89
  if (req.method !== 'GET') return reply(res, 405, '只读入口。');
85
90
  const status = url.pathname === '/__dsh_remote_status';
86
91
  res.writeHead(200, { 'content-type': status ? 'application/json; charset=utf-8' : 'application/javascript; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
87
- res.end(status ? JSON.stringify({ expiresAt: deadline, serverNow: now() }) : noticeScript()); return;
92
+ if (status) { res.end(JSON.stringify({ expiresAt: deadline, serverNow: now() })); return; }
93
+ const shell = cookieOf(req.headers.cookie, shellCookie) === '1';
94
+ res.end(noticeScript({ shell, platform })); return;
88
95
  }
89
96
  req.url = path;
90
97
  void upstream.forward(req, res);
@@ -1,4 +1,6 @@
1
1
  // 每台电脑独立选路:实测排序、失败退避与身份验证。
2
+ // 连接预算不写死:升级阶段按该线路的实测耗时(没有就用宽松默认)给上限,握手期间只要还在
3
+ // 收到消息就继续等;失败只影响先试谁,不缩短愿意等的时间。
2
4
  'use strict';
3
5
 
4
6
  const { createRoutePolicy } = require('../shared/route-order.cjs');
@@ -77,27 +79,50 @@ function createRemoteRouter({ binding, transport, tunnels, now = Date.now, onErr
77
79
  return work;
78
80
  }
79
81
 
80
- async function timed(operation, timeoutMs, late) {
81
- let timer;
82
- let elapsed = false;
82
+ // 只负责取消,不再自己卡一个总时限:超时交给 transport 的两段式判定(升级上限 + 握手沉默窗口)。
83
+ // 取消(关停 / 换网)时也要把自定义 transport 里挂住的 Promise 一并拒掉,晚到的结果回收掉。
84
+ async function timed(operation) {
83
85
  const abort = new AbortController();
84
86
  pending.add(abort);
87
+ let settled = false;
85
88
  const result = Promise.resolve().then(() => operation(abort.signal));
86
- result.then((value) => { if (elapsed) late?.(value); }, () => {});
89
+ result.then((value) => { if (abort.signal.aborted) value?.stream?.destroy(); }, () => {});
90
+ const cancelled = new Promise((_resolve, reject) => {
91
+ abort.signal.addEventListener('abort', () => {
92
+ if (!settled) reject(Object.assign(new Error('远程连接已取消'), { code: 'REMOTE_CONNECT' }));
93
+ }, { once: true });
94
+ });
87
95
  try {
88
- return await Promise.race([result, new Promise((_resolve, reject) => {
89
- const cancel = () => { elapsed = true; reject(Object.assign(new Error('远程连接已取消'), { code: 'REMOTE_CONNECT' })); };
90
- abort.signal.addEventListener('abort', cancel, { once: true });
91
- timer = setTimeout(() => { elapsed = true; reject(Object.assign(new Error('远程连接超时'), { code: 'REMOTE_TIMEOUT' })); abort.abort(); }, timeoutMs);
92
- timer.unref?.();
93
- })]);
94
- } finally { clearTimeout(timer); pending.delete(abort); }
96
+ return await Promise.race([result, cancelled]);
97
+ } finally {
98
+ settled = true;
99
+ pending.delete(abort);
100
+ }
95
101
  }
96
102
 
97
- function budget(route) {
98
- const item = account(route);
99
- if (['tunnel', 'p2p'].includes(route.channel)) return item.failures ? 4000 : 10000;
100
- return (!item.proven && route.channel !== 'relay') || item.failures ? 2500 : 7000;
103
+ const DEFAULT_CONNECT_MS = 10_000;
104
+ const MIN_CONNECT_MS = 4_000;
105
+ const MAX_CONNECT_MS = 30_000;
106
+ const DEFAULT_IDLE_MS = 10_000;
107
+ const MIN_IDLE_MS = 6_000;
108
+ const MAX_IDLE_MS = 45_000;
109
+
110
+ /** 升级阶段的上限:有实测握手耗时就在它上面加余量;没有就按线路类型给宽松默认。 */
111
+ function connectBudget(route) {
112
+ const measured = policy.routeLatencyOf(route.url);
113
+ if (typeof measured === 'number' && Number.isFinite(measured) && measured >= 0) {
114
+ return Math.min(MAX_CONNECT_MS, Math.max(MIN_CONNECT_MS, Math.round(measured + 5_000)));
115
+ }
116
+ return ['tunnel', 'p2p'].includes(route.channel) ? 15_000 : DEFAULT_CONNECT_MS;
117
+ }
118
+
119
+ /** 握手期间允许的沉默时长:有实测就跟着放大,没有给一个宽松默认。 */
120
+ function idleBudget(route) {
121
+ const measured = policy.routeLatencyOf(route.url);
122
+ if (typeof measured === 'number' && Number.isFinite(measured) && measured >= 0) {
123
+ return Math.min(MAX_IDLE_MS, Math.max(MIN_IDLE_MS, Math.round(measured + 5_000)));
124
+ }
125
+ return DEFAULT_IDLE_MS;
101
126
  }
102
127
 
103
128
  async function open({ expiresAt } = {}) {
@@ -109,9 +134,11 @@ function createRemoteRouter({ binding, transport, tunnels, now = Date.now, onErr
109
134
  for (const route of ordered()) {
110
135
  if (closed) throw Object.assign(new Error('远程连接已停止'), { code: 'REMOTE_CONNECT' });
111
136
  if (expiresAt && now() >= expiresAt) throw Object.assign(new Error('访问已到期'), { code: 'REMOTE_EXPIRED' });
112
- const timeoutMs = Math.max(1, Math.min(budget(route), expiresAt ? expiresAt - now() : Infinity));
137
+ const remaining = expiresAt ? Math.max(1, expiresAt - now()) : Infinity;
138
+ const connectTimeoutMs = Math.min(connectBudget(route), remaining);
139
+ const idleTimeoutMs = Math.min(idleBudget(route), remaining);
113
140
  try {
114
- const result = await timed((signal) => transport.openRemoteStream(binding, route, { timeoutMs, expiresAt, signal, onConnectionInfo: connectionInfo }), timeoutMs, (value) => value?.stream?.destroy());
141
+ const result = await timed((signal) => transport.openRemoteStream(binding, route, { connectTimeoutMs, idleTimeoutMs, expiresAt, signal, onConnectionInfo: connectionInfo }));
115
142
  if (closed || (expiresAt && now() >= expiresAt)) { result.stream.destroy(); throw Object.assign(new Error('访问已到期'), { code: 'REMOTE_EXPIRED' }); }
116
143
  selected = route; proven(route);
117
144
  await connectionInfo(result.host?.connectionInfo).catch(() => {});
@@ -144,9 +171,10 @@ function createRemoteRouter({ binding, transport, tunnels, now = Date.now, onErr
144
171
  const worker = async () => {
145
172
  while (!closed && ticket === generation && index < queue.length && !fatal) {
146
173
  const route = queue[index++];
147
- const timeoutMs = budget(route);
174
+ const connectTimeoutMs = connectBudget(route);
175
+ const idleTimeoutMs = idleBudget(route);
148
176
  try {
149
- const ms = await timed((signal) => transport.probeRemote(binding, route, { timeoutMs, signal, onConnectionInfo: connectionInfo }), timeoutMs);
177
+ const ms = await timed((signal) => transport.probeRemote(binding, route, { connectTimeoutMs, idleTimeoutMs, signal, onConnectionInfo: connectionInfo }));
150
178
  if (closed || ticket !== generation) return;
151
179
  if (typeof ms !== 'number' || !Number.isFinite(ms) || ms < 0) throw new Error('远程探测没有返回延迟');
152
180
  policy.noteRouteLatency(route.url, ms); proven(route); successes += 1;
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
  // 远程电脑管理仅接受本机可信界面;电脑配对和加密升级由各自协议独立认证。
3
+ // 桌面壳入口带专属标记,本机代理据此只给壳会话启用桌面端排版。
3
4
  const { sendJson, readJsonBody } = require('../shared/http-util.js');
4
5
  const { trustedLocalUi, crossSiteRequest } = require('../http/routing.js');
5
6
  const { launchShell } = require('./shell.cjs');
@@ -13,7 +14,7 @@ const PUBLIC_ERRORS = {
13
14
  REMOTE_CONNECT: '暂时无法连接远程电脑,请检查网络和对方是否在线',
14
15
  SHELL_UNAVAILABLE: '本机未安装远程电脑桌面端,请改用默认方式打开',
15
16
  };
16
- function createRemoteRoutes({ controller, host, credentials, instanceId, now = Date.now }) {
17
+ function createRemoteRoutes({ controller, host, credentials, instanceId, now = Date.now, launch = launchShell }) {
17
18
  function authorizedComputers() {
18
19
  return credentials.listRemoteComputers(instanceId);
19
20
  }
@@ -55,8 +56,11 @@ function createRemoteRoutes({ controller, host, credentials, instanceId, now = D
55
56
  const result = await controller.open(body.id);
56
57
  const devices = await controller.list();
57
58
  const deviceName = devices.find(row => row.id === body.id)?.name || '';
59
+ // 壳入口带专属标记,本机代理据此只给壳会话启用桌面端排版。
60
+ const shellUrl = new URL(result.url);
61
+ shellUrl.searchParams.set('shell', '1');
58
62
  // 记下这次拉起的桌面进程:它一退出就当窗口关掉,面板据此回到未打开。
59
- const child = launchShell({ url: result.url, deviceName });
63
+ const child = launch({ url: shellUrl.href, deviceName });
60
64
  controller.watchWindow(body.id, child);
61
65
  return sendJson(res, 200, { ok: true, ...result });
62
66
  }
@@ -1,4 +1,6 @@
1
1
  // 远程电脑邀请客户端与经端到端身份验证的加密字节通道。
2
+ // 握手超时按「有没有进展」判:升级阶段给一个上限,升级后每收到一条消息就重置沉默窗口,
3
+ // 慢网只要还在往前推就一直等,只有彻底没声音的线路才会被判死。
2
4
  'use strict';
3
5
 
4
6
  const http = require('node:http');
@@ -89,6 +91,14 @@ function openRemoteStream(binding, route, options = {}) {
89
91
  let stage = 'welcome';
90
92
  let settled = false;
91
93
  let timer;
94
+ const connectWindow = Math.max(1, Number(options.connectTimeoutMs) || Number(options.timeoutMs) || 10_000);
95
+ const idleWindow = Math.max(1, Number(options.idleTimeoutMs) || connectWindow);
96
+ // 定时器不是「总时限」:升级阶段给 connectWindow,之后每收到一条消息就重置成 idleWindow。
97
+ const arm = (ms) => {
98
+ clearTimeout(timer);
99
+ timer = setTimeout(() => fail(c.error('REMOTE_TIMEOUT', 'Computer connection timed out')), Math.max(1, Math.round(ms)));
100
+ timer.unref?.();
101
+ };
92
102
  const abort = () => fail(c.error('REMOTE_CONNECT', 'Computer connection cancelled'));
93
103
  const fail = (err) => {
94
104
  if (settled) return;
@@ -105,10 +115,11 @@ function openRemoteStream(binding, route, options = {}) {
105
115
  if (!binding.credential || !binding.instanceId || !/^[0-9a-f]{16}$/.test(binding.keyId)) throw c.error('REMOTE_AUTH');
106
116
  if (options.expiresAt && options.expiresAt <= Date.now()) throw c.error('REMOTE_EXPIRED');
107
117
  const context = { instanceId: binding.instanceId, keyId: binding.keyId, clientNonce: c.random() };
108
- ws = new WebSocket(c.endpoint(route, TUNNEL_PATH, true), { perMessageDeflate: false, maxPayload: c.MAX_MESSAGE, handshakeTimeout: options.timeoutMs || 10_000, headers: { 'x-dsh-instance': binding.instanceId } });
109
- timer = setTimeout(() => fail(c.error('REMOTE_TIMEOUT', 'Computer connection timed out')), options.timeoutMs || 10_000);
110
- timer.unref?.();
118
+ ws = new WebSocket(c.endpoint(route, TUNNEL_PATH, true), { perMessageDeflate: false, maxPayload: c.MAX_MESSAGE, handshakeTimeout: connectWindow, headers: { 'x-dsh-instance': binding.instanceId } });
119
+ arm(connectWindow);
111
120
  const receive = (data, binary) => {
121
+ // 收到任何一条协议消息都算「这条线还活着」,把沉默窗口从头计时。
122
+ arm(idleWindow);
112
123
  try {
113
124
  const message = c.parseMessage(data, binary);
114
125
  if (stage === 'welcome' && message.type === 'welcome') {
@@ -164,6 +175,8 @@ function openRemoteStream(binding, route, options = {}) {
164
175
  } catch (err) { fail(err); }
165
176
  };
166
177
  ws.on('message', receive);
178
+ // 升级完成即进入「沉默才算死」阶段;此后的握手步骤只要在推进就继续等。
179
+ ws.on('open', () => arm(idleWindow));
167
180
  ws.on('error', () => fail(c.error('REMOTE_CONNECT', 'Computer connection failed')));
168
181
  ws.on('close', () => fail(c.error('REMOTE_CONNECT', 'Computer connection closed')));
169
182
  } catch (err) { fail(err); }
@@ -7,6 +7,7 @@
7
7
  * 依赖以取值器 / 函数注入、不捕获对象:闭包里那些 let(sidecar 等)会被整体替换,`getSidecar` 拿到实例就等于拿到旧 facade 快照。
8
8
  * 改中转地址与手机端写同一份配置、走同一条下发路径;「先登记迁移、再重建隧道」在 worker 的 configure 里(见 ../relay/migrate.js),这里只把失败原因如实带回面板。
9
9
  * 设备清单一条路径回两份内容(活着的设备 / 已解绑的历史),按 query 分叉:路径进了白名单与路由清单,为一次多带的内容再开一条要两处跟着动。
10
+ * 危险动作(配对码、改配置、吊销设备、装更新等,见 LOCAL_OPERATOR_ROUTES)额外只认**真正来自本机**的请求:两小时窗口只放行只读面板,不放行这些会改本机状态或泄露密钥的动作。
10
11
  */
11
12
 
12
13
  const fs = require('node:fs');
@@ -85,6 +86,15 @@ function createWebAccessWindow({ now = Date.now, monotonicNow = () => performanc
85
86
  function createWebAccessLocalOnly({ localOnly, trustedLocalUi, webAccessWindow, sendJson }) {
86
87
  return (method, handler, options) => localOnly(method, async (req, res) => {
87
88
  const route = String(req?.url || '').split('?', 1)[0];
89
+ // 危险动作只认真实本机来源:窗口开着也不行。判据沿用「本机界面」那一把(socket 回环、
90
+ // Host 是回环、无转发头),桌面端经 forwardWebRequest 从回环转进来、本机浏览器、SSH 隧道
91
+ // 都算本机,不受影响;只有网络上别的机器(或经代理转发的)被挡。
92
+ if (LOCAL_OPERATOR_ROUTES.has(route) && !trustedLocalUi(req)) {
93
+ return sendJson(res, 403, {
94
+ ok: false,
95
+ error: { code: 'local_operator_only', message: '该操作会改动本机的配对、中转、设备授权或插件更新,只允许在本机 DSH 上执行' },
96
+ });
97
+ }
88
98
  if (WEB_ACCESS_ROUTES.has(route) && !trustedLocalUi(req) && !webAccessWindow.isOpen()) {
89
99
  return sendJson(res, 423, {
90
100
  ok: false,
@@ -1238,8 +1248,8 @@ const WEB_ACCESS_ROUTES = new Set([
1238
1248
  // 控制台那一窗:与上面几条同一张管理面,漏了就等于远程浏览器能绕过窗口读它。
1239
1249
  '/api/relay/panel/console',
1240
1250
  '/api/relay/faults',
1241
- // 配对二维码:里面是能派生整条链路密钥的一次性票据,所以它只在两小时窗口开着时给网页看
1242
- // ——窗口由本机设置页亲手开,服务器部署没有「本机屏幕」可看,这条是它唯一的出口。
1251
+ // 配对二维码:里面是能派生整条链路密钥的一次性票据。它同时也在 LOCAL_OPERATOR_ROUTES 里,
1252
+ // 所以只认真实本机来源——放窗口白名单里只为让本机面板的窗口语义统一,远程开窗也拿不到。
1243
1253
  '/api/relay/pairing',
1244
1254
  '/api/relay/toggle',
1245
1255
  '/api/relay/regenerate',
@@ -1274,6 +1284,34 @@ const WEB_ACCESS_ROUTES = new Set([
1274
1284
  '/api/relay/inbox/auto',
1275
1285
  ]);
1276
1286
 
1287
+ /**
1288
+ * 会改动本机状态或泄露密钥的「危险动作」。它们除了过 localOnly 与网页窗口,还要求请求真的
1289
+ * 来自本机(`trustedLocalUi`:socket 回环、Host 回环、无转发头)——两小时窗口只放行只读面板,
1290
+ * 不放行这些动作。桌面端经 forwardWebRequest 从回环转进来、本机浏览器、SSH 隧道都算本机,
1291
+ * 用户无感;只有网络上其它机器(或经代理转发的调用)被挡。
1292
+ *
1293
+ * 这里只收「动作」:读类的 status / addresses / devices(清单)/ faults / selfcheck 等仍走窗口,
1294
+ * 因为它们不改本机状态、也不吐密钥材料。
1295
+ */
1296
+ const LOCAL_OPERATOR_ROUTES = new Set([
1297
+ '/api/relay/pairing',
1298
+ '/api/relay/toggle',
1299
+ '/api/relay/regenerate',
1300
+ '/api/relay/config',
1301
+ '/api/relay/revoke-all',
1302
+ '/api/relay/devices/revoke',
1303
+ '/api/relay/devices/permissions',
1304
+ '/api/relay/tailcat/enabled',
1305
+ '/api/relay/tailcat/revoke',
1306
+ '/api/relay/update/apply',
1307
+ '/api/relay/update/auto',
1308
+ '/api/relay/update/ota/apply',
1309
+ '/api/relay/restart-sidecar',
1310
+ '/api/relay/reload-implementation',
1311
+ '/api/relay/inbox/clear',
1312
+ '/api/relay/inbox/auto',
1313
+ ]);
1314
+
1277
1315
  // `panelDiagnosis` 一并导出,只为让 test/panel-artifact.test.cjs 能拿临时目录跑那三条分支:
1278
1316
  // 三种「读不到」的文案分别对应「重启 / 升级 / 构建」,它们混起来就是这个 bug 的原样。
1279
1317
  module.exports = {
@@ -1282,6 +1320,7 @@ module.exports = {
1282
1320
  panelUrlOf,
1283
1321
  panelScopeOf,
1284
1322
  WEB_ACCESS_ROUTES,
1323
+ LOCAL_OPERATOR_ROUTES,
1285
1324
  WEB_ACCESS_WINDOW_MS,
1286
1325
  createWebAccessWindow,
1287
1326
  createWebAccessLocalOnly,
@@ -1,4 +1,6 @@
1
1
  'use strict';
2
+ // 手机切模型只改当前会话,App 默认不写回电脑。
3
+ // 模型目录支持空 sessionId,首次使用无需先创建会话。
2
4
  // 电脑间配对和网页隧道使用独立加密认证,不复用手机的全权凭据。
3
5
 
4
6
  /**
@@ -238,6 +240,11 @@ function registerMobileRoutes(deps) {
238
240
  // `credentialExpiresAt` 只在配对 / 升级时写过一次,靠它永远读不出「最近续过没有」。
239
241
  // 查不到记录(升级前的无状态通行证)就是 null,手机那边退回会话里存的那一格。
240
242
  credential: pairedDevices.credentialTimingFor(credentials, state.instanceId || '', req),
243
+ // 这台设备**当前有效**的权限位。电脑侧改档位后,手机只在这条每 30 秒必发的心跳上
244
+ // 才有机会知道新档位;不带这一格,手机就永远停在配对时那份、降权后还会接着按旧档
245
+ // 往外发(真机上正是「电脑改成可答审批、手机仍显示只读」)。出示无记录老凭据时
246
+ // currentPermissions 回全权,与「缺 permissions = 全权」同一口径。
247
+ permissions: devicePermissions.currentPermissions(req.__dshRecord),
241
248
  })
242
249
  }) })
243
250
  // 地址体检:手机在**配对之前**就要问「这个地址上到底是谁」,那时它手上没有任何
@@ -456,6 +463,7 @@ function registerMobileRoutes(deps) {
456
463
  route('/api/mobile/v1/session/rename', sessions.handleRename)
457
464
  route('/api/mobile/v1/session/fork', sessions.handleFork)
458
465
  route('/api/mobile/v1/session/models', sessions.handleModels)
466
+ // 只修改当前会话模型,App 默认留在手机,电脑默认不变。
459
467
  route('/api/mobile/v1/session/select-model', sessions.handleSelectModel)
460
468
  // 模型之外的附加选项(速度、输出详略……):写一条已声明的行,落地是宿主自己的设置。
461
469
  route('/api/mobile/v1/session/model-option', sessionModelOptions.handleModelOption)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.54",
3
+ "version": "0.5.55",
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",
@@ -71,14 +71,14 @@
71
71
  },
72
72
  "dependencies": {
73
73
  "qrcode": "1.5.4",
74
- "ws": "8.18.0"
74
+ "ws": "8.22.2"
75
75
  },
76
76
  "optionalDependencies": {
77
- "dsh-mobile-shell-darwin-arm64": "0.1.1",
78
- "dsh-mobile-shell-darwin-x64": "0.1.1",
79
- "dsh-mobile-shell-linux-arm64": "0.1.1",
80
- "dsh-mobile-shell-linux-x64": "0.1.1",
81
- "dsh-mobile-shell-win32-x64": "0.1.1",
77
+ "dsh-mobile-shell-darwin-arm64": "0.1.2",
78
+ "dsh-mobile-shell-darwin-x64": "0.1.2",
79
+ "dsh-mobile-shell-linux-arm64": "0.1.2",
80
+ "dsh-mobile-shell-linux-x64": "0.1.2",
81
+ "dsh-mobile-shell-win32-x64": "0.1.2",
82
82
  "dsh-mobile-tailcat-darwin-arm64": "1.1.2",
83
83
  "dsh-mobile-tailcat-darwin-x64": "1.1.2",
84
84
  "dsh-mobile-tailcat-linux-arm64": "1.1.2",