@andy.ian/dsh-homing 2.1.3 → 2.1.5

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.
Files changed (120) hide show
  1. package/README.md +84 -0
  2. package/SECURITY.md +90 -0
  3. package/bin/backup.mjs +3 -2
  4. package/bin/bootstrap-server.mjs +2 -1
  5. package/bin/renew-cert.mjs +2 -1
  6. package/index.js +723 -92
  7. package/lib/compress.mjs +29 -5
  8. package/lib/exec-path.mjs +85 -0
  9. package/lib/files-page.mjs +27 -2
  10. package/lib/files.mjs +3 -2
  11. package/lib/git.mjs +5 -2
  12. package/lib/guard.mjs +43 -0
  13. package/lib/local-socket.mjs +50 -0
  14. package/lib/log-file.mjs +50 -0
  15. package/lib/node-runtime.mjs +44 -0
  16. package/lib/office.mjs +133 -0
  17. package/lib/orientation.mjs +158 -0
  18. package/lib/pty.mjs +30 -16
  19. package/lib/secret.mjs +46 -0
  20. package/lib/shells.mjs +322 -0
  21. package/lib/term-page.mjs +12 -1
  22. package/lib/vendor/des-vnc.mjs +266 -0
  23. package/lib/vendor/novnc/LICENSE.txt +62 -0
  24. package/lib/vendor/novnc/core/base64.js +104 -0
  25. package/lib/vendor/novnc/core/crypto/aes.js +178 -0
  26. package/lib/vendor/novnc/core/crypto/bigint.js +34 -0
  27. package/lib/vendor/novnc/core/crypto/crypto.js +90 -0
  28. package/lib/vendor/novnc/core/crypto/des.js +330 -0
  29. package/lib/vendor/novnc/core/crypto/dh.js +55 -0
  30. package/lib/vendor/novnc/core/crypto/md5.js +82 -0
  31. package/lib/vendor/novnc/core/crypto/rsa.js +132 -0
  32. package/lib/vendor/novnc/core/decoders/copyrect.js +27 -0
  33. package/lib/vendor/novnc/core/decoders/h264.js +321 -0
  34. package/lib/vendor/novnc/core/decoders/hextile.js +181 -0
  35. package/lib/vendor/novnc/core/decoders/jpeg.js +161 -0
  36. package/lib/vendor/novnc/core/decoders/raw.js +59 -0
  37. package/lib/vendor/novnc/core/decoders/rre.js +44 -0
  38. package/lib/vendor/novnc/core/decoders/tight.js +393 -0
  39. package/lib/vendor/novnc/core/decoders/tightpng.js +27 -0
  40. package/lib/vendor/novnc/core/decoders/zlib.js +51 -0
  41. package/lib/vendor/novnc/core/decoders/zrle.js +185 -0
  42. package/lib/vendor/novnc/core/deflator.js +84 -0
  43. package/lib/vendor/novnc/core/display.js +578 -0
  44. package/lib/vendor/novnc/core/encodings.js +54 -0
  45. package/lib/vendor/novnc/core/inflator.js +65 -0
  46. package/lib/vendor/novnc/core/input/domkeytable.js +311 -0
  47. package/lib/vendor/novnc/core/input/fixedkeys.js +129 -0
  48. package/lib/vendor/novnc/core/input/gesturehandler.js +567 -0
  49. package/lib/vendor/novnc/core/input/keyboard.js +294 -0
  50. package/lib/vendor/novnc/core/input/keysym.js +616 -0
  51. package/lib/vendor/novnc/core/input/keysymdef.js +688 -0
  52. package/lib/vendor/novnc/core/input/util.js +191 -0
  53. package/lib/vendor/novnc/core/input/vkeys.js +116 -0
  54. package/lib/vendor/novnc/core/input/xtscancodes.js +173 -0
  55. package/lib/vendor/novnc/core/ra2.js +312 -0
  56. package/lib/vendor/novnc/core/rfb.js +3420 -0
  57. package/lib/vendor/novnc/core/util/browser.js +233 -0
  58. package/lib/vendor/novnc/core/util/cursor.js +249 -0
  59. package/lib/vendor/novnc/core/util/element.js +32 -0
  60. package/lib/vendor/novnc/core/util/events.js +138 -0
  61. package/lib/vendor/novnc/core/util/eventtarget.js +35 -0
  62. package/lib/vendor/novnc/core/util/int.js +15 -0
  63. package/lib/vendor/novnc/core/util/logging.js +56 -0
  64. package/lib/vendor/novnc/core/util/strings.js +28 -0
  65. package/lib/vendor/novnc/core/websock.js +369 -0
  66. package/lib/vendor/novnc/vendor/pako/LICENSE +21 -0
  67. package/lib/vendor/novnc/vendor/pako/README.md +6 -0
  68. package/lib/vendor/novnc/vendor/pako/lib/utils/common.js +45 -0
  69. package/lib/vendor/novnc/vendor/pako/lib/zlib/adler32.js +27 -0
  70. package/lib/vendor/novnc/vendor/pako/lib/zlib/constants.js +47 -0
  71. package/lib/vendor/novnc/vendor/pako/lib/zlib/crc32.js +36 -0
  72. package/lib/vendor/novnc/vendor/pako/lib/zlib/deflate.js +1846 -0
  73. package/lib/vendor/novnc/vendor/pako/lib/zlib/gzheader.js +35 -0
  74. package/lib/vendor/novnc/vendor/pako/lib/zlib/inffast.js +324 -0
  75. package/lib/vendor/novnc/vendor/pako/lib/zlib/inflate.js +1527 -0
  76. package/lib/vendor/novnc/vendor/pako/lib/zlib/inftrees.js +322 -0
  77. package/lib/vendor/novnc/vendor/pako/lib/zlib/messages.js +11 -0
  78. package/lib/vendor/novnc/vendor/pako/lib/zlib/trees.js +1195 -0
  79. package/lib/vendor/novnc/vendor/pako/lib/zlib/zstream.js +24 -0
  80. package/lib/vendor/vnc.bundle.js +14592 -0
  81. package/lib/vendor/ws/LICENSE +20 -0
  82. package/lib/vendor/ws/index.js +22 -0
  83. package/lib/vendor/ws/lib/buffer-util.js +142 -0
  84. package/lib/vendor/ws/lib/constants.js +19 -0
  85. package/lib/vendor/ws/lib/event-target.js +292 -0
  86. package/lib/vendor/ws/lib/extension.js +203 -0
  87. package/lib/vendor/ws/lib/limiter.js +55 -0
  88. package/lib/vendor/ws/lib/permessage-deflate.js +530 -0
  89. package/lib/vendor/ws/lib/receiver.js +743 -0
  90. package/lib/vendor/ws/lib/sender.js +610 -0
  91. package/lib/vendor/ws/lib/stream.js +161 -0
  92. package/lib/vendor/ws/lib/subprotocol.js +62 -0
  93. package/lib/vendor/ws/lib/validation.js +152 -0
  94. package/lib/vendor/ws/lib/websocket-server.js +562 -0
  95. package/lib/vendor/ws/lib/websocket.js +1426 -0
  96. package/lib/vendor/ws/package.json +74 -0
  97. package/lib/vendor/ws/wrapper.mjs +21 -0
  98. package/lib/vnc-app.js +567 -0
  99. package/lib/vnc-auth-proxy.mjs +179 -0
  100. package/lib/vnc-boot.js +45 -0
  101. package/lib/vnc-page.mjs +77 -0
  102. package/lib/vnc-pointer.mjs +17 -0
  103. package/lib/vnc.mjs +75 -0
  104. package/lib/window-app.js +155 -0
  105. package/lib/window-page.mjs +111 -0
  106. package/lib/window-remote.mjs +226 -0
  107. package/lib/ws-bridge.mjs +130 -0
  108. package/package.json +4 -2
  109. package/permissions.json +91 -0
  110. package/restart/client.mjs +85 -19
  111. package/restart/daemon/cli.mjs +55 -13
  112. package/restart/daemon/lib/detach.mjs +3 -2
  113. package/restart/daemon/lib/process-tree.mjs +17 -3
  114. package/restart/daemon/lib/restart-flow.mjs +36 -0
  115. package/restart/daemon/main.mjs +299 -80
  116. package/restart/engine.mjs +24 -8
  117. package/restart/port.mjs +88 -0
  118. package/restart/runner.mjs +4 -3
  119. package/restart/service.mjs +8 -5
  120. package/restart/watchdog.mjs +134 -0
