dsh-mobile-plugin 0.5.53 → 0.5.54

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.
@@ -5,16 +5,16 @@ 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) {
@@ -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,5 @@
1
- // 只监听本机的远程网页入口:一次性打开链接与手动租期。
1
+ // 只监听本机的远程网页入口:一次性打开链接、访问租期与按窗口自动续期。
2
+ // 每台网关各管各的租期;续期只延长期限,不重发入口地址、不动已建立的连接。
2
3
  'use strict';
3
4
 
4
5
  const http = require('node:http');
@@ -9,27 +10,36 @@ const { noticeScript, createNoticeTransform } = require('./browser-notice.cjs');
9
10
 
10
11
  const LEASE_MS = 60 * 60 * 1000;
11
12
  const OPEN_MS = 60 * 1000;
13
+ const ACTIVE_MS = 5 * 60 * 1000;
14
+ const RENEW_AHEAD_MS = 5 * 60 * 1000;
15
+ const RENEW_CHECK_MS = 30 * 1000;
16
+ // 判定「桌面窗口还连着」的宽限:刚有过请求也算连着,避免页面加载空档被误判成已关闭。
17
+ const ATTACH_GRACE_MS = 4 * 1000;
12
18
  const OPEN_PATH = '/__dsh_remote_open';
13
19
 
14
- function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = () => {}, onError }) {
20
+ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = () => {}, onError, onRenew = () => {} }) {
15
21
  const live = new Set();
16
22
  const cookieName = `dsh_remote_${crypto.randomBytes(12).toString('hex')}`;
17
23
  const session = crypto.randomBytes(32).toString('base64url');
18
24
  let ticket = crypto.randomBytes(32).toString('base64url');
19
25
  let ticketExpiresAt = now() + OPEN_MS;
20
26
  let deadline = Math.min(Number(expiresAt) || now() + LEASE_MS, now() + LEASE_MS);
27
+ let lastActivity = now();
21
28
  let port = 0;
22
29
  let closed = false;
23
30
  let timer = null;
31
+ let renewing = false;
24
32
  let starting = null;
25
33
  const origin = () => `http://127.0.0.1:${port}`;
26
34
  const active = () => !closed && now() < deadline;
35
+ const inUse = (time = now()) => !closed && (live.size > 0 || time - lastActivity < ACTIVE_MS);
27
36
  const upstream = createUpstream({ connect, active, live, origin, expiresAt: () => deadline, onError, noticeTransform: createNoticeTransform });
28
37
  const server = http.createServer(handle);
29
38
  server.requestTimeout = 0;
30
39
  server.headersTimeout = 15000;
31
40
  server.on('connection', (socket) => {
32
41
  live.add(socket);
42
+ lastActivity = now();
33
43
  socket.once('close', () => live.delete(socket));
34
44
  socket.on('error', () => {});
35
45
  });
@@ -38,6 +48,7 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
38
48
  if (!active() || !path || !sameOrigin(req, origin()) || cookieOf(req.headers.cookie, cookieName) !== session) {
39
49
  socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return;
40
50
  }
51
+ lastActivity = now();
41
52
  req.url = path;
42
53
  void upstream.upgrade(req, socket, head);
43
54
  });
@@ -68,6 +79,7 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
68
79
  res.end(); return;
69
80
  }
70
81
  if (cookieOf(req.headers.cookie, cookieName) !== session) return reply(res, 401, '请从本机面板打开这台电脑。');
