@andy.ian/dsh-homing 2.0.1 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/watchdog.mjs CHANGED
@@ -1,163 +1,144 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * 看门狗 / 重启脚本的安装器。
3
+ * 守护进程的安装 / 状态 / 卸载命令(纯 Node,无 PowerShell、无计划任务)。
4
4
  *
5
- * 为什么需要它:
6
- * 重启脚本必须跑在 DSH 之外(它要杀掉承载插件的进程),所以不能由插件自己在运行时执行。
7
- * 换电脑后,插件包装好了,但 ~/.dsh/watchdog 下的脚本和计划任务都不会自动跟过来。
8
- * 这个命令把这件事变成一条:
9
- *
10
- * dsh-homing-watchdog install # 装脚本 + 注册看门狗计划任务
11
- * dsh-homing-watchdog status # 看状态(等价 restart-now.ps1 -Check)
12
- * dsh-homing-watchdog remove # 卸载计划任务(保留脚本)
13
- * dsh-homing-watchdog restart # 立刻重启 DSH(默认等空闲)
14
- * dsh-homing-watchdog restart --immediate # 一空闲就重启
15
- *
16
- * 只支持 Windows(脚本是 PowerShell + 计划任务)。
5
+ * 守护逻辑在 bin/supervisor.mjs:常驻、监视 DSH、崩溃自动拉起、升级期间等待。
6
+ * 本命令只负责入口管理:
7
+ * install 写入「登录时启动守护进程」(Win 启动文件夹 / macOS LaunchAgent / Linux systemd user unit)
8
+ * status 向守护进程控制接口取状态
9
+ * remove 删除启动项
10
+ * restart 请求重启(默认等空闲,--immediate 立即)
11
+ * stop 让守护进程退出(不再拉起 DSH)
17
12
  */
18
13
  import fs from 'node:fs'
19
14
  import path from 'node:path'
20
- import { spawnSync } from 'node:child_process'
15
+ import os from 'node:os'
16
+ import http from 'node:http'
21
17
  import { fileURLToPath } from 'node:url'
22
18
 
23
19
  const here = path.dirname(fileURLToPath(import.meta.url))
24
20
  const pkgRoot = path.resolve(here, '..')
25
- const sourceDir = path.join(pkgRoot, 'ops', 'watchdog')
26
- const dshHome = process.env.DSH_HOME ?? path.join(process.env.USERPROFILE ?? '', '.dsh')
27
- const targetDir = path.join(dshHome, 'watchdog')
21
+ const supervisor = path.join(pkgRoot, 'bin', 'supervisor.mjs')
22
+ const controlPort = Number(process.env.DSH_HOMING_CONTROL ?? 8790)
28
23
 
29
- const TASK_WATCHDOG = 'DSH-Watchdog'
30
- const TASK_RESTART = 'DSH-Restart-Now'
31
- const EXE = 'powershell.exe'
32
- const NODE = process.execPath
24
+ const has = (name) => process.argv.includes('--' + name)
25
+ const [command] = process.argv.slice(2)
33
26
 
34
- const run = (args, opts = {}) => spawnSync(EXE, args, { encoding: 'utf8', windowsHide: true, ...opts })
35
- const ps = (script) => run(['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', script])
36
- const psFile = (file, extra = []) => {
37
- // 中文 Windows 的 PowerShell 默认按 GBK 输出,Node 按 utf8 读会乱码;
38
- // 这里先设 [Console]::OutputEncoding 再执行脚本,保证能读懂结果。
39
- const quoted = "'" + file.replaceAll("'", "''") + "'"
40
- // 开关参数必须原样传(加引号会变成位置参数,被 ValidateSet 拒绝)
41
- const args = extra.join(' ')
42
- return run(['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
43
- `[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; & ${quoted} ${args}`])
27
+ function call(pathname, method = 'POST') {
28
+ return new Promise((resolve, reject) => {
29
+ const req = http.request({ host: '127.0.0.1', port: controlPort, path: pathname, method, timeout: 8000 }, (res) => {
30
+ const chunks = []
31
+ res.on('data', (chunk) => chunks.push(chunk))
32
+ res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString('utf8') }))
33
+ })
34
+ req.on('timeout', () => { req.destroy(); reject(new Error('timeout')) })
35
+ req.on('error', reject)
36
+ req.end()
37
+ })
44
38
  }
