dsh-remote-plugin 0.7.2 → 0.7.4

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.
package/index.mjs CHANGED
@@ -194,7 +194,7 @@ function readBody(req, maxBytes) {
194
194
  })
195
195
  }
196
196
 
197
- /** 转发到本地网关管理 API; 失败/超时返回 null。 */
197
+ /** 转发到本地网关管理 API;缺少令牌返回 null,超时与连接失败保留具体错误。 */
198
198
  async function proxyGateway(path, method, body) {
199
199
  const token = gatewayToken()
200
200
  if (!token) return null
@@ -207,12 +207,14 @@ async function proxyGateway(path, method, body) {
207
207
  'x-dsh-remote-client': 'admin',
208
208
  },
209
209
  body: method === 'POST' ? body : undefined,
210
- signal: AbortSignal.timeout(1500),
210
+ signal: AbortSignal.timeout(path.startsWith('/admin/api/dsh') ? 15000 : 5000),
211
211
  })
212
212
  const json = await res.json().catch(() => ({ ok: false, error: `gateway ${res.status}` }))
213
213
  return { status: res.status, json }
214
- } catch {
215
- return null
214
+ } catch (error) {
215
+ const timeout = error?.name === 'TimeoutError' || error?.name === 'AbortError'
216
+ return { status: timeout ? 504 : 502, json: { ok: false, code: timeout ? 'GATEWAY_TIMEOUT' : 'GATEWAY_UNREACHABLE',
217
+ error: timeout ? '本地网关响应超时,请稍后重试' : '无法连接本地网关,请检查网关运行状态' } }
216
218
  }
217
219
  }
218
220
 
@@ -234,6 +236,7 @@ const GATEWAY_ENV_KEYS = [
234
236
  'TOKEN', 'TOKEN_FILE', 'DSH_REMOTE_TOKEN', 'DSH_REMOTE_DEVICE_KEYS', 'DSH_REMOTE_FS_ROOT', 'DSH_REMOTE_FS_WORKSPACE_CACHE_MS', 'DSH_REMOTE_FS_MAX_UPLOAD',
235
237
  'DSH_REMOTE_DSH_COOKIE_FILE',
236
238
  'DSH_REMOTE_NOTES', 'DSH_REMOTE_WORKBENCH', 'DSH_REMOTE_ADVERTISE_HOSTS', 'DSH_REMOTE_DSH_SERVICE', 'DSH_REMOTE_SYSTEMCTL', 'DSH_REMOTE_DSH_CONTROL_MODE',
239
+ 'DSH_REMOTE_AUTO_RESTART', 'DSH_REMOTE_CRASH_LOG_FILE',
237
240
  'DSH_REMOTE_DSH_CONTROL_TIMEOUT_MS', 'DSH_REMOTE_DSH_CONTROL_POLL_MS', 'DSH_REMOTE_FEEDBACK_URL',
238
241
  'UPDATE_CHECK_URL', 'UPDATE_INTERVAL_MS', 'UPDATE_PROXY', 'DSH_HEALTH_PATH',
239
242
  'GATEWAY_WS_IDLE_MS', 'GATEWAY_WS_PING_MS', 'GATEWAY_WS_PONG_TIMEOUT_MS',
@@ -273,10 +276,18 @@ function portInUse(port) {
273
276
  })
274
277
  }
275
278
 
279
+ let gatewayHealthJob = null
276
280
  async function gatewayRunning() {
281
+ const base = gatewayBase()
282
+ if (gatewayHealthJob?.base === base) return gatewayHealthJob.promise
283
+ const job = { base }
284
+ gatewayHealthJob = job
285
+ job.promise = probeGatewayRunning(base).finally(() => { if (gatewayHealthJob === job) gatewayHealthJob = null })
286
+ return job.promise
287
+ }
288
+ async function probeGatewayRunning(base) {
277
289
  try {
278
- const base = gatewayBase()
279
- const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(6000) })
290
+ const res = await fetch(`${base}/health?probe=live`, { signal: AbortSignal.timeout(6000) })
280
291
  if (!res.ok) return { running: false }
281
292
  const data = await res.json().catch(() => ({}))
282
293
  if (data.service !== 'dsh-remote' || !Number.isInteger(data.pid) || data.pid <= 1
@@ -364,7 +375,7 @@ async function startGateway() {
364
375
  if (health.running) {
365
376
  const auth = await proxyGateway('/admin/api/state', 'GET', '')
366
377
  if (!auth || auth.status !== 200 || auth.json.ok !== true) {
367
- return { ok: false, running: true, started: false, error: GATEWAY_AUTH_HINT }
378
+ return { ok: false, running: true, started: false, error: auth?.status === 401 || auth?.status === 403 ? GATEWAY_AUTH_HINT : auth?.json?.error || '本地网关管理接口响应异常,请稍后重试' }
368
379
  }
369
380
  setGatewayEnabled(true)
370
381
  return { ok: true, running: true, started: false }
@@ -389,7 +400,7 @@ async function startGateway() {
389
400
  '--user', '--unit=dsh-remote-gateway', '--service-type=exec',
390
401
  ...gatewaySystemdEnvArgs(),
391
402
  '--setenv=PORT=' + port, '--setenv=HOST=' + host, '--setenv=DSH_UPSTREAM=' + upstream,
392
- '--', process.execPath, script,
403
+ '--', process.execPath, script, '--supervise',
393
404
  ])) === 0
394
405
  } catch {}
