@andy.ian/dsh-homing 2.1.1 → 2.1.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
@@ -27,7 +27,8 @@ 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 { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage } from './lib/files-page.mjs';
31
32
  import { checkUnsafeOrigin } from './lib/csrf.mjs';
32
33
  import * as limits from './lib/limits.mjs';
33
34
 
@@ -356,161 +357,14 @@ function createCookieMinter(credentials, getUpstreamPort) {
356
357
 
357
358
  const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
358
359
  @media (max-width: 760px) {
359
- [aria-label="打开右侧边栏"] { display: none !important; }
360
360
  [class*="_frame"] { min-width: 0; }
361
-
362
- /* 隐藏时只把侧边栏那一列压成 0,主内容自然占满;其余布局仍归应用自己算 */
363
- html[data-dsh-homing-nav="hidden"] [class*="_frame"] {
364
- grid-template-columns: 0 1fr 0 !important;
365
- transition: none !important;
366
- }
367
- html[data-dsh-homing-nav="hidden"] [class*="sidebarCol"] {
368
- min-width: 0 !important;
369
- overflow: hidden !important;
370
- }
371
-
372
- /* 侧边栏完全隐藏时,左上角探出的小耳朵(磁吸感):点它恢复完整侧边栏 */
373
- .dsh-homing-ear {
374
- position: fixed;
375
- left: 0;
376
- top: 16px;
377
- width: 16px;
378
- height: 40px;
379
- z-index: 62;
380
- display: none;
381
- align-items: center;
382
- justify-content: center;
383
- padding: 0;
384
- border: 1px solid rgba(255, 255, 255, 0.14);
385
- border-left: 0;
386
- border-radius: 0 10px 10px 0;
387
- background: rgba(30, 34, 42, 0.72);
388
- color: #aeb5c2;
389
- font-size: 14px;
390
- line-height: 1;
391
- box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4);
392
- -webkit-tap-highlight-color: transparent;
393
- user-select: none;
394
- touch-action: manipulation;
395
- }
396
- .dsh-homing-ear:active { background: rgba(60, 66, 78, 0.95); color: #e8eaed; }
397
361
  }
398
362
  `;
399
363
 
400
364
  const MOBILE_JS = `(() => {
401
365
  const narrow = () => window.innerWidth <= 760
402
366
  const root = document.documentElement
403
- const frame = () => document.querySelector('[class*="_frame"]')
404
- const mainCol = () => { const f = frame(); return f ? f.children[1] : null }
405
367
  const sidebar = () => document.querySelector('[class*="sidebarCol"]')
406
- const openBtn = () => document.querySelector('[aria-label="打开侧边栏"]')
407
- const collapseBtn = () => document.querySelector('[aria-label="收起侧边栏"]')
408
- const isHidden = () => root.getAttribute('data-dsh-homing-nav') === 'hidden'
409
- // 我们自己去点应用按钮时,要绕过下面那个捕获拦截,否则会自己拦自己、无限递归
410
- let quietClick = false
411
- const clickQuietly = (btn) => {
412
- if (btn === null) return
413
- quietClick = true
414
- try { btn.click() } finally { setTimeout(() => { quietClick = false }, 0) }
415
- }
416
- const widthOf = (node) => (node ? node.getBoundingClientRect().width : 0)
417
-
418
- // 三态:expanded(完整) / rail(图标栏) / hidden(完全隐藏)
419
- const stateOf = () => {
420
- if (isHidden()) return 'hidden'
421
- return widthOf(sidebar()) > 70 ? 'expanded' : 'rail'
422
- }
423
-
424
- const hide = () => {
425
- if (!narrow()) return false
426
- const before = widthOf(mainCol())
427
- root.setAttribute('data-dsh-homing-nav', 'hidden')
428
- const after = widthOf(mainCol())
429
- if (!(after > before + 10)) {
430
- root.removeAttribute('data-dsh-homing-nav')
431
- console.warn('[dsh-homing] 侧边栏隐藏未生效,已自动撤销')
432
- updateEar()
433
- return false
434
- }
435
- updateEar()
436
- return true
437
- }
438
-
439
- const showAttribute = () => {
440
- root.removeAttribute('data-dsh-homing-nav')
441
- updateEar()
442
- }
443
-
444
- const toExpanded = () => {
445
- clickQuietly(openBtn())
446
- setTimeout(() => { showAttribute(); updateEar() }, 80)
447
- }
448
-
449
- const toRail = () => {
450
- showAttribute()
451
- clickQuietly(collapseBtn())
452
- }
453
-
454
- const toHidden = () => {
455
- clickQuietly(collapseBtn())
456
- hide()
457
- }
458
-
459
- // 应用自带的开关:按 完整 → 图标栏 → 隐藏 循环
460
- const cycle = () => {
461
- const state = stateOf()
462
- if (state === 'expanded') toRail()
463
- else if (state === 'rail') toHidden()
464
- else toExpanded()
465
- }
466
-
467
- // 隐藏时左上角探出的小耳朵,点它恢复完整侧边栏
468
- let ear = null
469
- const EAR_HEIGHT = 40
470
- // 对齐到应用自带开关的竖直中心(它在侧边栏里,即使侧边栏被压成 0 也能量到)
471
- const placeEar = () => {
472
- if (ear === null) return
473
- const anchor = collapseBtn() ?? openBtn()
474
- if (anchor === null) return
475
- const rect = anchor.getBoundingClientRect()
476
- if (rect.height === 0 && rect.width === 0) return
477
- const top = Math.round(rect.top + rect.height / 2 - EAR_HEIGHT / 2)
478
- ear.style.top = Math.max(2, top) + 'px'
479
- }
480
- const updateEar = () => {
481
- if (ear === null) return
482
- ear.style.display = narrow() && isHidden() ? 'flex' : 'none'
483
- placeEar()
484
- }
485
- const installEar = () => {
486
- ear = document.createElement('button')
487
- ear.type = 'button'
488
- ear.className = 'dsh-homing-ear'
489
- ear.setAttribute('aria-label', '展开侧边栏')
490
- ear.textContent = '›'
491
- ear.addEventListener('click', (event) => {
492
- event.preventDefault()
493
- event.stopPropagation()
494
- toExpanded()
495
- setTimeout(updateEar, 120)
496
- })
497
- document.body.appendChild(ear)
498
- placeEar()
499
- updateEar()
500
- }
501
-
502
- // 拦截应用自带开关的点击(捕获阶段,先于应用自己的处理)
503
- document.addEventListener('click', (event) => {
504
- if (quietClick) return
505
- if (!narrow()) return
506
- const target = event.target.closest('[aria-label="收起侧边栏"], [aria-label="打开侧边栏"]')
507
- if (target === null) return
508
- event.preventDefault()
509
- event.stopPropagation()
510
- cycle()
511
- setTimeout(updateEar, 200)
512
- }, true)
513
-
514
368
  // 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
515
369
  // 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
516
370
  const LAST_WS_KEY = 'dsh-homing:last-workspace'
@@ -673,30 +527,94 @@ const MOBILE_JS = `(() => {
673
527
  button.click()
674
528
  }
675
529
 
676
- // 点侧边栏里的会话后,回到完全隐藏
677
- document.addEventListener('click', (event) => {
678
- if (!narrow() || isHidden()) return
679
- const side = sidebar()
680
- if (side === null || !side.contains(event.target)) return
681
- const collapse = collapseBtn()
682
- if (collapse !== null && collapse.contains(event.target)) return
683
- if (event.target.closest('[aria-label="收起侧边栏"], [aria-label="打开侧边栏"]')) return
684
- setTimeout(() => toHidden(), 260)
685
- }, false)
530
+ const start = () => {
531
+ closeRightBar()
532
+ }
686
533
 
687
- window.addEventListener('resize', () => { updateEar(); if (!narrow()) showAttribute() })
534
+ /* ---------- SESSION_MENU_ITEMS ----------
535
+ * 在 DSH 会话「…」菜单里追加两项:
536
+ * - 下载工作区文件:跳到文件页(可逐个文件下载)
537
+ * - 重启 DSH / 守护进程:跳到重启页
538
+ * 做法:复制一个原生菜单项(连同图标容器与样式),只替换文字和图标路径;
539
+ * 每轮先清掉旧项,并全局 prune,保证每项最多一个。
540
+ */
541
+ const MENU_HINT = /下载 Session 日志|复制会话为 Markdown|反馈/u
542
+ 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"/>'
543
+ 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"/>'
544
+ let menuTimer = null
688
545
 
689
- const start = () => {
690
- if (!narrow()) { closeRightBar(); return }
691
- installEar()
692
- const collapse = collapseBtn()
693
- if (collapse !== null) collapse.click()
694
- setTimeout(() => {
695
- hide()
696
- closeRightBar()
697
- }, 350)
546
+ const textNodeMatching = (node, pattern) => {
547
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT)
548
+ for (let current = walker.nextNode(); current !== null; current = walker.nextNode()) {
549
+ if (pattern.test(current.nodeValue || '')) return current
550
+ }
551
+ return null
552
+ }
553
+
554
+ const buildMenuItem = (template, label, icon, action) => {
555
+ const link = template.cloneNode(true)
556
+ link.setAttribute('role', 'menuitem')
557
+ link.setAttribute('href', '#')
558
+ link.style.textDecoration = 'none'
559
+ const textNode = textNodeMatching(link, /反馈|下载 Session 日志|复制会话为 Markdown/u)
560
+ if (textNode !== null) textNode.nodeValue = label
561
+ else link.textContent = label
562
+ const svg = link.querySelector('svg')
563
+ if (svg !== null) {
564
+ svg.innerHTML = icon
565
+ svg.setAttribute('viewBox', '0 0 24 24')
566
+ svg.setAttribute('fill', 'none')
567
+ svg.setAttribute('stroke', 'currentColor')
568
+ svg.setAttribute('stroke-width', '2')
569
+ svg.setAttribute('stroke-linecap', 'round')
570
+ svg.setAttribute('stroke-linejoin', 'round')
571
+ }
572
+ link.addEventListener('click', (event) => {
573
+ event.preventDefault()
574
+ event.stopPropagation()
575
+ action()
576
+ }, true)
577
+ return link
578
+ }
579
+
580
+ const enhanceMenus = () => {
581
+ const done = new Set()
582
+ for (const item of document.querySelectorAll('[role="menuitem"]')) {
583
+ const menu = item.closest('[role="menu"]') ?? item.parentElement
584
+ if (menu === null || done.has(menu)) continue
585
+ if (!MENU_HINT.test(menu.textContent || '')) continue
586
+ done.add(menu)
587
+
588
+ for (const old of menu.querySelectorAll('[data-dsh-homing-download],[data-dsh-homing-restart]')) old.remove()
589
+
590
+ const items = [...menu.querySelectorAll('[role="menuitem"]')]
591
+ const template = items.find((node) => node.querySelector('svg')) ?? items[0]
592
+ if (!template) continue
593
+
594
+ const download = buildMenuItem(template, '下载工作区文件', ICON_DOWNLOAD, () => goFiles())
595
+ download.setAttribute('data-dsh-homing-download', '1')
596
+ const restart = buildMenuItem(template, '重启 DSH / 守护进程', ICON_RESTART, () => window.location.assign('/dsh_homing/restart'))
597
+ restart.setAttribute('data-dsh-homing-restart', '1')
598
+
599
+ menu.appendChild(download)
600
+ menu.appendChild(restart)
601
+ }
602
+ }
603
+
604
+ // 兜底:无论菜单容器怎么嵌套,每类最多保留一个
605
+ const pruneMenuItems = () => {
606
+ for (const selector of ['[data-dsh-homing-download]', '[data-dsh-homing-restart]']) {
607
+ const all = [...document.querySelectorAll(selector)]
608
+ for (let i = 0; i < all.length - 1; i += 1) all[i].remove()
609
+ }
698
610
  }
699
611
 
612
+ const menuObserver = new MutationObserver(() => {
613
+ if (menuTimer) return
614
+ menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneMenuItems() }, 80)
615
+ })
616
+ menuObserver.observe(document.body, { childList: true, subtree: true })
617
+
700
618
  /* ---------- ALIVE_BEACON ----------
701
619
  * 告诉插件"用户正在操作":重启脚本据此判断能否安全重启。
702
620
  * 手机上打字/滑动手势不会修改会话文件,只有这个信标能反映"人在用"。
@@ -727,57 +645,6 @@ const MOBILE_JS = `(() => {
727
645
  else start()
728
646
  })();
729
647
 
730
- // 左侧「小耳朵」:插到侧边栏开关旁边(复用它的 class,尺寸/配色自动一致)
731
- (function () {
732
- if (window.__dshEar) return;
733
- window.__dshEar = true;
734
-
735
- var a = document.createElement('a');
736
- a.href = '/dsh_homing/restart';
737
- a.title = '重启 / 守护进程';
738
- a.textContent = '\u267B';
739
- a.id = 'dsh-ear';
740
- a.style.cssText = 'text-decoration:none;display:flex;align-items:center;justify-content:center;';
741
-
742
- function toggleEl() {
743
- return document.querySelector('[aria-label="收起侧边栏"],[title="收起侧边栏"],[aria-label="打开侧边栏"],[title="打开侧边栏"]');
744
- }
745
-
746
- // 把耳朵放到开关按钮的后面(同一容器、同一行/列),并复制它的 class 以继承尺寸
747
- function place() {
748
- var toggle = toggleEl();
749
- if (!toggle || !toggle.parentNode) return false;
750
- if (a.parentNode === toggle.parentNode) return true;
751
- a.className = toggle.className;
752
- // 尺寸跟随按钮,避免"探出太多"
753
- var r = toggle.getBoundingClientRect();
754
- if (r.width > 0) { a.style.width = Math.round(r.width) + 'px'; a.style.height = Math.round(r.height) + 'px'; }
755
- a.style.fontSize = Math.round((r.height || 32) * 0.5) + 'px';
756
- toggle.parentNode.insertBefore(a, toggle.nextSibling);
757
- return true;
758
- }
759
-
760
- // DSH 是 SPA,普通 <a> 点击会被它自己的路由吞掉 → 在 window 捕获阶段强制整页跳转
761
- function jump(event) {
762
- var target = event.target;
763
- var ear = target && target.closest ? target.closest('#dsh-ear') : null;
764
- if (!ear) return;
765
- event.preventDefault();
766
- event.stopImmediatePropagation();
767
- window.location.assign('/dsh_homing/restart');
768
- }
769
- window.addEventListener('click', jump, true);
770
- window.addEventListener('touchend', jump, true);
771
-
772
- place();
773
- // 侧边栏可能延迟渲染或 React 重渲染把节点冲掉:用 MutationObserver 兜底,但只在丢失时重插
774
- var timer = null;
775
- var obs = new MutationObserver(function () {
776
- if (timer) return;
777
- timer = setTimeout(function () { timer = null; place(); }, 400);
778
- });
779
- obs.observe(document.body, { childList: true, subtree: true });
780
- })();
781
648
  `;
782
649
 
783
650
  const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
@@ -835,8 +702,6 @@ const restartService = createRestartService({
835
702
  postTimeoutMs: 5000,
836
703
  });
837
704
 
838
- const daemonStatus = () => restartService.status();
839
- const daemonPost = (pathAndQuery) => restartService.post(pathAndQuery);
840
705
 
841
706
  const LIVE_SCRIPT = `<div id="live" class="dim" style="margin-top:8px">脚本未加载</div>`
842
707
  + `<script src="/dsh_homing/restart.js"></script>`;
@@ -1138,7 +1003,7 @@ function sessionRunning(dshHomeDir) {
1138
1003
  }
1139
1004
  async function collectRestartState(dataDir) {
1140
1005
  const sessions = sessionRunning(path.resolve(dataDir, '..', '..'));
1141
- const status = await daemonStatus();
1006
+ const status = await restartService.status();
1142
1007
  const policyStatus = restartPolicy.status();
1143
1008
  const config = policyStatus?.config ?? null;
1144
1009
  return {
@@ -1197,7 +1062,7 @@ const restartPolicy = createRestartPolicy({
1197
1062
  return Number(raw.at) || 0;
1198
1063
  } catch { return 0 }
1199
1064
  },
1200
- triggerRestart: () => daemonPost('/restart-now'),
1065
+ triggerRestart: () => restartService.post('/restart-now'),
1201
1066
  // 策略来自配置文件(可热更新;写坏时保留上次有效配置)
1202
1067
  specPath: path.join(dataDir(), 'policy.json'),
1203
1068
  log: (message) => appendAudit(dataDir(), 'restart-policy', { message }),
@@ -1664,15 +1529,21 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1664
1529
  // 攻击者注入的脚本没有 nonce,即使 HTML 转义出漏洞也跑不起来。
1665
1530
  const nonce = crypto.randomBytes(16).toString('base64url');
1666
1531
  let responseType = '';
1532
+ let ownHtml = false; // 只给插件自身渲染的页面加 nonce,DSH 页面原样透传
1667
1533
  const rawWriteHead = res.writeHead.bind(res);
1668
1534
  res.writeHead = (status, headers, ...rest) => {
1669
1535
  if (headers && typeof headers === 'object' && typeof headers['content-type'] === 'string') {
1670
1536
  responseType = headers['content-type'];
1671
1537
  }
1672
- if (headers && typeof headers === 'object' && typeof headers['content-security-policy'] === 'string') {
1538
+ let csp = '';
1539
+ if (headers && typeof headers === 'object') csp = String(headers['content-security-policy'] ?? '');
1540
+ // 只有插件自己的页面以 default-src 'none' 开头;DSH 前端页面不能改写,
1541
+ // 否则会破坏 0.2.2 动态生成的 <script> 模板。
1542
+ if (csp.includes("default-src 'none'")) {
1543
+ ownHtml = true;
1673
1544
  headers = {
1674
1545
  ...headers,
1675
- 'content-security-policy': headers['content-security-policy'].replace(
1546
+ 'content-security-policy': csp.replace(
1676
1547
  "script-src 'self'",
1677
1548
  `script-src 'self' 'nonce-${nonce}'`,
1678
1549
  ),
@@ -1683,7 +1554,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1683
1554
  const rawEnd = res.end.bind(res);
1684
1555
  res.end = (body, ...rest) => {
1685
1556
  const type = responseType || String(res.getHeader('content-type') ?? '');
1686
- if (typeof body === 'string' && type.includes('text/html')) {
1557
+ if (ownHtml && typeof body === 'string' && type.includes('text/html')) {
1687
1558
  body = body.replaceAll('<script', `<script nonce="${nonce}"`);
1688
1559
  }
1689
1560
  return rawEnd(body, ...rest);
@@ -1938,7 +1809,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1938
1809
  // 重启界面:服务端渲染 + 表单提交(无内联脚本)
1939
1810
  if (url.pathname === '/dsh_homing/restart' && req.method === 'GET') {
1940
1811
  const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
1941
- const status = await daemonStatus();
1812
+ const status = await restartService.status();
1942
1813
  const message = url.searchParams.get('m') ?? '';
1943
1814
  res.writeHead(200, {
1944
1815
  'content-type': 'text/html; charset=utf-8',
@@ -1969,7 +1840,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1969
1840
  } else if (action === 'force') {
1970
1841
  if (sessions.length > 0 && form.get('confirm') !== '1') {
1971
1842
  // 繁忙:先渲染二次确认页,列出正在运行的会话
1972
- const status = await daemonStatus();
1843
+ const status = await restartService.status();
1973
1844
  res.writeHead(200, {
1974
1845
  'content-type': 'text/html; charset=utf-8',
1975
1846
  'cache-control': 'no-store',
@@ -1986,11 +1857,11 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1986
1857
  if (!Number.isFinite(minutes) || minutes <= 0) {
1987
1858
  message = '暂停失败:请填写正整数分钟';
1988
1859
  } else {
1989
- const r = await daemonPost('/pause?minutes=' + minutes);
1860
+ const r = await restartService.post('/pause?minutes=' + minutes);
1990
1861
  message = r.ok ? ('已暂停自动拉起 ' + minutes + ' 分钟') : '暂停失败:守护进程未运行';
1991
1862
  }
1992
1863
  } else if (action === 'resume') {
1993
- const r = await daemonPost('/resume');
1864
+ const r = await restartService.post('/resume');
1994
1865
  message = r.ok ? '已恢复自动拉起' : '恢复失败:守护进程未运行';
1995
1866
  }
1996
1867
  void broadcastRestartState(dataDir(), { event: 'restart-accepted', action });
@@ -2000,7 +1871,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2000
1871
  }
2001
1872
 
2002
1873
  if (url.pathname === '/dsh_homing/restart/state' && req.method === 'GET') {
2003
- const sup = await daemonStatus();
1874
+ const sup = await restartService.status();
2004
1875
  const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
2005
1876
  const payload = JSON.stringify({
2006
1877
  daemon: sup ? { running: sup.running, restarts: sup.daemon?.restarts ?? 0, paused: sup.paused ?? false, pausedSecondsLeft: sup.pausedSecondsLeft ?? 0, probeAgeSeconds: sup.probeAgeSeconds ?? null, lastProbeAt: sup.lastProbeAt ?? null } : null,
@@ -2491,7 +2362,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2491
2362
  return;
2492
2363
  }
2493
2364
 
2494
- if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/run'
2365
+ if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/download' || url.pathname === '/files/compress' || url.pathname === '/files/run'
2495
2366
  || url.pathname === '/files/rename'
2496
2367
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
2497
2368
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
@@ -2538,6 +2409,68 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2538
2409
  return;
2539
2410
  }
2540
2411
 
2412
+ if (url.pathname === '/files/compress' && req.method === 'GET') {
2413
+ const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
2414
+ const tools = compress.availableBackends().map((item) => ({ label: item.label, strength: item.strength, level: item.level }));
2415
+ appendAudit(dir, 'file-compress-view', { path: target, tools: tools.length });
2416
+ sendHtml(renderCompressPage({ target, archive: '', tools }));
2417
+ return;
2418
+ }
2419
+
2420
+ if (url.pathname === '/files/compress' && req.method === 'POST') {
2421
+ const form = new URLSearchParams(await readBody(req, 64 * 1024));
2422
+ const target = filebrowse.resolvePath(form.get('path') ?? '');
2423
+ const password = form.get('password') ?? '';
2424
+ const confirm = form.get('confirm') ?? '';
2425
+ const tools = compress.availableBackends().map((item) => ({ label: item.label, strength: item.strength, level: item.level }));
2426
+ if (password !== confirm) {
2427
+ sendHtml(renderCompressPage({ target, archive: '', tools, message: '两次输入的密码不一致', isError: true }));
2428
+ return;
2429
+ }
2430
+ const result = compress.createEncryptedArchive({ target, password });
2431
+ appendAudit(dir, 'file-compress', {
2432
+ path: target,
2433
+ ok: result.ok,
2434
+ tool: result.tool ?? null,
2435
+ bytes: result.bytes ?? 0,
2436
+ error: result.error ?? null,
2437
+ });
2438
+ sendHtml(renderCompressPage({
2439
+ target,
2440
+ archive: result.ok ? result.path : '',
2441
+ tools,
2442
+ tool: result.tool ?? '',
2443
+ strength: result.strength ?? '',
2444
+ message: result.ok ? '已生成加密压缩包' : result.error,
2445
+ isError: !result.ok,
2446
+ done: result.ok,
2447
+ }));
2448
+ return;
2449
+ }
2450
+
2451
+ if (url.pathname === '/files/download' && req.method === 'GET') {
2452
+ const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
2453
+ let stat = null;
2454
+ try { stat = fs.statSync(target); } catch { stat = null; }
2455
+ if (!stat || !stat.isFile()) {
2456
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
2457
+ res.end('文件不存在或不是普通文件\n');
2458
+ return;
2459
+ }
2460
+ const name = path.basename(target);
2461
+ const ascii = name.replace(/[^\x20-\x7E]/gu, '_').replace(/["\\]/gu, '_');
2462
+ appendAudit(dir, 'file-download', { path: target, bytes: stat.size });
2463
+ res.writeHead(200, {
2464
+ 'content-type': 'application/octet-stream',
2465
+ 'content-length': String(stat.size),
2466
+ 'content-disposition': `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`,
2467
+ 'cache-control': 'no-store',
2468
+ 'x-content-type-options': 'nosniff',
2469
+ });
2470
+ fs.createReadStream(target).pipe(res);
2471
+ return;
2472
+ }
2473
+
2541
2474
  if (url.pathname === '/files/view' && req.method === 'GET') {
2542
2475
  const info = filebrowse.readTextFile(url.searchParams.get('path') ?? '');
2543
2476
  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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.1.1",
3
+ "version": "2.1.3",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [