dsh-mobile-plugin 0.5.53 → 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,20 +1,20 @@
1
- /** 远程网页的只读租期提示与主文档流式脚本注入。 */
1
+ /** 远程网页的只读租期提示、桌面壳的排版适配与主文档流式脚本注入。 */
2
2
  'use strict';
3
3
 
4
4
  const { Transform } = require('node:stream');
5
5
 
6
6
  const SCRIPT_TAG = Buffer.from('<script src="/__dsh_remote_notice.js" defer></script>');
7
7
  const TEXT = {
8
- 'zh-Hans': ['访问即将到期,请返回本机插件续期。', '本次访问已到期,请返回本机插件重新打开。', '无法确认访问状态,请返回本机插件检查。'],
9
- 'zh-Hant': ['存取即將到期,請返回本機外掛續期。', '本次存取已到期,請返回本機外掛重新開啟。', '無法確認存取狀態,請返回本機外掛檢查。'],
10
- en: ['Access expires soon. Return to the local plugin to renew it.', 'This visit has expired. Return to the local plugin to open it again.', 'Access status could not be checked. Return to the local plugin to check it.'],
11
- ja: ['アクセスがまもなく終了します。このパソコンのプラグインで延長してください。', 'アクセス期限が切れました。このパソコンのプラグインから開き直してください。', 'アクセス状態を確認できません。このパソコンのプラグインで確認してください。'],
12
- ko: ['접속이 곧 만료됩니다. 이 컴퓨터의 플러그인으로 돌아가 연장하세요.', '접속이 만료되었습니다. 이 컴퓨터의 플러그인에서 다시 열어 주세요.', '접속 상태를 확인할 수 없습니다. 이 컴퓨터의 플러그인에서 확인하세요.'],
13
- de: ['Der Zugriff läuft bald ab. Verlängere ihn im lokalen Plugin.', 'Dieser Zugriff ist abgelaufen. Öffne ihn im lokalen Plugin erneut.', 'Der Zugriffsstatus konnte nicht geprüft werden. Prüfe ihn im lokalen Plugin.'],
14
- es: ['El acceso caduca pronto. Vuelve al complemento local para renovarlo.', 'Este acceso ha caducado. Vuelve al complemento local para abrirlo de nuevo.', 'No se pudo comprobar el acceso. Revísalo en el complemento local.'],
15
- fr: ['L’accès expire bientôt. Revenez au plugin local pour le renouveler.', 'Cet accès a expiré. Revenez au plugin local pour le rouvrir.', 'Impossible de vérifier l’accès. Vérifiez-le dans le plugin local.'],
16
- pt: ['O acesso expira em breve. Volte ao plugin local para renovar.', 'Este acesso expirou. Volte ao plugin local para abrir novamente.', 'Não foi possível verificar o acesso. Confira no plugin local.'],
17
- ru: ['Доступ скоро истечёт. Продлите его в локальном плагине.', 'Срок доступа истёк. Откройте его заново в локальном плагине.', 'Не удалось проверить доступ. Проверьте его в локальном плагине.'],
8
+ 'zh-Hans': ['访问即将到期,请保持此窗口在使用中以自动续期。', '本次访问已到期,请返回本机插件重新打开。', '无法确认访问状态,请返回本机插件检查。'],
9
+ 'zh-Hant': ['存取即將到期,請保持此視窗在使用中以自動續期。', '本次存取已到期,請返回本機外掛重新開啟。', '無法確認存取狀態,請返回本機外掛檢查。'],
10
+ en: ['Access expires soon. Keep this window in use to renew it automatically.', 'This visit has expired. Return to the local plugin to open it again.', 'Access status could not be checked. Return to the local plugin to check it.'],
11
+ ja: ['アクセスがまもなく終了します。このウィンドウを使い続けると自動で延長されます。', 'アクセス期限が切れました。このパソコンのプラグインから開き直してください。', 'アクセス状態を確認できません。このパソコンのプラグインで確認してください。'],
12
+ ko: ['접속이 곧 만료됩니다. 이 창을 계속 사용하면 자동으로 연장됩니다.', '접속이 만료되었습니다. 이 컴퓨터의 플러그인에서 다시 열어 주세요.', '접속 상태를 확인할 수 없습니다. 이 컴퓨터의 플러그인에서 확인하세요.'],
13
+ de: ['Der Zugriff läuft bald ab. Nutze dieses Fenster weiter, um automatisch zu verlängern.', 'Dieser Zugriff ist abgelaufen. Öffne ihn im lokalen Plugin erneut.', 'Der Zugriffsstatus konnte nicht geprüft werden. Prüfe ihn im lokalen Plugin.'],
14
+ es: ['El acceso caduca pronto. Mantén esta ventana en uso para renovarlo automáticamente.', 'Este acceso ha caducado. Vuelve al complemento local para abrirlo de nuevo.', 'No se pudo comprobar el acceso. Revísalo en el complemento local.'],
15
+ fr: ['L’accès expire bientôt. Continuez d’utiliser cette fenêtre pour le renouveler automatiquement.', 'Cet accès a expiré. Revenez au plugin local pour le rouvrir.', 'Impossible de vérifier l’accès. Vérifiez-le dans le plugin local.'],
16
+ pt: ['O acesso expira em breve. Continue usando esta janela para renovar automaticamente.', 'Este acesso expirou. Volte ao plugin local para abrir novamente.', 'Não foi possível verificar o acesso. Confira no plugin local.'],
17
+ ru: ['Доступ скоро истечёт. Продолжайте использовать это окно — доступ продлится автоматически.', 'Срок доступа истёк. Откройте его заново в локальном плагине.', 'Не удалось проверить доступ. Проверьте его в локальном плагине.'],
18
18
  };