82
+ lastActivity = now();
71
83
  if (url.pathname === '/__dsh_remote_status' || url.pathname === '/__dsh_remote_notice.js') {
72
84
  if (req.method !== 'GET') return reply(res, 405, '只读入口。');
73
85
  const status = url.pathname === '/__dsh_remote_status';
@@ -80,7 +92,8 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
80
92
 
81
93
  function arm() {
82
94
  clearTimeout(timer);
83
- timer = setTimeout(checkExpiry, Math.max(1, deadline - now()));
95
+ const remaining = Math.max(1, deadline - now());
96
+ timer = setTimeout(checkExpiry, Math.min(remaining, RENEW_CHECK_MS));
84
97
  timer.unref?.();
85
98
  }
86
99
 
@@ -97,8 +110,31 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
97
110
 
98
111
  function checkExpiry() {
99
112
  if (closed) return false;
100
- if (now() < deadline) { arm(); return false; }
101
- close(); onExpire(); return true;
113
+ if (now() >= deadline) { close(); onExpire(); return true; }
114
+ void autoRenew(now());
115
+ arm(); return false;
116
+ }
117
+
118
+ /** 临期且窗口还在用就原地续:只推期限,不重发入口、不动已建立的连接,页面不会刷新。 */
119
+ async function autoRenew(time = now()) {
120
+ if (closed || renewing || !active() || deadline - time > RENEW_AHEAD_MS || !inUse(time)) return false;
121
+ renewing = true;
122
+ try { await renew(); onRenew(deadline); return true; }
123
+ catch { return false; }
124
+ finally { renewing = false; }
125
+ }
126
+
127
+ async function renew(value = now() + LEASE_MS) {
128
+ if (!active()) { checkExpiry(); throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
129
+ let next = Math.min(Number(value) || now() + LEASE_MS, now() + LEASE_MS);
130
+ const streams = [...live].filter((stream) => typeof stream.renew === 'function' && !stream.destroyed);
131
+ const accepted = await Promise.all(streams.map((stream) => stream.renew(next)));
132
+ const added = [...live].filter((stream) => !streams.includes(stream) && typeof stream.renew === 'function' && !stream.destroyed);
133
+ accepted.push(...await Promise.all(added.map((stream) => stream.renew(next))));
134
+ if (!active()) { checkExpiry(); throw Object.assign(new Error('访问已到期,请重新打开'), { code: 'REMOTE_EXPIRED' }); }
135
+ for (const result of accepted) if (Number.isFinite(result)) next = Math.min(next, result);
136
+ deadline = next;
137
+ arm(); return { expiresAt: deadline };
102
138
  }
103
139
 
104
140
  return {
@@ -123,19 +159,12 @@ function createLocalGateway({ connect, expiresAt, now = Date.now, onExpire = ()
123
159
  ticketExpiresAt = now() + OPEN_MS;
124
160
  return { url: `${origin()}${OPEN_PATH}?ticket=${ticket}`, expiresAt: deadline };
125
161
  },
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
- },
162
+ renew,
138
163
  expiresAt: () => deadline,
164
+ /** 桌面窗口此刻是否连着:有活连接,或刚有过请求(关闭判定给 4 秒宽限,避免加载空档误报)。 */
165
+ attached() { return !closed && (live.size > 0 || now() - lastActivity < ATTACH_GRACE_MS); },
166
+ inUse,
167
+ autoRenew,
139
168
  disconnect() { for (const stream of live) stream.destroy(); live.clear(); upstream.close(); },
140
169
  checkExpiry, close,
141
170
  };
@@ -2,14 +2,16 @@
2
2
  // 远程电脑管理仅接受本机可信界面;电脑配对和加密升级由各自协议独立认证。
3
3
  const { sendJson, readJsonBody } = require('../shared/http-util.js');
4
4
  const { trustedLocalUi, crossSiteRequest } = require('../http/routing.js');
5
+ const { launchShell } = require('./shell.cjs');
5
6
  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' };
7
+ const METHODS = { '': 'GET', '/invite': 'POST', '/add': 'POST', '/open': 'POST', '/open-shell': 'POST',
8
+ '/renew': 'POST', '/stop': 'POST', '/remove': 'POST', '/mode': 'POST', '/probe': 'POST', '/revoke': 'POST' };
8
9
  const PUBLIC_ERRORS = {
9
10
  'credentials-unavailable': '宿主凭据存储暂不可用,请稍后重试',
10
11
  REMOTE_AUTH: '远程电脑认证失败,请重新绑定', REMOTE_REVOKED: '这台电脑的授权已被撤销,请重新绑定',
11
12
  REMOTE_EXPIRED: '授权已到期,请重新打开', REMOTE_TIMEOUT: '连接远程电脑超时,请重试或检测线路',
12
13
  REMOTE_CONNECT: '暂时无法连接远程电脑,请检查网络和对方是否在线',
14
+ SHELL_UNAVAILABLE: '本机未安装远程电脑桌面端,请改用默认方式打开',
13
15
  };
14
16
  function createRemoteRoutes({ controller, host, credentials, instanceId, now = Date.now }) {
15
17
  function authorizedComputers() {
@@ -49,6 +51,15 @@ function createRemoteRoutes({ controller, host, credentials, instanceId, now = D
49
51
  }
50
52
  if (typeof body.id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(body.id)) throw new Error('bad-id');
51
53
  if (suffix === '/open') return sendJson(res, 200, { ok: true, ...await controller.open(body.id) });
54
+ if (suffix === '/open-shell') {
55
+ const result = await controller.open(body.id);
56
+ const devices = await controller.list();
57
+ const deviceName = devices.find(row => row.id === body.id)?.name || '';
58
+ // 记下这次拉起的桌面进程:它一退出就当窗口关掉,面板据此回到未打开。
59
+ const child = launchShell({ url: result.url, deviceName });
60
+ controller.watchWindow(body.id, child);
61
+ return sendJson(res, 200, { ok: true, ...result });
62
+ }
52
63
  if (suffix === '/renew') return sendJson(res, 200, { ok: true, ...await controller.renew(body.id) });
53
64
  if (suffix === '/stop') await controller.stop(body.id);
54
65
  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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-plugin",
3
- "version": "0.5.53",
3
+ "version": "0.5.54",
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",
@@ -74,6 +74,11 @@
74
74
  "ws": "8.18.0"
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
82
  "dsh-mobile-tailcat-darwin-arm64": "1.1.2",
78
83
  "dsh-mobile-tailcat-darwin-x64": "1.1.2",
79
84
  "dsh-mobile-tailcat-linux-arm64": "1.1.2",