@@ -0,0 +1,158 @@
1
+ /**
2
+ * 跨平台屏幕方向控制。
3
+ *
4
+ * 设计:Node 负责编排与状态,具体动作交给各平台原生能力。
5
+ * - win32:复用 window-agent 的 rotate(ChangeDisplaySettingsEx + CDS_TEST,
6
+ * 已在本机验证:portrait → 1080x1920,landscape → 1920x1080)
7
+ * - linux:xrandr(X11);Wayland 下 xrandr 通常不可用,会明确报错
8
+ * - darwin:displayplacer(需要用户安装)
9
+ *
10
+ * 统一返回 { ok, platform, detail }
11
+ */
12
+ import { execFile } from 'node:child_process'
13
+ import fs from 'node:fs'
14
+ import os from 'node:os'
15
+ import path from 'node:path'
16
+ import { promisify } from 'node:util'
17
+
18
+ const run = promisify(execFile)
19
+
20
+ // 记录"竖屏是不是我们切过去的",用于崩溃/断开后自动恢复横屏
21
+ const MARKER = path.join(os.tmpdir(), 'dsh-homing-orientation.json')
22
+
23
+ function writeMarker(mode) {
24
+ try {
25
+ if (mode === 'portrait') {
26
+ fs.writeFileSync(MARKER, JSON.stringify({ byUs: true, ts: Date.now() }))
27
+ } else {
28
+ fs.rmSync(MARKER, { force: true })
29
+ }
30
+ } catch { /* 忽略 */ }
31
+ }
32
+
33
+ function markerPresent() {
34
+ try {
35
+ return JSON.parse(fs.readFileSync(MARKER, 'utf8')).byUs === true
36
+ } catch {
37
+ return false
38
+ }
39
+ }
40
+
41
+ const MODES = new Set(['portrait', 'landscape'])
42
+
43
+ function assertMode(mode) {
44
+ if (!MODES.has(mode)) {
45
+ throw new Error(`unsupported orientation: ${mode}`)
46
+ }
47
+ }
48
+
49
+ /** Linux:找到主输出(connected 且带 primary,否则取第一个 connected) */
50
+ async function linuxPrimaryOutput() {
51
+ const { stdout } = await run('xrandr', ['--query'])
52
+ const lines = stdout.split('\n')
53
+ const primary = lines.find((line) => /\bconnected\s+primary\b/u.test(line))
54
+ const connected = lines.find((line) => /\bconnected\b/u.test(line))
55
+ const line = primary ?? connected
56
+ if (!line) return null
57
+ return line.split(/\s+/u)[0] ?? null
58
+ }
59
+
60
+ async function rotateLinux(mode) {
61
+ const output = await linuxPrimaryOutput()
62
+ if (output === null) {
63
+ return { ok: false, platform: 'linux', detail: 'no connected output (xrandr)' }
64
+ }
65
+ const rotate = mode === 'portrait' ? 'left' : 'normal'
66
+ await run('xrandr', ['--output', output, '--rotate', rotate])
67
+ return { ok: true, platform: 'linux', detail: `${output} -> ${rotate}` }
68
+ }
69
+
70
+ async function rotateMac(mode) {
71
+ // displayplacer 需要参数:screen id;先用 list 解析
72
+ const { stdout } = await run('displayplacer', ['list'])
73
+ const idMatch = stdout.match(/Persistent screen id:\s*(\S+)/u)
74
+ if (!idMatch) {
75
+ return { ok: false, platform: 'darwin', detail: 'displayplacer: screen id not found' }
76
+ }
77
+ const rotation = mode === 'portrait' ? 'rotation:90' : 'rotation:0'
78
+ await run('displayplacer', [`id:${idMatch[1]}`, rotation, 'res:1920x1080', 'scaling:on'])
79
+ return { ok: true, platform: 'darwin', detail: `${idMatch[1]} -> ${rotation}` }
80
+ }
81
+
82
+ async function rotateWindows(mode) {
83
+ const { rotateScreen, stopAgent } = await import('./window-remote.mjs')
84
+ const result = await rotateScreen(mode)
85
+ if (typeof stopAgent === 'function') stopAgent()
86
+ return {
87
+ ok: result.ok === true && result.result === 0,
88
+ platform: 'win32',
89
+ detail: `result=${result.result ?? '?'} screen=${result.screenWidth}x${result.screenHeight}`,
90
+ screen: { width: result.screenWidth, height: result.screenHeight },
91
+ }
92
+ }
93
+
94
+ /** 设置屏幕方向:portrait(竖屏)/ landscape(横屏) */
95
+ export async function setOrientation(mode) {
96
+ assertMode(mode)
97
+ try {
98
+ let result
99
+ if (process.platform === 'win32') result = await rotateWindows(mode)
100
+ else if (process.platform === 'linux') result = await rotateLinux(mode)
101
+ else if (process.platform === 'darwin') result = await rotateMac(mode)
102
+ else result = { ok: false, platform: process.platform, detail: 'unsupported platform' }
103
+ if (result.ok === true) writeMarker(mode)
104
+ return result
105
+ } catch (error) {
106
+ return {
107
+ ok: false,
108
+ platform: process.platform,
109
+ detail: String(error?.stderr ?? error?.message ?? error).slice(0, 200),
110
+ }
111
+ }
112
+ }
113
+
114
+ /** 当前是否竖屏:Windows 用屏幕宽高判断,其它平台用 xrandr 输出判断 */
115
+ export async function isPortrait() {
116
+ if (process.platform === 'win32') {
117
+ const { listWindows, stopAgent } = await import('./window-remote.mjs')
118
+ const info = await listWindows()
119
+ if (typeof stopAgent === 'function') stopAgent()
120
+ const w = Number(info.screenWidth ?? 0)
121
+ const h = Number(info.screenHeight ?? 0)
122
+ if (w <= 0 || h <= 0) return null
123
+ return h > w
124
+ }
125
+ if (process.platform === 'linux') {
126
+ const { stdout } = await run('xrandr', ['--query'])
127
+ const line = stdout.split('\n').find((item) => /\bconnected\s+primary\b/u.test(item))
128
+ ?? stdout.split('\n').find((item) => /\bconnected\b/u.test(item))
129
+ if (!line) return null
130
+ const match = line.match(/(\d+)x(\d+)\+/u)
131
+ if (!match) return null
132
+ return Number(match[2]) > Number(match[1])
133
+ }
134
+ if (process.platform === 'darwin') {
135
+ const { stdout } = await run('displayplacer', ['list'])
136
+ return /rotation:90/u.test(stdout)
137
+ }
138
+ return null
139
+ }
140
+
141
+
142
+ /** 若上次是我们切的竖屏,启动/断开时恢复横屏(死锁/崩溃兜底) */
143
+ export async function ensureLandscape() {
144
+ if (!markerPresent()) return { ok: false, skipped: true, detail: 'no marker' }
145
+ const portrait = await isPortrait()
146
+ if (portrait !== true) {
147
+ writeMarker('landscape')
148
+ return { ok: true, skipped: true, detail: 'already landscape' }
149
+ }
150
+ const result = await setOrientation('landscape')
151
+ if (result.ok === true) writeMarker('landscape')
152
+ return result
153
+ }
154
+
155
+ /** 当前是否有"我们切了竖屏"的标记 */
156
+ export function hasOrientationMarker() {
157
+ return markerPresent()
158
+ }
package/lib/pty.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 真终端(PTY)—— 「远程登录到 Git Bash」。
2
+ * 真终端(PTY)—— 「远程登录到本机终端」(Git Bash / PowerShell / CMD / WSL / Python / Node)。
3
3
  *
