@andy.ian/dsh-homing 2.1.2 → 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 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
@@ -27,7 +27,9 @@ import * as deviceStore from './lib/devices.mjs';
27
27
  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
- import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage } from './lib/files-page.mjs';
30
+ import * as compress from './lib/compress.mjs';
31
+ import { customShells, detectShells, resolveShell, DEFAULT_SHELL } from './lib/shells.mjs';
32
+ import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage } from './lib/files-page.mjs';
31
33
  import { checkUnsafeOrigin } from './lib/csrf.mjs';
32
34
  import * as limits from './lib/limits.mjs';
33
35
 
@@ -530,15 +532,16 @@ const MOBILE_JS = `(() => {
530
532
  closeRightBar()
531
533
  }
532
534
 
533
- /* ---------- RESTART_MENU_ITEM ----------
534
- * 在 DSH 会话「…」菜单里追加一项「重启 DSH / 守护进程」。
535
- * 做法:复制一个已有的菜单项(连同图标与样式),只替换文字与图标路径,
536
- * 这样配色/尺寸/间距完全跟随 DSH 自己的风格。
537
- * 每次菜单变化先清掉旧项再插入,保证永远只有一项。
535
+ /* ---------- SESSION_MENU_ITEMS ----------
536
+ * 在 DSH 会话「…」菜单里追加两项:
537
+ * - 下载工作区文件:跳到文件页(可逐个文件下载)
538
+ * - 重启 DSH / 守护进程:跳到重启页
539
+ * 做法:复制一个原生菜单项(连同图标容器与样式),只替换文字和图标路径;
540
+ * 每轮先清掉旧项,并全局 prune,保证每项最多一个。
538
541
  */
539
542
  const MENU_HINT = /下载 Session 日志|复制会话为 Markdown|反馈/u
540
- // Lucide rotate-ccw:与 DSH 菜单同尺寸的“重启”图标
541
- const RESTART_ICON = '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'
543
+ const ICON_RESTART = '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'
544
+ const ICON_DOWNLOAD = '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5"/><path d="M12 15V3"/>'
542
545
  let menuTimer = null
543
546
 
544
547
  const textNodeMatching = (node, pattern) => {
@@ -549,9 +552,33 @@ const MOBILE_JS = `(() => {
549
552
  return null
550
553
  }
551
554
 
555
+ const buildMenuItem = (template, label, icon, action) => {
556
+ const link = template.cloneNode(true)
557
+ link.setAttribute('role', 'menuitem')
558
+ link.setAttribute('href', '#')
559
+ link.style.textDecoration = 'none'
560
+ const textNode = textNodeMatching(link, /反馈|下载 Session 日志|复制会话为 Markdown/u)
561
+ if (textNode !== null) textNode.nodeValue = label
562
+ else link.textContent = label
563
+ const svg = link.querySelector('svg')
564
+ if (svg !== null) {
565
+ svg.innerHTML = icon
566
+ svg.setAttribute('viewBox', '0 0 24 24')
567
+ svg.setAttribute('fill', 'none')
568
+ svg.setAttribute('stroke', 'currentColor')
569
+ svg.setAttribute('stroke-width', '2')
570
+ svg.setAttribute('stroke-linecap', 'round')
571
+ svg.setAttribute('stroke-linejoin', 'round')
572
+ }
573
+ link.addEventListener('click', (event) => {
574
+ event.preventDefault()
575
+ event.stopPropagation()
576
+ action()
577
+ }, true)
578
+ return link
579
+ }
580
+
552
581
  const enhanceMenus = () => {
553
- // 每个 role=menu 容器只处理一次;注意菜单项外面可能还包了一层 wrapper,
554
- // 所以必须向上找到真正的菜单容器,而不是用 item.parentElement。
555
582
  const done = new Set()
556
583
  for (const item of document.querySelectorAll('[role="menuitem"]')) {
557
584
  const menu = item.closest('[role="menu"]') ?? item.parentElement
@@ -559,52 +586,33 @@ const MOBILE_JS = `(() => {
559
586
  if (!MENU_HINT.test(menu.textContent || '')) continue
560
587
  done.add(menu)
561
588
 
562
- // 先清掉旧的(含 React 重渲染造成的重复),保证只有一项
563
- for (const old of menu.querySelectorAll('[data-dsh-homing-restart]')) old.remove()
589
+ for (const old of menu.querySelectorAll('[data-dsh-homing-download],[data-dsh-homing-restart]')) old.remove()
564
590
 
565
591
  const items = [...menu.querySelectorAll('[role="menuitem"]')]
566
592
  const template = items.find((node) => node.querySelector('svg')) ?? items[0]
567
593
  if (!template) continue
568
- const link = template.cloneNode(true)
569
- link.setAttribute('role', 'menuitem')
570
- link.setAttribute('data-dsh-homing-restart', '1')
571
- link.setAttribute('href', '/dsh_homing/restart')
572
- link.style.textDecoration = 'none'
573
-
574
- const textNode = textNodeMatching(link, /反馈|下载 Session 日志|复制会话为 Markdown/u)
575
- if (textNode !== null) textNode.nodeValue = '重启 DSH / 守护进程'
576
- else link.textContent = '重启 DSH / 守护进程'
577
-
578
- const svg = link.querySelector('svg')
579
- if (svg !== null) {
580
- // 图标按菜单项的描边风格来,避免 fill=currentColor 渲染成一坨实心圆
581
- svg.innerHTML = RESTART_ICON
582
- svg.setAttribute('viewBox', '0 0 24 24')
583
- svg.setAttribute('fill', 'none')
584
- svg.setAttribute('stroke', 'currentColor')
585
- svg.setAttribute('stroke-width', '2')
586
- svg.setAttribute('stroke-linecap', 'round')
587
- svg.setAttribute('stroke-linejoin', 'round')
588
- }
589
-
590
- link.addEventListener('click', (event) => {
591
- event.preventDefault()
592
- event.stopPropagation()
593
- window.location.assign('/dsh_homing/restart')
594
- }, true)
595
- menu.appendChild(link)
594
+
595
+ const download = buildMenuItem(template, '下载工作区文件', ICON_DOWNLOAD, () => goFiles())
596
+ download.setAttribute('data-dsh-homing-download', '1')
597
+ const restart = buildMenuItem(template, '重启 DSH / 守护进程', ICON_RESTART, () => window.location.assign('/dsh_homing/restart'))
598
+ restart.setAttribute('data-dsh-homing-restart', '1')
599
+
600
+ menu.appendChild(download)
601
+ menu.appendChild(restart)
596
602
  }
597
603
  }
598
604
 
599
- // 兜底:无论菜单容器怎么嵌套,页面上最多只保留一个
600
- const pruneRestartItems = () => {
601
- const all = [...document.querySelectorAll('[data-dsh-homing-restart]')]
602
- for (let i = 0; i < all.length - 1; i += 1) all[i].remove()
605
+ // 兜底:无论菜单容器怎么嵌套,每类最多保留一个
606
+ const pruneMenuItems = () => {
607
+ for (const selector of ['[data-dsh-homing-download]', '[data-dsh-homing-restart]']) {
608
+ const all = [...document.querySelectorAll(selector)]
609
+ for (let i = 0; i < all.length - 1; i += 1) all[i].remove()
610
+ }
603
611
  }
604
612
 
605
613
  const menuObserver = new MutationObserver(() => {
606
614
  if (menuTimer) return
607
- menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneRestartItems() }, 80)
615
+ menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneMenuItems() }, 80)
608
616
  })
609
617
  menuObserver.observe(document.body, { childList: true, subtree: true })
610
618
 
@@ -645,6 +653,8 @@ const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script
645
653
  // 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
646
654
  // 调试页上一键即可设置,页面坏了也点得到。
647
655
  const MOBILE_OFF_COOKIE = 'dsh-homing-off';
656
+ // 终端页选择过的 shell(每台设备各自记住)
657
+ const TERM_SHELL_COOKIE = 'dsh-homing-shell';
648
658
 
649
659
 
650
660
 
@@ -2123,6 +2133,13 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2123
2133
  return;
2124
2134
  }
2125
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 ?? '';
2126
2143
 
2127
2144
  const sendTerm = (pageHtml) => {
2128
2145
  res.writeHead(200, {
@@ -2179,6 +2196,26 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2179
2196
  return;
2180
2197
  }
2181
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
+
2182
2219
  // 输入
2183
2220
  if (url.pathname === '/term/input' && req.method === 'POST') {
2184
2221
  let payload = {};
@@ -2187,7 +2224,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2187
2224
  } catch {
2188
2225
  payload = {};
2189
2226
  }
2190
- const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
2227
+ const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, shellId: termShellId, custom: config.terminal?.custom });
2191
2228
  const ok = terminal.write(String(payload.data ?? ''));
2192
2229
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2193
2230
  res.end(JSON.stringify({ ok }));
@@ -2202,7 +2239,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2202
2239
  } catch {
2203
2240
  payload = {};
2204
2241
  }
2205
- const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
2242
+ const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, shellId: termShellId, custom: config.terminal?.custom });
2206
2243
  const ok = terminal.resize(payload.cols, payload.rows);
2207
2244
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2208
2245
  res.end(JSON.stringify({ ok, size: terminal.size }));
@@ -2211,7 +2248,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2211
2248
 
2212
2249
  // 重置
2213
2250
  if (url.pathname === '/term/reset' && req.method === 'POST') {
2214
- await ptyrun.resetPtyTerminal({ dshHome: dshHomeTerm });
2251
+ await ptyrun.resetPtyTerminal({ dshHome: dshHomeTerm, shellId: termShellId, custom: config.terminal?.custom });
2215
2252
  appendAudit(dir, 'term-reset', {});
2216
2253
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2217
2254
  res.end(JSON.stringify({ ok: true }));
@@ -2220,7 +2257,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2220
2257
 
2221
2258
  // 输出流(SSE)
2222
2259
  if (url.pathname === '/term/stream' && req.method === 'GET') {
2223
- const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
2260
+ const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, shellId: termShellId, custom: config.terminal?.custom });
2224
2261
  const since = Number(url.searchParams.get('since') ?? '0') || 0;
2225
2262
  res.writeHead(200, {
2226
2263
  'content-type': 'text/event-stream; charset=utf-8',
@@ -2269,7 +2306,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2269
2306
  // 先确保 sshd 与终端会话就绪,失败也要把页面开出来(页面上会显示状态)
2270
2307
  let connected = false;
2271
2308
  try {
2272
- const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, cwd });
2309
+ const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, cwd, shellId: termShellId, custom: config.terminal?.custom });
2273
2310
  // 会话是常驻的:从别的会话进来时,让终端切到那个工作区(和 PC 上点文件夹一致)
2274
2311
  if (terminal.cwd !== undefined && terminal.cwd !== cwd) {
2275
2312
  terminal.changeDir(cwd);
@@ -2283,6 +2320,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2283
2320
  user: process.env.USERNAME ?? '',
2284
2321
  host: os.hostname(),
2285
2322
  connected,
2323
+ shells: termShells.map((item) => ({ id: item.id, label: item.label })),
2324
+ shellId: termShellId,
2286
2325
  }));
2287
2326
  return;
2288
2327
  }
@@ -2355,7 +2394,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2355
2394
  return;
2356
2395
  }
2357
2396
 
2358
- if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/run'
2397
+ if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/download' || url.pathname === '/files/compress' || url.pathname === '/files/run'
2359
2398
  || url.pathname === '/files/rename'
2360
2399
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
2361
2400
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
@@ -2402,6 +2441,68 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2402
2441
  return;
2403
2442
  }
2404
2443
 
2444
+ if (url.pathname === '/files/compress' && req.method === 'GET') {
2445
+ const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
2446
+ const tools = compress.availableBackends().map((item) => ({ label: item.label, strength: item.strength, level: item.level }));
2447
+ appendAudit(dir, 'file-compress-view', { path: target, tools: tools.length });
2448
+ sendHtml(renderCompressPage({ target, archive: '', tools }));
2449
+ return;
2450
+ }
2451
+
2452
+ if (url.pathname === '/files/compress' && req.method === 'POST') {
2453
+ const form = new URLSearchParams(await readBody(req, 64 * 1024));
2454
+ const target = filebrowse.resolvePath(form.get('path') ?? '');
2455
+ const password = form.get('password') ?? '';
2456
+ const confirm = form.get('confirm') ?? '';
2457
+ const tools = compress.availableBackends().map((item) => ({ label: item.label, strength: item.strength, level: item.level }));
2458
+ if (password !== confirm) {
2459
+ sendHtml(renderCompressPage({ target, archive: '', tools, message: '两次输入的密码不一致', isError: true }));
2460
+ return;
2461
+ }
2462
+ const result = compress.createEncryptedArchive({ target, password });
2463
+ appendAudit(dir, 'file-compress', {
2464
+ path: target,
2465
+ ok: result.ok,
2466
+ tool: result.tool ?? null,
2467
+ bytes: result.bytes ?? 0,
2468
+ error: result.error ?? null,
2469
+ });
2470
+ sendHtml(renderCompressPage({
2471
+ target,
2472
+ archive: result.ok ? result.path : '',
2473
+ tools,
2474
+ tool: result.tool ?? '',
2475
+ strength: result.strength ?? '',
2476
+ message: result.ok ? '已生成加密压缩包' : result.error,
2477
+ isError: !result.ok,
2478
+ done: result.ok,
2479
+ }));
2480
+ return;
2481
+ }
2482
+
2483
+ if (url.pathname === '/files/download' && req.method === 'GET') {
2484
+ const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
2485
+ let stat = null;
2486
+ try { stat = fs.statSync(target); } catch { stat = null; }
2487
+ if (!stat || !stat.isFile()) {
2488
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
2489
+ res.end('文件不存在或不是普通文件\n');
2490
+ return;
2491
+ }
2492
+ const name = path.basename(target);
2493
+ const ascii = name.replace(/[^\x20-\x7E]/gu, '_').replace(/["\\]/gu, '_');
2494
+ appendAudit(dir, 'file-download', { path: target, bytes: stat.size });
2495
+ res.writeHead(200, {
2496
+ 'content-type': 'application/octet-stream',
2497
+ 'content-length': String(stat.size),
2498
+ 'content-disposition': `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`,
2499
+ 'cache-control': 'no-store',
2500
+ 'x-content-type-options': 'nosniff',
2501
+ });
2502
+ fs.createReadStream(target).pipe(res);
2503
+ return;
2504
+ }
2505
+
2405
2506
  if (url.pathname === '/files/view' && req.method === 'GET') {
2406
2507
  const info = filebrowse.readTextFile(url.searchParams.get('path') ?? '');
2407
2508
  appendAudit(dir, 'file-view', { path: info.path });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * 本机加密压缩(跨平台,不内置任何二进制)
3
+ *
4
+ * 设计:
5
+ * - 只调用机器上**已安装**的压缩工具,按可用性自动选择;
6
+ * - 支持 7-Zip / WinRAR / Info-ZIP zip,加密强度不同,页面上如实标注;
7
+ * - 插件目录不带二进制,避免平台绑定与体积膨胀;
8
+ * - 用户也可以把工具放进 <DSH_HOME>/integrations/dsh-homing/tools/,
9
+ * 或用 DSH_HOMING_ARCHIVER 指定。
10
+ */
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import { spawnSync } from 'node:child_process'
14
+
15
+ /** 工具候选:id → 可执行文件候选名 + 归档扩展名 + 加密说明 */
16
+ export const BACKENDS = [
17
+ {
18
+ id: '7z',
19
+ label: '7-Zip',
20
+ bins: ['7z', '7za', '7zr', '7zz'],
21
+ ext: '7z',
22
+ strength: 'AES-256(文件名也加密)',
23
+ level: 'strong',
24
+ },
25
+ {
26
+ id: 'rar',
27
+ label: 'WinRAR',
28
+ bins: ['rar'],
29
+ ext: 'rar',
30
+ strength: 'AES-256(文件名也加密)',
31
+ level: 'strong',
32
+ },
33
+ {
34
+ id: 'zip',
35
+ label: 'Info-ZIP',
36
+ bins: ['zip'],
37
+ ext: 'zip',
38
+ strength: 'ZipCrypto(较弱,仅兼容性用途)',
39
+ level: 'weak',
40
+ },
41
+ ]
42
+
43
+ const TOOL_DIRS = () => {
44
+ const home = process.env.DSH_HOME?.trim() || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.dsh')
45
+ return [
46
+ process.env.DSH_HOMING_TOOLS?.trim(),
47
+ path.join(home, 'integrations', 'dsh-homing', 'tools'),
48
+ ].filter(Boolean)
49
+ }
50
+
51
+ const which = (name) => {
52
+ const probe = spawnSync(name, ['--help'], { encoding: 'utf8', windowsHide: true, timeout: 8000 })
53
+ // 有的工具 --help 返回非 0,但只要能执行起来(不是 ENOENT)就算找到
54
+ return probe.error ? null : name
55
+ }
56
+
57
+ /** 在指定目录里找可执行文件(Windows 补 .exe) */
58
+ function findInDirs(dirs, name) {
59
+ const names = process.platform === 'win32' ? [`${name}.exe`, name] : [name]
60
+ for (const dir of dirs) {
61
+ for (const file of names) {
62
+ const full = path.join(dir, file)
63
+ try {
64
+ if (fs.statSync(full).isFile()) return full
65
+ } catch { /* 不存在 */ }
66
+ }
67
+ }
68
+ return null
69
+ }
70
+
71
+ /** 返回当前可用的后端列表(按优先级),每项含 bin 实际路径 */
72
+ export function availableBackends() {
73
+ const dirs = TOOL_DIRS()
74
+ const explicit = process.env.DSH_HOMING_ARCHIVER?.trim()
75
+ const found = []
76
+ for (const backend of BACKENDS) {
77
+ const fromExplicit = explicit && backend.bins.some((name) => explicit.toLowerCase().includes(name)) ? explicit : null
78
+ const binaries = []
79
+ if (fromExplicit) binaries.push(fromExplicit)
80
+ for (const name of backend.bins) {
81
+ const local = findInDirs(dirs, name)
82
+ if (local) binaries.push(local)
83
+ const onPath = which(name)
84
+ if (onPath) binaries.push(onPath)
85
+ }
86
+ const unique = [...new Set(binaries)]
87
+ if (unique.length === 0) continue
88
+ found.push({ ...backend, bin: unique[0] })
89
+ }
90
+ return found
91
+ }
92
+
93
+ /** 密码校验:太短起不到保护作用,太长没必要;返回错误文案或 null */
94
+ export function checkPassword(password) {
95
+ if (typeof password !== 'string' || password.length < 6) return '密码至少 6 位'
96
+ if (password.length > 128) return '密码最多 128 位'
97
+ return null
98
+ }
99
+
100
+ function nextArchivePath(dir, base, ext) {
101
+ let archive = path.join(dir, `${base}.${ext}`)
102
+ for (let i = 2; fs.existsSync(archive) && i < 100; i += 1) archive = path.join(dir, `${base}-${i}.${ext}`)
103
+ return archive
104
+ }
105
+
106
+ function run(bin, args, { cwd, timeoutMs }) {
107
+ return spawnSync(bin, args, { cwd, encoding: 'utf8', windowsHide: true, timeout: timeoutMs })
108
+ }
109
+
110
+ /**
111
+ * 把 target(文件或目录)压缩成加密归档,放在同级目录。
112
+ * 返回 { ok, path, bytes, tool, strength, error }
113
+ */
114
+ export function createEncryptedArchive({ target, password, timeoutMs = 10 * 60_000 }) {
115
+ const passwordError = checkPassword(password)
116
+ if (passwordError) return { ok: false, error: passwordError }
117
+ if (typeof target !== 'string' || target.trim() === '') return { ok: false, error: '路径为空' }
118
+ if (!fs.existsSync(target)) return { ok: false, error: '目标不存在' }
119
+
120
+ const backends = availableBackends()
121
+ if (backends.length === 0) {
122
+ return {
123
+ ok: false,
124
+ error: '本机没有可用的压缩工具:请安装 7-Zip / WinRAR / Info-ZIP,或把可执行文件放到 integrations/dsh-homing/tools/',
125
+ }
126
+ }
127
+
128
+ const abs = path.resolve(target)
129
+ const dir = path.dirname(abs)
130
+ const base = path.basename(abs)
131
+ const failures = []
132
+
133
+ for (const backend of backends) {
134
+ const archive = nextArchivePath(dir, base, backend.ext)
135
+ let result = null
136
+ if (backend.id === '7z') {
137
+ result = run(backend.bin, ['a', '-t7z', `-p${password}`, '-mhe=on', '-y', archive, base], { cwd: dir, timeoutMs })
138
+ } else if (backend.id === 'rar') {
139
+ result = run(backend.bin, ['a', `-p${password}`, `-hp${password}`, '-y', archive, base], { cwd: dir, timeoutMs })
140
+ } else if (backend.id === 'zip') {
141
+ result = run(backend.bin, ['-r', '-P', password, archive, base], { cwd: dir, timeoutMs })
142
+ }
143
+ if (result === null) continue
144
+
145
+ if (result.error || result.status !== 0 || !fs.existsSync(archive)) {
146
+ try { fs.rmSync(archive, { force: true }) } catch { /* 忽略 */ }
147
+ const detail = String(result.stderr || result.stdout || result.error?.message || '').split('\n').filter(Boolean).slice(-1).join(' ')
148
+ failures.push(`${backend.label}: ${detail || ('退出码 ' + result.status)}`)
149
+ continue
150
+ }
151
+
152
+ const stat = fs.statSync(archive)
153
+ return {
154
+ ok: true,
155
+ path: archive,
156
+ bytes: stat.size,
157
+ tool: backend.label,
158
+ strength: backend.strength,
159
+ level: backend.level,
160
+ }
161
+ }
162
+
163
+ return { ok: false, error: `压缩失败(${failures.join(';')})` }
164
+ }
@@ -117,6 +117,14 @@ const MENU_JS = `<script>
117
117
  location.href = '/files/run?path=' + encodeURIComponent(path);
118
118
  return;
119
119
  }
120
+ if (kind === 'download') {
121
+ location.href = '/files/download?path=' + encodeURIComponent(path);
122
+ return;
123
+ }
124
+ if (kind === 'compress') {
125
+ location.href = '/files/compress?path=' + encodeURIComponent(path);
126
+ return;
127
+ }
120
128
  if (kind === 'copy' || kind === 'cut') {
121
129
  try { localStorage.setItem('dsh-files-clip', JSON.stringify({ path: path, op: kind === 'cut' ? 'cut' : 'copy' })); } catch (error) { /* 忽略 */ }
122
130
  return;
@@ -217,6 +225,8 @@ export function renderListing({ info, message, isError, home, dataDir, workspace
217
225
  <button type="button" class="mm-btn" aria-haspopup="menu" title="更多操作">\u22ef</button>
218
226
  <span class="rowmenu" hidden role="menu">
219
227
  ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="edit" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u270F\uFE0F</span>编辑</a>`}
228
+ ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="download" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u2B07\uFE0F</span>下载</a>`}
229
+ <a class="mi" role="menuitem" data-act="compress" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F512}</span>加密压缩</a>
220
230
  ${entry.runnable ? `<a class="mi" role="menuitem" data-act="run" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u25B6\uFE0F</span>执行</a>` : ''}
221
231
  <a class="mi" role="menuitem" data-act="rename" data-path="${escapeHtml(entry.path)}" data-name="${escapeHtml(entry.name)}" href="#"><span class="ico">\u{1F3F7}\uFE0F</span>重命名</a>
222
232
  <a class="mi" role="menuitem" data-act="cut" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u2702\uFE0F</span>剪切</a>
@@ -314,7 +324,59 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
314
324
  return layout({ title: info.path, body })
315
325
  }
316
326
 
317
- /** 文件内容页 */
327
+ /** 加密压缩页:在电脑上生成加密归档,产物放在同级目录 */
328
+ export function renderCompressPage({ target, archive, message, isError, done = false, tools = [], tool = '', strength = '' }) {
329
+ const name = target.split(/[\\/]/u).pop() || target;
330
+ const dir = target.split(/[\\/]/u).slice(0, -1).join('/');
331
+ const toolsHtml = tools.length === 0
332
+ ? '<div class="msg err">本机没有可用的压缩工具:请安装 7-Zip / WinRAR / Info-ZIP,或把可执行文件放到 <code>~/.dsh/integrations/dsh-homing/tools/</code></div>'
333
+ : `<p style="margin:0 0 12px;color:#9aa3b2;font-size:13px">可用工具:${tools.map((item) => `${escapeHtml(item.label)}(${escapeHtml(item.strength)})`).join('、')}</p>`;
334
+ const body = `
335
+ <div class="bar">
336
+ <div style="display:flex;align-items:center;gap:8px;flex-wrap:nowrap;min-width:0">
337
+ <h1 style="margin:0;flex:0 0 auto;font-size:18px">加密压缩</h1>
338
+ <div style="flex:1 1 auto;display:flex;align-items:center;justify-content:flex-end;gap:4px;flex-wrap:nowrap;overflow-x:auto">
339
+ <a class="btn ghost" href="/files?path=${encodeURIComponent(dir)}" style="flex:0 0 auto;padding:4px 7px;border-radius:6px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:11px">返回目录</a>
340
+ </div>
341
+ </div>
342
+ </div>
343
+ ${messageHtml(message, isError)}
344
+ <div class="card" style="background:#20262f;border:1px solid #3a4351;border-radius:10px;padding:14px">
345
+ <p style="margin:0 0 10px;color:#9aa3b2;font-size:13px;line-height:1.6">
346
+ 在<b>这台电脑上</b>把目标压缩成加密归档,产物放在同级目录。<br>
347
+ 目标:<code style="color:#dce9f7">${escapeHtml(target)}</code>
348
+ ${done ? `<br>产物:<code style="color:#dce9f7">${escapeHtml(archive)}</code>` : ''}
349
+ </p>
350
+ ${toolsHtml}
351
+ ${done ? `
352
+ <p style="margin:0 0 12px;color:#9aa3b2;font-size:13px">使用工具:${escapeHtml(tool)} · ${escapeHtml(strength)}</p>
353
+ <div style="display:flex;gap:8px;flex-wrap:wrap">
354
+ <a class="btn" href="/files/download?path=${encodeURIComponent(archive)}" style="padding:8px 14px;border-radius:8px;background:#2f4a68;color:#dce9f7;text-decoration:none;font-size:13px">下载压缩包</a>
355
+ <a class="btn ghost" href="/files?path=${encodeURIComponent(dir)}" style="padding:8px 14px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:13px">返回目录</a>
356
+ </div>
357
+ ` : `
358
+ <form method="post" action="/files/compress" style="display:flex;flex-direction:column;gap:10px;max-width:420px">
359
+ <input type="hidden" name="path" value="${escapeHtml(target)}">
360
+ <label style="font-size:13px;color:#9aa3b2">密码(至少 6 位,不保存、忘记无法恢复)</label>
361
+ <input type="password" name="password" required minlength="6" maxlength="128" autocomplete="new-password"
362
+ style="padding:10px 12px;border-radius:8px;border:1px solid #3a4351;background:#161a20;color:#e6e8ee;font-size:15px">
363
+ <label style="font-size:13px;color:#9aa3b2">再输一次</label>
364
+ <input type="password" name="confirm" required minlength="6" maxlength="128" autocomplete="new-password"
365
+ style="padding:10px 12px;border-radius:8px;border:1px solid #3a4351;background:#161a20;color:#e6e8ee;font-size:15px">
366
+ <button type="submit" style="margin-top:4px;padding:10px 14px;border-radius:8px;border:1px solid #3f5f84;background:#2f4a68;color:#dce9f7;font-size:14px">开始压缩</button>
367
+ </form>
368
+ <p style="margin:14px 0 0;color:#6b7280;font-size:12px;line-height:1.6">
369
+ 文件:${escapeHtml(name)}<br>
370
+ 7-Zip / WinRAR 为 AES-256(强);Info-ZIP 为 ZipCrypto(弱,仅兼容用途)。<br>
371
+ Windows 自带解压不支持密码,需用 7-Zip / WinRAR / Bandizip。
372
+ </p>
373
+ `}
374
+ </div>`;
375
+
376
+ return layout({ title: '加密压缩 · ' + name, body })
377
+ }
378
+
379
+ /** 文件内容页 *//** 文件内容页 */
318
380
  export function renderFile({ info, message, isError }) {
319
381
  const body = `
320
382
  <div class="bar">
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,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 启动 Git Bash(client.shell() 会落到系统默认的 cmd.exe)
211
- const command = '"C:/Program Files/Git/bin/bash.exe" -l'
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 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('\\', '/'))
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('cd "' + target.replaceAll('"', '\\"') + '"\r')
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>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.1.2",
3
+ "version": "2.1.4",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [