dsh-remote-plugin 0.7.3 → 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.
Binary file
package/gateway.cjs CHANGED
@@ -36,6 +36,51 @@ const fs = require('node:fs')
36
36
  const path = require('node:path')
37
37
  const os = require('node:os')
38
38
  const crypto = require('node:crypto')
39
+ const zlib = require('node:zlib')
40
+ const { pipeline } = require('node:stream')
41
+
42
+ // Compression is local to Remote responses, without changing DSH prototypes.
43
+ const HTTP_COMPRESSION = process.env.GATEWAY_HTTP_COMPRESSION !== '0'
44
+ function acceptsGzip(req) {
45
+ const choices = new Map(String(req.headers['accept-encoding'] || '').toLowerCase().split(',').map(part => {
46
+ const [name, ...params] = part.trim().split(';')
47
+ const weight = params.find(p => /^\s*q\s*=/.test(p))
48
+ const q = weight ? Number(weight.split('=')[1]) : 1
49
+ return [name, Number.isFinite(q) && q >= 0 && q <= 1 ? q : 0]
50
+ }))
51
+ return (choices.get('gzip') ?? choices.get('*') ?? 0) > 0
52
+ }
53
+ function compressibleType(type) {
54
+ return /^(?:text\/(?:html|css|plain|javascript|xml)|application\/(?:javascript|json|manifest\+json|xml)|image\/svg\+xml)(?:;|$)/i.test(String(type || ''))
55
+ }
56
+ function addEncodingVary(headers, existing = '') {
57
+ const values = (String(existing || '') + ',' + String(headers.vary || '')).split(',').map(v => v.trim()).filter(Boolean)
58
+ if (!values.some(v => v.toLowerCase() === 'accept-encoding' || v === '*')) values.push('Accept-Encoding')
59
+ headers.vary = values.join(', ')
60
+ return headers
61
+ }
62
+ function sendHttpBody(res, status, headers, body, compress = false) {
63
+ const data = Buffer.isBuffer(body) ? body : Buffer.from(String(body || ''))
64
+ const req = res.req, out = { ...headers }
65
+ if (compress) addEncodingVary(out, res.getHeader?.('vary'))
66
+ const finish = bytes => {
67
+ if (res.destroyed || res.writableEnded) return
68
+ res.writeHead(status, { ...out, 'content-length': bytes.length })
69
+ res.end(req?.method === 'HEAD' ? undefined : bytes)
70
+ }
71
+ if (!compress || !HTTP_COMPRESSION || !req || req.method === 'HEAD' || status !== 200 || data.length < 1024
72
+ || req.headers.range || out['content-encoding'] || /no-transform/i.test(out['cache-control'] || '')
73
+ || !compressibleType(out['content-type']) || !acceptsGzip(req)) return finish(data)
74
+ zlib.gzip(data, { level: 3 }, (error, zipped) => {
75
+ if (error || zipped.length >= data.length) return finish(data)
76
+ out['content-encoding'] = 'gzip'
77
+ finish(zipped)
78
+ })
79
+ }
80
+ function compressibleRpc(req) {
81
+ const pathname = String(req?.url || '').split('?')[0]
82
+ return ['/api/session.history', '/api/session.list', '/api/workspace.list', '/api/host.describe'].includes(pathname)
83
+ }
39
84
 
40
85
  // Crash records deliberately contain facts and source positions, never arbitrary error text.
41
86
  const CRASH_LOG_FILE=process.env.DSH_REMOTE_CRASH_LOG_FILE || path.join(os.homedir(),'.dsh-remote','crashes.jsonl')
