@andy.ian/dsh-homing 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.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
 
@@ -1040,7 +1037,7 @@ function sendLogin(res, message = '', requireTotp = false) {
1040
1037
  'cache-control': 'no-store',
1041
1038
  // 登录页的安全头:禁止被嵌入(防点击劫持)、禁止外链、限制表单只能提交给自己
1042
1039
  'x-frame-options': 'DENY',
1043
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1040
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1044
1041
  'x-content-type-options': 'nosniff',
1045
1042
  'referrer-policy': 'no-referrer',
1046
1043
  });
@@ -1279,6 +1276,35 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1279
1276
  const touchActivity = createActivityRecorder(dir);
1280
1277
 
1281
1278
  const handler = async (req, res) => {
1279
+ // 每个响应生成一次性 nonce:内联脚本必须带 nonce 才能执行,
1280
+ // 攻击者注入的脚本没有 nonce,即使 HTML 转义出漏洞也跑不起来。
1281
+ const nonce = crypto.randomBytes(16).toString('base64url');
1282
+ let responseType = '';
1283
+ const rawWriteHead = res.writeHead.bind(res);
1284
+ res.writeHead = (status, headers, ...rest) => {
1285
+ if (headers && typeof headers === 'object' && typeof headers['content-type'] === 'string') {
1286
+ responseType = headers['content-type'];
1287
+ }
1288
+ if (headers && typeof headers === 'object' && typeof headers['content-security-policy'] === 'string') {
1289
+ headers = {
1290
+ ...headers,
1291
+ 'content-security-policy': headers['content-security-policy'].replace(
1292
+ "script-src 'self'",
1293
+ `script-src 'self' 'nonce-${nonce}'`,
1294
+ ),
1295
+ };
1296
+ }
1297
+ return rawWriteHead(status, headers, ...rest);
1298
+ };
1299
+ const rawEnd = res.end.bind(res);
1300
+ res.end = (body, ...rest) => {
1301
+ const type = responseType || String(res.getHeader('content-type') ?? '');
1302
+ if (typeof body === 'string' && type.includes('text/html')) {
1303
+ body = body.replaceAll('<script', `<script nonce="${nonce}"`);
1304
+ }
1305
+ return rawEnd(body, ...rest);
1306
+ };
1307
+
1282
1308
 
1283
1309
  const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
1284
1310
  // 任何来自浏览器的请求都算"人在用"(静态资源除外,避免预加载把空闲判断拖长)
@@ -1294,7 +1320,6 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1294
1320
  || url.pathname.startsWith('/dsh_homing/')
1295
1321
  || url.pathname === '/files' || url.pathname.startsWith('/files/')
1296
1322
  || url.pathname === '/git' || url.pathname.startsWith('/git/')
1297
- || url.pathname === '/shell' || url.pathname.startsWith('/shell/')
1298
1323
  || url.pathname === '/term' || url.pathname.startsWith('/term/')
1299
1324
  || url.pathname === '/debug' || url.pathname.startsWith('/debug/');
1300
1325
  appendAudit(dir, 'origin-check', {
@@ -1425,7 +1450,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1425
1450
  'content-type': 'text/html; charset=utf-8',
1426
1451
  'cache-control': 'no-store',
1427
1452
  'x-frame-options': 'DENY',
1428
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1453
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1429
1454
  'x-content-type-options': 'nosniff',
1430
1455
  'referrer-policy': 'no-referrer',
1431
1456
  });
@@ -1449,7 +1474,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1449
1474
  'content-type': 'text/html; charset=utf-8',
1450
1475
  'cache-control': 'no-store',
1451
1476
  'x-frame-options': 'DENY',
1452
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1477
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1453
1478
  'x-content-type-options': 'nosniff',
1454
1479
  'referrer-policy': 'no-referrer',
1455
1480
  });
@@ -1714,157 +1739,6 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1714
1739
  }
1715
1740
 
1716
1741
  // 终端:执行任意 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
1742
  if (url.pathname === '/git' || url.pathname === '/git/run') {
1869
1743
  if (!sessionValid(req) && currentDevice(req) === null) {
1870
1744
  res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
@@ -1876,7 +1750,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1876
1750
  'content-type': 'text/html; charset=utf-8',
1877
1751
  'cache-control': 'no-store',
1878
1752
  'x-frame-options': 'DENY',
1879
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1753
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1880
1754
  'x-content-type-options': 'nosniff',
1881
1755
  'referrer-policy': 'no-referrer',
1882
1756
  });
@@ -1928,7 +1802,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1928
1802
  }
1929
1803
 
1930
1804
  if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/run'
1931
- || url.pathname === '/files/ask' || url.pathname === '/files/rename'
1805
+ || url.pathname === '/files/rename'
1932
1806
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
1933
1807
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
1934
1808
  if (!sessionValid(req) && currentDevice(req) === null) {
@@ -1941,7 +1815,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1941
1815
  'content-type': 'text/html; charset=utf-8',
1942
1816
  'cache-control': 'no-store',
1943
1817
  'x-frame-options': 'DENY',
1944
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1818
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1945
1819
  'x-content-type-options': 'nosniff',
1946
1820
  'referrer-policy': 'no-referrer',
1947
1821
  });
@@ -1987,44 +1861,12 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1987
1861
  return;
1988
1862
  }
1989
1863
 
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') {
1864
+ if (url.pathname === '/files/delete' && req.method === 'POST') {
2021
1865
  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' });
1866
+ const target = form.get('path') ?? '';
1867
+ const result = filebrowse.deleteEntry(target);
1868
+ appendAudit(dir, 'file-delete', { target, ok: result.ok, error: result.error ?? null });
1869
+ res.writeHead(303, { location: '/files?path=' + encodeURIComponent(path.dirname(target)), 'cache-control': 'no-store' });
2028
1870
  res.end();
2029
1871
  return;
2030
1872
  }