395
406
  if (sysd) {
@@ -405,11 +416,14 @@ async function startGateway() {
405
416
  try {
406
417
  logFd = openSync(`${homedir()}/.dsh-remote/plugin-gateway.log`, 'a')
407
418
  } catch {}
408
- const child = spawn(process.execPath, [script], {
419
+ const gatewayEnv = { ...process.env, PORT: port, HOST: host, DSH_UPSTREAM: upstream }
420
+ delete gatewayEnv.NODE_CHANNEL_FD
421
+ delete gatewayEnv.NODE_CHANNEL_SERIALIZATION_MODE
422
+ const child = spawn(process.execPath, [script, '--supervise'], {
409
423
  cwd: dirname(script),
410
424
  detached: true,
411
425
  stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'],
412
- env: { ...process.env, PORT: port, HOST: host, DSH_UPSTREAM: upstream },
426
+ env: gatewayEnv,
413
427
  })
414
428
  child.unref()
415
429
  writeGatewayPid(child.pid)
@@ -698,11 +712,15 @@ async function serveStatic(req, res, ctx) {
698
712
  sendJson(res, proxied.status, { ...proxied.json, token: localToken, mode: 'gateway', via: 'gateway', gatewayInstalled })
699
713
  return
700
714
  }
715
+ if (health.running && proxied?.status >= 500) {
716
+ sendJson(res, proxied.status, { ...proxied.json, gatewayRunning: true })
717
+ return
718
+ }
701
719
  sendJson(res, 200, {
702
720
  ok: true,
703
721
  mode: 'plugin',
704
722
  gatewayRunning: health.running,
705
- gatewayAuthError: health.running ? GATEWAY_AUTH_HINT : '',
723
+ gatewayAuthError: health.running && (!localToken || proxied?.status === 401 || proxied?.status === 403) ? GATEWAY_AUTH_HINT : '',
706
724
  gatewayVersion: health.version || '',
707
725
  version,
708
726
  token: health.running ? '' : localToken || '',
@@ -850,7 +868,8 @@ async function serveStatic(req, res, ctx) {
850
868
  return
851
869
  }
852
870
  const body = req.method === 'POST' ? await readBody(req, 4096) : ''
853
- const proxied = await proxyGateway('/admin/api/dsh', req.method, body)
871
+ const query = new URL(req.url, 'http://x').search
872
+ const proxied = await proxyGateway('/admin/api/dsh' + query, req.method, body)
854
873
  if (proxied !== null) {
855
874
  sendJson(res, proxied.status, proxied.json)
856
875
  } else {
@@ -986,18 +1005,36 @@ async function serveStatic(req, res, ctx) {
986
1005
  }
987
1006
 
988
1007
  const pluginCenters = new WeakMap()
1008
+ export function desktopLaunchConfig(ctx) {
1009
+ if (process.platform !== 'win32' || !process.versions.electron) return null
1010
+ const profile = detectProfile(ctx)
1011
+ const hostScript = process.argv[1] || ''
1012
+ if (profile?.name !== 'desktop' || !/[\\/]@deepseek-ai[\\/]dsh-desktop-host[\\/]lib[\\/]index\.js$/.test(hostScript)) return null
1013
+ const pid = process.pid, parent = process.ppid
1014
+ try {
1015
+ const script = '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); @(' + [pid,parent].map(id =>
1016
+ "Get-CimInstance Win32_Process -Filter 'ProcessId=" + id + "' | ForEach-Object { @{pid=$_.ProcessId;parent=$_.ParentProcessId;executable=$_.ExecutablePath;command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')} }").join('; ') + ') | ConvertTo-Json -Compress'
1017
+ const rows = JSON.parse(execFileSync('powershell.exe', ['-NoLogo','-NoProfile','-NonInteractive','-Command',script], { encoding:'utf8', timeout:8000, windowsHide:true }))
1018
+ const host = rows.find(row => row.pid === pid), root = rows.find(row => row.pid === parent)
1019
+ if (!host || !root || host.parent !== root.pid || resolve(root.executable) !== resolve(process.execPath) || resolve(host.executable) !== resolve(process.execPath) || /--(?:type|expose-internals)\b/.test(root.command)) return null
1020
+ return { version:1, kind:'desktop', executable:process.execPath, args:[], cwd:dirname(process.execPath), profile:'desktop', env:{DSH_HOME:profile.home},
1021
+ upstream:upstreamUrlForListener(ctx.webServer), desktop:{root:{pid:root.pid,started:root.started},host:{pid:host.pid,started:host.started},hostScript,profilePath:profile.dir} }
1022
+ } catch (error) { logGateway('Desktop 启动信息核验失败: ' + error.message); return null }
1023
+ }
1024
+
989
1025
  export function saveDshLaunchConfig(ctx) {
990
- // Desktop owns its Electron runtime. Never record a desktop or unknown launcher.
991
- if (process.platform !== 'win32' || process.versions.electron) return false
1026
+ if (process.platform !== 'win32') return false
1027
+ const desktop = desktopLaunchConfig(ctx)
1028
+ if (process.versions.electron && !desktop) return false
992
1029
  const profile = detectProfile(ctx)
993
- if (!profile?.cli || profile.name === 'desktop' || resolve(process.argv[1] || '') !== resolve(profile.cli)) return false
1030
+ if (!desktop && (!profile?.cli || profile.name === 'desktop' || resolve(process.argv[1] || '') !== resolve(profile.cli))) return false
994
1031
  const env = { DSH_HOME: profile.home }
995
1032
  for (const key of ['HOME', 'USERPROFILE', 'PATH', 'NODE_OPTIONS']) {
996
1033
  if (process.env[key] !== undefined) env[key] = process.env[key]
997
1034
  }
998
- const args = [profile.cli, ...process.argv.slice(2)]
999
- if (!args.includes('--no-open')) args.push('--no-open')
1000
- const config = { version: 1, executable: process.execPath, args, cwd: process.cwd(),
1035
+ const args = desktop ? [] : [profile.cli, ...process.argv.slice(2)]
1036
+ if (!desktop && !args.includes('--no-open')) args.push('--no-open')
1037
+ const config = desktop || { version: 1, executable: process.execPath, args, cwd: process.cwd(),
1001
1038
  env, profile: profile.name, upstream: upstreamUrlForListener({ host: ctx.webServer.host, port: ctx.webServer.port }) }
1002
1039
  const file = process.env.DSH_REMOTE_DSH_LAUNCH_FILE || `${homedir()}/.dsh-remote/dsh-launch.json`
1003
1040
  const tmp = `${file}.${process.pid}.tmp`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.7.2",
3
+ "version": "0.7.4",
4
4
  "description": "DSH Remote 官方 bundle 插件:DSH 左侧原生边栏入口 + 右侧抽屉内嵌管理控制台;内置网关随 DSH 自动启停(systemd 独立单元),抽屉直显令牌与设备监控;网关提供 /fs/* 文件传输端点(列表/断点下载/上传),配合 Android App 远程操控会话/审批/提问/goal 与文件互传(多服务器测速切换、聊天记录离线缓存)。",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
package/public/admin.js CHANGED
@@ -419,17 +419,30 @@ function renderDeviceKeys(st, isGateway) {
419
419
  document.querySelectorAll('[data-device-key-revoke]').forEach(button => button.addEventListener('click', () => revokeDeviceKey(byId(button.dataset.deviceKeyRevoke))))
420
420
  }
421
421
 
422
+ let stateLoadJob = null
422
423
  async function loadState() {
423
424
  if (!token && !pluginMode) return
425
+ if (stateLoadJob?.token === token) return stateLoadJob.promise
426
+ const job = { token }
427
+ stateLoadJob = job
428
+ job.promise = readState(job).finally(() => { if (stateLoadJob === job) stateLoadJob = null })
429
+ return job.promise
430
+ }
431
+ async function readState(job) {
424
432
  try {
425
433
  const res = await fetch(`${API}/state`, {
426
- headers: adminHeaders(), credentials: 'same-origin'
434
+ headers: adminHeaders({}, job.token), credentials: 'same-origin',
435
+ signal: typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(10000) : undefined
427
436
  })
437
+ if (stateLoadJob !== job || token !== job.token) return
438
+ if (!res.ok && res.status !== 401) throw new Error('HTTP ' + res.status)
428
439
  if (res.status === 401) throw new Error(pluginMode ? 'AUTH_LAYER' : 'AUTH')
429
440
  if (pluginMode && !String(res.headers.get('content-type') || '').includes('application/json')) throw new Error('AUTH_LAYER')
430
441
  const st = await res.json()
442
+ if (stateLoadJob !== job || token !== job.token) return
431
443
  render(st)
432
444
  } catch (e) {
445
+ if (stateLoadJob !== job || token !== job.token) return
433
446
  if (e.message === 'AUTH') {
434
447
  toast(t('toast.tokenInvalid'), 'err')
435
448
  logout()
@@ -835,7 +848,7 @@ $('btn-host-ip-add').addEventListener('click', addManualHostIP)
835
848
  $('conn-badge').addEventListener('click', () => {
836
849
  const st = lastState
837
850
  if (!st || st.mode !== 'gateway') { toast(t('toast.gatewayDown'), 'err'); return }
838
- const host = location.hostname || '127.0.0.1'
851
+ const host = location.protocol === 'dsh-app:' ? '127.0.0.1' : location.hostname || '127.0.0.1'
839
852
  const port = st.port || 8787
840
853
  const url = `http://${host}:${port}/admin?token=${encodeURIComponent(shownToken || token)}`
841
854
  try {