19
19
 
20
20
  function browserNotice(text) {
@@ -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 };
@@ -49,7 +49,7 @@ function createRemoteController({ store, transport, name, tunnels }) {
49
49
  const id = String(binding.id || binding.instanceId);
50
50
  let item = devices.get(id);
51
51
  if (item) return item;
52
- item = { binding: { ...binding, id }, mode: binding.mode || 'auto', state: 'idle', expiresAt: null, lastError: '', gateway: null, opening: null };
52
+ item = { binding: { ...binding, id }, mode: binding.mode || 'auto', state: 'idle', expiresAt: null, lastError: '', gateway: null, opening: null, windowChild: null, windowClosed: false };
53
53
  item.router = routerFor(item);
54
54
  devices.set(id, item);
55
55
  return item;
@@ -78,11 +78,15 @@ function createRemoteController({ store, transport, name, tunnels }) {
78
78
  check(item);
79
79
  const snapshot = item.router.snapshot();
80
80
  const selected = safeRoutes(snapshot.route ? [snapshot.route] : [])[0];
81
+ // 桌面窗口是否还连着:进程没退出、网关也还连着才算「已打开」;关掉窗口后回到未打开(租期仍按既有规则自然到期)。
82
+ const attached = !item.windowClosed && Boolean(item.gateway && typeof item.gateway.attached === 'function' && item.gateway.attached());
83
+ const state = !attached && ['connected', 'connecting', 'offline'].includes(item.state) ? 'idle' : item.state;
81
84
  return {
82
85
  id: item.binding.id, name: String(item.binding.name || item.binding.instanceId), instanceId: item.binding.instanceId,
83
86
  mode: item.mode, channel: selected?.channel || null, url: selected?.url || null,
84
- latencyMs: snapshot.latencyMs, state: item.state, expiresAt: item.expiresAt,
87
+ latencyMs: snapshot.latencyMs, state, expiresAt: item.expiresAt,
85
88
  ...(item.lastError ? { lastError: item.lastError, lastErrorCode: item.lastErrorCode || 'REMOTE_CONNECT' } : {}), routes: safeRoutes(snapshot.routes),
89
+ attached,
86
90
  };
87
91
  }
88
92
 
@@ -90,6 +94,7 @@ function createRemoteController({ store, transport, name, tunnels }) {
90
94
  item.gateway?.close(); item.gateway = null;
91
95
  item.router.close();
92
96
  item.state = 'idle'; item.expiresAt = null; item.lastError = ''; item.lastErrorCode = '';
97
+ item.windowClosed = false; item.windowChild = null;
93
98
  await tunnels?.close?.(item.binding.id);
94
99
  item.router = routerFor(item);
95
100
  }
@@ -113,6 +118,8 @@ function createRemoteController({ store, transport, name, tunnels }) {
113
118
 
114
119
  async function open(id) {
115
120
  const item = await find(id);
121
+ // 每次打开都算重新拉起:清掉上一轮窗口的关闭标记,等新进程接手。
122
+ item.windowClosed = false; item.windowChild = null;
116
123
  if (item.opening) return item.opening;
117
124
  if (check(item)) return item.gateway.openLink();
118
125
  item.router.close(); item.router = routerFor(item);
@@ -134,6 +141,8 @@ function createRemoteController({ store, transport, name, tunnels }) {
134
141
  } catch (error) { if (current()) fault(item, error); throw error; }
135
142
  },
136
143
  onExpire: () => { if (current()) expire(item); },
144
+ // 网关按「窗口还在用」自动续期时,同步控制器认的到期时刻,避免 check() 拿旧期限误判到期。
145
+ onRenew: (deadline) => { if (current()) item.expiresAt = deadline; },
137
146
  onError: (error) => { if (current()) { router.failure(error); fault(item, error); } },
138
147
  });
139
148
  item.gateway = gateway;
@@ -164,6 +173,15 @@ function createRemoteController({ store, transport, name, tunnels }) {
164
173
  return row(ensure(binding));
165
174
  },
166
175
  open,
176
+ /** 记下这台设备当前拉起的桌面进程:进程一退出就当作窗口关掉,面板据此回到未打开。 */
177
+ watchWindow(id, child) {
178
+ const item = devices.get(String(id));
179
+ if (!item || !child) return;
180
+ item.windowChild = child;
181
+ item.windowClosed = false;
182
+ if (child.exitCode !== null && child.exitCode !== undefined) { item.windowClosed = true; return; }
183
+ child.on?.('exit', () => { if (item.windowChild === child) item.windowClosed = true; });
184
+ },
167
185
  async renew(id) {
168
186
  const item = await find(id);
169
187
  if (!check(item)) throw expiredError();
@@ -1,4 +1,6 @@
1
- // 只监听本机的远程网页入口:一次性打开链接与手动租期。
1
+ // 只监听本机的远程网页入口:一次性打开链接、访问租期与按窗口自动续期。
2
+ // 每台网关各管各的租期;续期只延长期限,不重发入口地址、不动已建立的连接。
3
+ // 壳会话另发一枚只读标记:只给桌面窗口启用官方自带的让位与拖动排版。
2
4
  'use strict';
3
5
 
4
6
  const http = require('node:http');
@@ -9,27 +11,37 @@ const { noticeScript, createNoticeTransform } = require('./browser-notice.cjs');
9
11
 
10
12
  const LEASE_MS = 60 * 60 * 1000;
11
13
  const OPEN_MS = 60 * 1000;
14
+ const ACTIVE_MS = 5 * 60 * 1000;
15
+ const RENEW_AHEAD_MS = 5 * 60 * 1000;
16
+ const RENEW_CHECK_MS = 30 * 1000;
17
+ // 判定「桌面窗口还连着」的宽限:刚有过请求也算连着,避免页面加载空档被误判成已关闭。
18
+ const ATTACH_GRACE_MS = 4 * 1000;
12
19
  const OPEN_PATH = '/__dsh_remote_open';
13
20
 
14
- function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = () => {}, onError }) {
21
+ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = () => {}, onError, onRenew = () => {}, platform = process.platform }) {
15
22
  const live = new Set();
16
23
  const cookieName = `dsh_remote_${crypto.randomBytes(12).toString('hex')}`;
24
+ const shellCookie = `${cookieName}_shell`;
17
25
  const session = crypto.randomBytes(32).toString('base64url');
18
26
  let ticket = crypto.randomBytes(32).toString('base64url');
19
27
  let ticketExpiresAt = now() + OPEN_MS;
20
28
  let deadline = Math.min(Number(expiresAt) || now() + LEASE_MS, now() + LEASE_MS);
29
+ let lastActivity = now();
21
30
  let port = 0;
22
31
  let closed = false;
23
32
  let timer = null;
33
+ let renewing = false;
24
34
  let starting = null;
25
35
  const origin = () => `http://127.0.0.1:${port}`;
26
36
  const active = () => !closed && now() < deadline;
37
+ const inUse = (time = now()) => !closed && (live.size > 0 || time - lastActivity < ACTIVE_MS);
27
38
  const upstream = createUpstream({ connect, active, live, origin, expiresAt: () => deadline, onError, noticeTransform: createNoticeTransform });
28
39
  const server = http.createServer(handle);
29
40
  server.requestTimeout = 0;
30
41
  server.headersTimeout = 15000;
31
42
  server.on('connection', (socket) => {
32
43
  live.add(socket);
44
+ lastActivity = now();
33
45
  socket.once('close', () => live.delete(socket));
34
46
  socket.on('error', () => {});
35
47
  });
@@ -38,6 +50,7 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
38
50
  if (!active() || !path || !sameOrigin(req, origin()) || cookieOf(req.headers.cookie, cookieName) !== session) {
39
51
  socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return;
40
52
  }
53
+ lastActivity = now();
41
54
  req.url = path;
42
55
  void upstream.upgrade(req, socket, head);
43
56
  });
@@ -61,18 +74,24 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
61
74
  const value = url.searchParams.get('ticket');
62
75
  if (req.method !== 'GET' || !ticket || now() >= ticketExpiresAt || value !== ticket) return reply(res, 403, '打开链接已失效,请在本机面板重新打开。');
63
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`);
64
80
  res.writeHead(303, {
65
- location: '/', 'set-cookie': `${cookieName}=${session}; Path=/; HttpOnly; SameSite=Strict`,
81
+ location: '/', 'set-cookie': cookies,
66
82
  'cache-control': 'no-store', 'referrer-policy': 'no-referrer',
67
83
  });
68
84
  res.end(); return;
69
85
  }
70
86
  if (cookieOf(req.headers.cookie, cookieName) !== session) return reply(res, 401, '请从本机面板打开这台电脑。');
87
+ lastActivity = now();
71
88
  if (url.pathname === '/__dsh_remote_status' || url.pathname === '/__dsh_remote_notice.js') {
72
89
  if (req.method !== 'GET') return reply(res, 405, '只读入口。');
73
90
  const status = url.pathname === '/__dsh_remote_status';
74
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' });
75
- 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;
76
95
  }
77
96
  req.url = path;
78
97
  void upstream.forward(req, res);
@@ -80,7 +99,8 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
80
99
 
81
100
  function arm() {
82
101
  clearTimeout(timer);
83
- timer = setTimeout(checkExpiry, Math.max(1, deadline - now()));
102
+ const remaining = Math.max(1, deadline - now());
103
+ timer = setTimeout(checkExpiry, Math.min(remaining, RENEW_CHECK_MS));
84
104
  timer.unref?.();
85
105
  }
86
106
 
@@ -97,8 +117,31 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
97
117
 
98
118
  function checkExpiry() {
99
119
  if (closed) return false;
100
- if (now() < deadline) { arm(); return false; }
101
- close(); onExpire(); return true;
120
+ if (now() >= deadline) { close(); onExpire(); return true; }
121
+ void autoRenew(now());
122
+ arm(); return false;
123
+ }
124
+
125
+ /** 临期且窗口还在用就原地续:只推期限,不重发入口、不动已建立的连接,页面不会刷新。 */
126
+ async function autoRenew(time = now()) {
127
+ if (closed || renewing || !active() || deadline - time > RENEW_AHEAD_MS || !inUse(time)) return false;
128
+ renewing = true;
129
+ try { await renew(); onRenew(deadline); return true; }
130
+ catch { return false; }
131
+ finally { renewing = false; }
132
+ }
133
+
134
+ async function renew(value = now() + LEASE_MS) {
135
+ if (!active()) { checkExpiry(); throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
136
+ let next = Math.min(Number(value) || now() + LEASE_MS, now() + LEASE_MS);
137
+ const streams = [...live].filter((stream) => typeof stream.renew === 'function' && !stream.destroyed);
138
+ const accepted = await Promise.all(streams.map((stream) => stream.renew(next)));
139
+ const added = [...live].filter((stream) => !streams.includes(stream) && typeof stream.renew === 'function' && !stream.destroyed);
140
+ accepted.push(...await Promise.all(added.map((stream) => stream.renew(next))));
141
+ if (!active()) { checkExpiry(); throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
142
+ for (const result of accepted) if (Number.isFinite(result)) next = Math.min(next, result);
143
+ deadline = next;
144
+ arm(); return { expiresAt: deadline };
102
145
  }
103
146
 
104
147
  return {
@@ -123,19 +166,12 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
123
166
  ticketExpiresAt = now() + OPEN_MS;
124
167
  return { url: `${origin()}${OPEN_PATH}?ticket=${ticket}`, expiresAt: deadline };
125
168
  },
126
- async renew(value = now() + LEASE_MS) {
127
- if (!active()) { checkExpiry(); throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
128
- let next = Math.min(Number(value) || now() + LEASE_MS, now() + LEASE_MS);
129
- const streams = [...live].filter((stream) => typeof stream.renew === 'function' && !stream.destroyed);
130
- const accepted = await Promise.all(streams.map((stream) => stream.renew(next)));
131
- const added = [...live].filter((stream) => !streams.includes(stream) && typeof stream.renew === 'function' && !stream.destroyed);
132
- accepted.push(...await Promise.all(added.map((stream) => stream.renew(next))));
133
- if (!active()) { checkExpiry(); throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
134
- for (const result of accepted) if (Number.isFinite(result)) next = Math.min(next, result);
135
- deadline = next;
136
- arm(); return { expiresAt: deadline };
137
- },
169
+ renew,
138
170
  expiresAt: () => deadline,
171
+ /** 桌面窗口此刻是否连着:有活连接,或刚有过请求(关闭判定给 4 秒宽限,避免加载空档误报)。 */
172
+ attached() { return !closed && (live.size > 0 || now() - lastActivity < ATTACH_GRACE_MS); },
173
+ inUse,
174
+ autoRenew,
139
175
  disconnect() { for (const stream of live) stream.destroy(); live.clear(); upstream.close(); },
140
176
  checkExpiry, close,
141
177
  };
@@ -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,17 +1,20 @@
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');
6
+ const { launchShell } = require('./shell.cjs');
5
7
  const PREFIX = '/api/relay/remote-computers';
6
- const METHODS = { '': 'GET', '/invite': 'POST', '/add': 'POST', '/open': 'POST', '/renew': 'POST',
7
- '/stop': 'POST', '/remove': 'POST', '/mode': 'POST', '/probe': 'POST', '/revoke': 'POST' };
8
+ const METHODS = { '': 'GET', '/invite': 'POST', '/add': 'POST', '/open': 'POST', '/open-shell': 'POST',
9
+ '/renew': 'POST', '/stop': 'POST', '/remove': 'POST', '/mode': 'POST', '/probe': 'POST', '/revoke': 'POST' };
8
10
  const PUBLIC_ERRORS = {
9
11
  'credentials-unavailable': '宿主凭据存储暂不可用,请稍后重试',
10
12
  REMOTE_AUTH: '远程电脑认证失败,请重新绑定', REMOTE_REVOKED: '这台电脑的授权已被撤销,请重新绑定',
11
13
  REMOTE_EXPIRED: '授权已到期,请重新打开', REMOTE_TIMEOUT: '连接远程电脑超时,请重试或检测线路',
12
14
  REMOTE_CONNECT: '暂时无法连接远程电脑,请检查网络和对方是否在线',
15
+ SHELL_UNAVAILABLE: '本机未安装远程电脑桌面端,请改用默认方式打开',
13
16
  };
14
- function createRemoteRoutes({ controller, host, credentials, instanceId, now = Date.now }) {
17
+ function createRemoteRoutes({ controller, host, credentials, instanceId, now = Date.now, launch = launchShell }) {
15
18
  function authorizedComputers() {
16
19
  return credentials.listRemoteComputers(instanceId);
17
20
  }
@@ -49,6 +52,18 @@ function createRemoteRoutes({ controller, host, credentials, instanceId, now = D
49
52
  }
50
53
  if (typeof body.id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(body.id)) throw new Error('bad-id');
51
54
  if (suffix === '/open') return sendJson(res, 200, { ok: true, ...await controller.open(body.id) });
55
+ if (suffix === '/open-shell') {
56
+ const result = await controller.open(body.id);
57
+ const devices = await controller.list();
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');
62
+ // 记下这次拉起的桌面进程:它一退出就当窗口关掉,面板据此回到未打开。
63
+ const child = launch({ url: shellUrl.href, deviceName });
64
+ controller.watchWindow(body.id, child);
65
+ return sendJson(res, 200, { ok: true, ...result });
66
+ }
52
67
  if (suffix === '/renew') return sendJson(res, 200, { ok: true, ...await controller.renew(body.id) });
53
68
  if (suffix === '/stop') await controller.stop(body.id);
54
69
  if (suffix === '/remove') await controller.remove(body.id);
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+ // 远程电脑桌面端显示壳:按平台包找到随插件分发的可执行文件,用一次性入口拉起独立窗口。
3
+ const { spawn } = require('node:child_process');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ /** 五个分发平台,与平台包 dsh-mobile-shell-<id> 一一对应。 */
8
+ const PLATFORM_IDS = ['darwin-arm64', 'darwin-x64', 'linux-x64', 'linux-arm64', 'win32-x64'];
9
+
10
+ /** 平台包不可用时的统一错误码。 */
11
+ const SHELL_UNAVAILABLE = 'SHELL_UNAVAILABLE';
12
+
13
+ const DEV_ROOT = path.resolve(__dirname, '..', '..', '..');
14
+
15
+ function failure(code) {
16
+ const error = new Error(code);
17
+ error.code = code;
18
+ return error;
19
+ }
20
+
21
+ /** 这台机器对应哪个平台包;没有对应包就返回 undefined。 */
22
+ function platformId(platform = process.platform, arch = process.arch) {
23
+ const os = platform === 'win32' ? 'win32' : platform;
24
+ const cpu = arch === 'x64' ? 'x64' : arch === 'arm64' ? 'arm64' : arch;
25
+ const id = `${os}-${cpu}`;
26
+ return PLATFORM_IDS.includes(id) ? id : undefined;
27
+ }
28
+
29
+ /** 平台包内可执行文件的相对路径(macOS 是 .app 包里的那个二进制)。 */
30
+ function binaryPath(platform) {
31
+ if (platform === 'win32-x64') return 'dsh-mobile-shell.exe';
32
+ if (platform.startsWith('darwin-')) return 'dsh-mobile-shell.app/Contents/MacOS/dsh-mobile-shell';
33
+ return 'dsh-mobile-shell';
34
+ }
35
+
36
+ /** 只认本机代理给出的一次性入口:带端口的 http://127.0.0.1,不带账号密码。 */
37
+ function validRemoteUrl(value) {
38
+ if (typeof value !== 'string' || !value || /[\u0000-\u0020\u007f]/.test(value)) return false;
39
+ let url;
40
+ try { url = new URL(value); } catch { return false; }
41
+ return url.protocol === 'http:' && url.hostname === '127.0.0.1' && Boolean(url.port)
42
+ && !url.username && !url.password;
43
+ }
44
+
45
+ /**
46
+ * 找桌面端可执行文件:先按本模块所在位置解析可选依赖(npm / pnpm 的嵌套与 hoisted 布局都
47
+ * 命中),再退回调用方指定路径 / 当前工作目录,然后是开发产物与环境变量覆盖。找不到一律
48
+ * 回 null,把这条通道标成不可用,不抛错、不影响插件其余功能。
49
+ */
50
+ function resolveShell(options = {}) {
51
+ const exists = options.exists || fs.existsSync;
52
+ const platform = options.platformId || platformId(options.platform, options.arch);
53
+ if (!platform) return null;
54
+ const relative = binaryPath(platform);
55
+ const pkg = `dsh-mobile-shell-${platform}`;
56
+ for (const paths of [undefined, options.paths || [process.cwd()]]) {
57
+ try {
58
+ const manifest = require.resolve(`${pkg}/package.json`, paths ? { paths } : undefined);
59
+ const candidate = path.join(path.dirname(manifest), relative);
60
+ if (exists(candidate)) return candidate;
61
+ } catch {
62
+ /* 这一路没有:试下一路 */
63
+ }
64
+ }
65
+ const override = (options.env || process.env).DSHM_MOBILE_SHELL;
66
+ if (typeof override === 'string' && override && exists(override)) return override;
67
+ // 随包分发的本机原生产物(开发机由 reload-dev 从 build/desktop-shell 拷进来)。
68
+ const nativeRoot = options.nativeRoot || path.join(__dirname, '..', '..', 'native', 'desktop-shell');
69
+ const native = path.join(nativeRoot, platform, relative);
70
+ if (exists(native)) return native;
71
+ const dev = path.join(options.devRoot || DEV_ROOT, 'build', 'desktop-shell', platform, relative);
72
+ if (exists(dev)) return dev;
73
+ return null;
74
+ }
75
+
76
+ /** 命令行参数固定两项:一次性地址与设备名,不经 shell、不拼命令。 */
77
+ function buildArgs({ url, deviceName } = {}) {
78
+ return [`--remote-url=${url}`, `--device-name=${String(deviceName || '')}`];
79
+ }
80
+
81
+ /**
82
+ * 一次点击拉起一个窗口:进程 detached、stdio 丢弃、unref,插件退出不拖着窗口。
83
+ * 地址只来自 controller.open,校验过后交给参数数组,不写日志、不落盘。
84
+ */
85
+ function launchShell({ url, deviceName } = {}, options = {}) {
86
+ if (!validRemoteUrl(url)) throw failure('REMOTE_OPEN_URL');
87
+ const binary = (options.resolve || resolveShell)(options);
88
+ if (!binary) throw failure(SHELL_UNAVAILABLE);
89
+ const launch = options.spawn || spawn;
90
+ let child;
91
+ try {
92
+ child = launch(binary, buildArgs({ url, deviceName }), { detached: true, stdio: 'ignore', windowsHide: true });
93
+ } catch {
94
+ throw failure(SHELL_UNAVAILABLE);
95
+ }
96
+ child?.on?.('error', () => {});
97
+ child?.unref?.();
98
+ return child;
99
+ }
100
+
101
+ module.exports = { PLATFORM_IDS, SHELL_UNAVAILABLE, platformId, binaryPath, resolveShell, buildArgs, launchShell };