45
39
 
46
- function requireWindows() {
47
- if (process.platform !== 'win32') {
48
- console.error('这个命令只支持 Windows(用 PowerShell + 计划任务实现)。')
49
- process.exit(1)
40
+ function startupPath() {
41
+ if (process.platform === 'win32') {
42
+ return path.join(process.env.APPDATA ?? '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'dsh-homing-supervisor.vbs')
43
+ }
44
+ if (process.platform === 'darwin') {
45
+ return path.join(os.homedir(), 'Library', 'LaunchAgents', 'online.gitsrc.dsh-homing.plist')
50
46
  }
47
+ return path.join(os.homedir(), '.config', 'systemd', 'user', 'dsh-homing-supervisor.service')
51
48
  }
52
49
 
53
50
  function install() {
54
- requireWindows()
55
- if (!fs.existsSync(sourceDir)) {
56
- console.error(`找不到脚本目录:${sourceDir}`)
57
- process.exit(1)
58
- }
59
- fs.mkdirSync(targetDir, { recursive: true })
60
- for (const name of fs.readdirSync(sourceDir)) {
61
- if (!name.endsWith('.ps1')) continue
62
- fs.copyFileSync(path.join(sourceDir, name), path.join(targetDir, name))
63
- console.log(` ✓ 已复制 ${name}`)
64
- }
51
+ const file = startupPath()
52
+ fs.mkdirSync(path.dirname(file), { recursive: true })
53
+ if (process.platform === 'win32') {
54
+ // 用 wscript 启动,登录时才不会闪控制台窗口
55
+ const vbs = `' 由 dsh-homing 生成:登录时以隐藏窗口启动守护进程\r\nSet sh = CreateObject("WScript.Shell")\r\nsh.Run """${process.execPath}"" ""${supervisor}"" --detach", 0, False\r\n`
56
+ fs.writeFileSync(file, vbs, 'ascii')
57
+ } else if (process.platform === 'darwin') {
58
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
59
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
60
+ <plist version="1.0"><dict>
61
+ <key>Label</key><string>online.gitsrc.dsh-homing</string>
62
+ <key>ProgramArguments</key><array><string>${process.execPath}</string><string>${supervisor}</string><string>--detach</string></array>
63
+ <key>RunAtLoad</key><true/>
64
+ </dict></plist>
65
+ `
66
+ fs.writeFileSync(file, xml, 'utf8')
67
+ } else {
68
+ const text = `[Unit]
69
+ Description=DSH Homing supervisor
65
70
 
66
- const watchdog = path.join(targetDir, 'dsh-watchdog.ps1')
67
- const register = `
68
- $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "${watchdog}"'
69
- $trigger1 = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(2) -RepetitionInterval (New-TimeSpan -Minutes 5)
70
- $trigger2 = New-ScheduledTaskTrigger -AtLogOn
71
- $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 10)
72
- $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\\$env:USERNAME" -LogonType Interactive -RunLevel Limited
73
- Register-ScheduledTask -TaskName '${TASK_WATCHDOG}' -Action $action -Trigger $trigger1,$trigger2 -Settings $settings -Principal $principal -Force | Out-Null
74
- Write-Output 'registered'
75
- `
76
- const registered = ps(register)
77
- if (!String(registered.stdout).includes('registered')) {
78
- console.error('注册看门狗计划任务失败:' + (registered.stderr || registered.stdout || '').slice(0, 400))
79
- process.exit(1)
71
+ [Service]
72
+ ExecStart=${process.execPath} ${supervisor} --detach
73
+
74
+ [Install]
75
+ WantedBy=default.target
76
+ `
77
+ fs.writeFileSync(file, text, 'utf8')
80
78
  }
81
- console.log(` ✓ 已注册计划任务 ${TASK_WATCHDOG}(每 5 分钟体检)`)
82
- console.log('\n装好了。常用命令:')
83
- console.log(' dsh-homing-watchdog status 查看状态与能否重启')
84
- console.log(' dsh-homing-watchdog restart 重启 DSH(等空闲)')
85
- console.log(' dsh-homing-watchdog restart --immediate 一空闲就重启')
79
+ console.log(` ✓ 已写入启动项:${file}`)
80
+ if (process.platform === 'linux') console.log(' 启用:systemctl --user enable --now dsh-homing-supervisor')
81
+ console.log('\n常用命令:')
82
+ console.log(' dsh-homing-watchdog status')
83
+ console.log(' dsh-homing-watchdog restart [--immediate]')
84
+ console.log(' dsh-homing-watchdog stop')
86
85
  }
87
86
 
88
- function status() {
89
- requireWindows()
90
- const restart = path.join(targetDir, 'restart-now.ps1')
91
- if (!fs.existsSync(restart)) {
92
- console.error('还没安装:先跑 dsh-homing-watchdog install')
93
- process.exit(1)
94
- }
95
- const result = psFile(restart, ['-Check'])
96
- const text = String(result.stdout || '').replace(/^\uFEFF/u, '')
97
- if (text.trim() === '') {
98
- console.error('读取状态失败:' + (result.stderr || '').slice(0, 300))
87
+ async function status() {
88
+ try {
89
+ const res = await call('/status', 'GET')
90
+ console.log(res.body.trim())
91
+ } catch {
92
+ console.error('守护进程没在运行(控制端口连不上)。先 dsh-homing-watchdog install,或手动运行 supervisor.mjs --detach。')
99
93
  process.exit(1)
100
94
  }
101
- console.log(text.trim())
102
95
  }
103
96
 
104
97
  function remove() {
105
- requireWindows()
106
- const result = ps(`Unregister-ScheduledTask -TaskName '${TASK_WATCHDOG}' -Confirm:$false -ErrorAction SilentlyContinue; Unregister-ScheduledTask -TaskName '${TASK_RESTART}' -Confirm:$false -ErrorAction SilentlyContinue; Write-Output 'removed'`)
107
- if (String(result.stdout).includes('removed')) {
108
- console.log(` ✓ 已卸载计划任务(脚本仍保留在 ${targetDir})`)
98
+ const file = startupPath()
99
+ if (fs.existsSync(file)) {
100
+ fs.rmSync(file, { force: true })
101
+ console.log(` ✓ 已删除启动项:${file}`)
109
102
  } else {
110
- console.error('卸载失败:' + (result.stderr || '').slice(0, 300))
111
- process.exit(1)
103
+ console.log(' 启动项不存在')
112
104
  }
113
105
  }
114
106
 
115
- function restart({ immediate }) {
116
- requireWindows()
107
+ async function restart(immediate) {
117
108
  const mode = immediate ? 'immediate' : 'default'
118
- // 优先走常驻守护进程(无闪窗、事件驱动);它不在时退回旧计划任务
119
- const request = spawnSync(NODE, [path.join(pkgRoot, 'bin', 'supervisor.mjs'), '--restart', ...(immediate ? ['--immediate'] : [])], {
120
- encoding: 'utf8', windowsHide: true,
121
- })
122
- if (request.status === 0) {
123
- console.log(String(request.stdout).trim() || `已请求守护进程重启(模式 ${mode})`)
124
- return
125
- }
126
- // 守护进程不在:退回计划任务(仍然可用,但会有闪窗)
127
- const script = path.join(targetDir, 'restart-now.ps1')
128
- if (!fs.existsSync(script)) {
129
- console.error('守护进程没有运行,且找不到 restart-now.ps1。先启动守护进程:dsh-homing-supervisor --detach')
109
+ try {
110
+ const res = await call(`/restart?mode=${mode}`)
111
+ console.log(res.status === 202 ? ` 已请求重启(模式 ${mode})` : ` 请求被拒绝(HTTP ${res.status})`)
112
+ } catch {
113
+ console.error('守护进程没在运行。先 install 或手动启动 supervisor.mjs --detach。')
130
114
  process.exit(1)
131
115
  }
132
- console.warn('守护进程未运行,退回计划任务方式(可能闪窗)')
133
- const cmd = `
134
- $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "${script}" -Mode ${mode} -Reason "命令行请求"'
135
- $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(5)
136
- $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -MultipleInstances IgnoreNew -ExecutionTimeLimit (New-TimeSpan -Minutes 30)
137
- $principal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\\$env:USERNAME" -LogonType Interactive -RunLevel Limited
138
- Register-ScheduledTask -TaskName 'DSH-Restart-Now' -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null
139
- Write-Output 'queued'
140
- `
141
- const result = ps(cmd)
142
- if (String(result.stdout).includes('queued')) console.log(`已排队(模式 ${mode})`)
143
- else { console.error('排队失败:' + (result.stderr || '').slice(0, 300)); process.exit(1) }
144
116
  }
145
117
 
146
- const [command, ...rest] = process.argv.slice(2)
147
- const has = (flag) => rest.includes(flag)
118
+ async function stop() {
119
+ try {
120
+ await call('/stop')
121
+ console.log(' 守护进程已退出(不会自动拉起 DSH)')
122
+ } catch {
123
+ console.error('守护进程没在运行')
124
+ process.exit(1)
125
+ }
126
+ }
148
127
 
149
128
  switch (command) {
150
129
  case 'install': install(); break
151
- case 'status': status(); break
130
+ case 'status': await status(); break
152
131
  case 'remove': remove(); break
153
- case 'restart': restart({ immediate: has('--immediate') || has('-i') }); break
132
+ case 'restart': await restart(has('--immediate') || has('-i')); break
133
+ case 'stop': await stop(); break
154
134
  default:
155
- console.log(`用法: dsh-homing-watchdog <install|status|remove|restart> [--immediate]
135
+ console.log(`用法: dsh-homing-watchdog <install|status|remove|restart|stop> [--immediate]
156
136
 
157
- install 安装/更新重启脚本与看门狗计划任务(换电脑后跑这个)
158
- status 查看进程、端口、会话活动与能否重启
159
- remove 卸载计划任务(保留脚本文件)
160
- restart 重启 DSH;默认等会话空闲,加 --immediate 则一空闲就重启
137
+ install 写入登录自启(Windows 启动项 / macOS LaunchAgent / Linux systemd user unit)
138
+ status 向守护进程查询状态
139
+ remove 删除登录自启
140
+ restart 请求重启 DSH(默认等空闲,--immediate 立即)
141
+ stop 让守护进程退出(不再拉起 DSH)
161
142
  `)
162
143
  process.exit(command === undefined ? 0 : 1)
163
144
  }
package/index.js CHANGED
@@ -23,12 +23,9 @@ import zlib from 'node:zlib';
23
23
  import * as deviceStore from './lib/devices.mjs';
24
24
  import * as filebrowse from './lib/files.mjs';
25
25
  import * as gitrun from './lib/git.mjs';
26
- import * as shellrun from './lib/shell.mjs';
27
- import { sharedSession, resetSharedSession } from './lib/session.mjs';
28
26
  import * as ptyrun from './lib/pty.mjs';
29
27
  import { renderTermPage } from './lib/term-page.mjs';
30
- import { renderShellPage as renderTerminalPage } from './lib/shell-page.mjs';
31
- import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderShellPage } from './lib/files-page.mjs';
28
+ import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage } from './lib/files-page.mjs';
32
29
  import { checkUnsafeOrigin } from './lib/csrf.mjs';
33
30
  import * as limits from './lib/limits.mjs';
34
31
 
@@ -1294,7 +1291,6 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1294
1291
  || url.pathname.startsWith('/dsh_homing/')
1295
1292
  || url.pathname === '/files' || url.pathname.startsWith('/files/')
1296
1293
  || url.pathname === '/git' || url.pathname.startsWith('/git/')
1297
- || url.pathname === '/shell' || url.pathname.startsWith('/shell/')
1298
1294
  || url.pathname === '/term' || url.pathname.startsWith('/term/')
1299
1295
  || url.pathname === '/debug' || url.pathname.startsWith('/debug/');
1300
1296
  appendAudit(dir, 'origin-check', {
@@ -1714,157 +1710,6 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1714
1710
  }
1715
1711
 
1716
1712
  // 终端:执行任意 shell 命令(手机端的 Git Bash)。需要登录。
1717
- if (url.pathname === '/shell' || url.pathname === '/shell/complete' || url.pathname === '/shell/run') {
1718
- if (!sessionValid(req) && currentDevice(req) === null) {
1719
- res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
1720
- res.end();
1721
- return;
1722
- }
1723
- const sendShell = (pageHtml) => {
1724
- res.writeHead(200, {
1725
- 'content-type': 'text/html; charset=utf-8',
1726
- 'cache-control': 'no-store',
1727
- 'x-frame-options': 'DENY',
1728
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'",
1729
- 'x-content-type-options': 'nosniff',
1730
- 'referrer-policy': 'no-referrer',
1731
- });
1732
- res.end(pageHtml);
1733
- };
1734
- const dshHomeShell = path.resolve(dir, '..', '..');
1735
- const wsIndex = filebrowse.workspaceIndex(dshHomeShell);
1736
- const shellName = shellrun.findBash() === null ? 'cmd.exe' : 'bash';
1737
-
1738
- if (url.pathname === '/shell/complete') {
1739
- const cwdParam = url.searchParams.get('cwd') ?? filebrowse.HOME;
1740
- const line = url.searchParams.get('line') ?? '';
1741
- const items = shellrun.completeCandidates(cwdParam, line);
1742
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1743
- res.end(JSON.stringify(items));
1744
- return;
1745
- }
1746
-
1747
- // 终端页用:执行命令并返回 JSON(页面不刷新)
1748
- if (url.pathname === '/shell/run' && req.method === 'POST') {
1749
- let payload = {};
1750
- try {
1751
- payload = JSON.parse(await readBody(req, 64 * 1024));
1752
- } catch {
1753
- payload = {};
1754
- }
1755
- const commandText = String(payload.command ?? '');
1756
- const baseCwd = String(payload.cwd ?? wsIndex.defaultPath ?? filebrowse.HOME);
1757
- const terminal = sharedSession(baseCwd);
1758
- const sendJson = (data) => {
1759
- res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1760
- res.end(JSON.stringify(data));
1761
- };
1762
- if (payload.reset === true) {
1763
- resetSharedSession();
1764
- appendAudit(dir, 'shell-reset', {});
1765
- sendJson({ ok: true, code: 0, output: '会话已重置', cwd: terminal.info().cwd });
1766
- return;
1767
- }
1768
- // Ctrl+C:中断当前命令(杀掉 bash 及子进程树后重启)
1769
- if (payload.interrupt === true) {
1770
- appendAudit(dir, 'shell-interrupt', {});
1771
- const stopped = terminal.interrupt();
1772
- sendJson({
1773
- ok: true,
1774
- code: null,
1775
- interrupted: true,
1776
- output: stopped.output,
1777
- cwd: terminal.info().cwd,
1778
- branch: '',
1779
- });
1780
- return;
1781
- }
1782
- appendAudit(dir, 'shell-run', { cwd: baseCwd, command: commandText });
1783
- const result = await terminal.run(commandText);
1784
- terminal.record({
1785
- command: commandText,
1786
- output: String(result.output ?? ''),
1787
- code: result.code ?? null,
1788
- ok: result.ok !== false,
1789
- timeout: result.timeout === true,
1790
- cwd: result.cwd ?? baseCwd,
1791
- });
1792
- const afterBranch = gitrun.isRepo(terminal.info().cwd)
1793
- ? await gitrun.runGit(terminal.info().cwd, ['branch', '--show-current'])
1794
- : null;
1795
- sendJson({
1796
- ok: result.ok !== false,
1797
- code: result.code ?? null,
1798
- output: result.output ?? '',
1799
- cwd: terminal.info().cwd,
1800
- branch: afterBranch !== null && afterBranch.ok ? afterBranch.output.trim() : '',
1801
- timeout: result.timeout === true,
1802
- });
1803
- return;
1804
- }
1805
-
1806
- // 简易终端已下线:GET 一律跳到真终端 /term(保留 POST 接口兼容旧页面)
1807
- if (req.method === 'GET') {
1808
- const query = url.searchParams.toString();
1809
- res.writeHead(303, { location: '/term' + (query === '' ? '' : '?' + query), 'cache-control': 'no-store' });
1810
- res.end();
1811
- return;
1812
- }
1813
-
1814
-
1815
- if (req.method === 'POST') {
1816
- const form = new URLSearchParams(await readBody(req, 64 * 1024));
1817
- let cwd = form.get('cwd') ?? filebrowse.HOME;
1818
- const command = form.get('command') ?? '';
1819
- if (form.get('action') === 'reset') {
1820
- resetSharedSession();
1821
- appendAudit(dir, 'shell-reset', {});
1822
- const fresh = sharedSession(cwd);
1823
- sendShell(renderShellPage({
1824
- cwd: fresh.info().cwd,
1825
- shellName: 'bash · 常驻会话(已重置)',
1826
- result: { ok: true, code: 0, output: '会话已重置:环境变量清空,当前目录保持' },
1827
- }));
1828
- return;
1829
- }
1830
- // 支持 cd:只改工作目录,不真的执行
1831
- const nextCwd = shellrun.parseCd(command, cwd);
1832
- if (nextCwd !== null) {
1833
- const exists = (() => {
1834
- try {
1835
- return fs.statSync(nextCwd).isDirectory();
1836
- } catch {
1837
- return false;
1838
- }
1839
- })();
1840
- sendShell(renderShellPage({
1841
- cwd: exists ? nextCwd : cwd,
1842
- command: '',
1843
- shellName,
1844
- result: { ok: exists, code: exists ? 0 : 1, output: exists ? nextCwd : '目录不存在:' + nextCwd },
1845
- }));
1846
- return;
1847
- }
1848
- appendAudit(dir, 'shell-run', { cwd, command });
1849
- // 常驻会话:cd / export / 函数定义都跨命令保留
1850
- const session = sharedSession(cwd);
1851
- if (cwd !== session.info().cwd) {
1852
- await session.run('cd "' + String(cwd).replaceAll('"', '""') + '"');
1853
- }
1854
- const result = await session.run(command);
1855
- const info = session.info();
1856
- sendShell(renderShellPage({
1857
- cwd: info.cwd,
1858
- command,
1859
- result,
1860
- shellName: info.running ? 'bash · 常驻会话' : 'bash · 会话已重启',
1861
- history: [command],
1862
- }));
1863
- return;
1864
- }
1865
- }
1866
-
1867
- // git 页:跑任意 git 子命令(不经过 shell),需要登录
1868
1713
  if (url.pathname === '/git' || url.pathname === '/git/run') {
1869
1714
  if (!sessionValid(req) && currentDevice(req) === null) {
1870
1715
  res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
@@ -1928,7 +1773,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1928
1773
  }
1929
1774
 
1930
1775
  if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/run'
1931
- || url.pathname === '/files/ask' || url.pathname === '/files/rename'
1776
+ || url.pathname === '/files/rename'
1932
1777
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
1933
1778
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
1934
1779
  if (!sessionValid(req) && currentDevice(req) === null) {
@@ -1987,70 +1832,6 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1987
1832
  return;
1988
1833
  }
1989
1834
 
1990
- if (url.pathname === '/files/ask' && req.method === 'GET') {
1991
- const target = url.searchParams.get('path') ?? '';
1992
- const name = path.basename(target);
1993
- const dir = path.dirname(target);
1994
- const esc = (v) => String(v).replace(/[&<>"]/gu, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
1995
- sendHtml(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
1996
- <meta name="viewport" content="width=device-width,initial-scale=1">
1997
- <title>操作</title><style>
1998
- body{background:#12161d;color:#dbe2ea;font:15px/1.5 system-ui;margin:0;padding:16px}
1999
- h1{font-size:18px;margin:0 0 12px}
2000
- .card{background:#1a1f27;border:1px solid #2b3340;border-radius:10px;padding:14px;margin-bottom:12px}
2001
- input{width:100%;box-sizing:border-box;padding:11px;border-radius:8px;border:1px solid #39424f;background:#0f1319;color:#e6edf5;font-size:15px}
2002
- button{width:100%;margin-top:10px;padding:12px;border-radius:8px;border:0;background:#4f7cff;color:#fff;font-size:15px;font-weight:600}
2003
- a.btn{display:block;padding:11px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;text-align:center;margin-top:8px}
2004
- .path{color:#8b93a1;font-size:12px;word-break:break-all;margin-bottom:8px}
2005
- </style></head><body>
2006
- <h1>⋯ 操作</h1>
2007
- <div class="card"><div class="path">${esc(target)}</div>
2008
- <form method="post" action="/files/rename">
2009
- <input type="hidden" name="path" value="${esc(target)}">
2010
- <input type="text" name="name" value="${esc(name)}" autofocus>
2011
- <button type="submit">重命名</button>
2012
- </form></div>
2013
- <a class="btn" href="/files?path=${encodeURIComponent(dir)}">返回所在目录</a>
2014
- <a class="btn" href="/files/view?path=${encodeURIComponent(target)}">查看内容</a>
2015
- <a class="btn" href="/">返回 DSH</a>
2016
- </body></html>`);
2017
- return;
2018
- }
2019
-
2020
- if ((url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') && req.method === 'POST') {
2021
- const form = new URLSearchParams(await readBody(req, 64 * 1024));
2022
- const targetDir = form.get('dir') ?? '';
2023
- const name = form.get('name') ?? '';
2024
- const isDir = url.pathname === '/files/mkdir';
2025
- const result = filebrowse.createEntry(targetDir, name, isDir);
2026
- appendAudit(dir, isDir ? 'file-mkdir' : 'file-newfile', { dir: targetDir, name, ok: result.ok, error: result.error ?? null });
2027
- res.writeHead(303, { location: '/files?path=' + encodeURIComponent(targetDir), 'cache-control': 'no-store' });
2028
- res.end();
2029
- return;
2030
- }
2031
-
2032
- if (url.pathname === '/files/paste' && req.method === 'POST') {
2033
- const form = new URLSearchParams(await readBody(req, 64 * 1024));
2034
- const src = form.get('src') ?? '';
2035
- const dir = form.get('dir') ?? '';
2036
- const op = form.get('op') === 'cut' ? 'cut' : 'copy';
2037
- const result = op === 'cut' ? filebrowse.moveInto(src, dir) : filebrowse.copyInto(src, dir);
2038
- appendAudit(dir, op === 'cut' ? 'file-move' : 'file-paste', { src, dir, ok: result.ok, target: result.path ?? null, error: result.error ?? null });
2039
- res.writeHead(303, { location: '/files?path=' + encodeURIComponent(dir), 'cache-control': 'no-store' });
2040
- res.end();
2041
- return;
2042
- }
2043
-
2044
- if (url.pathname === '/files/delete' && req.method === 'POST') {
2045
- const form = new URLSearchParams(await readBody(req, 64 * 1024));
2046
- const target = form.get('path') ?? '';
2047
- const result = filebrowse.deleteEntry(target);
2048
- appendAudit(dir, 'file-delete', { target, ok: result.ok, error: result.error ?? null });
2049
- res.writeHead(303, { location: '/files?path=' + encodeURIComponent(path.dirname(target)), 'cache-control': 'no-store' });
2050
- res.end();
2051
- return;
2052
- }
2053
-
2054
1835
  if (url.pathname === '/files/rename' && req.method === 'POST') {
2055
1836
  const form = new URLSearchParams(await readBody(req, 64 * 1024));
2056
1837
  const target = form.get('path') ?? '';