@@ -1203,13 +1248,18 @@ async function desktopProcessEvidence(config) {
1203
1248
  const d = config.desktop
1204
1249
  const script = '[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false); $rows=@(' + [d.root.pid,d.host.pid].map(pid =>
1205
1250
  "Get-CimInstance Win32_Process -Filter 'ProcessId=" + pid + "' | ForEach-Object { @{pid=$_.ProcessId;parent=$_.ParentProcessId;executable=$_.ExecutablePath;command=$_.CommandLine;started=$_.CreationDate.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')} }").join('; ') +
1206
- '); $owners=@(Get-NetTCPConnection -State Listen -LocalPort ' + UPSTREAM_PORT + ' -ErrorAction SilentlyContinue | ForEach-Object {$_.OwningProcess}); @{rows=$rows;owners=$owners} | ConvertTo-Json -Compress -Depth 4'
1251
+ '); $owners=@(Get-NetTCPConnection -State Listen -LocalPort ' + UPSTREAM_PORT + ' -ErrorAction SilentlyContinue | ForEach-Object {@{pid=$_.OwningProcess;address=$_.LocalAddress}}); @{rows=$rows;owners=$owners} | ConvertTo-Json -Compress -Depth 4'
1207
1252
  const result = await execFileResult('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command',script],10000)
1208
1253
  if (!result.ok) throw new Error('无法读取 Desktop 进程身份: ' + result.stderr)
1209
1254
  return JSON.parse(result.stdout)
1210
1255
  }
1211
1256
  function verifyDesktopEvidence(config, evidence) {
1212
- const d=config.desktop, rows=evidence.rows || [], owners=evidence.owners || []
1257
+ const d=config.desktop, rows=evidence.rows || []
1258
+ const target=UPSTREAM.hostname.replace(/^\[|\]$/g,'').toLowerCase()
1259
+ const owners=(evidence.owners || []).filter(owner=>typeof owner==='number' ||
1260
+ (owner.address==='0.0.0.0' && !target.includes(':')) || owner.address==='::' ||
1261
+ (target==='localhost' ? ['127.0.0.1','::1'].includes(owner.address) : owner.address===target))
1262
+ .map(owner=>typeof owner==='number'?owner:owner.pid)
1213
1263
  const root=rows.find(row=>row.pid===d.root.pid), host=rows.find(row=>row.pid===d.host.pid)
1214
1264
  const sameExecutable=row=>row?.executable && path.resolve(row.executable).toLowerCase()===path.resolve(config.executable).toLowerCase()
1215
1265
  const rootValid=sameExecutable(root) && root.started===d.root.started && !/--(?:type|expose-internals)\b/.test(root.command || '')
@@ -1266,7 +1316,7 @@ function dshPortOccupied() {
1266
1316
  })
1267
1317
  }
1268
1318
 
1269
- async function dshProcessStatus() {
1319
+ async function dshProcessStatus({ cachedProbe = false } = {}) {
1270
1320
  const base = { ok: true, supported: true, manager: 'process', service: 'dsh-process', running: false, mainPid: 0, canRestart: false }
1271
1321
  try { readDshLaunch() } catch (err) {
1272
1322
  return { ...base, supported: false, code: 'LAUNCH_CONFIG_INVALID', message: '缺少有效 DSH 启动配置,请先从 DSH Web 启动 Remote 插件', detail: err.message }
@@ -1277,7 +1327,7 @@ async function dshProcessStatus() {
1277
1327
  return { ...base, running: true, mainPid: dshManagedChild.pid, owned: true, canRestart: true, activeState: 'active', subState: 'running' }
1278
1328
  }
1279
1329
  const occupied = await dshPortOccupied()
1280
- const probe = occupied ? await probeDshUpstream() : null
1330
+ const probe = occupied ? await (cachedProbe ? refreshHealthProbe() : probeDshUpstream()) : null
1281
1331
  return { ...base, running: !!probe?.ok, occupied, owned: false,
1282
1332
  activeState: occupied ? (probe?.ok ? 'active' : 'inactive') : dshManagedExit ? 'failed' : 'inactive',
1283
1333
  subState: occupied ? 'external' : 'stopped',
@@ -1328,17 +1378,17 @@ async function executeDshProcessAction(action) {
1328
1378
  })
1329
1379
  }
1330
1380
 
1331
- async function dshServiceStatus() {
1381
+ async function dshServiceStatus(options = {}) {
1332
1382
  if (!/^[A-Za-z0-9_.@-]+$/.test(DSH_SERVICE)) {
1333
1383
  return { ok: false, supported: false, running: false, service: DSH_SERVICE, code: 'INVALID_SERVICE', message: 'DSH_REMOTE_DSH_SERVICE 服务名配置不合法' }
1334
1384
  }
1335
1385
  if (!DSH_CONTROL_SUPPORT.supported) {
1336
1386
  return { ok: true, supported: false, running: false, service: DSH_SERVICE, ...DSH_CONTROL_SUPPORT }
1337
1387
  }
1338
- if (DSH_CONTROL_MODE === 'process') return dshProcessStatus()
1388
+ if (DSH_CONTROL_MODE === 'process') return dshProcessStatus(options)
1339
1389
  if (process.platform === 'win32') {
1340
1390
  const service = await windowsServiceStatus()
1341
- if (DSH_CONTROL_MODE === 'auto' && service.code === 'SERVICE_NOT_FOUND') return dshProcessStatus()
1391
+ if (DSH_CONTROL_MODE === 'auto' && service.code === 'SERVICE_NOT_FOUND') return dshProcessStatus(options)
1342
1392
  return { ...service, manager: 'windows' }
1343
1393
  }
1344
1394
  const r = await execFileResult(SYSTEMCTL, [
@@ -1408,12 +1458,12 @@ function delay(ms) {
1408
1458
  return new Promise(resolvePromise => setTimeout(resolvePromise, ms))
1409
1459
  }
1410
1460
 
1411
- async function probeDshUpstream() {
1461
+ async function probeDshUpstream(timeoutMs = 2500) {
1412
1462
  const startedAt = Date.now()
1413
1463
  try {
1414
1464
  const probe = await fetch(new URL(DSH_HEALTH_PATH, UPSTREAM), {
1415
1465
  headers: dshUpstreamHeaders(),
1416
- signal: AbortSignal.timeout(Math.min(2500, UPSTREAM_REQUEST_TIMEOUT_MS)),
1466
+ signal: AbortSignal.timeout(Math.min(timeoutMs, UPSTREAM_REQUEST_TIMEOUT_MS)),
1417
1467
  cache: 'no-store',
1418
1468
  })
1419
1469
  return {
@@ -1480,14 +1530,21 @@ async function desktopCrashEvidence(config) {
1480
1530
  }
1481
1531
  let desktopWatchBusy=false
1482
1532
  const desktopCrashSeen=new Set()
1533
+ const desktopMissingSince=new Map()
1483
1534
  async function checkDesktopCrash() {
1484
- if(!AUTO_RESTART||desktopWatchBusy||(dshControlOperation&&!dshControlOperation.done))return
1535
+ if(!AUTO_RESTART||!DSH_CONTROL_SUPPORT.supported||desktopWatchBusy||(dshControlOperation&&!dshControlOperation.done))return
1485
1536
  let config;try{config=readDshLaunch()}catch{return}
1486
1537
  if(config.kind!=='desktop')return
1487
1538
  const alive=pid=>{try{process.kill(pid,0);return true}catch(e){return e.code!=='ESRCH'}}
1488
- if(alive(config.desktop.root.pid)&&alive(config.desktop.host.pid))return
1539
+ if(alive(config.desktop.root.pid)&&alive(config.desktop.host.pid)){desktopMissingSince.clear();return}
1489
1540
  const identity=config.desktop.root.started+':'+config.desktop.root.pid+':'+config.desktop.host.pid
1490
1541
  if(desktopCrashSeen.has(identity)||recoveryTimers.has('desktop'))return
1542
+ if(!desktopMissingSince.has(identity)){desktopMissingSince.clear();desktopMissingSince.set(identity,Date.now())}
1543
+ // Event logs can arrive late, but a normal quit must not poll crash logs forever.
1544
+ if(Date.now()-desktopMissingSince.get(identity)>=120000){
1545
+ desktopCrashSeen.add(identity);if(desktopCrashSeen.size>20)desktopCrashSeen.delete(desktopCrashSeen.values().next().value)
1546
+ desktopMissingSince.delete(identity);return
1547
+ }
1491
1548
  desktopWatchBusy=true
1492
1549
  try{
1493
1550
  if(await desktopCrashEvidence(config)){
@@ -2167,11 +2224,10 @@ function eventPollPayload(kind, since, waitSupported = false) {
2167
2224
  function sendEventPollResponse(waiter, payload) {
2168
2225
  if (waiter.req.destroyed || waiter.res.destroyed) return
2169
2226
  cors(waiter.res)
2170
- waiter.res.writeHead(200, {
2227
+ sendHttpBody(waiter.res, 200, {
2171
2228
  'content-type': 'application/json; charset=utf-8',
2172
2229
  'cache-control': 'no-store'
2173
- })
2174
- waiter.res.end(JSON.stringify(payload))
2230
+ }, JSON.stringify(payload), true)
2175
2231
  }
2176
2232
 
2177
2233
  function finishEventPollWaiter(waiter, send = true) {
@@ -2255,11 +2311,10 @@ function serveEventPoll(req, res, url) {
2255
2311
  const payload = eventPollPayload(kind, since, waitSupported)
2256
2312
  if (payload.events.length || wait <= 0 || EVENT_POLL_WAIT_MAX <= 0) {
2257
2313
  cors(res)
2258
- res.writeHead(200, {
2314
+ sendHttpBody(res, 200, {
2259
2315
  'content-type': 'application/json; charset=utf-8',
2260
2316
  'cache-control': 'no-store'
2261
- })
2262
- res.end(JSON.stringify(payload))
2317
+ }, JSON.stringify(payload), true)
2263
2318
  return
2264
2319
  }
2265
2320
  const waiter = { req, res, kind, since, timer: null }
@@ -3207,6 +3262,7 @@ function serveStatic(req, res, url) {
3207
3262
  return
3208
3263
  }
3209
3264
  fs.stat(filePath, (err, st) => {
3265
+ if (res.destroyed || res.writableEnded) return
3210
3266
  if (err || !st.isFile()) {
3211
3267
  res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
3212
3268
  res.end('404 Not Found')
@@ -3215,40 +3271,38 @@ function serveStatic(req, res, url) {
3215
3271
  const ext = path.extname(filePath).toLowerCase()
3216
3272
  const lastModified = st.mtime.toUTCString()
3217
3273
  const mtimeSec = Math.floor(st.mtime.getTime() / 1000) * 1000
3274
+ const type = MIME[ext] || 'application/octet-stream'
3275
+ const text = compressibleType(type)
3276
+ const zipped = HTTP_COMPRESSION && text && st.size >= 1024 && req.method !== 'HEAD' && !req.headers.range && acceptsGzip(req)
3277
+ const etag = `W/"${st.size}-${st.mtimeMs}-${zipped ? 'gzip' : 'identity'}"`
3218
3278
  cors(res)
3219
3279
  const ims = req.headers['if-modified-since']
3220
- if (ims && new Date(ims).getTime() >= mtimeSec) {
3221
- res.writeHead(304, { 'last-modified': lastModified })
3280
+ const matched = req.headers['if-none-match']
3281
+ const cache = pathname === '/harmonyos-update.json' ? 'no-store' : ext === '.html' || ext === '.js' || ext === '.css' ? 'no-cache' : 'public, max-age=300'
3282
+ const headers = { 'content-type': type, 'cache-control': cache, 'last-modified': lastModified, etag }
3283
+ if (text) addEncodingVary(headers, res.getHeader('vary'))
3284
+ if (cache !== 'no-store' && (matched ? String(matched).split(',').some(v => v.trim() === etag || v.trim() === '*') : ims && new Date(ims).getTime() >= mtimeSec)) {
3285
+ res.writeHead(304, headers)
3222
3286
  res.end()
3223
3287
  return
3224
3288
  }
3225
- res.writeHead(200, {
3226
- 'content-type': MIME[ext] || 'application/octet-stream',
3227
- 'cache-control': pathname === '/harmonyos-update.json' ? 'no-store' : ext === '.html' || ext === '.js' || ext === '.css' ? 'no-cache' : 'public, max-age=300',
3228
- 'content-length': st.size,
3229
- 'last-modified': lastModified
3230
- })
3289
+ if (zipped) headers['content-encoding'] = 'gzip'
3290
+ else headers['content-length'] = st.size
3291
+ res.writeHead(200, headers)
3231
3292
  if (req.method === 'HEAD') res.end()
3232
- else fs.createReadStream(filePath).pipe(res)
3293
+ else {
3294
+ const stream = fs.createReadStream(filePath)
3295
+ const done = error => { if (error && !res.destroyed) res.destroy() }
3296
+ if (zipped) pipeline(stream, zlib.createGzip({ level: 3 }), res, done)
3297
+ else pipeline(stream, res, done)
3298
+ }
3233
3299
  })
3234
3300
  }
3235
3301
 
3236
3302
  // ---------- 管理 API ----------
3237
3303
  function upstreamReachable(cb) {
3238
- const req = UPSTREAM_TRANSPORT.request({
3239
- hostname: UPSTREAM_HOSTNAME,
3240
- port: UPSTREAM_PORT,
3241
- method: 'GET',
3242
- path: '/health',
3243
- headers: dshUpstreamHeaders(),
3244
- timeout: 1500
3245
- }, (res) => {
3246
- res.resume()
3247
- cb(true)
3248
- })
3249
- req.on('error', () => cb(false))
3250
- req.on('timeout', () => { req.destroy(); cb(false) })
3251
- req.end()
3304
+ void refreshHealthProbe()
3305
+ cb(healthProbeState.reachable)
3252
3306
  }
3253
3307
 
3254
3308
  async function serveAdminApi(req, res, url) {
@@ -4740,11 +4794,10 @@ async function forwardLegacyRpc(url, raw, allowVisionBridge = true) {
4740
4794
 
4741
4795
  function sendBufferedUpstreamResponse(res, response) {
4742
4796
  cors(res)
4743
- res.writeHead(response.status || 502, {
4797
+ sendHttpBody(res, response.status || 502, {
4744
4798
  'content-type': response.headers?.get?.('content-type') || 'application/json; charset=utf-8',
4745
4799
  'cache-control': 'no-store',
4746
- })
4747
- res.end(response.raw || '')
4800
+ }, response.raw || '', compressibleRpc(res.req))
4748
4801
  }
4749
4802
 
4750
4803
  async function proxyLegacyRpcWithModernFallback(req, res, url) {
@@ -4780,8 +4833,7 @@ async function proxyLegacyRpcWithModernFallback(req, res, url) {
4780
4833
  }
4781
4834
  }
4782
4835
  cors(res)
4783
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
4784
- res.end(JSON.stringify(translated))
4836
+ sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify(translated), compressibleRpc(req))
4785
4837
  }
4786
4838
 
4787
4839
  async function proxyModernApi(req, res, url) {
@@ -4828,8 +4880,7 @@ async function proxyModernApi(req, res, url) {
4828
4880
  sendBufferedUpstreamResponse(res, legacy)
4829
4881
  return true
4830
4882
  }
4831
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
4832
- res.end(JSON.stringify(translated))
4883
+ sendHttpBody(res, 200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }, JSON.stringify(translated), compressibleRpc(req))
4833
4884
  return true
4834
4885
  } catch (error) {
4835
4886
  if (!res.headersSent) {
@@ -4933,13 +4984,42 @@ function proxyApi(req, res, url) {
4933
4984
  }
4934
4985
 
4935
4986
  // ---------- 其它 ----------
4936
- async function dshControlDescription() {
4987
+ // Expensive OS/upstream checks run once in the background; public status never
4988
+ // grants restart authority. Actual lifecycle actions still verify fresh evidence.
4989
+ let healthProbeState = { ok: false, reachable: false, status: 0, checkedAt: 0, error: '' }
4990
+ let healthProbeTask = null
4991
+ function refreshHealthProbe(force = false) {
4992
+ if (healthProbeTask) return healthProbeTask
4993
+ if (!force && healthProbeState.checkedAt && Date.now() - healthProbeState.checkedAt < 5000) return Promise.resolve(healthProbeState)
4994
+ healthProbeTask = probeDshUpstream(5000).then(value => {
4995
+ healthProbeState = { ...value, checkedAt: Date.now() }
4996
+ return healthProbeState
4997
+ }).finally(() => { healthProbeTask = null })
4998
+ return healthProbeTask
4999
+ }
5000
+ let controlDescriptionState = null
5001
+ let controlDescriptionTask = null
5002
+ let controlDescriptionAt = 0
5003
+ async function dshControlDescription(force = false) {
4937
5004
  if (!DSH_CONTROL_SUPPORT.supported) return DSH_CONTROL_SUPPORT
4938
5005
  if (process.platform !== 'win32' && DSH_CONTROL_MODE !== 'process') return DSH_CONTROL_SUPPORT
4939
- const status = await dshServiceStatus()
4940
- return { supported: status.supported, manager: status.manager || DSH_CONTROL_SUPPORT.manager,
4941
- ...(status.code ? { code: status.code, message: status.message } : {}),
4942
- ...(status.canRestart !== undefined ? { canRestart: status.canRestart } : {}) }
5006
+ if (DSH_CONTROL_MODE === 'process') {
5007
+ try { readDshLaunch() } catch (error) {
5008
+ return { supported: false, manager: 'process', code: 'LAUNCH_CONFIG_INVALID', message: '缺少有效 DSH 启动配置,请先从 DSH 插件重新生成', canRestart: false }
5009
+ }
5010
+ }
5011
+ if (!controlDescriptionTask && (force || Date.now() - controlDescriptionAt >= 5000)) {
5012
+ controlDescriptionTask = dshServiceStatus({ cachedProbe: true }).then(status => {
5013
+ controlDescriptionState = { supported: status.supported, manager: status.manager || DSH_CONTROL_SUPPORT.manager,
5014
+ ...(status.code ? { code: status.code, message: status.message } : {}),
5015
+ ...(status.canRestart !== undefined ? { canRestart: status.canRestart } : {}) }
5016
+ controlDescriptionAt = Date.now()
5017
+ }).catch(() => {
5018
+ controlDescriptionState = { supported: false, code: 'STATUS_PARSE_FAILED', message: '无法读取 DSH 生命周期状态', canRestart: false }
5019
+ controlDescriptionAt = Date.now()
5020
+ }).finally(() => { controlDescriptionTask = null })
5021
+ }
5022
+ return controlDescriptionState || { ...DSH_CONTROL_SUPPORT, canRestart: false, checking: true }
4943
5023
  }
4944
5024
 
4945
5025
  async function serveHealth(req, res, url) {
@@ -4955,30 +5035,11 @@ async function serveHealth(req, res, url) {
4955
5035
  clients: state.clients,
4956
5036
  }]))
4957
5037
  const liveness = { ok: true, pid: process.pid, uptimeMs: Math.max(0, Date.now() - STARTED_AT), runtime: runtimeState }
4958
- if (url?.searchParams.get('probe') === 'live') {
4959
- cors(res)
4960
- res.writeHead(200, { 'content-type': 'application/json' })
4961
- res.end(JSON.stringify({ ok: true, service: 'dsh-remote', version: VERSION, probe: 'live', liveness }))
4962
- return
4963
- }
4964
- let upstreamOk = false
4965
- let upstreamReachable = false
4966
- let upstreamStatus = 0
4967
- let upstreamError = ''
4968
- let timer = null
4969
- try {
4970
- const ctrl = new AbortController()
4971
- timer = setTimeout(() => ctrl.abort(), 5000)
4972
- const probeUrl = new URL(DSH_HEALTH_PATH, UPSTREAM).toString()
4973
- const probe = await fetch(probeUrl, { headers: dshUpstreamHeaders(), signal: ctrl.signal, cache: 'no-store' })
4974
- upstreamReachable = true
4975
- upstreamStatus = probe.status
4976
- upstreamOk = probe.ok
4977
- } catch (err) {
4978
- upstreamError = String(err?.message || err || '')
4979
- } finally {
4980
- if (timer) clearTimeout(timer)
4981
- }
5038
+ const live = url?.searchParams.get('probe') === 'live'
5039
+ const probeTask = refreshHealthProbe()
5040
+ // A small cold-start budget preserves useful readiness on fast local upstreams.
5041
+ if (!live && !healthProbeState.checkedAt) await Promise.race([probeTask, delay(100)])
5042
+ const { ok: upstreamOk, reachable: upstreamReachable, status: upstreamStatus, error: upstreamError } = healthProbeState
4982
5043
  const eventsOk = eventHealth.mux.connected && eventHealth.host.connected
4983
5044
  const readiness = { ok: upstreamOk && eventsOk, upstreamOk, eventsOk }
4984
5045
  const status = readiness.ok ? 'ready' : upstreamReachable ? 'degraded' : 'offline'
@@ -4988,6 +5049,7 @@ async function serveHealth(req, res, url) {
4988
5049
  res.end(JSON.stringify({
4989
5050
  ok: true,
4990
5051
  service: 'dsh-remote',
5052
+ ...(live ? { probe: 'live' } : {}),
4991
5053
  status,
4992
5054
  liveness,
4993
5055
  readiness,
@@ -5001,6 +5063,8 @@ async function serveHealth(req, res, url) {
5001
5063
  upstreamOk,
5002
5064
  upstreamReachable,
5003
5065
  upstreamStatus,
5066
+ upstreamCheckedAt: healthProbeState.checkedAt,
5067
+ upstreamChecking: !!healthProbeTask,
5004
5068
  ...(upstreamError ? { upstreamError } : {}),
5005
5069
  events: eventHealth,
5006
5070
  runtime: runtimeState,
@@ -5424,6 +5488,10 @@ server.on('clientError', (err, socket) => {
5424
5488
  })
5425
5489
 
5426
5490
  server.listen(PORT, HOST, () => {
5491
+ void refreshHealthProbe()
5492
+ void dshControlDescription()
5493
+ const healthRefresh = setInterval(() => { void refreshHealthProbe(true); void dshControlDescription(true) }, 5000)
5494
+ healthRefresh.unref?.()
5427
5495
  recordCrash('gateway','startup')
5428
5496
  const crashWatch=setInterval(()=>{void checkDesktopCrash()},5000);crashWatch.unref?.()
5429
5497
  const clientToken = deviceKeyState.enabled ? deviceKeyState.keys[0]?.token : TOKEN
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
 
@@ -274,10 +276,18 @@ function portInUse(port) {
274
276
  })
275
277
  }
276
278
 
279
+ let gatewayHealthJob = null
277
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) {
278
289
  try {
279
- const base = gatewayBase()
280
- const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(6000) })
290
+ const res = await fetch(`${base}/health?probe=live`, { signal: AbortSignal.timeout(6000) })
281
291
  if (!res.ok) return { running: false }
282
292
  const data = await res.json().catch(() => ({}))
283
293
  if (data.service !== 'dsh-remote' || !Number.isInteger(data.pid) || data.pid <= 1
@@ -365,7 +375,7 @@ async function startGateway() {
365
375
  if (health.running) {
366
376
  const auth = await proxyGateway('/admin/api/state', 'GET', '')
367
377
  if (!auth || auth.status !== 200 || auth.json.ok !== true) {
368
- 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 || '本地网关管理接口响应异常,请稍后重试' }
369
379
  }
370
380
  setGatewayEnabled(true)
371
381
  return { ok: true, running: true, started: false }
@@ -702,11 +712,15 @@ async function serveStatic(req, res, ctx) {
702
712
  sendJson(res, proxied.status, { ...proxied.json, token: localToken, mode: 'gateway', via: 'gateway', gatewayInstalled })
703
713
  return
704
714
  }
715
+ if (health.running && proxied?.status >= 500) {
716
+ sendJson(res, proxied.status, { ...proxied.json, gatewayRunning: true })
717
+ return
718
+ }
705
719
  sendJson(res, 200, {
706
720
  ok: true,
707
721
  mode: 'plugin',
708
722
  gatewayRunning: health.running,
709
- gatewayAuthError: health.running ? GATEWAY_AUTH_HINT : '',
723
+ gatewayAuthError: health.running && (!localToken || proxied?.status === 401 || proxied?.status === 403) ? GATEWAY_AUTH_HINT : '',
710
724
  gatewayVersion: health.version || '',
711
725
  version,
712
726
  token: health.running ? '' : localToken || '',
@@ -854,7 +868,8 @@ async function serveStatic(req, res, ctx) {
854
868
  return
855
869
  }
856
870
  const body = req.method === 'POST' ? await readBody(req, 4096) : ''
857
- 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)
858
873
  if (proxied !== null) {
859
874
  sendJson(res, proxied.status, proxied.json)
860
875
  } else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-remote-plugin",
3
- "version": "0.7.3",
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 {