dsh-remote-plugin 0.8.0 → 0.8.2

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
@@ -3,14 +3,15 @@
3
3
  * - /remote/... 移动控制台 + 主机管理页静态资源
4
4
  * - /remote/admin/api 管理控制台数据: 优先代理本地网关(完整设备监控/更新检查),
5
5
  * 网关不可用时回退到插件模式主机状态
6
- * 浏览器侧入口由 client half 注册在 DSH 原生侧边栏(见 client.js)。
6
+ * 浏览器侧入口由 client half 注册在 DSH「更多」菜单(见 client.js)。
7
7
  */
8
- import { execFileSync, spawn } from 'node:child_process'
9
- import { appendFileSync, chmodSync, createReadStream, existsSync, mkdirSync, openSync, readFileSync, writeFileSync, renameSync } from 'node:fs'
8
+ import { registerFileDeliveryTools } from './file-delivery.mjs'
9
+ import { execFileSync, spawn, spawnSync } from 'node:child_process'
10
+ import { appendFileSync, chmodSync, closeSync, copyFileSync, createReadStream, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
10
11
  import { stat } from 'node:fs/promises'
11
12
  import net from 'node:net'
12
- import { homedir, hostname, networkInterfaces } from 'node:os'
13
- import { dirname, extname, normalize, resolve } from 'node:path'
13
+ import { homedir, hostname, networkInterfaces, tmpdir } from 'node:os'
14
+ import { basename, dirname, extname, isAbsolute, join, normalize, resolve } from 'node:path'
14
15
  import { fileURLToPath } from 'node:url'
15
16
  import { randomUUID } from 'node:crypto'
16
17
  import { createPluginCenter, detectProfile } from './plugin-center.mjs'
@@ -105,6 +106,18 @@ export function upstreamUrlForListener({ host, port }) {
105
106
  return `http://${net.isIP(target) === 6 ? `[${target}]` : target}:${port}`
106
107
  }
107
108
 
109
+ /** Desktop hands a fixed local browser landing to the host's own auth flow. */
110
+ export function browserLaunchUrl(ctx) {
111
+ if (typeof ctx.connection?.authenticatedUrl !== 'function') return null
112
+ const base = new URL(upstreamUrlForListener(ctx.webServer))
113
+ if (ctx.webServer.protocol === 'https:') base.protocol = 'https:'
114
+ if (!['127.0.0.1', '[::1]'].includes(base.hostname)) return null
115
+ const url = new URL(ctx.connection.authenticatedUrl(base.href))
116
+ if (url.origin !== base.origin || url.pathname !== '/' || url.username || url.password) return null
117
+ url.hash = 'dsh-remote-connect'
118
+ return url.href
119
+ }
120
+
108
121
  function dshUpstreamCookieFile() {
109
122
  return process.env.DSH_REMOTE_DSH_COOKIE_FILE || `${homedir()}/.dsh-remote/dsh-upstream.cookie`
110
123
  }
@@ -385,6 +398,413 @@ function setGatewayEnabled(on) {
385
398
  } catch {}
386
399
  }
387
400
 
401
+ /* ---------- 网关解释器解析 ----------
402
+ * Windows 不允许覆盖正在运行的可执行文件,而 DSH Desktop 的 NSIS 更新器会原地替换整棵
403
+ * 安装目录。旧实现用 process.execPath(桌面版即 DeepSeek Harness.exe) + detached 启动
404
+ * 常驻网关,等于让插件进程长期占用 DSH 安装目录,导致 DSH 自更新失败。因此网关解释器
405
+ * 必须位于安装目录之外,同时保留「网关活过 DSH 退出/重启」的既有设计。
406
+ *
407
+ * 选择顺序(取第一个通过校验的候选):
408
+ * 1. DSH_REMOTE_NODE: 绝对路径, -v 可执行且主版本 >= 18
409
+ * 2. PATH 中的 node: 同样校验
410
+ * 3. DSH Desktop 自带 runtime, 复制到 ~/.dsh-remote/runtime/node-<ver>(.exe)
411
+ * 4. process.execPath 兜底: 显式标记 runtimeInsideInstallDir 并写警告, 不允许静默降级
412
+ * 所有被跳过的候选及原因都会写进 ~/.dsh-remote/plugin-gateway.log。
413
+ */
414
+ export const GATEWAY_RUNTIME_MIN_MAJOR = 18
415
+ const GATEWAY_RUNTIME_DIR = ['.dsh-remote', 'runtime']
416
+
417
+ function runtimeProbeEnv() {
418
+ // 桌面版宿主进程的 process.execPath 是 Electron 可执行文件;探测它需要 node 语义。
419
+ const env = { ...process.env, ELECTRON_RUN_AS_NODE: '1' }
420
+ delete env.NODE_CHANNEL_FD
421
+ delete env.NODE_CHANNEL_SERIALIZATION_MODE
422
+ return env
423
+ }
424
+
425
+ /** 默认探测: 执行 `<candidate> -v`。返回 {ok, version, major, code, detail},绝不抛错。 */
426
+ let probeSequence = 0
427
+ function probeNodeVersion(file) {
428
+ // 用临时文件接收 stdout 而不是管道:受限环境/沙箱下 Node 无法创建管道句柄
429
+ // (spawn stdio:'pipe' 会 EPERM),写文件在各权限模式下都可用。
430
+ let fd = null
431
+ const outputFile = join(tmpdir(), 'dsh-remote-probe-' + process.pid + '-' + randomUUID().slice(0, 8) + '-' + (++probeSequence) + '.txt')
432
+ try {
433
+ fd = openSync(outputFile, 'w')
434
+ const spawned = spawnSync(file, ['-v'], {
435
+ timeout: 5000, windowsHide: true, env: runtimeProbeEnv(),
436
+ stdio: ['ignore', fd, 'ignore'],
437
+ })
438
+ try { closeSync(fd); fd = null } catch {}
439
+ if (spawned.error) {
440
+ return { ok: false, code: 'PROBE_FAILED', detail: String(spawned.error.code || spawned.error.message).slice(0, 160) }
441
+ }
442
+ const output = readFileSync(outputFile, 'utf8')
443
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(output || '').trim())
444
+ if (!match) return { ok: false, code: 'PROBE_FAILED', detail: '无法解析 node -v 输出' }
445
+ return { ok: true, version: `${match[1]}.${match[2]}.${match[3]}`, major: Number(match[1]) }
446
+ } catch (error) {
447
+ if (fd !== null) { try { closeSync(fd) } catch {} }
448
+ const detail = String(error?.code ? error.code + ' ' : '') + String(error?.message || error)
449
+ return { ok: false, code: 'PROBE_FAILED', detail: detail.slice(0, 160) }
450
+ } finally {
451
+ try { rmSync(outputFile, { force: true }) } catch {}
452
+ }
453
+ }
454
+
455
+ function normalizeNodeVersion(value) {
456
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(value || '').trim())
457
+ return match ? `${match[1]}.${match[2]}.${match[3]}` : ''
458
+ }
459
+
460
+ /** 比较真实路径;不存在的复制目标也解析最近的既有父目录,避免 junction 绕过边界。 */
461
+ function normalizeRuntimePath(value, platform) {
462
+ let text = String(value || '')
463
+ if (!text) return ''
464
+ try {
465
+ text = resolve(text)
466
+ let ancestor = text
467
+ const suffix = []
468
+ for (;;) {
469
+ try { text = join(realpathSync.native(ancestor), ...suffix); break } catch {}
470
+ const parent = dirname(ancestor)
471
+ if (parent === ancestor) break
472
+ suffix.unshift(basename(ancestor))
473
+ ancestor = parent
474
+ }
475
+ } catch { /* 无法规范化时保留原文;候选另有存在/可执行性校验。 */ }
476
+ if (platform === 'win32') text = text.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '')
477
+ if (platform === 'win32') text = text.toLowerCase().replaceAll('/', '\\')
478
+ return text.replace(/[\\/]+$/, '') || text
479
+ }
480
+
481
+ function isPathInsideDir(parent, child, platform) {
482
+ const parentPath = normalizeRuntimePath(parent, platform)
483
+ const childPath = normalizeRuntimePath(child, platform)
484
+ if (!parentPath || !childPath) return false
485
+ const separator = platform === 'win32' ? '\\' : '/'
486
+ return childPath === parentPath || childPath.startsWith(parentPath.endsWith(separator) ? parentPath : parentPath + separator)
487
+ }
488
+
489
+ function desktopBundledNodePath(installDir, platform) {
490
+ return join(installDir, 'resources', 'runtime', 'primary-runtime', 'dependencies', 'node', 'bin', platform === 'win32' ? 'node.exe' : 'node')
491
+ }
492
+
493
+ function runtimeCopyTarget(home, version, platform) {
494
+ return join(home, ...GATEWAY_RUNTIME_DIR, 'node-' + version + (platform === 'win32' ? '.exe' : ''))
495
+ }
496
+
497
+ function envPathValue(env) {
498
+ if (!env || typeof env !== 'object') return ''
499
+ const key = Object.keys(env).find(name => name.toLowerCase() === 'path')
500
+ const value = key ? env[key] : ''
501
+ return typeof value === 'string' ? value : ''
502
+ }
503
+
504
+ /** 按 PATH 顺序列出真实存在的 node 可执行文件;Windows 只看 node.exe(不解析 .cmd 垫片)。 */
505
+ function findPathNodeCandidates(env, platform) {
506
+ const names = platform === 'win32' ? ['node.exe'] : ['node']
507
+ const found = []
508
+ for (const rawEntry of envPathValue(env).split(platform === 'win32' ? ';' : ':')) {
509
+ const entry = rawEntry.trim().replace(/^"(.*)"$/, '$1')
510
+ if (!entry) continue
511
+ for (const name of names) {
512
+ const file = join(entry, name)
513
+ try { if (statSync(file).isFile()) found.push(file) } catch {}
514
+ }
515
+ }
516
+ return found
517
+ }
518
+
519
+ /** 默认复制实现: 先写 *.partial, 校验大小后原子 rename;失败清理半成品。 */
520
+ function copyNodeRuntimeFile(source, target) {
521
+ const dir = dirname(target)
522
+ const partial = target + '.' + process.pid + '.partial'
523
+ try {
524
+ const sourceStat = statSync(source)
525
+ if (!sourceStat.isFile() || sourceStat.size <= 0) return { ok: false, error: '源文件不可用' }
526
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
527
+ // 清理上次失败留下的半成品, 避免 90MB 级文件无限堆积。
528
+ try {
529
+ for (const name of readdirSync(dir)) {
530
+ if (name.startsWith(basename(target) + '.') && name.endsWith('.partial')) rmSync(join(dir, name), { force: true })
531
+ }
532
+ } catch {}
533
+ copyFileSync(source, partial)
534
+ try { chmodSync(partial, 0o755) } catch {}
535
+ const copiedStat = statSync(partial)
536
+ if (copiedStat.size !== sourceStat.size) throw new Error('复制后大小校验失败')
537
+ rmSync(target, { force: true })
538
+ renameSync(partial, target)
539
+ return { ok: true, bytes: copiedStat.size }
540
+ } catch (error) {
541
+ try { rmSync(partial, { force: true }) } catch {}
542
+ return { ok: false, error: error?.code || error?.message || 'COPY_FAILED' }
543
+ }
544
+ }
545
+
546
+ function insideInstallDirWarning(platform) {
547
+ return platform === 'win32'
548
+ ? '本次网关解释器位于 DSH 安装目录内,DSH 更新可能失败;请安装 Node.js 18+ 到系统 PATH,或设置 DSH_REMOTE_NODE 指向安装目录外的 node。'
549
+ : '本次网关解释器位于 DSH 安装目录内;建议设置 DSH_REMOTE_NODE 或安装系统 Node.js 18+,避免网关占用安装目录。'
550
+ }
551
+
552
+ /**
553
+ * 解析并校验网关解释器。永远返回可用结果(最差为 process.execPath 兜底),不抛错。
554
+ * 全部选项均可注入,便于在临时目录中测试真实的启动策略。
555
+ */
556
+ export async function resolveGatewayRuntime(options = {}) {
557
+ const env = options.env && typeof options.env === 'object' ? options.env : process.env
558
+ const platform = options.platform || process.platform
559
+ const home = options.home || homedir()
560
+ const execPath = resolve(typeof options.execPath === 'string' && options.execPath ? options.execPath : process.execPath)
561
+ const installDir = dirname(execPath)
562
+ const desktopHost = options.desktopHost === undefined
563
+ ? Boolean(process.versions.electron) || existsSync(join(installDir, 'resources', 'app.asar'))
564
+ : options.desktopHost === true
565
+ const probe = typeof options.probe === 'function' ? options.probe : probeNodeVersion
566
+ const copyRuntime = typeof options.copyRuntime === 'function' ? options.copyRuntime : copyNodeRuntimeFile
567
+ const log = typeof options.log === 'function' ? options.log : logGateway
568
+
569
+ const attempts = []
570
+ const candidates = []
571
+ const seen = new Set()
572
+ let copy = null
573
+
574
+ const addAttempt = (source, candidate, ok, code, detail) => {
575
+ attempts.push({ source, candidate: candidate || '', ok: !!ok, code, detail: detail || '' })
576
+ }
577
+ const skip = (source, candidate, code, detail) => {
578
+ addAttempt(source, candidate, false, code, detail)
579
+ log('网关解释器候选跳过: ' + source + ' ' + (candidate || '(未提供)') + ' - ' + (detail || code))
580
+ return null
581
+ }
582
+ const runProbe = async (file) => {
583
+ try {
584
+ const result = await Promise.resolve(probe(file))
585
+ return result && typeof result === 'object' ? result : { ok: false, code: 'PROBE_FAILED', detail: '无效的探测结果' }
586
+ } catch (error) {
587
+ return { ok: false, code: 'PROBE_FAILED', detail: String(error?.message || error).slice(0, 160) }
588
+ }
589
+ }
590
+ const accept = (source, executable, version, major, reused) => {
591
+ const key = normalizeRuntimePath(executable, platform)
592
+ if (seen.has(key)) return false
593
+ seen.add(key)
594
+ candidates.push({ executable, source, version, major, insideInstallDir: false, reused: !!reused, valid: true })
595
+ addAttempt(source, executable, true, 'OK', reused ? '复用已存在的 node ' + version + ' 副本' : '')
596
+ log('网关解释器: ' + source + ' -> ' + executable + ' (node ' + version + ')')
597
+ return true
598
+ }
599
+ /** 校验一个 node 候选: 绝对路径/存在/边界/probe/版本。boundary=false 用于安装目录内的复制源。 */
600
+ const checkNode = async (source, rawCandidate, { boundary = true } = {}) => {
601
+ if (typeof rawCandidate !== 'string' || !rawCandidate.trim()) return skip(source, '', 'MISSING', '路径为空')
602
+ if (!isAbsolute(rawCandidate)) return skip(source, rawCandidate, 'NOT_ABSOLUTE', '不是绝对路径')
603
+ const candidate = resolve(rawCandidate)
604
+ if (!existsSync(candidate)) return skip(source, candidate, 'MISSING', '文件不存在')
605
+ try { if (!statSync(candidate).isFile()) return skip(source, candidate, 'MISSING', '不是文件') } catch { return skip(source, candidate, 'MISSING', '无法读取文件信息') }
606
+ if (boundary && desktopHost && isPathInsideDir(installDir, candidate, platform)) {
607
+ return skip(source, candidate, 'INSIDE_INSTALL_DIR', '位于 DSH 安装目录内, 会阻止 DSH 原地更新')
608
+ }
609
+ const probed = await runProbe(candidate)
610
+ if (!probed.ok) return skip(source, candidate, 'PROBE_FAILED', '无法执行 -v: ' + (probed.detail || '未知错误'))
611
+ const version = normalizeNodeVersion(probed.version)
612
+ const major = Number(probed.major) || Number((/(\d+)\./.exec(version) || [])[1]) || 0
613
+ if (!version || !Number.isFinite(major) || major < GATEWAY_RUNTIME_MIN_MAJOR) {
614
+ return skip(source, candidate, 'VERSION_TOO_OLD', 'node ' + (version || String(probed.version || '?')) + ' < ' + GATEWAY_RUNTIME_MIN_MAJOR)
615
+ }
616
+ return { executable: candidate, version, major }
617
+ }
618
+
619
+ // 1) DSH_REMOTE_NODE
620
+ const envNode = typeof env.DSH_REMOTE_NODE === 'string' ? env.DSH_REMOTE_NODE.trim() : ''
621
+ if (envNode) {
622
+ const checked = await checkNode('env', envNode)
623
+ if (checked) accept('env', checked.executable, checked.version, checked.major, false)
624
+ }
625
+
626
+ // 2) PATH 中的 node
627
+ const pathCandidates = findPathNodeCandidates(env, platform)
628
+ if (!pathCandidates.length) skip('path', '', 'NOT_FOUND', 'PATH 中没有找到 node')
629
+ for (const file of pathCandidates) {
630
+ const checked = await checkNode('path', file)
631
+ if (checked && accept('path', checked.executable, checked.version, checked.major, false)) break
632
+ }
633
+
634
+ // 3) 按需准备内置副本:没有外部候选,或外部候选实际启动失败时才复制。
635
+ let desktopPrepared = false
636
+ const prepareDesktopRuntime = async () => {
637
+ if (!desktopHost || desktopPrepared) return null
638
+ desktopPrepared = true
639
+ const previousCount = candidates.length
640
+ const source = desktopBundledNodePath(installDir, platform)
641
+ if (!existsSync(source)) {
642
+ skip('desktop-runtime', source, 'SOURCE_MISSING', '未找到桌面版自带 node 运行时')
643
+ } else {
644
+ const sourceChecked = await checkNode('desktop-runtime', source, { boundary: false })
645
+ if (sourceChecked) {
646
+ const target = runtimeCopyTarget(home, sourceChecked.version, platform)
647
+ if (desktopHost && isPathInsideDir(installDir, target, platform)) {
648
+ skip('desktop-runtime', target, 'INSIDE_INSTALL_DIR', 'node 副本目标位于 DSH 安装目录内')
649
+ } else {
650
+ const existingProbe = existsSync(target) ? await runProbe(target) : null
651
+ if (existingProbe?.ok && normalizeNodeVersion(existingProbe.version) === sourceChecked.version) {
652
+ copy = { source, target, version: sourceChecked.version, reused: true, bytes: safeFileSize(target) }
653
+ accept('desktop-runtime', target, sourceChecked.version, sourceChecked.major, true)
654
+ } else {
655
+ let copied = null
656
+ try { copied = await copyRuntime(source, target) } catch (error) { copied = { ok: false, error: error?.message || String(error) } }
657
+ if (!copied?.ok) {
658
+ skip('desktop-runtime', target, 'COPY_FAILED', '复制 node 运行时失败: ' + (copied?.error || '未知错误'))
659
+ } else {
660
+ const verified = await runProbe(target)
661
+ if (!verified?.ok || normalizeNodeVersion(verified.version) !== sourceChecked.version) {
662
+ try { rmSync(target, { force: true }) } catch {}
663
+ skip('desktop-runtime', target, 'COPY_PROBE_FAILED', '副本无法执行或版本不符: ' + (verified?.detail || normalizeNodeVersion(verified?.version) || '未知错误'))
664
+ } else {
665
+ const bytes = Number(copied.bytes) || safeFileSize(target)
666
+ copy = { source, target, version: sourceChecked.version, reused: false, bytes }
667
+ log('已复制网关解释器: ' + source + ' -> ' + target + ' (' + bytes + ' B)')
668
+ accept('desktop-runtime', target, sourceChecked.version, sourceChecked.major, false)
669
+ }
670
+ }
671
+ }
672
+ }
673
+ }
674
+ }
675
+ return candidates[previousCount] || null
676
+ }
677
+ if (!candidates.length) await prepareDesktopRuntime()
678
+
679
+ // 4) 兜底 process.execPath: 即使探测失败也保留为最后尝试,但必须显式记录
680
+ const hostKey = normalizeRuntimePath(execPath, platform)
681
+ if (!seen.has(hostKey)) {
682
+ const probed = await runProbe(execPath)
683
+ const version = probed.ok ? normalizeNodeVersion(probed.version) : ''
684
+ const major = probed.ok ? (Number(probed.major) || Number((/(\d+)\./.exec(version) || [])[1]) || 0) : 0
685
+ const insideInstallDir = desktopHost && isPathInsideDir(installDir, execPath, platform)
686
+ candidates.push({ executable: execPath, source: 'host', version, major, insideInstallDir, reused: false, valid: probed.ok })
687
+ seen.add(hostKey)
688
+ addAttempt('host', execPath, probed.ok, probed.ok ? 'OK' : 'PROBE_FAILED', probed.ok ? '' : '无法执行 -v: ' + (probed.detail || '未知错误'))
689
+ if (probed.ok) log('网关解释器兜底: host -> ' + execPath + ' (node ' + version + ')')
690
+ else log('网关解释器兜底: host -> ' + execPath + ' (探测失败, 仍作为最后尝试)')
691
+ }
692
+
693
+ const selected = candidates[0]
694
+ const warning = selected?.insideInstallDir ? insideInstallDirWarning(platform) : ''
695
+ if (warning) log('警告: ' + warning)
696
+ const plan = {
697
+ executable: selected.executable,
698
+ source: selected.source,
699
+ version: selected.version,
700
+ major: selected.major,
701
+ installDir,
702
+ desktopHost,
703
+ platform,
704
+ insideInstallDir: !!selected.insideInstallDir,
705
+ // 提示词/文档使用的显式标记名;insideInstallDir 是内部与状态字段名,二者保持同义。
706
+ runtimeInsideInstallDir: !!selected.insideInstallDir,
707
+ warning,
708
+ candidates,
709
+ attempts,
710
+ copy,
711
+ }
712
+ plan.prepareDesktopFallback = async () => {
713
+ const candidate = await prepareDesktopRuntime()
714
+ plan.copy = copy
715
+ if (candidate) {
716
+ // accept() 追加的新候选应排在 host 兜底之前。
717
+ candidates.splice(candidates.indexOf(candidate), 1)
718
+ const hostIndex = candidates.findIndex(entry => entry.source === 'host')
719
+ candidates.splice(hostIndex < 0 ? candidates.length : hostIndex, 0, candidate)
720
+ }
721
+ return candidate
722
+ }
723
+ return plan
724
+ }
725
+
726
+ function safeFileSize(file) {
727
+ try { return statSync(file).size } catch { return 0 }
728
+ }
729
+
730
+ function gatewayRuntimeSummary(plan) {
731
+ if (!plan) return null
732
+ return {
733
+ executable: plan.executable,
734
+ source: plan.source,
735
+ version: plan.version,
736
+ major: plan.major,
737
+ installDir: plan.installDir,
738
+ desktopHost: plan.desktopHost,
739
+ insideInstallDir: plan.insideInstallDir,
740
+ runtimeInsideInstallDir: plan.runtimeInsideInstallDir ?? plan.insideInstallDir,
741
+ warning: plan.warning,
742
+ copy: plan.copy ? { target: plan.copy.target, version: plan.copy.version, reused: plan.copy.reused } : null,
743
+ attempts: plan.attempts.map(entry => ({ source: entry.source, ok: entry.ok, code: entry.code, detail: entry.detail })),
744
+ }
745
+ }
746
+
747
+ let gatewayRuntimePlanPromise = null
748
+ let gatewayRuntimeState = null
749
+ let gatewayRuntimeStartedPid = 0
750
+ let gatewayRuntimeSupervisorPid = 0
751
+
752
+ /** 解析结果按进程缓存(环境变量变化需重启 DSH);解析失败也回退为显式警告而不是静默。 */
753
+ function gatewayRuntimePlan() {
754
+ if (!gatewayRuntimePlanPromise) {
755
+ gatewayRuntimePlanPromise = (async () => {
756
+ let plan
757
+ try {
758
+ plan = await resolveGatewayRuntime()
759
+ } catch (error) {
760
+ const installDir = dirname(resolve(process.execPath))
761
+ const warning = '网关解释器解析失败,回退到 DSH 可执行文件,DSH 更新可能失败: ' + (error?.message || error)
762
+ logGateway('警告: ' + warning)
763
+ plan = {
764
+ executable: process.execPath, source: 'host', version: '', major: 0, installDir,
765
+ desktopHost: Boolean(process.versions.electron), insideInstallDir: true, warning,
766
+ candidates: [{ executable: process.execPath, source: 'host', version: '', major: 0, insideInstallDir: true, reused: false, valid: false }],
767
+ attempts: [], copy: null,
768
+ }
769
+ }
770
+ return plan
771
+ })()
772
+ }
773
+ return gatewayRuntimePlanPromise
774
+ }
775
+
776
+ /** 仅报告绑定到当前 worker PID 的实际解释器;解析计划不能证明现存网关用了它。 */
777
+ async function gatewayRuntimeForStatus(reported, health) {
778
+ const current = health || await gatewayRunning()
779
+ if (!current.running) return null
780
+ if (gatewayRuntimeState?.pid === current.pid) return gatewayRuntimeState
781
+ if (reported === undefined) {
782
+ const response = await proxyGateway('/admin/api/runtime', 'GET', '')
783
+ reported = response?.status === 200 && response.json.ok === true ? response.json.gatewayRuntime : null
784
+ }
785
+ if (reported?.pid !== current.pid || typeof reported.executable !== 'string' || !isAbsolute(reported.executable)) {
786
+ return { source: 'unknown', pid: current.pid, executable: '', version: '', insideInstallDir: null,
787
+ runtimeInsideInstallDir: null, warning: '当前网关未报告实际解释器;请停止并重新启动网关后确认。' }
788
+ }
789
+ const plan = await gatewayRuntimePlan()
790
+ if (gatewayRuntimeSupervisorPid && reported.supervisorPid === gatewayRuntimeSupervisorPid) gatewayRuntimeStartedPid = current.pid
791
+ const matched = plan.candidates.find(candidate => normalizeRuntimePath(candidate.executable, process.platform) === normalizeRuntimePath(reported.executable, process.platform))
792
+ const version = normalizeNodeVersion(reported.version)
793
+ const actual = { executable: reported.executable, source: matched?.source || 'external', version,
794
+ major: Number(version.split('.')[0]) || 0, insideInstallDir: plan.desktopHost && isPathInsideDir(plan.installDir, reported.executable, process.platform) }
795
+ gatewayRuntimeState = { ...gatewayRuntimeStateFor(plan, actual), pid: current.pid }
796
+ return gatewayRuntimeState
797
+ }
798
+
799
+ function gatewayRuntimeStateFor(plan, candidate) {
800
+ const used = { ...plan, executable: candidate.executable, source: candidate.source, version: candidate.version, major: candidate.major,
801
+ insideInstallDir: !!candidate.insideInstallDir, runtimeInsideInstallDir: !!candidate.insideInstallDir }
802
+ // 实际启动可能回退到 host(安装目录内)候选: 必须重新给出对应警告,不能沿用首选候选的空 warning。
803
+ const usedWarning = used.insideInstallDir ? (plan.warning || insideInstallDirWarning(plan.platform || process.platform)) : ''
804
+ if (usedWarning) logGateway('警告: ' + usedWarning)
805
+ return { ...gatewayRuntimeSummary({ ...used, warning: usedWarning }), at: Date.now() }
806
+ }
807
+
388
808
  /** 启动随插件分发的 gateway.cjs; 已运行则直接返回。 */