4
4
  * 架构:
5
5
  * 浏览器(xterm.js) ──SSE/POST── 插件 ──ssh2── 本机 sshd ── ConPTY ── bash
@@ -18,6 +18,8 @@ import fs from 'node:fs'
18
18
  import net from 'node:net'
19
19
  import path from 'node:path'
20
20
  import { spawn, spawnSync } from 'node:child_process'
21
+ import { systemExe } from './exec-path.mjs'
22
+ import { cdCommand, customShells, detectShells, resolveShell, DEFAULT_SHELL } from './shells.mjs'
21
23
  import { createRequire } from 'node:module'
22
24
  import { fileURLToPath } from 'node:url'
23
25
 
@@ -40,8 +42,10 @@ export const loadSsh2 = () => {
40
42
  return null
41
43
  }
42
44
 
43
- const SSHD_EXE = 'C:/Windows/System32/OpenSSH/sshd.exe'
44
- const KEYGEN_EXE = 'C:/Windows/System32/OpenSSH/ssh-keygen.exe'
45
+ const TASKKILL = systemExe('taskkill')
46
+ const OPENSSH_DIR = path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'OpenSSH')
47
+ const SSHD_EXE = path.join(OPENSSH_DIR, 'sshd.exe')
48
+ const KEYGEN_EXE = path.join(OPENSSH_DIR, 'ssh-keygen.exe')
45
49
 
