@andy.ian/dsh-homing 2.1.3 → 2.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/index.js +37 -5
- package/lib/pty.mjs +24 -13
- package/lib/shells.mjs +321 -0
- package/lib/term-page.mjs +10 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -44,6 +44,48 @@
|
|
|
44
44
|
| `legacyFunc` | 是否仍接受旧版 `?func=` 常量暗号(默认 `false`) | `false` |
|
|
45
45
|
| `login` | 是否要求账号密码 | `true` |
|
|
46
46
|
|
|
47
|
+
## 远程终端
|
|
48
|
+
|
|
49
|
+
**跨平台自动探测**(插件启动时按当前系统扫描,不需要模型去猜):
|
|
50
|
+
|
|
51
|
+
| 平台 | 自动发现 |
|
|
52
|
+
|---|---|
|
|
53
|
+
| Windows | Git Bash、MSYS2 Bash、Cygwin Bash、PowerShell 5/7、CMD、WSL、Nushell |
|
|
54
|
+
| Linux | $SHELL、bash、zsh、fish、sh、dash、ksh、PowerShell 7、Nushell、/etc/shells 里登记的其它 shell |
|
|
55
|
+
| macOS | $SHELL、zsh、bash、fish、sh、PowerShell 7、Nushell(含 Homebrew 路径) |
|
|
56
|
+
| 全平台 | Python REPL、Node REPL |
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
终端页支持切换多种 shell,选择会记在浏览器 Cookie(每台设备独立):
|
|
60
|
+
|
|
61
|
+
| 类型 | 说明 |
|
|
62
|
+
|---|---|
|
|
63
|
+
| Git Bash / PowerShell 5 / PowerShell 7 / CMD / WSL / Python REPL / Node REPL | 启动时自动探测,装了才出现 |
|
|
64
|
+
|
|
65
|
+
默认值可在 `settings.json` 指定:
|
|
66
|
+
|
|
67
|
+
```json
|
|
68
|
+
{ "terminal": { "shell": "powershell" } }
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
自定义命令行(例如把某个便携版 bash 接进来):
|
|
72
|
+
|
|
73
|
+
```json
|
|
74
|
+
{
|
|
75
|
+
"terminal": {
|
|
76
|
+
"custom": {
|
|
77
|
+
"label": "MobaXterm Bash",
|
|
78
|
+
"path": "C:\\Program Files\\Git\\bin\\bash.exe",
|
|
79
|
+
"args": ["-l"],
|
|
80
|
+
"cd": "bash"
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
`custom` 也可以是数组;`cd` 可选 `bash` / `wsl` / `windows` / `python` / `node`。
|
|
87
|
+
注意:MobaXterm / Windows Terminal 是图形程序,不能嵌入网页终端,只能接它们底层的 shell。
|
|
88
|
+
|
|
47
89
|
## 账号
|
|
48
90
|
|
|
49
91
|
首次启动自动生成随机账号,打印在 DSH 日志里;存在
|
package/index.js
CHANGED
|
@@ -28,6 +28,7 @@ import { createRestartPolicy } from './restart/face.mjs';
|
|
|
28
28
|
import * as ptyrun from './lib/pty.mjs';
|
|
29
29
|
import { renderTermPage } from './lib/term-page.mjs';
|
|
30
30
|
import * as compress from './lib/compress.mjs';
|
|
31
|
+
import { customShells, detectShells, resolveShell, DEFAULT_SHELL } from './lib/shells.mjs';
|
|
31
32
|
import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage } from './lib/files-page.mjs';
|
|
32
33
|
import { checkUnsafeOrigin } from './lib/csrf.mjs';
|
|
33
34
|
import * as limits from './lib/limits.mjs';
|
|
@@ -652,6 +653,8 @@ const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script
|
|
|
652
653
|
// 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
|
|
653
654
|
// 调试页上一键即可设置,页面坏了也点得到。
|
|
654
655
|
const MOBILE_OFF_COOKIE = 'dsh-homing-off';
|
|
656
|
+
// 终端页选择过的 shell(每台设备各自记住)
|
|
657
|
+
const TERM_SHELL_COOKIE = 'dsh-homing-shell';
|
|
655
658
|
|
|
656
659
|
|
|
657
660
|
|
|
@@ -2130,6 +2133,13 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2130
2133
|
return;
|
|
2131
2134
|
}
|
|
2132
2135
|
const dshHomeTerm = path.resolve(dataDir(), '..', '..');
|
|
2136
|
+
// 终端类型:cookie(每台设备)→ 查询参数 → settings.terminal.shell → 默认
|
|
2137
|
+
const termCustom = customShells(config.terminal?.custom);
|
|
2138
|
+
const termShells = detectShells(termCustom);
|
|
2139
|
+
const termShellAsked = readCookies(req.headers.cookie)[TERM_SHELL_COOKIE]
|
|
2140
|
+
?? url.searchParams.get('shell')
|
|
2141
|
+
?? (typeof config.terminal?.shell === 'string' ? config.terminal.shell : DEFAULT_SHELL);
|
|
2142
|
+
const termShellId = resolveShell(termShellAsked, termShells)?.id ?? '';
|
|
2133
2143
|
|
|
2134
2144
|
const sendTerm = (pageHtml) => {
|
|
2135
2145
|
res.writeHead(200, {
|
|
@@ -2186,6 +2196,26 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2186
2196
|
return;
|
|
2187
2197
|
}
|
|
2188
2198
|
|
|
2199
|
+
// 切换终端类型(写 cookie 后回到终端页,下一次连接生效)
|
|
2200
|
+
if (url.pathname === '/term/shell' && req.method === 'POST') {
|
|
2201
|
+
const form = new URLSearchParams(await readBody(req, 16 * 1024));
|
|
2202
|
+
const wanted = form.get('shell') ?? '';
|
|
2203
|
+
const chosen = termShells.find((item) => item.id === wanted);
|
|
2204
|
+
if (chosen) {
|
|
2205
|
+
appendAudit(dir, 'term-shell', { shell: chosen.id });
|
|
2206
|
+
res.writeHead(303, {
|
|
2207
|
+
location: '/term',
|
|
2208
|
+
'cache-control': 'no-store',
|
|
2209
|
+
'set-cookie': `${TERM_SHELL_COOKIE}=${chosen.id}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000${secureCookies ? '; Secure' : ''}`,
|
|
2210
|
+
});
|
|
2211
|
+
res.end();
|
|
2212
|
+
return;
|
|
2213
|
+
}
|
|
2214
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
2215
|
+
res.end('不支持的终端类型\n');
|
|
2216
|
+
return;
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2189
2219
|
// 输入
|
|
2190
2220
|
if (url.pathname === '/term/input' && req.method === 'POST') {
|
|
2191
2221
|
let payload = {};
|
|
@@ -2194,7 +2224,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2194
2224
|
} catch {
|
|
2195
2225
|
payload = {};
|
|
2196
2226
|
}
|
|
2197
|
-
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
|
|
2227
|
+
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, shellId: termShellId, custom: config.terminal?.custom });
|
|
2198
2228
|
const ok = terminal.write(String(payload.data ?? ''));
|
|
2199
2229
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
2200
2230
|
res.end(JSON.stringify({ ok }));
|
|
@@ -2209,7 +2239,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2209
2239
|
} catch {
|
|
2210
2240
|
payload = {};
|
|
2211
2241
|
}
|
|
2212
|
-
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
|
|
2242
|
+
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, shellId: termShellId, custom: config.terminal?.custom });
|
|
2213
2243
|
const ok = terminal.resize(payload.cols, payload.rows);
|
|
2214
2244
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
2215
2245
|
res.end(JSON.stringify({ ok, size: terminal.size }));
|
|
@@ -2218,7 +2248,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2218
2248
|
|
|
2219
2249
|
// 重置
|
|
2220
2250
|
if (url.pathname === '/term/reset' && req.method === 'POST') {
|
|
2221
|
-
await ptyrun.resetPtyTerminal({ dshHome: dshHomeTerm });
|
|
2251
|
+
await ptyrun.resetPtyTerminal({ dshHome: dshHomeTerm, shellId: termShellId, custom: config.terminal?.custom });
|
|
2222
2252
|
appendAudit(dir, 'term-reset', {});
|
|
2223
2253
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
2224
2254
|
res.end(JSON.stringify({ ok: true }));
|
|
@@ -2227,7 +2257,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2227
2257
|
|
|
2228
2258
|
// 输出流(SSE)
|
|
2229
2259
|
if (url.pathname === '/term/stream' && req.method === 'GET') {
|
|
2230
|
-
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
|
|
2260
|
+
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, shellId: termShellId, custom: config.terminal?.custom });
|
|
2231
2261
|
const since = Number(url.searchParams.get('since') ?? '0') || 0;
|
|
2232
2262
|
res.writeHead(200, {
|
|
2233
2263
|
'content-type': 'text/event-stream; charset=utf-8',
|
|
@@ -2276,7 +2306,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2276
2306
|
// 先确保 sshd 与终端会话就绪,失败也要把页面开出来(页面上会显示状态)
|
|
2277
2307
|
let connected = false;
|
|
2278
2308
|
try {
|
|
2279
|
-
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, cwd });
|
|
2309
|
+
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, cwd, shellId: termShellId, custom: config.terminal?.custom });
|
|
2280
2310
|
// 会话是常驻的:从别的会话进来时,让终端切到那个工作区(和 PC 上点文件夹一致)
|
|
2281
2311
|
if (terminal.cwd !== undefined && terminal.cwd !== cwd) {
|
|
2282
2312
|
terminal.changeDir(cwd);
|
|
@@ -2290,6 +2320,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2290
2320
|
user: process.env.USERNAME ?? '',
|
|
2291
2321
|
host: os.hostname(),
|
|
2292
2322
|
connected,
|
|
2323
|
+
shells: termShells.map((item) => ({ id: item.id, label: item.label })),
|
|
2324
|
+
shellId: termShellId,
|
|
2293
2325
|
}));
|
|
2294
2326
|
return;
|
|
2295
2327
|
}
|
package/lib/pty.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* 真终端(PTY)——
|
|
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,7 @@ 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 { cdCommand, customShells, detectShells, resolveShell, DEFAULT_SHELL } from './shells.mjs'
|
|
21
22
|
import { createRequire } from 'node:module'
|
|
22
23
|
import { fileURLToPath } from 'node:url'
|
|
23
24
|
|
|
@@ -159,9 +160,12 @@ export const ensureSshd = async ({ dshHome = resolveDshHome(), startPort = 22222
|
|
|
159
160
|
* 输出用带序号的环形缓冲保存,前端可用 since=<seq> 补发。
|
|
160
161
|
*/
|
|
161
162
|
export class PtyTerminal {
|
|
162
|
-
constructor({ port, dshHome = resolveDshHome(), cwd = null, maxBuffered = 512 * 1024, cols = 80, rows = 24 } = {}) {
|
|
163
|
+
constructor({ port, dshHome = resolveDshHome(), cwd = null, maxBuffered = 512 * 1024, cols = 80, rows = 24, shellId = DEFAULT_SHELL, custom = null } = {}) {
|
|
163
164
|
this.port = port
|
|
164
165
|
this.dshHome = dshHome
|
|
166
|
+
this.shells = detectShells(customShells(custom))
|
|
167
|
+
this.shell = resolveShell(shellId, this.shells)
|
|
168
|
+
this.shellId = this.shell?.id ?? ''
|
|
165
169
|
this.cwd = cwd
|
|
166
170
|
this.cols = cols
|
|
167
171
|
this.rows = rows
|
|
@@ -207,8 +211,13 @@ export class PtyTerminal {
|
|
|
207
211
|
await new Promise((resolve, reject) => {
|
|
208
212
|
const timer = setTimeout(() => reject(new Error('SSH 连接超时')), 15000)
|
|
209
213
|
client.on('ready', () => {
|
|
210
|
-
// 用 exec + pty
|
|
211
|
-
|
|
214
|
+
// 用 exec + pty 启动选中的 shell(client.shell() 会落到系统默认的 cmd.exe)
|
|
215
|
+
if (this.shell === null) {
|
|
216
|
+
clearTimeout(timer)
|
|
217
|
+
reject(new Error('本机没有可用的终端程序'))
|
|
218
|
+
return
|
|
219
|
+
}
|
|
220
|
+
const command = this.shell.command
|
|
212
221
|
client.exec(command, {
|
|
213
222
|
pty: { term: 'xterm-256color', cols: this.cols, rows: this.rows },
|
|
214
223
|
}, (error, stream) => {
|
|
@@ -282,12 +291,10 @@ export class PtyTerminal {
|
|
|
282
291
|
/** 切换工作目录(会话是常驻的,所以只发一条 cd) */
|
|
283
292
|
changeDir(winPath) {
|
|
284
293
|
if (typeof winPath !== 'string' || winPath.trim() === '') return false
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
? winPath.trim()
|
|
288
|
-
: '/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
|
|
294
|
+
const command = cdCommand(this.shellId, winPath, this.shell?.cdStyle ?? '')
|
|
295
|
+
if (command === null) return false
|
|
289
296
|
this.cwd = winPath.trim()
|
|
290
|
-
return this.write(
|
|
297
|
+
return this.write(command)
|
|
291
298
|
}
|
|
292
299
|
|
|
293
300
|
subscribe(listener) {
|
|
@@ -328,19 +335,23 @@ export class PtyTerminal {
|
|
|
328
335
|
|
|
329
336
|
let sharedTerminal = null
|
|
330
337
|
|
|
331
|
-
export const sharedPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null } = {}) => {
|
|
338
|
+
export const sharedPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null, shellId = DEFAULT_SHELL, custom = null } = {}) => {
|
|
332
339
|
const { port } = await ensureSshd({ dshHome })
|
|
340
|
+
if (sharedTerminal !== null && !sharedTerminal.closed && sharedTerminal.shellId !== shellId) {
|
|
341
|
+
sharedTerminal.stop()
|
|
342
|
+
sharedTerminal = null
|
|
343
|
+
}
|
|
333
344
|
if (sharedTerminal === null || sharedTerminal.closed) {
|
|
334
|
-
sharedTerminal = new PtyTerminal({ port, dshHome, cwd })
|
|
345
|
+
sharedTerminal = new PtyTerminal({ port, dshHome, cwd, shellId, custom })
|
|
335
346
|
await sharedTerminal.start()
|
|
336
347
|
}
|
|
337
348
|
return sharedTerminal
|
|
338
349
|
}
|
|
339
350
|
|
|
340
|
-
export const resetPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null } = {}) => {
|
|
351
|
+
export const resetPtyTerminal = async ({ dshHome = resolveDshHome(), cwd = null, shellId = DEFAULT_SHELL, custom = null } = {}) => {
|
|
341
352
|
if (sharedTerminal !== null) sharedTerminal.stop()
|
|
342
353
|
sharedTerminal = null
|
|
343
|
-
return sharedPtyTerminal({ dshHome, cwd })
|
|
354
|
+
return sharedPtyTerminal({ dshHome, cwd, shellId, custom })
|
|
344
355
|
}
|
|
345
356
|
|
|
346
357
|
export const stopSshd = (dshHome = resolveDshHome()) => {
|
package/lib/shells.mjs
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
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 path from 'node:path'
|
|
16
|
+
|
|
17
|
+
const isWindows = process.platform === 'win32'
|
|
18
|
+
const SEP = isWindows ? ';' : ':'
|
|
19
|
+
const PATH_DIRS = (process.env.PATH ?? '').split(SEP).filter(Boolean)
|
|
20
|
+
const WINDIR = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows'
|
|
21
|
+
const PF = process.env.ProgramFiles || 'C:\\Program Files'
|
|
22
|
+
const PF86 = process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)'
|
|
23
|
+
|
|
24
|
+
const isFile = (file) => {
|
|
25
|
+
try { return fs.statSync(file).isFile() } catch { return false }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** POSIX 上还要求可执行位 */
|
|
29
|
+
const isExecutable = (file) => {
|
|
30
|
+
if (!isFile(file)) return false
|
|
31
|
+
if (isWindows) return true
|
|
32
|
+
try { fs.accessSync(file, fs.constants.X_OK); return true } catch { return false }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const exts = isWindows
|
|
36
|
+
? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';').filter(Boolean).map((item) => item.toLowerCase())
|
|
37
|
+
: ['']
|
|
38
|
+
|
|
39
|
+
/** 在 PATH 里找可执行文件,返回绝对路径或 null */
|
|
40
|
+
export function findOnPath(names) {
|
|
41
|
+
const list = Array.isArray(names) ? names : [names]
|
|
42
|
+
for (const dir of PATH_DIRS) {
|
|
43
|
+
for (const name of list) {
|
|
44
|
+
const candidates = isWindows && !/\.[A-Za-z0-9]+$/u.test(name)
|
|
45
|
+
? exts.map((ext) => path.join(dir, name + ext))
|
|
46
|
+
: [path.join(dir, name)]
|
|
47
|
+
for (const file of candidates) {
|
|
48
|
+
if (isExecutable(file)) return file
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 依次尝试绝对路径,返回第一个存在的可执行文件 */
|
|
56
|
+
const firstExisting = (candidates) => candidates.filter(Boolean).find(isExecutable) ?? null
|
|
57
|
+
|
|
58
|
+
/** POSIX:/etc/shells 里登记的 shell */
|
|
59
|
+
const etcShells = () => {
|
|
60
|
+
if (isWindows) return []
|
|
61
|
+
try {
|
|
62
|
+
return fs.readFileSync('/etc/shells', 'utf8')
|
|
63
|
+
.split('\n')
|
|
64
|
+
.map((line) => line.trim())
|
|
65
|
+
.filter((line) => line !== '' && !line.startsWith('#') && isExecutable(line))
|
|
66
|
+
} catch {
|
|
67
|
+
return []
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const quote = (value) => (isWindows ? `"${value.replaceAll('"', '\\"')}"` : `'${value.replaceAll('\'', `'\\''`)}'`)
|
|
72
|
+
|
|
73
|
+
/** POSIX 路径风格(bash 系列在 Windows 上需要 /d/...) */
|
|
74
|
+
const toPosixBashPath = (winPath) => {
|
|
75
|
+
const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath)
|
|
76
|
+
if (match === null) return winPath.replaceAll('\\', '/')
|
|
77
|
+
return '/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const toWslPath = (winPath) => {
|
|
81
|
+
const match = /^([A-Za-z]):[\\/]?(.*)$/u.exec(winPath)
|
|
82
|
+
if (match === null) return winPath.replaceAll('\\', '/')
|
|
83
|
+
return '/mnt/' + match[1].toLowerCase() + (match[2] === '' ? '' : '/' + match[2].replaceAll('\\', '/'))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** win/POSIX 路径 → 各 shell 的 cd 命令;会话常驻,切目录靠发一条命令 */
|
|
87
|
+
export const cdCommand = (id, target, style = '') => {
|
|
88
|
+
const raw = String(target ?? '').trim()
|
|
89
|
+
if (raw === '') return null
|
|
90
|
+
const kind = style || id
|
|
91
|
+
const windowsPath = /^[A-Za-z]:[\\/]/u.test(raw)
|
|
92
|
+
|
|
93
|
+
// Python / Node REPL:直接调 API
|
|
94
|
+
if (kind === 'python') return `import os; os.chdir(${JSON.stringify(raw)})\r`
|
|
95
|
+
if (kind === 'node') return `process.chdir(${JSON.stringify(raw)})\r`
|
|
96
|
+
|
|
97
|
+
// POSIX 主机:路径本来就是 POSIX
|
|
98
|
+
if (!isWindows) return `cd ${JSON.stringify(raw)}\r`
|
|
99
|
+
|
|
100
|
+
// Windows 主机:按 shell 类型转换
|
|
101
|
+
if (kind === 'wsl') return `cd ${JSON.stringify(windowsPath ? toWslPath(raw) : raw)}\r`
|
|
102
|
+
if (kind === 'bash' || kind === 'git-bash' || kind === 'msys2' || kind === 'cygwin') {
|
|
103
|
+
return `cd ${JSON.stringify(windowsPath ? toPosixBashPath(raw) : raw)}\r`
|
|
104
|
+
}
|
|
105
|
+
return `cd ${JSON.stringify(raw)}\r`
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 所有候选;available 在 detectShells 时填充 */
|
|
109
|
+
const WINDOWS_PROFILES = [
|
|
110
|
+
{
|
|
111
|
+
id: 'git-bash',
|
|
112
|
+
label: 'Git Bash',
|
|
113
|
+
detect: () => firstExisting([
|
|
114
|
+
path.join(PF, 'Git', 'bin', 'bash.exe'),
|
|
115
|
+
path.join(PF, 'Git', 'usr', 'bin', 'bash.exe'),
|
|
116
|
+
findOnPath(['bash']),
|
|
117
|
+
]),
|
|
118
|
+
command: (bin) => `${quote(bin)} -l`,
|
|
119
|
+
cdStyle: 'bash',
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
id: 'msys2',
|
|
123
|
+
label: 'MSYS2 Bash',
|
|
124
|
+
detect: () => firstExisting([
|
|
125
|
+
'C:\\msys64\\usr\\bin\\bash.exe',
|
|
126
|
+
path.join(PF, 'msys64', 'usr', 'bin', 'bash.exe'),
|
|
127
|
+
]),
|
|
128
|
+
command: (bin) => `${quote(bin)} -l`,
|
|
129
|
+
cdStyle: 'bash',
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
id: 'cygwin',
|
|
133
|
+
label: 'Cygwin Bash',
|
|
134
|
+
detect: () => firstExisting([
|
|
135
|
+
'C:\\cygwin64\\bin\\bash.exe',
|
|
136
|
+
'C:\\cygwin\\bin\\bash.exe',
|
|
137
|
+
]),
|
|
138
|
+
command: (bin) => `${quote(bin)} -l`,
|
|
139
|
+
cdStyle: 'bash',
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
id: 'powershell',
|
|
143
|
+
label: 'PowerShell 5',
|
|
144
|
+
detect: () => firstExisting([
|
|
145
|
+
path.join(WINDIR, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
146
|
+
findOnPath(['powershell']),
|
|
147
|
+
]),
|
|
148
|
+
command: (bin) => `${quote(bin)} -NoLogo -NoExit -Command "[Console]::OutputEncoding=[Text.Encoding]::UTF8;$OutputEncoding=[Text.Encoding]::UTF8"`,
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
id: 'pwsh',
|
|
152
|
+
label: 'PowerShell 7',
|
|
153
|
+
detect: () => firstExisting([path.join(PF, 'PowerShell', '7', 'pwsh.exe'), findOnPath(['pwsh'])]),
|
|
154
|
+
command: (bin) => `${quote(bin)} -NoLogo`,
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
id: 'cmd',
|
|
158
|
+
label: 'CMD',
|
|
159
|
+
detect: () => firstExisting([path.join(WINDIR, 'System32', 'cmd.exe'), findOnPath(['cmd'])]),
|
|
160
|
+
command: (bin) => `${quote(bin)} /K chcp 65001>nul`,
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
id: 'wsl',
|
|
164
|
+
label: 'WSL',
|
|
165
|
+
detect: () => firstExisting([path.join(WINDIR, 'System32', 'wsl.exe'), findOnPath(['wsl'])]),
|
|
166
|
+
command: (bin) => quote(bin),
|
|
167
|
+
cdStyle: 'wsl',
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
id: 'nu',
|
|
171
|
+
label: 'Nushell',
|
|
172
|
+
detect: () => findOnPath(['nu']),
|
|
173
|
+
command: (bin) => quote(bin),
|
|
174
|
+
},
|
|
175
|
+
]
|
|
176
|
+
|
|
177
|
+
const POSIX_PROFILES = [
|
|
178
|
+
{
|
|
179
|
+
id: 'default-shell',
|
|
180
|
+
label: '默认 Shell($SHELL)',
|
|
181
|
+
detect: () => {
|
|
182
|
+
const shell = process.env.SHELL
|
|
183
|
+
return shell && isExecutable(shell) ? shell : null
|
|
184
|
+
},
|
|
185
|
+
command: (bin) => `${quote(bin)} -l`,
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
id: 'bash',
|
|
189
|
+
label: 'Bash',
|
|
190
|
+
detect: () => firstExisting(['/bin/bash', '/usr/bin/bash', '/usr/local/bin/bash', findOnPath(['bash'])]),
|
|
191
|
+
command: (bin) => `${quote(bin)} -l`,
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
id: 'zsh',
|
|
195
|
+
label: 'Zsh',
|
|
196
|
+
detect: () => firstExisting(['/bin/zsh', '/usr/bin/zsh', '/usr/local/bin/zsh', '/opt/homebrew/bin/zsh', findOnPath(['zsh'])]),
|
|
197
|
+
command: (bin) => `${quote(bin)} -l`,
|
|
198
|
+
},
|
|
199
|
+
{
|
|
200
|
+
id: 'fish',
|
|
201
|
+
label: 'Fish',
|
|
202
|
+
detect: () => firstExisting(['/usr/bin/fish', '/usr/local/bin/fish', '/opt/homebrew/bin/fish', findOnPath(['fish'])]),
|
|
203
|
+
command: (bin) => quote(bin),
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
id: 'sh',
|
|
207
|
+
label: 'sh',
|
|
208
|
+
detect: () => firstExisting(['/bin/sh', findOnPath(['sh'])]),
|
|
209
|
+
command: (bin) => quote(bin),
|
|
210
|
+
},
|
|
211
|
+
{
|
|
212
|
+
id: 'dash',
|
|
213
|
+
label: 'Dash',
|
|
214
|
+
detect: () => firstExisting(['/bin/dash', '/usr/bin/dash', findOnPath(['dash'])]),
|
|
215
|
+
command: (bin) => quote(bin),
|
|
216
|
+
},
|
|
217
|
+
{
|
|
218
|
+
id: 'ksh',
|
|
219
|
+
label: 'Ksh',
|
|
220
|
+
detect: () => firstExisting(['/bin/ksh', '/usr/bin/ksh', findOnPath(['ksh'])]),
|
|
221
|
+
command: (bin) => quote(bin),
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
id: 'pwsh',
|
|
225
|
+
label: 'PowerShell 7',
|
|
226
|
+
detect: () => firstExisting(['/usr/local/bin/pwsh', '/opt/homebrew/bin/pwsh', findOnPath(['pwsh'])]),
|
|
227
|
+
command: (bin) => `${quote(bin)} -NoLogo`,
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
id: 'nu',
|
|
231
|
+
label: 'Nushell',
|
|
232
|
+
detect: () => firstExisting(['/usr/local/bin/nu', '/opt/homebrew/bin/nu', findOnPath(['nu'])]),
|
|
233
|
+
command: (bin) => quote(bin),
|
|
234
|
+
},
|
|
235
|
+
]
|
|
236
|
+
|
|
237
|
+
/** 已支持的内置 shell(按平台) */
|
|
238
|
+
export const PROFILES = isWindows ? WINDOWS_PROFILES : POSIX_PROFILES
|
|
239
|
+
|
|
240
|
+
const REPL_PROFILES = [
|
|
241
|
+
{
|
|
242
|
+
id: 'python',
|
|
243
|
+
label: 'Python REPL',
|
|
244
|
+
detect: () => findOnPath(isWindows ? ['python', 'python3', 'py'] : ['python3', 'python']),
|
|
245
|
+
command: (bin) => `${quote(bin)} -i -q`,
|
|
246
|
+
cdStyle: 'python',
|
|
247
|
+
},
|
|
248
|
+
{
|
|
249
|
+
id: 'node',
|
|
250
|
+
label: 'Node REPL',
|
|
251
|
+
// DSH 自带的 node 不一定在 PATH 里,用 process.execPath 兜底
|
|
252
|
+
detect: () => findOnPath(['node']) ?? (isExecutable(process.execPath) ? process.execPath : null),
|
|
253
|
+
command: (bin) => quote(bin),
|
|
254
|
+
cdStyle: 'node',
|
|
255
|
+
},
|
|
256
|
+
]
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 把 settings.json 里的 terminal.custom 解析成可选项。
|
|
260
|
+
* 支持单个对象或数组;cd 可选 bash/wsl/windows/python/node。
|
|
261
|
+
*/
|
|
262
|
+
export function customShells(custom) {
|
|
263
|
+
if (custom === null || custom === undefined) return []
|
|
264
|
+
const list = Array.isArray(custom) ? custom : [custom]
|
|
265
|
+
const out = []
|
|
266
|
+
list.forEach((item, index) => {
|
|
267
|
+
if (item === null || typeof item !== 'object') return
|
|
268
|
+
if (typeof item.path !== 'string' || !isExecutable(item.path)) return
|
|
269
|
+
const args = Array.isArray(item.args) ? item.args.map((arg) => String(arg)) : []
|
|
270
|
+
const single = list.length === 1
|
|
271
|
+
out.push({
|
|
272
|
+
id: single ? 'custom' : `custom-${index + 1}`,
|
|
273
|
+
label: typeof item.label === 'string' && item.label.trim() !== '' ? item.label.trim() : `自定义 ${index + 1}`,
|
|
274
|
+
bin: item.path,
|
|
275
|
+
command: [quote(item.path), ...args].join(' '),
|
|
276
|
+
custom: true,
|
|
277
|
+
cdStyle: typeof item.cd === 'string' ? item.cd : 'windows',
|
|
278
|
+
})
|
|
279
|
+
})
|
|
280
|
+
return out
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** 探测可用类型 → [{ id, label, bin, command, cdStyle }] */
|
|
284
|
+
export function detectShells(extra = []) {
|
|
285
|
+
const seen = new Set()
|
|
286
|
+
const list = []
|
|
287
|
+
const push = (id, label, bin, command, cdStyle) => {
|
|
288
|
+
if (bin === null || !isExecutable(bin) || seen.has(id)) return
|
|
289
|
+
seen.add(id)
|
|
290
|
+
list.push({ id, label, bin, command, ...(cdStyle ? { cdStyle } : {}) })
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// /etc/shells 里额外登记的 shell(POSIX),用文件名做 id
|
|
294
|
+
const NOT_SHELLS = new Set(['screen', 'tmux', 'script', 'rbash'])
|
|
295
|
+
const extraPosix = etcShells()
|
|
296
|
+
.filter((shell) => !NOT_SHELLS.has(path.basename(shell)))
|
|
297
|
+
.filter((shell) => !PROFILES.some((profile) => profile.id === path.basename(shell).replace(/^-/u, '')))
|
|
298
|
+
.slice(0, 6)
|
|
299
|
+
|
|
300
|
+
for (const profile of [...PROFILES, ...REPL_PROFILES]) {
|
|
301
|
+
let bin = null
|
|
302
|
+
try { bin = profile.detect() } catch { bin = null }
|
|
303
|
+
push(profile.id, profile.label, bin, bin === null ? null : profile.command(bin), profile.cdStyle)
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
for (const shell of extraPosix) {
|
|
307
|
+
const name = path.basename(shell)
|
|
308
|
+
push(name, name, shell, `${quote(shell)} -l`, '')
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
for (const item of extra) push(item.id, item.label, item.bin, item.command, item.cdStyle)
|
|
312
|
+
return list
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** 根据 id 解析;未知 id 回退第一个可用项 */
|
|
316
|
+
export function resolveShell(id, shells = detectShells()) {
|
|
317
|
+
if (shells.length === 0) return null
|
|
318
|
+
return shells.find((item) => item.id === id) ?? shells[0]
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
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,12 @@ 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
|
+
${shells.length > 0 ? `<form method="post" action="/term/shell" class="shellpick" style="display:flex;gap:4px;align-items:center;margin:0">
|
|
94
|
+
<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">
|
|
95
|
+
${shellOptions}
|
|
96
|
+
</select>
|
|
97
|
+
<button type="submit" style="padding:2px 7px;border-radius:5px;border:1px solid #333;background:#232323;color:#cfcfcf;font:inherit;font-size:11px">切换</button>
|
|
98
|
+
</form>` : ''}
|
|
90
99
|
<span class="spacer"></span>
|
|
91
100
|
<span style="overflow:hidden;text-overflow:ellipsis">${escapeHtml(user)}@${escapeHtml(host)}</span>
|
|
92
101
|
<span id="mode" title="光标模式" hidden>普通</span>
|