389
809
  const GATEWAY_AUTH_HINT = '网关正在运行,但管理认证不可用。请检查 TOKEN_FILE、TOKEN / DSH_REMOTE_TOKEN 与文件权限;若旧网关无法恢复令牌,请在主机上确认进程归属后手动重启网关,再刷新此页。'
390
810
 
@@ -396,6 +816,7 @@ async function startGateway() {
396
816
  if (!auth || auth.status !== 200 || auth.json.ok !== true) {
397
817
  return { ok: false, running: true, started: false, error: auth?.status === 401 || auth?.status === 403 ? GATEWAY_AUTH_HINT : auth?.json?.error || '本地网关管理接口响应异常,请稍后重试' }
398
818
  }
819
+ await gatewayRuntimeForStatus(auth.json.gatewayRuntime ?? null, health)
399
820
  setGatewayEnabled(true)
400
821
  return { ok: true, running: true, started: false }
401
822
  }
@@ -409,33 +830,77 @@ async function startGateway() {
409
830
  logGateway(`端口 ${port} 已被占用, 拒绝启动`)
410
831
  return { ok: false, running: false, error: `端口 ${port} 已被占用,请在插件页修改网关端口后重试` }
411
832
  }
412
- logGateway('启动网关, 端口: ' + port + ', 上游: ' + upstream)
833
+ // Windows 上运行中的 exe 不能被覆盖,网关解释器必须位于 DSH 安装目录之外,
834
+ // 否则 DSH 原地更新(NSIS 替换整棵安装目录)会被插件进程挡住。
835
+ // 顺序: DSH_REMOTE_NODE > PATH node > 桌面版内置 runtime 副本 > process.execPath(显式警告)。
836
+ const runtime = await gatewayRuntimePlan()
837
+ logGateway('启动网关, 端口: ' + port + ', 上游: ' + upstream + ', 解释器: ' + runtime.executable
838
+ + ' (' + runtime.source + (runtime.version ? ', node ' + runtime.version : '') + ')')
839
+
840
+ // Windows locks a process's current directory. Keep both supervisor and
841
+ // worker outside the replaceable node_modules package during self-update.
842
+ const gatewayCwd = `${homedir()}/.dsh-remote`
843
+ let cwdReady = false
844
+ try { mkdirSync(gatewayCwd, { recursive: true }); cwdReady = true } catch {}
845
+
846
+ /** 最多等 4 秒; 超过可能是端口冲突或首次初始化, 前端稍后刷新即可。 */
847
+ const waitGatewayReady = async () => {
848
+ for (let i = 0; i < 16; i++) {
849
+ await sleep(250)
850
+ const healthNow = await gatewayRunning()
851
+ if (healthNow.running) return healthNow
852
+ }
853
+ return null
854
+ }
855
+ const startedResult = (candidate, healthNow) => {
856
+ if (healthNow.pid) writeGatewayPid(healthNow.pid)
857
+ gatewayRuntimeStartedPid = healthNow.pid
858
+ gatewayRuntimeState = { ...gatewayRuntimeStateFor(runtime, candidate), pid: healthNow.pid }
859
+ setGatewayEnabled(true)
860
+ return { ok: true, running: true, started: true, runtime: gatewayRuntimeState }
861
+ }
413
862
 