46
50
  /**
47
51
  * DSH_HOME:优先用插件传进来的值。
@@ -159,9 +163,12 @@ export const ensureSshd = async ({ dshHome = resolveDshHome(), startPort = 22222
159
163
  * 输出用带序号的环形缓冲保存,前端可用 since=<seq> 补发。
160
164
  */
161
165
  export class PtyTerminal {
162
- constructor({ port, dshHome = resolveDshHome(), cwd = null, maxBuffered = 512 * 1024, cols = 80, rows = 24 } = {}) {
166
+ constructor({ port, dshHome = resolveDshHome(), cwd = null, maxBuffered = 512 * 1024, cols = 80, rows = 24, shellId = DEFAULT_SHELL, custom = null } = {}) {
163
167
  this.port = port
164
168
  this.dshHome = dshHome
169
+ this.shells = detectShells(customShells(custom))
170
+ this.shell = resolveShell(shellId, this.shells)
171
+ this.shellId = this.shell?.id ?? ''
165
172
  this.cwd = cwd
166
173
  this.cols = cols
167
174
  this.rows = rows
@@ -207,8 +214,13 @@ export class PtyTerminal {
207
214
  await new Promise((resolve, reject) => {
208
215
  const timer = setTimeout(() => reject(new Error('SSH 连接超时')), 15000)
209
216
  client.on('ready', () => {
210
- // 用 exec + pty 启动 Git Bash(client.shell() 会落到系统默认的 cmd.exe)
211
- const command = '"C:/Program Files/Git/bin/bash.exe" -l'
217
+ // 用 exec + pty 启动选中的 shell(client.shell() 会落到系统默认的 cmd.exe)
218
+ if (this.shell === null) {
219
+ clearTimeout(timer)
220
+ reject(new Error('本机没有可用的终端程序'))
221
+ return
222
+ }
223
+ const command = this.shell.command
212
224
  client.exec(command, {
213
225
  pty: { term: 'xterm-256color', cols: this.cols, rows: this.rows },
214
226
  }, (error, stream) => {
@@ -282,12 +294,10 @@ export class PtyTerminal {
282
294
  /** 切换工作目录(会话是常驻的,所以只发一条 cd) */
283
295
  changeDir(winPath) {
284
296
  if (typeof winPath !== 'string' || winPath.trim() === '') return false
285
- const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath.trim())
286
- const target = match === null
287
- ? winPath.trim()
288
- : '/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
297
+ const command = cdCommand(this.shellId, winPath, this.shell?.cdStyle ?? '')
298
+ if (command === null) return false
289
299
  this.cwd = winPath.trim()
290
- return this.write('cd "' + target.replaceAll('"', '\\"') + '"\r')
300
+ return this.write(command)
291
301
  }
292
302
 
293
303
  subscribe(listener) {
@@ -328,19 +338,23 @@ export class PtyTerminal {
328
338
 
329
339
  let sharedTerminal = null
330
340
 
331
- export const sharedPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null } = {}) => {
341
+ export const sharedPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null, shellId = DEFAULT_SHELL, custom = null } = {}) => {
332
342
  const { port } = await ensureSshd({ dshHome })
343
+ if (sharedTerminal !== null && !sharedTerminal.closed && sharedTerminal.shellId !== shellId) {
344
+ sharedTerminal.stop()
345
+ sharedTerminal = null
346
+ }
333
347
  if (sharedTerminal === null || sharedTerminal.closed) {
334
- sharedTerminal = new PtyTerminal({ port, dshHome, cwd })
348
+ sharedTerminal = new PtyTerminal({ port, dshHome, cwd, shellId, custom })
335
349
  await sharedTerminal.start()
336
350
  }
337
351
  return sharedTerminal
338
352
  }
339
353
 
340
- export const resetPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null } = {}) => {
354
+ export const resetPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null, shellId = DEFAULT_SHELL, custom = null } = {}) => {
341
355
  if (sharedTerminal !== null) sharedTerminal.stop()
342
356
  sharedTerminal = null
343
- return sharedPtyTerminal({ dshHome, cwd })
357
+ return sharedPtyTerminal({ dshHome, cwd, shellId, custom })
344
358
  }
345
359
 
346
360
  export const stopSshd = (dshHome = resolveDshHome()) => {
@@ -349,7 +363,7 @@ export const stopSshd = (dshHome = resolveDshHome()) => {
349
363
  const state = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
350
364
  if (state.pid) {
351
365
  // Windows 上用 taskkill 连子进程一起收:只 kill 父进程会留下 per-connection 的 sshd
352
- const result = spawnSync('taskkill', ['/F', '/T', '/PID', String(state.pid)], { windowsHide: true, encoding: 'utf8' })
366
+ const result = spawnSync(TASKKILL, ['/F', '/T', '/PID', String(state.pid)], { windowsHide: true, encoding: 'utf8' })
353
367
  if (result.status !== 0) {
354
368
  try { process.kill(state.pid) } catch { /* 已退出 */ }
355
369
  }
package/lib/secret.mjs ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * 本机密钥的加密存储(Windows DPAPI,CurrentUser 作用域)。
3
+ *
4
+ * 目的:settings.json 里不再出现明文 VNC 密码。
5
+ * 通过 PowerShell 调用 ProtectedData;明文只经环境变量传递,不出现在命令行参数里。
6
+ */
7
+ import { execFile } from 'node:child_process'
8
+ import { promisify } from 'node:util'
9
+
10
+ const run = promisify(execFile)
11
+
12
+ const PS = process.platform === 'win32' ? 'powershell.exe' : null
13
+
14
+ const PROTECT_SCRIPT = [
15
+ 'Add-Type -AssemblyName System.Security;',
16
+ '$b=[Text.Encoding]::UTF8.GetBytes($env:DSH_SECRET);',
17
+ '[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Protect($b,$null,\'CurrentUser\'))',
18
+ ].join(' ')
19
+
20
+ const UNPROTECT_SCRIPT = [
21
+ 'Add-Type -AssemblyName System.Security;',
22
+ '$b=[Convert]::FromBase64String($env:DSH_SECRET);',
23
+ '[Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect($b,$null,\'CurrentUser\'))',
24
+ ].join(' ')
25
+
26
+ /** 加密为 DPAPI Base64 字符串;非 Windows 返回 null */
27
+ export async function protectSecret(plain) {
28
+ if (PS === null || typeof plain !== 'string' || plain === '') return null
29
+ const { stdout } = await run(PS, ['-NoProfile', '-NonInteractive', '-Command', PROTECT_SCRIPT], {
30
+ env: { ...process.env, DSH_SECRET: plain },
31
+ windowsHide: true,
32
+ timeout: 15_000,
33
+ })
34
+ return stdout.trim()
35
+ }
36
+
37
+ /** 解密 DPAPI Base64 字符串;失败返回 null */
38
+ export async function unprotectSecret(encrypted) {
39
+ if (PS === null || typeof encrypted !== 'string' || encrypted === '') return null
40
+ const { stdout } = await run(PS, ['-NoProfile', '-NonInteractive', '-Command', UNPROTECT_SCRIPT], {
41
+ env: { ...process.env, DSH_SECRET: encrypted },
42
+ windowsHide: true,
43
+ timeout: 15_000,
44
+ })
45
+ return stdout.trim()
46
+ }
package/lib/shells.mjs ADDED
@@ -0,0 +1,322 @@
1
+ /**
2
+ * 远程终端的 Shell 探测与启动配置(跨平台)
3
+ *
4
+ * 目标:不同操作系统自动发现本机常见 shell,模型/用户不需要手动探测。
5
+ *
6
+ * 探测顺序:
7
+ * 1. 平台内置的常见安装路径(Windows 的 Git/MSYS2/Cygwin,macOS 的 Homebrew,Linux 的 /usr/bin)
8
+ * 2. POSIX 上读取 /etc/shells 里登记的 shell
9
+ * 3. PATH 扫描(带 PATHEXT / 可执行权限判断)
10
+ * 4. $SHELL(当前用户默认 shell)
11
+ *
12
+ * 说明:MobaXterm / Windows Terminal 是图形终端程序,不是 shell,无法在这里运行。
13
+ */
14
+ import fs from 'node:fs'
15
+ import { findNodeRuntime } from './node-runtime.mjs'
16
+ import path from 'node:path'
17
+
18
+ const isWindows = process.platform === 'win32'
19
+ const SEP = isWindows ? ';' : ':'
20
+ const PATH_DIRS = (process.env.PATH ?? '').split(SEP).filter(Boolean)
21
+ const WINDIR = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows'
22
+ const PF = process.env.ProgramFiles || 'C:\\Program Files'
23
+ const PF86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)'
24
+
25
+ const isFile = (file) => {
26
+ try { return fs.statSync(file).isFile() } catch { return false }
27
+ }
28
+
29
+ /** POSIX 上还要求可执行位 */
30
+ const isExecutable = (file) => {
31
+ if (!isFile(file)) return false
32
+ if (isWindows) return true
33
+ try { fs.accessSync(file, fs.constants.X_OK); return true } catch { return false }
34
+ }
35
+
36
+ const exts = isWindows
37
+ ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';').filter(Boolean).map((item) => item.toLowerCase())
38
+ : ['']
39
+
40
+ /** 在 PATH 里找可执行文件,返回绝对路径或 null */
41
+ export function findOnPath(names) {
42
+ const list = Array.isArray(names) ? names : [names]
43
+ for (const dir of PATH_DIRS) {
44
+ for (const name of list) {
45
+ const candidates = isWindows && !/\.[A-Za-z0-9]+$/u.test(name)
46
+ ? exts.map((ext) => path.join(dir, name + ext))
47
+ : [path.join(dir, name)]
48
+ for (const file of candidates) {
49
+ if (isExecutable(file)) return file
50
+ }
51
+ }
52
+ }
53
+ return null
54
+ }
55
+
56
+ /** 依次尝试绝对路径,返回第一个存在的可执行文件 */
57
+ const firstExisting = (candidates) => candidates.filter(Boolean).find(isExecutable) ?? null
58
+
59
+ /** POSIX:/etc/shells 里登记的 shell */
60
+ const etcShells = () => {
61
+ if (isWindows) return []
62
+ try {
63
+ return fs.readFileSync('/etc/shells', 'utf8')
64
+ .split('\n')
65
+ .map((line) => line.trim())
66
+ .filter((line) => line !== '' && !line.startsWith('#') && isExecutable(line))
67
+ } catch {
68
+ return []
69
+ }
70
+ }
71
+
72
+ const quote = (value) => (isWindows ? `"${value.replaceAll('"', '\\"')}"` : `'${value.replaceAll('\'', `'\\''`)}'`)
73
+
74
+ /** POSIX 路径风格(bash 系列在 Windows 上需要 /d/...) */
75
+ const toPosixBashPath = (winPath) => {
76
+ const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath)
77
+ if (match === null) return winPath.replaceAll('\\', '/')
78
+ return '/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
79
+ }
80
+
81
+ const toWslPath = (winPath) => {
82
+ const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath)
83
+ if (match === null) return winPath.replaceAll('\\', '/')
84
+ return '/mnt/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
85
+ }
86
+
87
+ /** win/POSIX 路径 → 各 shell 的 cd 命令;会话常驻,切目录靠发一条命令 */
88
+ export const cdCommand = (id, target, style = '') => {
89
+ const raw = String(target ?? '').trim()
90
+ if (raw === '') return null
91
+ const kind = style || id
92
+ const windowsPath = /^[A-Za-z]:[\\/]/u.test(raw)
93
+
94
+ // Python / Node REPL:直接调 API
95
+ if (kind === 'python') return `import os; os.chdir(${JSON.stringify(raw)})\r`
96
+ if (kind === 'node') return `process.chdir(${JSON.stringify(raw)})\r`
97
+
98
+ // POSIX 主机:路径本来就是 POSIX
99
+ if (!isWindows) return `cd ${JSON.stringify(raw)}\r`
100
+
101
+ // Windows 主机:按 shell 类型转换
102
+ if (kind === 'wsl') return `cd ${JSON.stringify(windowsPath ? toWslPath(raw) : raw)}\r`
103
+ if (kind === 'bash' || kind === 'git-bash' || kind === 'msys2' || kind === 'cygwin') {
104
+ return `cd ${JSON.stringify(windowsPath ? toPosixBashPath(raw) : raw)}\r`
105
+ }
106
+ return `cd ${JSON.stringify(raw)}\r`
107
+ }
108
+
109
+ /** 所有候选;available 在 detectShells 时填充 */
110
+ const WINDOWS_PROFILES = [
111
+ {
112
+ id: 'git-bash',
113
+ label: 'Git Bash',
114
+ detect: () => firstExisting([
115
+ path.join(PF, 'Git', 'bin', 'bash.exe'),
116
+ path.join(PF, 'Git', 'usr', 'bin', 'bash.exe'),
117
+ findOnPath(['bash']),
118
+ ]),
119
+ command: (bin) => `${quote(bin)} -l`,
120
+ cdStyle: 'bash',
121
+ },
122
+ {
123
+ id: 'msys2',
124
+ label: 'MSYS2 Bash',
125
+ detect: () => firstExisting([
126
+ 'C:\\msys64\\usr\\bin\\bash.exe',
127
+ path.join(PF, 'msys64', 'usr', 'bin', 'bash.exe'),
128
+ ]),
129
+ command: (bin) => `${quote(bin)} -l`,
130
+ cdStyle: 'bash',
131
+ },
132
+ {
133
+ id: 'cygwin',
134
+ label: 'Cygwin Bash',
135
+ detect: () => firstExisting([
136
+ 'C:\\cygwin64\\bin\\bash.exe',
137
+ 'C:\\cygwin\\bin\\bash.exe',
138
+ ]),
139
+ command: (bin) => `${quote(bin)} -l`,
140
+ cdStyle: 'bash',
141
+ },
142
+ {
143
+ id: 'powershell',
144
+ label: 'PowerShell 5',
145
+ detect: () => firstExisting([
146
+ path.join(WINDIR, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
147
+ findOnPath(['powershell']),
148
+ ]),
149
+ command: (bin) => `${quote(bin)} -NoLogo -NoExit -Command "[Console]::OutputEncoding=[Text.Encoding]::UTF8;$OutputEncoding=[Text.Encoding]::UTF8"`,
150
+ },
151
+ {
152
+ id: 'pwsh',
153
+ label: 'PowerShell 7',
154
+ detect: () => firstExisting([path.join(PF, 'PowerShell', '7', 'pwsh.exe'), findOnPath(['pwsh'])]),
155
+ command: (bin) => `${quote(bin)} -NoLogo`,
156
+ },
157
+ {
158
+ id: 'cmd',
159
+ label: 'CMD',
160
+ detect: () => firstExisting([path.join(WINDIR, 'System32', 'cmd.exe'), findOnPath(['cmd'])]),
161
+ command: (bin) => `${quote(bin)} /K chcp 65001>nul`,
162
+ },
163
+ {
164
+ id: 'wsl',
165
+ label: 'WSL',
166
+ detect: () => firstExisting([path.join(WINDIR, 'System32', 'wsl.exe'), findOnPath(['wsl'])]),
167
+ command: (bin) => quote(bin),
168
+ cdStyle: 'wsl',
169
+ },
170
+ {
171
+ id: 'nu',
172
+ label: 'Nushell',
173
+ detect: () => findOnPath(['nu']),
174
+ command: (bin) => quote(bin),
175
+ },
176
+ ]
177
+
178
+ const POSIX_PROFILES = [
179
+ {
180
+ id: 'default-shell',
181
+ label: '默认 Shell($SHELL)',
182
+ detect: () => {
183
+ const shell = process.env.SHELL
184
+ return shell && isExecutable(shell) ? shell : null
185
+ },
186
+ command: (bin) => `${quote(bin)} -l`,
187
+ },
188
+ {
189
+ id: 'bash',
190
+ label: 'Bash',
191
+ detect: () => firstExisting(['/bin/bash', '/usr/bin/bash', '/usr/local/bin/bash', findOnPath(['bash'])]),
192
+ command: (bin) => `${quote(bin)} -l`,
193
+ },
194
+ {
195
+ id: 'zsh',
196
+ label: 'Zsh',
197
+ detect: () => firstExisting(['/bin/zsh', '/usr/bin/zsh', '/usr/local/bin/zsh', '/opt/homebrew/bin/zsh', findOnPath(['zsh'])]),
198
+ command: (bin) => `${quote(bin)} -l`,
199
+ },
200
+ {
201
+ id: 'fish',
202
+ label: 'Fish',
203
+ detect: () => firstExisting(['/usr/bin/fish', '/usr/local/bin/fish', '/opt/homebrew/bin/fish', findOnPath(['fish'])]),
204
+ command: (bin) => quote(bin),
205
+ },
206
+ {
207
+ id: 'sh',
208
+ label: 'sh',
209
+ detect: () => firstExisting(['/bin/sh', findOnPath(['sh'])]),
210
+ command: (bin) => quote(bin),
211
+ },
212
+ {
213
+ id: 'dash',
214
+ label: 'Dash',
215
+ detect: () => firstExisting(['/bin/dash', '/usr/bin/dash', findOnPath(['dash'])]),
216
+ command: (bin) => quote(bin),
217
+ },
218
+ {
219
+ id: 'ksh',
220
+ label: 'Ksh',
221
+ detect: () => firstExisting(['/bin/ksh', '/usr/bin/ksh', findOnPath(['ksh'])]),
222
+ command: (bin) => quote(bin),
223
+ },
224
+ {
225
+ id: 'pwsh',
226
+ label: 'PowerShell 7',
227
+ detect: () => firstExisting(['/usr/local/bin/pwsh', '/opt/homebrew/bin/pwsh', findOnPath(['pwsh'])]),
228
+ command: (bin) => `${quote(bin)} -NoLogo`,
229
+ },
230
+ {
231
+ id: 'nu',
232
+ label: 'Nushell',
233
+ detect: () => firstExisting(['/usr/local/bin/nu', '/opt/homebrew/bin/nu', findOnPath(['nu'])]),
234
+ command: (bin) => quote(bin),
235
+ },
236
+ ]
237
+
238
+ /** 已支持的内置 shell(按平台) */
239
+ export const PROFILES = isWindows ? WINDOWS_PROFILES : POSIX_PROFILES
240
+
241
+ const REPL_PROFILES = [
242
+ {
243
+ id: 'python',
244
+ label: 'Python REPL',
245
+ detect: () => findOnPath(isWindows ? ['python', 'python3', 'py'] : ['python3', 'python']),
246
+ command: (bin) => `${quote(bin)} -i -q`,
247
+ cdStyle: 'python',
248
+ },
249
+ {
250
+ id: 'node',
251
+ label: 'Node REPL',
252
+ // DSH 自带的 node 不一定在 PATH 里,用 process.execPath 兜底
253
+ detect: () => findOnPath(['node']) ?? findNodeRuntime(),
254
+ command: (bin) => quote(bin),
255
+ cdStyle: 'node',
256
+ },
257
+ ]
258
+
259
+ /**
260
+ * 把 settings.json 里的 terminal.custom 解析成可选项。
261
+ * 支持单个对象或数组;cd 可选 bash/wsl/windows/python/node。
262
+ */
263
+ export function customShells(custom) {
264
+ if (custom === null || custom === undefined) return []
265
+ const list = Array.isArray(custom) ? custom : [custom]
266
+ const out = []
267
+ list.forEach((item, index) => {
268
+ if (item === null || typeof item !== 'object') return
269
+ if (typeof item.path !== 'string' || !isExecutable(item.path)) return
270
+ const args = Array.isArray(item.args) ? item.args.map((arg) => String(arg)) : []
271
+ const single = list.length === 1
272
+ out.push({
273
+ id: single ? 'custom' : `custom-${index + 1}`,
274
+ label: typeof item.label === 'string' && item.label.trim() !== '' ? item.label.trim() : `自定义 ${index + 1}`,
275
+ bin: item.path,
276
+ command: [quote(item.path), ...args].join(' '),
277
+ custom: true,
278
+ cdStyle: typeof item.cd === 'string' ? item.cd : 'windows',
279
+ })
280
+ })
281
+ return out
282
+ }
283
+
284
+ /** 探测可用类型 → [{ id, label, bin, command, cdStyle }] */
285
+ export function detectShells(extra = []) {
286
+ const seen = new Set()
287
+ const list = []
288
+ const push = (id, label, bin, command, cdStyle) => {
289
+ if (bin === null || !isExecutable(bin) || seen.has(id)) return
290
+ seen.add(id)
291
+ list.push({ id, label, bin, command, ...(cdStyle ? { cdStyle } : {}) })
292
+ }
293
+
294
+ // /etc/shells 里额外登记的 shell(POSIX),用文件名做 id
295
+ const NOT_SHELLS = new Set(['screen', 'tmux', 'script', 'rbash'])
296
+ const extraPosix = etcShells()
297
+ .filter((shell) => !NOT_SHELLS.has(path.basename(shell)))
298
+ .filter((shell) => !PROFILES.some((profile) => profile.id === path.basename(shell).replace(/^-/u, '')))
299
+ .slice(0, 6)
300
+
301
+ for (const profile of [...PROFILES, ...REPL_PROFILES]) {
302
+ let bin = null
303
+ try { bin = profile.detect() } catch { bin = null }
304
+ push(profile.id, profile.label, bin, bin === null ? null : profile.command(bin), profile.cdStyle)
305
+ }
306
+
307
+ for (const shell of extraPosix) {
308
+ const name = path.basename(shell)
309
+ push(name, name, shell, `${quote(shell)} -l`, '')
310
+ }
311
+
312
+ for (const item of extra) push(item.id, item.label, item.bin, item.command, item.cdStyle)
313
+ return list
314
+ }
315
+
316
+ /** 根据 id 解析;未知 id 回退第一个可用项 */
317
+ export function resolveShell(id, shells = detectShells()) {
318
+ if (shells.length === 0) return null
319
+ return shells.find((item) => item.id === id) ?? shells[0]
320
+ }
321
+
322
+ export const DEFAULT_SHELL = isWindows ? 'git-bash' : 'default-shell'
package/lib/term-page.mjs CHANGED
@@ -73,7 +73,10 @@ const STYLE = `
73
73
  .keys button.warn { border-color: #5a2a2a; color: #f0b6bf; }
74
74
  `
75
75
 
76
- export function renderTermPage({ cwd = '', host = '', user = '', connected = true } = {}) {
76
+ export function renderTermPage({ cwd = '', host = '', user = '', connected = true, shells = [], shellId = '' } = {}) {
77
+ const shellOptions = shells
78
+ .map((item) => `<option value="${escapeHtml(item.id)}"${item.id === shellId ? ' selected' : ''}>${escapeHtml(item.label)}</option>`)
79
+ .join('')
77
80
  return `<!doctype html>
78
81
  <html lang="zh-CN"><head>
79
82
  <meta charset="utf-8">
@@ -87,6 +90,14 @@ export function renderTermPage({ cwd = '', host = '', user = '', connected = tru
87
90
  <a href="/">DSH</a>
88
91
  <a href="/files?path=${encodeURIComponent(cwd)}">文件</a>
89
92
  <a href="/git?path=${encodeURIComponent(cwd)}">Git</a>
93
+ <a href="/remote">窗口</a>
94
+ <a href="/vnc">桌面</a>
95
+ ${shells.length > 0 ? `<form method="post" action="/term/shell" class="shellpick" style="display:flex;gap:4px;align-items:center;margin:0">
96
+ <select name="shell" aria-label="终端类型" style="max-width:130px;padding:2px 4px;border-radius:5px;border:1px solid #333;background:#232323;color:#cfcfcf;font:inherit;font-size:11px">
97
+ ${shellOptions}
98
+ </select>
99
+ <button type="submit" style="padding:2px 7px;border-radius:5px;border:1px solid #333;background:#232323;color:#cfcfcf;font:inherit;font-size:11px">切换</button>
100
+ </form>` : ''}
90
101
  <span class="spacer"></span>
91
102
  <span style="overflow:hidden;text-overflow:ellipsis">${escapeHtml(user)}@${escapeHtml(host)}</span>
92
103
  <span id="mode" title="光标模式" hidden>普通</span>