@@ -2032,21 +1874,23 @@ a.btn{display:block;padding:11px;border-radius:8px;background:#2a2f3a;color:#c7c
2032
1874
  if (url.pathname === '/files/paste' && req.method === 'POST') {
2033
1875
  const form = new URLSearchParams(await readBody(req, 64 * 1024));
2034
1876
  const src = form.get('src') ?? '';
2035
- const dir = form.get('dir') ?? '';
1877
+ const destDir = form.get('dir') ?? '';
2036
1878
  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' });
1879
+ const result = op === 'cut' ? filebrowse.moveInto(src, destDir) : filebrowse.copyInto(src, destDir);
1880
+ appendAudit(dir, op === 'cut' ? 'file-move' : 'file-paste', { src, dir: destDir, ok: result.ok, target: result.path ?? null, error: result.error ?? null });
1881
+ res.writeHead(303, { location: '/files?path=' + encodeURIComponent(destDir), 'cache-control': 'no-store' });
2040
1882
  res.end();
2041
1883
  return;
2042
1884
  }
2043
1885
 
2044
- if (url.pathname === '/files/delete' && req.method === 'POST') {
1886
+ if ((url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') && req.method === 'POST') {
2045
1887
  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' });
1888
+ const targetDir = form.get('dir') ?? '';
1889
+ const name = form.get('name') ?? '';
1890
+ const isDir = url.pathname === '/files/mkdir';
1891
+ const result = filebrowse.createEntry(targetDir, name, isDir);
1892
+ appendAudit(dir, isDir ? 'file-mkdir' : 'file-newfile', { dir: targetDir, name, ok: result.ok, error: result.error ?? null });
1893
+ res.writeHead(303, { location: '/files?path=' + encodeURIComponent(targetDir), 'cache-control': 'no-store' });
2050
1894
  res.end();
2051
1895
  return;
2052
1896
  }
@@ -2128,7 +1972,7 @@ a.btn{display:block;padding:11px;border-radius:8px;background:#2a2f3a;color:#c7c
2128
1972
  'content-type': 'text/html; charset=utf-8',
2129
1973
  'cache-control': 'no-store',
2130
1974
  'x-frame-options': 'DENY',
2131
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
1975
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'self'; form-action 'self'; base-uri 'none'",
2132
1976
  'x-content-type-options': 'nosniff',
2133
1977
  'referrer-policy': 'no-referrer',
2134
1978
  });
@@ -2262,7 +2106,7 @@ a.btn{display:block;padding:11px;border-radius:8px;background:#2a2f3a;color:#c7c
2262
2106
  'content-type': 'text/html; charset=utf-8',
2263
2107
  'cache-control': 'no-store',
2264
2108
  'x-frame-options': 'DENY',
2265
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
2109
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
2266
2110
  'x-content-type-options': 'nosniff',
2267
2111
  'referrer-policy': 'no-referrer',
2268
2112
  });
@@ -2660,7 +2504,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
2660
2504
  'content-type': 'text/html; charset=utf-8',
2661
2505
  'cache-control': 'no-store',
2662
2506
  'x-frame-options': 'DENY',
2663
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
2507
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
2664
2508
  'x-content-type-options': 'nosniff',
2665
2509
  'referrer-policy': 'no-referrer',
2666
2510
  ...(deviceCookies.length > 0 ? { 'set-cookie': deviceCookies } : {}),
@@ -67,7 +67,7 @@ const messageHtml = (message, isError) => (message
67
67
  : '')
68
68
 
69
69
  /** 目录列表页 */
70
- const LONG_PRESS_JS = `<script>
70
+ const MENU_JS = `<script>
71
71
  (() => {
72
72
  var openMenu = null;
73
73
  function closeAll() {
@@ -283,6 +283,7 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
283
283
  .mm { position: relative; display: inline-block; }
284
284
  .mm-btn { margin-left: 6px; padding: 6px 10px; border-radius: 8px; background: #2a2f3a; border: 1px solid #3a4351; color: #c7cdd8; font-size: 14px; line-height: 1; }
285
285
  .mm-btn:active { background: #3a4351; }
286
+ .mm-btn-add { background: #2f4a68; border-color: #3f5f84; color: #dce9f7; font-size: 15px; padding: 4px 11px; }
286
287
  .rowmenu { position: fixed; z-index: 9999; min-width: 0; padding: 4px 0; background: #20262f; border: 1px solid #3a4351; border-radius: 10px; box-shadow: 0 12px 32px rgba(0,0,0,.6); }
287
288
  .rowmenu[hidden] { display: none; }
288
289
  .rowmenu .mi { display: flex; align-items: center; gap: 9px; padding: 8px 14px 8px 10px; color: #e3e9f1; text-decoration: none; font-size: 13px; line-height: 1.35; white-space: nowrap; text-align: left; }
@@ -297,9 +298,18 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
297
298
  <button type="button" class="sortbtn" data-sort="name">名称</button>
298
299
  <button type="button" class="sortbtn" data-sort="size">大小</button>
299
300
  <button type="button" class="sortbtn" data-sort="time">时间</button>
301
+ <span style="margin-left:auto" class="mm">
302
+ <button type="button" class="mm-btn mm-btn-add" title="当前目录操作(新建 / 粘贴 / 复制路径)">\uFF0B</button>
303
+ <span class="rowmenu" hidden role="menu">
304
+ <a class="mi" role="menuitem" data-act="paste" data-path="${escapeHtml(info.path)}" href="#"><span class="ico">\u{1F4E5}</span>粘贴到此处</a>
305
+ <a class="mi" role="menuitem" data-act="mkdir" data-path="${escapeHtml(info.path)}" href="#"><span class="ico">\u{1F4C1}</span>新建文件夹</a>
306
+ <a class="mi" role="menuitem" data-act="newfile" data-path="${escapeHtml(info.path)}" href="#"><span class="ico">\u{1F4C4}</span>新建文件</a>
307
+ <a class="mi" role="menuitem" data-act="copypath" data-path="${escapeHtml(info.path)}" href="#"><span class="ico">\u{1F4CB}</span>复制路径</a>
308
+ </span>
309
+ </span>
300
310
  </div>
301
311
  <div class="flist">${rows || '<div class="fempty">空目录</div>'}</div>
302
- ${LONG_PRESS_JS}\n <p class="crumbs">提示:点目录进入,点文件名查看内容;标 ⚙️ 的可直接运行(会在这台电脑上执行)。</p>`
312
+ ${MENU_JS}\n <p class="crumbs">提示:点目录进入,点文件名查看内容;标 ⚙️ 的可直接运行(会在这台电脑上执行)。</p>`
303
313
 
304
314
  return layout({ title: info.path, body })
305
315
  }
@@ -479,114 +489,3 @@ export function renderEditPage({ info, message = '', isError = false }) {
479
489
  }
480
490
 
481
491
  /** shell 页(手机端 Git Bash):命令 + 工作目录 + 输出 */
482
- export function renderShellPage({ cwd, command = '', result = null, history = [], shellName = '' }) {
483
- const failed = result !== null && (result.ok === false || (typeof result.code === 'number' && result.code !== 0))
484
- const body = `
485
- <div class="bar">
486
- <h1>终端</h1>
487
- <div class="path">${escapeHtml(cwd)}${shellName ? ' · ' + escapeHtml(shellName) : ''}</div>
488
- </div>
489
- <form method="post" action="/shell">
490
- <label style="display:block;margin-top:10px;font-size:13px;color:#9aa4b2">工作目录</label>
491
- <input type="text" name="cwd" list="shell-paths" value="${escapeHtml(cwd)}" style="width:100%;box-sizing:border-box">
492
- <label style="display:block;margin-top:10px;font-size:13px;color:#9aa4b2">命令</label>
493
- <input type="text" id="cmd" name="command" value="${escapeHtml(command)}" autocomplete="off" autocapitalize="off"
494
- autocorrect="off" spellcheck="false"
495
- placeholder='例如:git status / ls -la / npm test'
496
- style="width:100%;box-sizing:border-box">
497
- <div class="row">
498
- <button type="submit" style="flex:2">执行</button>
499
- <button type="button" id="tabkey" style="flex:1;background:#2a2f3a;color:#c7cdd8">Tab</button>
500
- <button type="submit" name="action" value="reset" formnovalidate style="flex:1;background:#3a2a2a;color:#f0b6bf">重置</button>
501
- </div>
502
- </form>
503
- <div id="cands" style="display:flex;flex-wrap:wrap;gap:6px;margin-top:8px"></div>
504
- <script id="shell-complete.js">
505
- (function () {
506
- var input = document.getElementById('cmd');
507
- var box = document.getElementById('cands');
508
- var cwdInput = document.querySelector('input[name=cwd]');
509
- if (!input || !box) return;
510
- var timer = null;
511
- function apply(value) {
512
- var text = input.value;
513
- var m = text.match(/(\\S+)$/);
514
- input.value = (m ? text.slice(0, m.index) : text) + value;
515
- input.focus();
516
- refresh();
517
- }
518
- function render(items) {
519
- box.innerHTML = '';
520
- items.slice(0, 12).forEach(function (item) {
521
- var btn = document.createElement('button');
522
- btn.type = 'button';
523
- btn.textContent = item.label;
524
- btn.style.cssText = 'padding:6px 10px;border-radius:999px;background:#1b2030;border:1px solid #2a3550;color:#9fc0ff;font-size:12px';
525
- btn.addEventListener('click', function () { apply(item.value); });
526
- box.appendChild(btn);
527
- });
528
- }
529
- function refresh() {
530
- var cwd = cwdInput ? cwdInput.value : '';
531
- var line = input.value;
532
- if (line.trim() === '') { box.innerHTML = ''; return; }
533
- fetch('/shell/complete?cwd=' + encodeURIComponent(cwd) + '&line=' + encodeURIComponent(line))
534
- .then(function (r) { return r.ok ? r.json() : []; })
535
- .then(function (items) { render(Array.isArray(items) ? items : []); })
536
- .catch(function () { /* 忽略补全失败 */ });
537
- }
538
- function completeNow() {
539
- var cwd = cwdInput ? cwdInput.value : '';
540
- var line = input.value;
541
- if (line.trim() === '') return;
542
- fetch('/shell/complete?cwd=' + encodeURIComponent(cwd) + '&line=' + encodeURIComponent(line))
543
- .then(function (r) { return r.ok ? r.json() : []; })
544
- .then(function (items) {
545
- if (!Array.isArray(items) || items.length === 0) {
546
- box.textContent = '无候选';
547
- setTimeout(function () { box.textContent = ''; }, 1200);
548
- return;
549
- }
550
- render(items);
551
- if (items.length === 1) { apply(items[0].value); return; }
552
- // 多个候选:把最后一段改成它们的公共前缀(像 bash 的 Tab 那样)
553
- var prefix = items[0].value;
554
- for (var i = 1; i < items.length; i += 1) {
555
- while (prefix.length > 0 && items[i].value.indexOf(prefix) !== 0) prefix = prefix.slice(0, -1);
556
- }
557
- if (prefix.length > 0) apply(prefix);
558
- })
559
- .catch(function () { /* 忽略 */ });
560
- }
561
- var tabBtn = document.getElementById('tabkey');
562
- if (tabBtn) tabBtn.addEventListener('click', completeNow);
563
-
564
- input.addEventListener('input', function () {
565
- clearTimeout(timer);
566
- timer = setTimeout(refresh, 250);
567
- });
568
- input.addEventListener('focus', refresh);
569
- })();
570
- </script>
571
- ${history.length === 0 ? '' : `<div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:10px">
572
- ${history.slice(0, 8).map((cmd) => `<form method="post" action="/shell" style="display:inline">
573
- <input type="hidden" name="cwd" value="${escapeHtml(cwd)}">
574
- <input type="hidden" name="command" value="${escapeHtml(cmd)}">
575
- <button type="submit" style="padding:6px 10px;border-radius:999px;background:#1b2030;border:1px solid #2a3550;color:#9fc0ff;font-size:12px">${escapeHtml(cmd)}</button>
576
- </form>`).join('')}
577
- </div>`}
578
- ${result === null ? '' : `
579
- <div class="msg${failed ? ' err' : ''}" style="margin-top:14px">
580
- ${failed ? escapeHtml(result.error ?? (result.timeout ? '超时(30 秒),已终止' : `退出码 ${result.code}`)) : `退出码 ${result.code}`}
581
- </div>
582
- <pre>${escapeHtml(result.output ?? '')}</pre>
583
- `}
584
- <div class="row">
585
- <a class="btn ghost" href="/git?path=${encodeURIComponent(cwd)}"
586
- style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">Git 页</a>
587
- <a class="btn ghost" href="/files?path=${encodeURIComponent(cwd)}"
588
- style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">文件</a>
589
- </div>
590
- <p class="crumbs">命令直接在你电脑上执行,输出截断到 64KB,30 秒超时。可以用 cd 切换工作目录。</p>`
591
- return layout({ title: '终端', body })
592
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.0.1",
3
+ "version": "2.0.3",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [
@@ -54,9 +54,7 @@
54
54
  "icon.svg",
55
55
  "README.md",
56
56
  "LICENSE",
57
- "lib/vendor/**",
58
- "ops/**",
59
- "client.js"
57
+ "lib/vendor/**"
60
58
  ],
61
59
  "publishConfig": {
62
60
  "access": "public",
package/client.js DELETED
@@ -1,79 +0,0 @@
1
- /**
2
- * dsh-homing 的浏览器端:在侧边栏底部放一组守护进程控制按钮。
3
- *
4
- * 为什么放在客户端:用户要求用按钮代替命令行,且不要用 PowerShell。
5
- * 按钮直接调用本机守护进程的控制接口(http://127.0.0.1:8790),
6
- * 该接口已在 supervisor.mjs 里放行跨端口请求(CORS)。
7
- *
8
- * 契约参考 DSH 客户端插件(window.__ModuleLoader__.load + slots 注册)。
9
- */
10
- window.__ModuleLoader__.load({
11
- id: '@andy.ian/dsh-homing',
12
- factory(require) {
13
- const React = require('react')
14
- const h = React.createElement
15
-
16
- const CONTROL = 'http://127.0.0.1:8790'
17
-
18
- async function call(pathname) {
19
- const res = await fetch(CONTROL + pathname, { method: 'POST' })
20
- return res.json()
21
- }
22
-
23
- function Controls() {
24
- const [notice, setNotice] = React.useState('')
25
- const [busy, setBusy] = React.useState(false)
26
-
27
- async function run(pathname, text) {
28
- if (busy) return
29
- setBusy(true)
30
- try {
31
- await call(pathname)
32
- setNotice(text)
33
- } catch (error) {
34
- setNotice('守护进程未运行')
35
- } finally {
36
- setBusy(false)
37
- setTimeout(() => setNotice(''), 4000)
38
- }
39
- }
40
-
41
- const button = (label, title, pathname, text) => h('button', {
42
- type: 'button',
43
- title,
44
- disabled: busy,
45
- onClick: () => void run(pathname, text),
46
- style: {
47
- background: 'transparent',
48
- border: '1px solid rgba(255,255,255,.18)',
49
- borderRadius: '6px',
50
- color: 'inherit',
51
- cursor: busy ? 'default' : 'pointer',
52
- fontSize: '12px',
53
- padding: '4px 8px',
54
- },
55
- }, label)
56
-
57
- return h('div', { style: { display: 'flex', gap: '6px', alignItems: 'center', padding: '4px 8px' } },
58
- button('⏻', '重启 DSH(等空闲)', '/restart?mode=default', '已请求重启'),
59
- button('⚡', '立即重启 DSH', '/restart?mode=immediate', '已请求立即重启'),
60
- button('⏸', '暂停自动拉起 30 分钟', '/pause?minutes=30', '已暂停 30 分钟'),
61
- button('▶', '恢复自动拉起', '/resume', '已恢复'),
62
- button('⏹', '停止守护进程(不再拉起)', '/stop', '守护进程已退出'),
63
- notice ? h('span', { style: { fontSize: '11px', opacity: 0.7 } }, notice) : null,
64
- )
65
- }
66
-
67
- return {
68
- name: 'ui-dsh-homing',
69
- inject: ['slots'],
70
- apply(ctx) {
71
- const dispose = ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register(
72
- { name: 'sidebar.footer.action', id: 'dsh-homing', order: 11 },
73
- Controls,
74
- ))
75
- if (typeof ctx.effect === 'function') ctx.effect(() => dispose, 'dsh-homing: sidebar controls')
76
- },
77
- }
78
- },
79
- })