414
- // 首选 systemd-run: 网关成为独立 user 单元, DSH 重启/升级不会连带杀掉它
415
- let sysd = false
416
- try {
417
- await runExit('systemctl', ['--user', 'reset-failed', 'dsh-remote-gateway'])
418
- sysd = (await runExit('systemd-run', [
419
- '--user', '--unit=dsh-remote-gateway', '--service-type=exec',
420
- ...gatewaySystemdEnvArgs(),
421
- '--setenv=PORT=' + port, '--setenv=HOST=' + host, '--setenv=DSH_UPSTREAM=' + upstream,
422
- '--', process.execPath, script, '--supervise',
423
- ])) === 0
424
- } catch {}
425
- if (sysd) {
863
+ // 逐个候选尝试: 解释器立即退出/无法执行时回退下一候选,绝不静默改回 process.execPath。
864
+ const failures = []
865
+ async function* runtimeCandidates() {
866
+ // 快照防止按需准备副本时修改 candidates,导致重复启动或漏掉候选。
867
+ for (const candidate of [...runtime.candidates]) {
868
+ if (candidate.source === 'host' && runtime.prepareDesktopFallback) {
869
+ const fallback = await runtime.prepareDesktopFallback()
870
+ if (fallback) yield fallback
871
+ }
872
+ yield candidate
873
+ }
874
+ }
875
+ for await (const candidate of runtimeCandidates()) {
876
+ // 首选 systemd-run: 网关成为独立 user 单元, DSH 重启/升级不会连带杀掉它
877
+ let sysd = false
426
878
  try {
427
- const pid = Number(execFileSync('systemctl', ['--user', 'show', '-p', 'MainPID', '--value', 'dsh-remote-gateway'], { encoding: 'utf8' }).trim())
428
- if (Number.isFinite(pid) && pid > 1) writeGatewayPid(pid)
879
+ await runExit('systemctl', ['--user', 'reset-failed', 'dsh-remote-gateway'])
880
+ sysd = (await runExit('systemd-run', [
881
+ '--user', '--unit=dsh-remote-gateway', '--service-type=exec',
882
+ ...gatewaySystemdEnvArgs(),
883
+ '--setenv=PORT=' + port, '--setenv=HOST=' + host, '--setenv=DSH_UPSTREAM=' + upstream,
884
+ '--', candidate.executable, script, '--supervise',
885
+ ])) === 0
429
886
  } catch {}
430
- }
887
+ if (sysd) {
888
+ try {
889
+ const pid = Number(execFileSync('systemctl', ['--user', 'show', '-p', 'MainPID', '--value', 'dsh-remote-gateway'], { encoding: 'utf8' }).trim())
890
+ if (Number.isFinite(pid) && pid > 1) { writeGatewayPid(pid); gatewayRuntimeSupervisorPid = pid }
891
+ } catch {}
892
+ const healthNow = await waitGatewayReady()
893
+ if (healthNow) return startedResult(candidate, healthNow)
894
+ // 单元立即失败(解释器不可执行等)才换候选;仍在启动时可能只是慢,不重复拉起。
895
+ const unitState = gatewaySystemdUnitState()
896
+ failures.push({ executable: candidate.executable, reason: 'systemd 单元 ' + (unitState || '未就绪') })
897
+ logGateway('解释器 ' + candidate.executable + ' 的 systemd 单元未就绪(' + (unitState || '未知状态') + '), 尝试下一候选')
898
+ if (unitState === 'activating' || unitState === 'active') return { ok: true, running: false, pending: true, hint: '网关启动中, 稍后刷新' }
899
+ continue
900
+ }
431
901
 
432
- // 无 systemd 的机器回退: detached 子进程
433
- if (!sysd) {
434
- // Windows locks a process's current directory. Keep both supervisor and
435
- // worker outside the replaceable node_modules package during self-update.
436
- const gatewayCwd = `${homedir()}/.dsh-remote`
437
- try { mkdirSync(gatewayCwd, { recursive: true }) }
438
- catch { return { ok: false, running: false, error: '无法创建网关运行目录,请检查用户目录权限' } }
902
+ // 无 systemd 的机器回退: detached 子进程
903
+ if (!cwdReady) return { ok: false, running: false, error: '无法创建网关运行目录,请检查用户目录权限' }
439
904
  let logFd = null
440
905
  try {
441
906
  logFd = openSync(`${homedir()}/.dsh-remote/plugin-gateway.log`, 'a')
@@ -443,26 +908,58 @@ async function startGateway() {
443
908
  const gatewayEnv = { ...process.env, PORT: port, HOST: host, DSH_UPSTREAM: upstream }
444
909
  delete gatewayEnv.NODE_CHANNEL_FD
445
910
  delete gatewayEnv.NODE_CHANNEL_SERIALIZATION_MODE
446
- const child = spawn(process.execPath, [script, '--supervise'], {
447
- cwd: gatewayCwd,
448
- detached: true,
449
- stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'],
450
- env: gatewayEnv,
451
- })
911
+ let child = null
912
+ try {
913
+ child = spawn(candidate.executable, [script, '--supervise'], {
914
+ cwd: gatewayCwd,
915
+ detached: true,
916
+ stdio: ['ignore', logFd ?? 'ignore', logFd ?? 'ignore'],
917
+ env: gatewayEnv,
918
+ })
919
+ } catch (error) {
920
+ failures.push({ executable: candidate.executable, reason: 'spawn 失败: ' + (error?.message || error) })
921
+ logGateway('解释器 ' + candidate.executable + ' 无法启动网关: ' + (error?.message || error) + ', 尝试下一候选')
922
+ continue
923
+ } finally {
924
+ if (logFd !== null) { try { closeSync(logFd) } catch {} }
925
+ }
926
+ let exited = null
927
+ child.once('exit', (code, signal) => { exited = { code, signal } })
928
+ child.once('error', (error) => { exited = { code: null, error: error?.message || String(error) } })
452
929
  child.unref()
453
- writeGatewayPid(child.pid)
454
- }
455
- // 最多等 4 秒; 超过可能是端口冲突或首次初始化, 前端稍后刷新即可
456
- for (let i = 0; i < 16; i++) {
457
- await sleep(250)
458
- const h = await gatewayRunning()
459
- if (h.running) {
460
- if (h.pid) writeGatewayPid(h.pid)
461
- setGatewayEnabled(true)
462
- return { ok: true, running: true, started: true }
930
+ if (Number.isInteger(child.pid) && child.pid > 1) { writeGatewayPid(child.pid); gatewayRuntimeSupervisorPid = child.pid }
931
+ let healthNow = null
932
+ for (let i = 0; i < 16; i++) {
933
+ await sleep(250)
934
+ const healthProbe = await gatewayRunning()
935
+ if (healthProbe.running) { healthNow = healthProbe; break }
936
+ if (exited) break
463
937
  }
938
+ if (healthNow) return startedResult(candidate, healthNow)
939
+ if (exited) {
940
+ const detail = 'code=' + exited.code + (exited.signal ? ' signal=' + exited.signal : '') + (exited.error ? ' error=' + exited.error : '')
941
+ failures.push({ executable: candidate.executable, reason: '立即退出(' + detail + ')' })
942
+ logGateway('解释器 ' + candidate.executable + ' 启动的网关立即退出(' + detail + '), 尝试下一候选')
943
+ continue
944
+ }
945
+ // 进程仍活着但 4 秒内未就绪: 保持原行为等待前端刷新,不重复启动第二个网关。
946
+ return { ok: true, running: false, pending: true, hint: '网关启动中, 稍后刷新' }
947
+ }
948
+ const failureDetail = failures.map(item => item.executable + ' (' + item.reason + ')').join('; ')
949
+ logGateway('网关启动失败: 所有解释器候选均未成功: ' + failureDetail)
950
+ return {
951
+ ok: false, running: false,
952
+ error: '网关启动失败: ' + failures.length + ' 个解释器候选均未成功' + (runtime.warning ? ';' + runtime.warning : ''),
953
+ runtime: gatewayRuntimeState || gatewayRuntimeSummary(runtime),
464
954
  }
465
- return { ok: true, running: false, pending: true, hint: '网关启动中, 稍后刷新' }
955
+ }
956
+
957
+ function gatewaySystemdUnitState() {
958
+ try {
959
+ return String(execFileSync('systemctl', ['--user', 'show', '-p', 'ActiveState', '--value', 'dsh-remote-gateway'], {
960
+ encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'],
961
+ })).trim()
962
+ } catch { return '' }
466
963
  }
467
964
 
468
965
  let ensurePromise = null
@@ -472,6 +969,8 @@ function ensureGateway() {
472
969
  if (ensurePromise) return ensurePromise
473
970
  ensurePromise = (async () => {
474
971
  try {
972
+ // 提前解析解释器(结果缓存):即使网关已在运行,插件页也能显示实际选择与理由。
973
+ const runtime = await gatewayRuntimePlan()
475
974
  await refreshDshUpstreamCookie()
476
975
  const health = await gatewayRunning()
477
976
  if (!health.running) {
@@ -482,10 +981,17 @@ function ensureGateway() {
482
981
  const oldUpstream = health.upstream || ''
483
982
  const oldVersion = health.version || '?'
484
983
  const versionMismatch = oldVersion !== version
984
+ const actualRuntime = runtime.desktopHost ? await gatewayRuntimeForStatus(undefined, health) : null
985
+ // DSH 重启后接管遗留的宿主解释器,或应用新的外部解释器配置。
986
+ // 本进程已尝试并回退的实例不再反复重启,避免坏候选导致重启风暴。
987
+ const runtimeMismatch = runtime.desktopHost && gatewayRuntimeStartedPid !== health.pid
988
+ && !runtime.insideInstallDir && actualRuntime?.executable
989
+ && normalizeRuntimePath(actualRuntime.executable, process.platform) !== normalizeRuntimePath(runtime.executable, process.platform)
485
990
  // 上游暂时不可达不应重启网关: VPN/DSH 重启/短暂网络抖动时,
486
991
  // 重启只能制造额外断线,网关应保持运行并通过 /health 暴露 degraded 状态。
487
- if (versionMismatch || (oldUpstream && oldUpstream !== upstream) || (!oldUpstream && upstream)) {
992
+ if (versionMismatch || runtimeMismatch || (oldUpstream && oldUpstream !== upstream) || (!oldUpstream && upstream)) {
488
993
  logGateway(`网关需刷新: 版本 ${oldVersion} -> ${version}, 上游 ${oldUpstream || '?'} -> ${upstream}`)
994
+ if (runtimeMismatch) logGateway('网关解释器需迁移: ' + actualRuntime.executable + ' -> ' + runtime.executable)
489
995
  if (!await killGateway(health)) {
490
996
  logGateway('拒绝自动重启: 无法通过认证关闭旧网关,请检查令牌或端口占用')
491
997
  return false
@@ -702,6 +1208,21 @@ export function hostDescription(ctx, runtime = process) {
702
1208
 
703
1209
  async function serveStatic(req, res, ctx) {
704
1210
  const pathname = new URL(req.url ?? '/', 'http://x').pathname
1211
+ if (pathname === `${MOUNT}/admin/api/browser-launch`) {
1212
+ res.setHeader('cache-control', 'no-store')
1213
+ res.setHeader('referrer-policy', 'no-referrer')
1214
+ if (req.method !== 'POST') return sendJson(res, 405, { ok: false, code: 'method-not-allowed' })
1215
+ if (req.headers['x-dsh-remote-client'] !== 'entry') return sendJson(res, 403, { ok: false, code: 'explicit-entry-required' })
1216
+ if ([...new URL(req.url, 'http://x').searchParams].length) return sendJson(res, 400, { ok: false, code: 'invalid-query' })
1217
+ // Prefix routes are not automatically authenticated by DSH. Require its
1218
+ // signed browser cookie before minting a browser launch URL.
1219
+ if (typeof ctx.connection?.authorizeIndex !== 'function') return sendJson(res, 503, { ok: false, code: 'browser-auth-unavailable' })
1220
+ if (!ctx.connection.authorizeIndex(req, res)) return
1221
+ // Never accept a destination/Host header or expose a Remote gateway token.
1222
+ let url
1223
+ try { url = browserLaunchUrl(ctx) } catch (_) {}
1224
+ return sendJson(res, url ? 200 : 503, url ? { ok: true, url } : { ok: false, code: 'browser-auth-unavailable' })
1225
+ }
705
1226
  if (pathname === `${MOUNT}/api/doctor/target` || pathname === `${MOUNT}/admin/api/doctor-target`) {
706
1227
  res.setHeader('cache-control','no-store')
707
1228
  if(pathname===`${MOUNT}/api/doctor/target` && !remoteCommandAuthorized(req))return sendJson(res,401,{ok:false,code:'unauthorized'})
@@ -833,7 +1354,7 @@ async function serveStatic(req, res, ctx) {
833
1354
  if (proxied?.status === 200 && proxied.json.ok === true) {
834
1355
  // 主机端 DSH 面板本身已登录本机用户, 管理页无需令牌门禁;
835
1356
  // 把真实网关令牌一并返回, 抽屉里直接显示并允许复制(供手机 App 使用)。
836
- sendJson(res, proxied.status, { ...proxied.json, token: localToken, mode: 'gateway', via: 'gateway', gatewayInstalled })
1357
+ sendJson(res, proxied.status, { ...proxied.json, token: localToken, mode: 'gateway', via: 'gateway', gatewayInstalled, gatewayRuntime: await gatewayRuntimeForStatus(proxied.json.gatewayRuntime ?? null, health) })
837
1358
  return
838
1359
  }
839
1360
  if (health.running && proxied?.status >= 500) {
@@ -846,6 +1367,7 @@ async function serveStatic(req, res, ctx) {
846
1367
  gatewayRunning: health.running,
847
1368
  gatewayAuthError: health.running && (!localToken || proxied?.status === 401 || proxied?.status === 403) ? GATEWAY_AUTH_HINT : '',
848
1369
  gatewayVersion: health.version || '',
1370
+ gatewayRuntime: await gatewayRuntimeForStatus(null, health),
849
1371
  version,
850
1372
  token: health.running ? '' : localToken || '',
851
1373
  gatewayInstalled,
@@ -893,10 +1415,10 @@ async function serveStatic(req, res, ctx) {
893
1415
  [`${MOUNT}/admin/api/device-keys/rotate`, '/device-keys/rotate'],
894
1416
  [`${MOUNT}/admin/api/device-keys/revoke`, '/device-keys/revoke'],
895
1417
  ])
896
- if (pathname === `${MOUNT}/admin/api/relay` || pathname === `${MOUNT}/admin/api/autostart`) {
1418
+ if (pathname === `${MOUNT}/admin/api/relay` || pathname === `${MOUNT}/admin/api/autostart` || pathname === `${MOUNT}/admin/api/lan`) {
897
1419
  if (!['GET', 'POST'].includes(req.method)) { res.writeHead(405, { allow: 'GET, POST' }); res.end(); return }
898
1420
  const body = req.method === 'POST' ? await readBody(req, 4096) : undefined
899
- const proxied = await proxyGateway(pathname.endsWith('/autostart') ? '/admin/api/autostart' : '/admin/api/relay', req.method, body)
1421
+ const proxied = await proxyGateway('/admin/api/' + pathname.split('/').pop(), req.method, body)
900
1422
  sendJson(res, proxied?.status || 502, proxied?.json || { error: 'GATEWAY_UNAVAILABLE' })
901
1423
  return
902
1424
  }
@@ -972,7 +1494,10 @@ async function serveStatic(req, res, ctx) {
972
1494
  if (pathname === `${MOUNT}/admin/api/gateway`) {
973
1495
  if (req.method === 'GET') {
974
1496
  const h = await gatewayRunning()
975
- sendJson(res, 200, { ok: true, running: h.running, version: h.version || '', upstream: h.upstream || '', upstreamOk: h.upstreamOk === true })
1497
+ sendJson(res, 200, {
1498
+ ok: true, running: h.running, version: h.version || '', upstream: h.upstream || '', upstreamOk: h.upstreamOk === true,
1499
+ runtime: await gatewayRuntimeForStatus(undefined, h),
1500
+ })
976
1501
  return
977
1502
  }
978
1503
  if (req.method === 'POST') {
@@ -1196,6 +1721,7 @@ export function apply(ctx) {
1196
1721
  // Optional on older DSH: register the packaged read-only doctor skill when
1197
1722
  // the host exposes a skill registry. Failure never blocks the plugin.
1198
1723
  registerDoctorSkill(ctx)
1724
+ registerFileDeliveryTools(ctx, { gatewayBase, gatewayToken })
1199
1725
  watchDoctorWorkspaces(ctx)
1200
1726
  ctx.effect(() => ctx.webServer.register({
1201
1727
  kind: 'prefix',