@andy.ian/dsh-homing 2.0.2 → 2.1.0

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.
Files changed (138) hide show
  1. package/bin/restart-daemon.mjs +3 -0
  2. package/bin/restart.mjs +3 -0
  3. package/index.js +785 -29
  4. package/lib/devices.mjs +0 -1
  5. package/lib/files-page.mjs +10 -18
  6. package/lib/files.mjs +39 -27
  7. package/package.json +8 -9
  8. package/restart/client.mjs +184 -0
  9. package/restart/config.mjs +187 -0
  10. package/restart/engine.mjs +93 -0
  11. package/restart/face.mjs +62 -0
  12. package/restart/runner.mjs +184 -0
  13. package/restart/service.mjs +91 -0
  14. package/restart-daemon/README.md +66 -0
  15. package/restart-daemon/cli.mjs +321 -0
  16. package/restart-daemon/lib/detach.mjs +126 -0
  17. package/restart-daemon/lib/process-tree.mjs +69 -0
  18. package/restart-daemon/lib/restart-flow.mjs +111 -0
  19. package/restart-daemon/lib/update-state.mjs +72 -0
  20. package/restart-daemon/main.mjs +691 -0
  21. package/bin/supervisor.mjs +0 -488
  22. package/bin/watchdog.mjs +0 -144
  23. package/lib/vendor/node_modules/ssh2/examples/server-chat.js +0 -238
  24. package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +0 -134
  25. package/lib/vendor/node_modules/ssh2/test/common.js +0 -316
  26. package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +0 -26
  27. package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +0 -33
  28. package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +0 -52
  29. package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +0 -12
  30. package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +0 -5
  31. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +0 -15
  32. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +0 -26
  33. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +0 -30
  34. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +0 -21
  35. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +0 -1
  36. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +0 -7
  37. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +0 -7
  38. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +0 -22
  39. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +0 -1
  40. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +0 -7
  41. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +0 -7
  42. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +0 -23
  43. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +0 -1
  44. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +0 -7
  45. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +0 -7
  46. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +0 -9
  47. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +0 -1
  48. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +0 -7
  49. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +0 -7
  50. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +0 -10
  51. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +0 -1
  52. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +0 -8
  53. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +0 -7
  54. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +0 -10
  55. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +0 -1
  56. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +0 -8
  57. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +0 -7
  58. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +0 -7
  59. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +0 -1
  60. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +0 -7
  61. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +0 -7
  62. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +0 -27
  63. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +0 -1
  64. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +0 -7
  65. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +0 -7
  66. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +0 -28
  67. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +0 -1
  68. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +0 -8
  69. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +0 -7
  70. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +0 -29
  71. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +0 -1
  72. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +0 -8
  73. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +0 -7
  74. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +0 -12
  75. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +0 -1
  76. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +0 -7
  77. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +0 -7
  78. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +0 -15
  79. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +0 -1
  80. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +0 -8
  81. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +0 -7
  82. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +0 -5
  83. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +0 -1
  84. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +0 -7
  85. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +0 -7
  86. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +0 -8
  87. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +0 -1
  88. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +0 -8
  89. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +0 -7
  90. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +0 -27
  91. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +0 -1
  92. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +0 -7
  93. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +0 -7
  94. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +0 -30
  95. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +0 -1
  96. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +0 -8
  97. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +0 -7
  98. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +0 -54
  99. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +0 -1
  100. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +0 -6
  101. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +0 -6
  102. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +0 -17
  103. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +0 -7
  104. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +0 -26
  105. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +0 -7
  106. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +0 -18
  107. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +0 -7
  108. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +0 -9
  109. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +0 -7
  110. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +0 -10
  111. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +0 -7
  112. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +0 -11
  113. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +0 -7
  114. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +0 -11
  115. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +0 -7
  116. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +0 -8
  117. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +0 -7
  118. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +0 -13
  119. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +0 -7
  120. package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +0 -27
  121. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +0 -12
  122. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +0 -5
  123. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +0 -15
  124. package/lib/vendor/node_modules/ssh2/test/test-exec.js +0 -578
  125. package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +0 -486
  126. package/lib/vendor/node_modules/ssh2/test/test-keygen.js +0 -60
  127. package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +0 -1460
  128. package/lib/vendor/node_modules/ssh2/test/test-openssh.js +0 -261
  129. package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +0 -631
  130. package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +0 -177
  131. package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +0 -138
  132. package/lib/vendor/node_modules/ssh2/test/test-sftp.js +0 -842
  133. package/lib/vendor/node_modules/ssh2/test/test-shell.js +0 -109
  134. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +0 -110
  135. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +0 -171
  136. package/lib/vendor/node_modules/ssh2/test/test-userauth.js +0 -611
  137. package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +0 -25
  138. package/lib/vendor/node_modules/ssh2/test/test.js +0 -20
package/index.js CHANGED
@@ -19,10 +19,12 @@ import path from 'node:path';
19
19
  import crypto from 'node:crypto';
20
20
  import { spawn, spawnSync } from 'node:child_process';
21
21
  import { fileURLToPath } from 'node:url';
22
+ import { createRestartService, RESTART_DAEMON_PORT } from './restart/service.mjs';
22
23
  import zlib from 'node:zlib';
23
24
  import * as deviceStore from './lib/devices.mjs';
24
25
  import * as filebrowse from './lib/files.mjs';
25
26
  import * as gitrun from './lib/git.mjs';
27
+ import { createRestartPolicy } from './restart/face.mjs';
26
28
  import * as ptyrun from './lib/pty.mjs';
27
29
  import { renderTermPage } from './lib/term-page.mjs';
28
30
  import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage } from './lib/files-page.mjs';
@@ -174,15 +176,6 @@ function signEntryFor(sessionKeyBase64, expiresAt) {
174
176
  }
175
177
 
176
178
  /** 模块级:入口令牌校验,返回 0 表示无效。 */
177
- function entryExpiryFor(sessionKeyBase64, value) {
178
- if (typeof value !== 'string') return 0;
179
- const [body, mac] = value.split('.');
180
- if (!body || !mac) return 0;
181
- const expected = base64url(crypto.createHmac('sha256', Buffer.from(sessionKeyBase64, 'base64')).update(`entry:${body}`).digest());
182
- if (!safeEqual(mac, expected)) return 0;
183
- const expiresAt = Number(Buffer.from(body.replaceAll('-', '+').replaceAll('_', '/'), 'base64').toString('utf8'));
184
- return Number.isFinite(expiresAt) && expiresAt > Date.now() ? expiresAt : 0;
185
- }
186
179
 
187
180
  function readCookies(headerValue) {
188
181
  const out = {};
@@ -733,6 +726,58 @@ const MOBILE_JS = `(() => {
733
726
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)
734
727
  else start()
735
728
  })();
729
+
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
+ })();
736
781
  `;
737
782
 
738
783
  const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
@@ -741,6 +786,139 @@ const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script
741
786
  // 调试页上一键即可设置,页面坏了也点得到。
742
787
  const MOBILE_OFF_COOKIE = 'dsh-homing-off';
743
788
 
789
+
790
+
791
+
792
+ // 重启界面:服务端渲染 + 表单提交,不依赖任何脚本(避免 CSP/SPA 拦截)
793
+
794
+ // ---------- 开机自启 ----------
795
+ // 安装后第一次打开重启页时询问用户;选择写进数据目录,之后不再打扰。
796
+ function autostartMarkerPath() {
797
+ return path.join(dataDir(), '..', '..', 'restart-daemon', 'autostart.json');
798
+ }
799
+
800
+ function autostartState() {
801
+ let marker = null;
802
+ try { marker = JSON.parse(fs.readFileSync(autostartMarkerPath(), 'utf8')); } catch { /* 未安装 */ }
803
+ let dismissed = false;
804
+ try {
805
+ const flag = JSON.parse(fs.readFileSync(path.join(dataDir(), 'autostart-dismissed.json'), 'utf8'));
806
+ dismissed = flag?.dismissed === true;
807
+ } catch { /* 没选过 */ }
808
+ return { configured: Boolean(marker), mode: marker?.mode ?? null, dismissed };
809
+ }
810
+
811
+ // 策略层令牌:所有"会触发重启"的操作必须带它(DSH 插件从同一文件读取)
812
+ function policyToken() {
813
+ const file = path.join(dataDir(), 'policy-token');
814
+ try {
815
+ const existing = fs.readFileSync(file, 'utf8').trim();
816
+ if (existing.length >= 32) return existing;
817
+ } catch { /* 不存在就生成 */ }
818
+ const created = crypto.randomBytes(24).toString('hex');
819
+ fs.mkdirSync(dataDir(), { recursive: true });
820
+ fs.writeFileSync(file, created + '\n', { mode: 0o600 });
821
+ return created;
822
+ }
823
+
824
+ function policyAuthorized(req, fields) {
825
+ const given = String(req.headers['x-dsh-policy-token'] ?? fields?.get?.('token') ?? '');
826
+ const expected = policyToken();
827
+ if (given.length !== expected.length) return false;
828
+ return crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));
829
+ }
830
+
831
+ // 守护进程客户端:具体实现在 restart/service.mjs(唯一出口)
832
+ const restartService = createRestartService({
833
+ port: RESTART_DAEMON_PORT,
834
+ statusTimeoutMs: 3000,
835
+ postTimeoutMs: 5000,
836
+ });
837
+
838
+ const daemonStatus = () => restartService.status();
839
+ const daemonPost = (pathAndQuery) => restartService.post(pathAndQuery);
840
+
841
+ const LIVE_SCRIPT = `<div id="live" class="dim" style="margin-top:8px">脚本未加载</div>`
842
+ + `<script src="/dsh_homing/restart.js"></script>`;
843
+
844
+ function renderRestartPage({ status, sessions, message, confirmForce }) {
845
+ const running = status?.running ?? false;
846
+ const paused = status?.paused ?? false;
847
+ const left = status?.pausedSecondsLeft ?? 0;
848
+ const busyList = sessions.length
849
+ ? '<ul>' + sessions.map((s) => '<li><b>' + escapeHtml(s.title || '(未命名会话)') + '</b> · ' + s.age + ' 秒前' + (s.cwd ? '<br><span class="dim">' + escapeHtml(s.cwd) + '</span>' : '') + '</li>').join('') + '</ul>'
850
+ : '<p class="dim" style="margin:6px 0 0">无</p>';
851
+
852
+ const confirmBlock = confirmForce
853
+ ? '<div class="card warn"><div class="row"><span class="k">确认强制重启</span></div>'
854
+ + '<p class="dim">以下 ' + sessions.length + ' 个会话正在运行,强制重启会立即中断它们:</p>' + busyList
855
+ + '<form method="post" action="/dsh_homing/restart/do">'
856
+ + '<input type="hidden" name="action" value="force"><input type="hidden" name="confirm" value="1">'
857
+ + '<button class="danger" type="submit">确认中断并强制重启</button></form>'
858
+ + '<form method="get" action="/dsh_homing/restart"><button class="ghost" type="submit">取消</button></form></div>'
859
+ : '';
860
+
861
+ return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
862
+ + '<meta name="viewport" content="width=device-width,initial-scale=1">'
863
+ + '<title>重启 DSH</title><style>'
864
+ + 'body{background:#12161d;color:#dbe2ea;font:15px/1.55 system-ui;margin:0;padding:16px}'
865
+ + 'h1{font-size:19px;margin:0 0 6px}.dim{color:#8b93a1;font-size:13px}'
866
+ + '.card{background:#1a1f27;border:1px solid #2b3340;border-radius:10px;padding:14px;margin-bottom:12px}'
867
+ + '.warn{border-color:#7a5a2c}.k{color:#8b93a1;font-size:12px;margin-right:8px}.v{font-weight:600}'
868
+ + 'button{width:100%;margin-top:10px;padding:12px;border-radius:8px;border:0;font-size:15px;font-weight:600}'
869
+ + '.primary{background:#4f7cff;color:#fff}.ghost{background:#2a2f3a;color:#c7cdd8}'
870
+ + '.danger{background:#7a2c34;color:#ffd7dc}'
871
+ + 'input{width:100%;box-sizing:border-box;padding:11px;border-radius:8px;border:1px solid #39424f;background:#0f1319;color:#e6edf5;font-size:15px;margin-top:8px}'
872
+ + 'ul{margin:8px 0 0;padding-left:18px;color:#ffcdd2;font-size:13px}li{margin-bottom:6px}'
873
+ + 'a{color:#8ab4f8}.msg{background:#243447;border-radius:8px;padding:10px;margin-bottom:12px;font-size:14px}'
874
+ + '</style></head><body>'
875
+ + '<meta name="restart-state" content="/dsh_homing/restart/state" id="restart-state-url">'
876
+ + '<h1>重启 DSH</h1><p class="dim">普通重启会等到所有会话结束、且安静满 5 秒;强制重启立即中断。</p>'
877
+ + (message ? '<div class="msg">' + escapeHtml(message) + '</div>' : '')
878
+ + confirmBlock
879
+ + '<div class="card"><div class="row"><span class="k">守护进程</span><span class="v" id="sup-state">' + (running ? ('运行中 · 重启 ' + (status?.daemon?.restarts ?? 0) + ' 次' + (paused ? (' · 暂停剩 ' + left + ' 秒') : '')) : '未运行') + '</span></div>'
880
+ + '<div style="margin-top:8px"><span class="k">重启队列</span><span class="v" id="queue-state">'
881
+ + (() => { const p = restartPolicy.status(); return p.active ? ('排队中 · ' + escapeHtml(p.reason || '等待空闲')) : '未排队'; })()
882
+ + '</span></div>'
883
+ + '<div style="margin-top:8px"><span class="k">当前策略</span><span class="v" id="policy-state">'
884
+ + (() => { const c = restartPolicy.status()?.config ?? {}; return escapeHtml((c.name || 'default') + ' · 安静 ' + Math.round((c.quietMs ?? 0) / 1000) + ' 秒 · 轮询 ' + Math.round((c.pollMs ?? 0) / 1000) + ' 秒'); })()
885
+ + '</span></div>'
886
+ + '<div style="margin-top:8px"><span class="k">繁忙</span><span class="v" id="busy-state">' + (sessions.length ? ('是(' + sessions.length + ' 个会话运行中)') : '否(空闲)') + '</span></div>'
887
+ + '<ul id="busy-list" style="margin:8px 0 0;padding-left:18px;font-size:13px;color:#ffcdd2">' + sessions.map((s) => '<li><b>' + escapeHtml(s.title || '(未命名会话)') + '</b> · ' + s.age + ' 秒前' + (s.cwd ? '<br><span class="dim">' + escapeHtml(s.cwd) + '</span>' : '') + '</li>').join('') + '</ul></div>'
888
+ + '<div class="card"><form method="post" action="/dsh_homing/restart/do">'
889
+ + '<input type="hidden" name="action" value="normal">'
890
+ + '<button class="primary" type="submit" id="btn-normal">重启(等空闲)</button></form>'
891
+ + '<form method="post" action="/dsh_homing/restart/do" id="force-form">'
892
+ + '<input type="hidden" name="action" value="force"><input type="hidden" name="token" value="' + escapeHtml(policyToken()) + '"><input type="hidden" name="confirm" value="1">'
893
+ + '<button class="danger" type="submit" id="btn-force">立即强制重启</button>'
894
+ + '<div id="force-confirm" style="display:none">'
895
+ + '<p class="dim" style="margin:6px 0">强制重启会立即中断正在运行的会话。5 秒内不确认将自动取消。</p>'
896
+ + '<button class="danger" type="submit" id="btn-force-confirm">确认重启</button>'
897
+ + '<button class="ghost" type="button" id="btn-force-cancel">取消</button>'
898
+ + '</div>'
899
+ + '</form>'
900
+ + '<p class="dim" style="margin-top:8px">点「立即强制重启」后,需在 5 秒内再次确认才会真正重启。</p></div>'
901
+ + '<div class="card"><form method="post" action="/dsh_homing/restart/do">'
902
+ + '<input type="hidden" name="action" value="pause">'
903
+ + '<input id="pause-min" name="minutes" type="number" min="1" step="1" placeholder="暂停分钟数(必填)" required>'
904
+ + '<button class="ghost" type="submit">暂停自动拉起</button></form>'
905
+ + '<form method="post" action="/dsh_homing/restart/do">'
906
+ + '<input type="hidden" name="action" value="resume">'
907
+ + '<button class="ghost" type="submit">恢复自动拉起</button></form></div>'
908
+ + (autostartState().configured || autostartState().dismissed ? ''
909
+ : '<div class="card"><div class="row"><span class="k">开机自启</span><span class="v">未设置</span></div>'
910
+ + '<p class="dim" style="margin:6px 0 0">设置后,登录系统时守护进程自动启动,DSH 崩溃可被自动拉起。</p>'
911
+ + '<form method="post" action="/dsh_homing/autostart" style="display:inline">'
912
+ + '<input type="hidden" name="action" value="install">'
913
+ + '<button class="primary" type="submit">启用开机自启</button></form>'
914
+ + '<form method="post" action="/dsh_homing/autostart" style="display:inline">'
915
+ + '<input type="hidden" name="action" value="dismiss">'
916
+ + '<button class="ghost" type="submit">以后再说</button></form></div>')
917
+ + LIVE_SCRIPT
918
+ + '<p class="dim"><a href="/">← 返回 DSH</a> · <a href="/files">文件</a> · <a href="/git">Git</a> · <a href="/term">终端</a> · <a href="/debug">调试</a></p>'
919
+ + '</body></html>';
920
+ }
921
+
744
922
  const DEBUG_HTML = `<!doctype html>
745
923
  <html lang="zh-CN"><head><meta charset="utf-8">
746
924
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -813,6 +991,8 @@ const DEBUG_HTML = `<!doctype html>
813
991
  <div class="row"><span class="k">最近错误</span><span class="v">{{errors}}</span></div>
814
992
  </div>
815
993
 
994
+ {{inbox}}
995
+
816
996
  <h2>快捷入口</h2>
817
997
  <div class="card">
818
998
  <a class="btn ghost" href="/dsh_homing/account">账户设置</a>
@@ -918,6 +1098,201 @@ const ACCOUNT_HTML = `<!doctype html>
918
1098
  <p><a href="/">← 返回 DSH</a></p>
919
1099
  </div></body></html>`;
920
1100
 
1101
+
1102
+ // ---------- 重启界面的 SSE 推送 ----------
1103
+ // 事件驱动:会话/输入变化、重启动作发生时立即广播;另每 5 秒兜底一次。
1104
+ const sseClients = new Set();
1105
+ const ackCounts = new Map();
1106
+ let watchersStarted = false;
1107
+ let broadcastTimer = null;
1108
+
1109
+ function sessionRunning(dshHomeDir) {
1110
+ const dir = path.join(dshHomeDir, 'storages', 'session_projcache', 'sessions');
1111
+ const now = Date.now();
1112
+ const out = [];
1113
+ let entries = [];
1114
+ try { entries = fs.readdirSync(dir) } catch { return out }
1115
+ for (const name of entries) {
1116
+ if (!name.endsWith('.json')) continue;
1117
+ const full = path.join(dir, name);
1118
+ let stat = null;
1119
+ try { stat = fs.statSync(full) } catch { continue }
1120
+ // 5 分钟没写入的会话视为残留,不再阻塞/显示
1121
+ if (now - stat.mtimeMs > 5 * 60_000) continue;
1122
+ let json = null;
1123
+ try { json = JSON.parse(fs.readFileSync(full, 'utf8')) } catch { continue }
1124
+ const rows = json?.record?.rows ?? {};
1125
+ const boundary = rows?.turnBoundary?.val ?? {};
1126
+ const kind = boundary?.lastStepBoundary?.kind ?? null;
1127
+ const openTurn = boundary?.openTurnStartSeq ?? null;
1128
+ if (!(kind === 'start' || openTurn !== null)) continue;
1129
+ out.push({
1130
+ id: name.replace(/^session-|\.json$/gu, ''),
1131
+ title: rows?.title?.val ?? '',
1132
+ cwd: json?.record?.identity?.cwd ?? '',
1133
+ step: kind,
1134
+ age: Math.round(((now - stat.mtimeMs) / 1000) * 10) / 10,
1135
+ });
1136
+ }
1137
+ return out;
1138
+ }
1139
+ async function collectRestartState(dataDir) {
1140
+ const sessions = sessionRunning(path.resolve(dataDir, '..', '..'));
1141
+ const status = await daemonStatus();
1142
+ const policyStatus = restartPolicy.status();
1143
+ const config = policyStatus?.config ?? null;
1144
+ return {
1145
+ config,
1146
+ policy: {
1147
+ active: policyStatus?.active === true,
1148
+ reason: policyStatus?.reason ?? '',
1149
+ waitedSeconds: policyStatus?.waitedSeconds ?? 0,
1150
+ busy: policyStatus?.busy === true,
1151
+ },
1152
+ running: status?.running ?? false,
1153
+ restarts: status?.daemon?.restarts ?? 0,
1154
+ paused: status?.paused ?? false,
1155
+ pausedSecondsLeft: status?.pausedSecondsLeft ?? 0,
1156
+ busy: sessions.length > 0,
1157
+ sessions: sessions.map((s) => ({ title: s.title || '', cwd: s.cwd || '', age: s.age })),
1158
+ };
1159
+ }
1160
+
1161
+ let lastPayload = '';
1162
+ let lastPushAt = 0;
1163
+
1164
+ async function broadcastRestartState(dataDir, extra) {
1165
+ if (sseClients.size === 0) return;
1166
+ const payload = JSON.stringify({ ...(await collectRestartState(dataDir)), ...(extra ?? {}) });
1167
+ const now = Date.now();
1168
+ const changed = payload !== lastPayload;
1169
+ // 内容变了立即推;内容没变但 15 秒没发字节,就发一个注释行保暖(防止 NAT 清表)
1170
+ if (!changed && now - lastPushAt < 15000) return;
1171
+ lastPayload = payload;
1172
+ lastPushAt = now;
1173
+ for (const res of [...sseClients]) {
1174
+ try { res.write((changed ? 'data: ' + payload : ': ping') + '\n\n') } catch { sseClients.delete(res) }
1175
+ }
1176
+ }
1177
+
1178
+ // 目录变化(会话开始/结束、输入)后 300ms 合并广播一次
1179
+ function watchRestartSources(dataDir) {
1180
+ const schedule = () => {
1181
+ if (broadcastTimer) return;
1182
+ broadcastTimer = setTimeout(() => { broadcastTimer = null; void broadcastRestartState(dataDir) }, 300);
1183
+ };
1184
+ const sessions = path.join(path.resolve(dataDir, '..', '..'), 'storages', 'session_projcache', 'sessions');
1185
+ const beacon = path.join(dataDir, 'activity.json');
1186
+ try { fs.watch(sessions, schedule) } catch { /* 目录可能不存在 */ }
1187
+ try { fs.watch(beacon, schedule) } catch { /* 文件可能不存在 */ }
1188
+ setInterval(() => { void broadcastRestartState(dataDir) }, 5000);
1189
+ }
1190
+
1191
+ // ---------- 重启策略(业务层,从守护进程迁出) ----------
1192
+ const restartPolicy = createRestartPolicy({
1193
+ busySessions: () => sessionRunning(path.resolve(dataDir(), '..', '..')),
1194
+ lastActivityAt: () => {
1195
+ try {
1196
+ const raw = JSON.parse(fs.readFileSync(path.join(dataDir(), 'activity.json'), 'utf8'));
1197
+ return Number(raw.at) || 0;
1198
+ } catch { return 0 }
1199
+ },
1200
+ triggerRestart: () => daemonPost('/restart-now'),
1201
+ // 策略来自配置文件(可热更新;写坏时保留上次有效配置)
1202
+ specPath: path.join(dataDir(), 'policy.json'),
1203
+ log: (message) => appendAudit(dataDir(), 'restart-policy', { message }),
1204
+ audit: (event, data) => appendAudit(dataDir(), event, data),
1205
+ });
1206
+
1207
+ // ---------- 调试收件箱(方案 A:文件中转,绕开 DSH 内部协议) ----------
1208
+ function listSessionsForDebug(dshHomeDir) {
1209
+ const dir2 = path.join(dshHomeDir, 'storages', 'session_projcache', 'sessions');
1210
+ const out = [];
1211
+ try {
1212
+ for (const name of fs.readdirSync(dir2)) {
1213
+ if (!name.endsWith('.json')) continue;
1214
+ try {
1215
+ const rows = JSON.parse(fs.readFileSync(path.join(dir2, name), 'utf8'))?.record?.rows ?? {};
1216
+ out.push({ id: name.replace(/^session-|\.json$/gu, ''), title: rows?.title?.val ?? '' });
1217
+ } catch { /* 跳过 */ }
1218
+ }
1219
+ } catch { /* 没目录 */ }
1220
+ return out.sort((a, b) => (b.title ? 1 : 0) - (a.title ? 1 : 0));
1221
+ }
1222
+
1223
+ function inboxPaths(dataDir) {
1224
+ const base = path.join(dataDir, 'debug-inbox');
1225
+ return {
1226
+ base,
1227
+ messages: path.join(base, 'messages.json'),
1228
+ uploads: path.join(base, 'uploads'),
1229
+ };
1230
+ }
1231
+
1232
+ function readJsonArray(file) {
1233
+ try {
1234
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
1235
+ return Array.isArray(value) ? value : [];
1236
+ } catch { return [] }
1237
+ }
1238
+
1239
+ function writeJson(file, value) {
1240
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1241
+ fs.writeFileSync(file, JSON.stringify(value, null, 2), 'utf8');
1242
+ }
1243
+
1244
+ // 解析 multipart/form-data(只处理文本字段与文件字段)
1245
+ function parseMultipart(buffer, boundary) {
1246
+ const fields = {};
1247
+ const files = [];
1248
+ const delim = Buffer.from('--' + boundary);
1249
+ const chunks = [];
1250
+ let index = 0;
1251
+ while (true) {
1252
+ const next = buffer.indexOf(delim, index);
1253
+ if (next < 0) break;
1254
+ chunks.push(buffer.subarray(index, next));
1255
+ index = next + delim.length;
1256
+ }
1257
+ const parts = chunks.map((c) => c.toString('latin1'));
1258
+ for (const part of parts) {
1259
+ const trimmed = part.trim();
1260
+ if (!trimmed || trimmed === '--') continue;
1261
+ const split = part.indexOf('\r\n\r\n');
1262
+ if (split < 0) continue;
1263
+ const head = part.slice(0, split);
1264
+ const content = part.slice(split + 4, part.endsWith('\r\n') ? -2 : undefined);
1265
+ const name = /name="([^"]+)"/u.exec(head)?.[1];
1266
+ if (!name) continue;
1267
+ const filename = /filename="([^"]*)"/u.exec(head)?.[1];
1268
+ if (filename) {
1269
+ if (filename) files.push({ name, filename, data: Buffer.from(content, 'binary') });
1270
+ } else {
1271
+ fields[name] = Buffer.from(content, 'binary').toString('utf8');
1272
+ }
1273
+ }
1274
+ return { fields, files };
1275
+ }
1276
+
1277
+ function renderInbox(entries, sessions) {
1278
+ const options = sessions.map((s) => '<option value="' + escapeHtml(s.id) + '">' + escapeHtml(s.title || s.id) + '</option>').join('');
1279
+ const rows = entries.map((m) => {
1280
+ const images = (m.images ?? []).map((img) => '<div><a href="/dsh_homing/debug/inbox/' + encodeURIComponent(m.id) + '/' + encodeURIComponent(img) + '">' + escapeHtml(img) + '</a></div>').join('');
1281
+ const reply = m.reply ? '<div class="reply"><span class="k">回复</span><div>' + escapeHtml(m.reply).replaceAll('\n', '<br>') + '</div></div>' : '<div class="dim">等待回复…</div>';
1282
+ return '<div class="card"><div class="dim">' + escapeHtml(m.at) + ' · 会话 ' + escapeHtml(m.sessionTitle || m.sessionId || '-') + (m.images?.length ? ' · ' + m.images.length + ' 张图片' : '') + '</div>'
1283
+ + '<div class="text">' + escapeHtml(m.text || '').replaceAll('\n', '<br>') + '</div>' + images + reply + '</div>';
1284
+ }).join('');
1285
+ return '<h2>调试收件箱</h2>'
1286
+ + '<div class="card"><form method="post" action="/dsh_homing/debug/send" enctype="multipart/form-data">'
1287
+ + '<div class="row"><span class="k">目标会话</span></div>'
1288
+ + '<select name="sessionId" style="width:100%;padding:10px;border-radius:8px;border:1px solid #39424f;background:#0f1319;color:#e6edf5;margin-top:6px">' + options + '</select>'
1289
+ + '<textarea name="text" rows="4" placeholder="要发给会话的内容(可留空,仅传图片)" style="width:100%;box-sizing:border-box;margin-top:8px;padding:10px;border-radius:8px;border:1px solid #39424f;background:#0f1319;color:#e6edf5;font-size:15px"></textarea>'
1290
+ + '<input type="file" name="images" accept="image/*" multiple style="margin-top:8px;color:#c7cdd8">'
1291
+ + '<button class="btn primary" type="submit" style="margin-top:10px;width:100%">发送到收件箱</button>'
1292
+ + '</form><p class="sub" style="margin-top:8px">文字与图片会存到插件数据目录;会话侧读取后回复会显示在下方。</p></div>'
1293
+ + '<h2>消息(最近 20 条)</h2>' + (rows || '<p class="sub">还没有消息。</p>');
1294
+ }
1295
+
921
1296
  function escapeHtml(value) {
922
1297
  return String(value)
923
1298
  .replaceAll('&', '&amp;')
@@ -1037,7 +1412,7 @@ function sendLogin(res, message = '', requireTotp = false) {
1037
1412
  'cache-control': 'no-store',
1038
1413
  // 登录页的安全头:禁止被嵌入(防点击劫持)、禁止外链、限制表单只能提交给自己
1039
1414
  'x-frame-options': 'DENY',
1040
- '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:",
1415
+ '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:",
1041
1416
  'x-content-type-options': 'nosniff',
1042
1417
  'referrer-policy': 'no-referrer',
1043
1418
  });
@@ -1059,6 +1434,20 @@ function clientKey(req) {
1059
1434
  return socket;
1060
1435
  }
1061
1436
 
1437
+ function readBodyBuffer(req, limit) {
1438
+ return new Promise((resolve) => {
1439
+ let size = 0;
1440
+ const chunks = [];
1441
+ req.on('data', (chunk) => {
1442
+ size += chunk.length;
1443
+ if (size > limit) { req.destroy(); resolve(Buffer.alloc(0)); return }
1444
+ chunks.push(chunk);
1445
+ });
1446
+ req.on('end', () => resolve(Buffer.concat(chunks)));
1447
+ req.on('error', () => resolve(Buffer.alloc(0)));
1448
+ });
1449
+ }
1450
+
1062
1451
  function readBody(req, limit = 8192) {
1063
1452
  return new Promise((resolve) => {
1064
1453
  let size = 0;
@@ -1170,11 +1559,6 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1170
1559
  return Buffer.from(auth.sessionKey, 'base64');
1171
1560
  }
1172
1561
 
1173
- function signEntry(expiresAt) {
1174
- const body = base64url(String(expiresAt));
1175
- const mac = base64url(crypto.createHmac('sha256', entryKey()).update(`entry:${body}`).digest());
1176
- return `${body}.${mac}`;
1177
- }
1178
1562
 
1179
1563
  /** 校验令牌,返回到期时间;伪造、残缺、过期一律返回 0。 */
1180
1564
  function entryExpiry(value) {
@@ -1276,10 +1660,41 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1276
1660
  const touchActivity = createActivityRecorder(dir);
1277
1661
 
1278
1662
  const handler = async (req, res) => {
1663
+ // 每个响应生成一次性 nonce:内联脚本必须带 nonce 才能执行,
1664
+ // 攻击者注入的脚本没有 nonce,即使 HTML 转义出漏洞也跑不起来。
1665
+ const nonce = crypto.randomBytes(16).toString('base64url');
1666
+ let responseType = '';
1667
+ const rawWriteHead = res.writeHead.bind(res);
1668
+ res.writeHead = (status, headers, ...rest) => {
1669
+ if (headers && typeof headers === 'object' && typeof headers['content-type'] === 'string') {
1670
+ responseType = headers['content-type'];
1671
+ }
1672
+ if (headers && typeof headers === 'object' && typeof headers['content-security-policy'] === 'string') {
1673
+ headers = {
1674
+ ...headers,
1675
+ 'content-security-policy': headers['content-security-policy'].replace(
1676
+ "script-src 'self'",
1677
+ `script-src 'self' 'nonce-${nonce}'`,
1678
+ ),
1679
+ };
1680
+ }
1681
+ return rawWriteHead(status, headers, ...rest);
1682
+ };
1683
+ const rawEnd = res.end.bind(res);
1684
+ res.end = (body, ...rest) => {
1685
+ const type = responseType || String(res.getHeader('content-type') ?? '');
1686
+ if (typeof body === 'string' && type.includes('text/html')) {
1687
+ body = body.replaceAll('<script', `<script nonce="${nonce}"`);
1688
+ }
1689
+ return rawEnd(body, ...rest);
1690
+ };
1691
+
1279
1692
 
1280
1693
  const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
1281
- // 任何来自浏览器的请求都算"人在用"(静态资源除外,避免预加载把空闲判断拖长)
1282
- if (!/^\/(?:dsh_homing\/alive|assets?\/|favicon)/u.test(url.pathname)) touchActivity('request');
1694
+ // 只有"人会做"的请求才算活跃。
1695
+ // 排除:SSE 长连接与其 2 秒回执、状态轮询、静态资源、alive 信标——
1696
+ // 否则页面开着就会不停刷新活动时间,安静窗口永远满足不了。
1697
+ if (!/^\/(?:dsh_homing\/alive|dsh_homing\/restart(?:\/(?:ack|events|state)|\.js)|assets?\/|favicon)/u.test(url.pathname)) touchActivity('request');
1283
1698
  // 写操作来源校验:
1284
1699
  // - 代理到 DSH 的请求必须严格校验(代理会改写 Origin/Referer,上游的同源检查形同虚设);
1285
1700
  // - 本插件自己的页面(登录/账户/设备)只记录不阻断:它的 Cookie 都是 SameSite=Lax,
@@ -1308,6 +1723,310 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1308
1723
  }
1309
1724
  }
1310
1725
 
1726
+ // 守护进程控制代理(同源):/dsh_homing/restart-daemon/status|restart|pause|resume|stop
1727
+ if (url.pathname.startsWith('/dsh_homing/restart-daemon/')) {
1728
+ const rest = url.pathname.slice('/dsh_homing/restart-daemon/'.length);
1729
+ // 只放行只读状态;所有变更类操作必须走策略层,禁止借代理直连守护进程
1730
+ if (!rest.startsWith('status')) {
1731
+ res.writeHead(403, { 'content-type': 'application/json; charset=utf-8' });
1732
+ res.end(JSON.stringify({ error: '变更类操作请走策略层接口(/dsh_homing/restart/*)' }));
1733
+ return;
1734
+ }
1735
+ const upstream = http.request({
1736
+ host: '127.0.0.1',
1737
+ port: RESTART_DAEMON_PORT,
1738
+ path: '/' + rest + (url.search ?? ''),
1739
+ method: req.method,
1740
+ timeout: 8000,
1741
+ }, (up) => {
1742
+ res.writeHead(up.statusCode ?? 502, { 'content-type': up.headers['content-type'] ?? 'application/json', 'cache-control': 'no-store' });
1743
+ up.pipe(res);
1744
+ });
1745
+ upstream.on('timeout', () => { upstream.destroy(); res.writeHead(504).end('restart-daemon timeout'); });
1746
+ upstream.on('error', () => { res.writeHead(502, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: '守护进程未运行' })); });
1747
+ upstream.end();
1748
+ return;
1749
+ }
1750
+
1751
+
1752
+
1753
+
1754
+ // 会话繁忙度:以会话文件里的 turnBoundary 为准(step=start 即运行中),
1755
+ // mtime 只用于排除陈年残留会话。
1756
+
1757
+ // 会话繁忙度:以会话文件里的 turnBoundary 为准(step=start 即运行中)
1758
+
1759
+ // 重启页面的客户端脚本(外部文件,script-src 'self' 直接放行)
1760
+ if (url.pathname === '/dsh_homing/restart.js' && req.method === 'GET') {
1761
+ try {
1762
+ const js = fs.readFileSync(new URL('./restart/client.mjs', import.meta.url), 'utf8');
1763
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
1764
+ res.end(js);
1765
+ } catch (error) {
1766
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
1767
+ res.end('restart.js 读取失败:' + error.message);
1768
+ }
1769
+ return;
1770
+ }
1771
+
1772
+ // 开机自启:页面上的"启用 / 以后再说"
1773
+ if (url.pathname === '/dsh_homing/autostart' && req.method === 'POST') {
1774
+ const form = new URLSearchParams(await readBody(req, 4096));
1775
+ const action = form.get('action') ?? '';
1776
+ let message = '';
1777
+ if (action === 'install') {
1778
+ const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), 'restart-daemon', 'cli.mjs');
1779
+ const result = spawnSync(process.execPath, [cli, 'install'], { encoding: 'utf8', timeout: 60_000, windowsHide: true });
1780
+ const ok = result.status === 0;
1781
+ message = ok ? '已设置开机自启' : '设置失败:' + String(result.stderr ?? result.stdout ?? '').trim().split('\n').slice(-2).join(' ');
1782
+ appendAudit(dataDir(), 'autostart-install', { ok });
1783
+ } else if (action === 'dismiss') {
1784
+ try {
1785
+ fs.mkdirSync(dataDir(), { recursive: true });
1786
+ fs.writeFileSync(path.join(dataDir(), 'autostart-dismissed.json'), JSON.stringify({ dismissed: true, at: new Date().toISOString() }, null, 2), 'utf8');
1787
+ } catch { /* 写不了就每次问 */ }
1788
+ message = '已跳过,之后可在命令行运行 dsh-homing-restart install 设置';
1789
+ }
1790
+ res.writeHead(303, { location: '/dsh_homing/restart?m=' + encodeURIComponent(message), 'cache-control': 'no-store' });
1791
+ res.end();
1792
+ return;
1793
+ }
1794
+
1795
+ // 重启排队:交给策略层(等空闲 / 最早 N 秒)判断,满足后由策略调守护进程
1796
+ if (url.pathname === '/dsh_homing/restart/force' && req.method === 'POST') {
1797
+ // 强制重启也只能经策略层:鉴权后交给 restartPolicy.force()
1798
+ const rawBody = await readBody(req, 4096);
1799
+ const fields = new URLSearchParams(rawBody);
1800
+ if (!policyAuthorized(req, fields) && !sessionValid(req)) {
1801
+ appendAudit(dataDir(), 'policy-denied', { path: url.pathname });
1802
+ res.writeHead(401, { 'content-type': 'application/json; charset=utf-8' });
1803
+ res.end(JSON.stringify({ error: '缺少或错误的策略令牌' }));
1804
+ return;
1805
+ }
1806
+ const result = await restartPolicy.force();
1807
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
1808
+ res.end(JSON.stringify(result));
1809
+ return;
1810
+ }
1811
+
1812
+ if (url.pathname === '/dsh_homing/restart/cancel' && req.method === 'POST') {
1813
+ const rawBody = await readBody(req, 4096);
1814
+ const fields = new URLSearchParams(rawBody);
1815
+ if (!policyAuthorized(req, fields) && !sessionValid(req)) {
1816
+ res.writeHead(401, { 'content-type': 'application/json; charset=utf-8' });
1817
+ res.end(JSON.stringify({ error: '缺少或错误的策略令牌' }));
1818
+ return;
1819
+ }
1820
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
1821
+ res.end(JSON.stringify(restartPolicy.cancel()));
1822
+ return;
1823
+ }
1824
+
1825
+ if (url.pathname === '/dsh_homing/restart/queue' && req.method === 'POST') {
1826
+ const rawBody = await readBody(req, 4096);
1827
+ const fields = new URLSearchParams(rawBody);
1828
+ if (!policyAuthorized(req, fields) && !sessionValid(req)) {
1829
+ appendAudit(dataDir(), 'policy-denied', { path: url.pathname });
1830
+ res.writeHead(401, { 'content-type': 'application/json; charset=utf-8' });
1831
+ res.end(JSON.stringify({ error: '缺少或错误的策略令牌' }));
1832
+ return;
1833
+ }
1834
+ const after = Number(fields.get('after') ?? url.searchParams.get('after') ?? '0');
1835
+ const result = restartPolicy.queue(Number.isFinite(after) && after > 0 ? after : 0);
1836
+ appendAudit(dataDir(), 'restart-queue', { after, already: result.already });
1837
+ res.writeHead(202, { 'content-type': 'application/json; charset=utf-8' });
1838
+ res.end(JSON.stringify(result));
1839
+ return;
1840
+ }
1841
+
1842
+ // 重启界面状态推送(SSE):每 2 秒推一次,带序号便于回执核对
1843
+ if (url.pathname === '/dsh_homing/restart/events' && req.method === 'GET') {
1844
+ res.writeHead(200, {
1845
+ 'content-type': 'text/event-stream; charset=utf-8',
1846
+ 'cache-control': 'no-store',
1847
+ connection: 'keep-alive',
1848
+ 'x-accel-buffering': 'no',
1849
+ });
1850
+ const clientId = 'c' + Date.now().toString(36).slice(-5);
1851
+ res.write('retry: 1000\n\n');
1852
+ if (!watchersStarted) { watchersStarted = true; watchRestartSources(dataDir()) }
1853
+ sseClients.add(res);
1854
+ const openedAt = Date.now();
1855
+ appendAudit(dataDir(), 'sse-open', { clients: sseClients.size, client: clientId, ua: String(req.headers['user-agent'] ?? '').slice(0, 60) });
1856
+ let seq = 0;
1857
+ const push = async () => {
1858
+ const state = await collectRestartState(dataDir());
1859
+ seq += 1;
1860
+ try {
1861
+ res.write('data: ' + JSON.stringify({ ...state, seq, client: clientId, ts: Date.now() }) + '\n\n');
1862
+ } catch { sseClients.delete(res) }
1863
+ };
1864
+ void push();
1865
+ const timer = setInterval(() => { void push() }, 2000);
1866
+ req.on('close', () => {
1867
+ clearInterval(timer);
1868
+ sseClients.delete(res);
1869
+ appendAudit(dataDir(), 'sse-close', { client: clientId, seconds: Math.round((Date.now() - openedAt) / 1000), sent: seq, clients: sseClients.size });
1870
+ });
1871
+ return;
1872
+ }
1873
+
1874
+ // 客户端回执:证明"这一刻真的收到了推送"
1875
+ if (url.pathname === '/dsh_homing/restart/ack' && req.method === 'POST') {
1876
+ const raw = await readBody(req, 4096);
1877
+ let ack = {};
1878
+ try { ack = JSON.parse(raw) } catch { /* 忽略坏包 */ }
1879
+ const key = 'ack-' + String(ack.client ?? '?');
1880
+ const count = (ackCounts.get(key) ?? 0) + 1;
1881
+ ackCounts.set(key, count);
1882
+ // 第 1 次和每第 15 次记录,避免日志爆炸
1883
+ if (count === 1 || count % 15 === 0) {
1884
+ appendAudit(dataDir(), 'sse-ack', { client: String(ack.client ?? '?'), seq: ack.seq ?? null, count, latencyMs: ack.ts ? Date.now() - Number(ack.ts) : null });
1885
+ }
1886
+ res.writeHead(204, { 'cache-control': 'no-store' });
1887
+ res.end();
1888
+ return;
1889
+ }
1890
+
1891
+ // 调试收件箱:接收文字 + 图片,落盘供会话侧读取
1892
+ if (url.pathname === '/dsh_homing/debug/send' && req.method === 'POST') {
1893
+ const inbox = inboxPaths(dataDir());
1894
+ const contentType = String(req.headers['content-type'] ?? '');
1895
+ const boundary = /boundary=([^;]+)/u.exec(contentType)?.[1];
1896
+ const raw = await readBodyBuffer(req, 12 * 1024 * 1024);
1897
+ const { fields, files } = boundary ? parseMultipart(raw, boundary) : { fields: {}, files: [] };
1898
+ const messageId = 'm' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
1899
+ fs.mkdirSync(inbox.uploads, { recursive: true });
1900
+ const images = [];
1901
+ for (const file of files) {
1902
+ if (!file.filename || file.data.length === 0) continue;
1903
+ const safe = messageId + '-' + file.filename.replace(/[^\w.-]/gu, '_');
1904
+ fs.writeFileSync(path.join(inbox.uploads, safe), file.data);
1905
+ images.push(safe);
1906
+ }
1907
+ const sessions = listSessionsForDebug(path.resolve(dataDir(), '..', '..'));
1908
+ const sessionId = fields.sessionId ?? '';
1909
+ const entry = {
1910
+ id: messageId,
1911
+ at: new Date().toISOString().replace('T', ' ').slice(0, 19),
1912
+ sessionId,
1913
+ sessionTitle: sessions.find((s) => s.id === sessionId)?.title ?? '',
1914
+ text: fields.text ?? '',
1915
+ images,
1916
+ reply: null,
1917
+ };
1918
+ const all = readJsonArray(inbox.messages);
1919
+ all.push(entry);
1920
+ writeJson(inbox.messages, all);
1921
+ appendAudit(dir, 'debug-inbox', { id: messageId, sessionId, images: images.length });
1922
+ res.writeHead(303, { location: '/debug?m=' + encodeURIComponent('已发送到收件箱'), 'cache-control': 'no-store' });
1923
+ res.end();
1924
+ return;
1925
+ }
1926
+
1927
+ if (url.pathname.startsWith('/dsh_homing/debug/inbox/') && req.method === 'GET') {
1928
+ const inbox = inboxPaths(dataDir());
1929
+ const rest = decodeURIComponent(url.pathname.slice('/dsh_homing/debug/inbox/'.length));
1930
+ const parts = rest.split('/');
1931
+ const file = path.join(inbox.uploads, path.basename(parts[1] ?? ''));
1932
+ if (!fs.existsSync(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); res.end('not found'); return }
1933
+ res.writeHead(200, { 'content-type': 'image/*', 'cache-control': 'private, max-age=60' });
1934
+ fs.createReadStream(file).pipe(res);
1935
+ return;
1936
+ }
1937
+
1938
+ // 重启界面:服务端渲染 + 表单提交(无内联脚本)
1939
+ if (url.pathname === '/dsh_homing/restart' && req.method === 'GET') {
1940
+ const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
1941
+ const status = await daemonStatus();
1942
+ const message = url.searchParams.get('m') ?? '';
1943
+ res.writeHead(200, {
1944
+ 'content-type': 'text/html; charset=utf-8',
1945
+ 'cache-control': 'no-store',
1946
+ 'x-frame-options': 'DENY',
1947
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'",
1948
+ });
1949
+ res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1' }));
1950
+ return;
1951
+ }
1952
+
1953
+ // GET /restart/do 重定向:浏览器刷新/回退会用 GET 请求这个地址
1954
+ if (url.pathname === '/dsh_homing/restart/do' && req.method === 'GET') {
1955
+ res.writeHead(303, { location: '/dsh_homing/restart', 'cache-control': 'no-store' });
1956
+ res.end();
1957
+ return;
1958
+ }
1959
+
1960
+ if (url.pathname === '/dsh_homing/restart/do' && req.method === 'POST') {
1961
+ const form = new URLSearchParams(await readBody(req, 16 * 1024));
1962
+ const action = form.get('action') ?? '';
1963
+ const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
1964
+ let message = '';
1965
+ void broadcastRestartState(dataDir(), { event: 'restart-requested', action });
1966
+ if (action === 'normal') {
1967
+ const result = restartPolicy.queue(0);
1968
+ message = result.accepted ? '已排队:等所有会话结束、且安静满 5 秒后重启' : '排队失败';
1969
+ } else if (action === 'force') {
1970
+ if (sessions.length > 0 && form.get('confirm') !== '1') {
1971
+ // 繁忙:先渲染二次确认页,列出正在运行的会话
1972
+ const status = await daemonStatus();
1973
+ res.writeHead(200, {
1974
+ 'content-type': 'text/html; charset=utf-8',
1975
+ 'cache-control': 'no-store',
1976
+ 'x-frame-options': 'DENY',
1977
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'",
1978
+ });
1979
+ res.end(renderRestartPage({ status, sessions, message: '', confirmForce: true }));
1980
+ return;
1981
+ }
1982
+ const result = await restartPolicy.force();
1983
+ message = result.ok ? '已触发强制重启(策略层已放行)' : '提交失败:守护进程未运行';
1984
+ } else if (action === 'pause') {
1985
+ const minutes = Number(form.get('minutes'));
1986
+ if (!Number.isFinite(minutes) || minutes <= 0) {
1987
+ message = '暂停失败:请填写正整数分钟';
1988
+ } else {
1989
+ const r = await daemonPost('/pause?minutes=' + minutes);
1990
+ message = r.ok ? ('已暂停自动拉起 ' + minutes + ' 分钟') : '暂停失败:守护进程未运行';
1991
+ }
1992
+ } else if (action === 'resume') {
1993
+ const r = await daemonPost('/resume');
1994
+ message = r.ok ? '已恢复自动拉起' : '恢复失败:守护进程未运行';
1995
+ }
1996
+ void broadcastRestartState(dataDir(), { event: 'restart-accepted', action });
1997
+ res.writeHead(303, { location: '/dsh_homing/restart?m=' + encodeURIComponent(message), 'cache-control': 'no-store' });
1998
+ res.end();
1999
+ return;
2000
+ }
2001
+
2002
+ if (url.pathname === '/dsh_homing/restart/state' && req.method === 'GET') {
2003
+ const sup = await daemonStatus();
2004
+ const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
2005
+ const payload = JSON.stringify({
2006
+ 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,
2007
+ busy: sessions.length > 0,
2008
+ policy: restartPolicy.status(),
2009
+ sseClients: sseClients.size,
2010
+ sessions,
2011
+ });
2012
+ const stable = JSON.stringify({
2013
+ running: sup?.running ?? false,
2014
+ restarts: sup?.daemon?.restarts ?? 0,
2015
+ paused: sup?.paused ?? false,
2016
+ busy: sessions.length > 0,
2017
+ sessions: sessions.map((s) => [s.title, s.cwd, s.step]),
2018
+ });
2019
+ const etag = '"' + crypto.createHash('sha1').update(stable).digest('base64url').slice(0, 16) + '"';
2020
+ if (req.headers['if-none-match'] === etag) {
2021
+ res.writeHead(304, { etag, 'cache-control': 'no-store' });
2022
+ res.end();
2023
+ return;
2024
+ }
2025
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', etag, 'cache-control': 'no-store' });
2026
+ res.end(payload);
2027
+ return;
2028
+ }
2029
+
1311
2030
  if (url.pathname === '/dsh_homing/mobile.css') {
1312
2031
  res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' });
1313
2032
  res.end(MOBILE_CSS);
@@ -1421,7 +2140,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1421
2140
  'content-type': 'text/html; charset=utf-8',
1422
2141
  'cache-control': 'no-store',
1423
2142
  'x-frame-options': 'DENY',
1424
- '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:",
2143
+ '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:",
1425
2144
  'x-content-type-options': 'nosniff',
1426
2145
  'referrer-policy': 'no-referrer',
1427
2146
  });
@@ -1445,7 +2164,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1445
2164
  'content-type': 'text/html; charset=utf-8',
1446
2165
  'cache-control': 'no-store',
1447
2166
  'x-frame-options': 'DENY',
1448
- '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:",
2167
+ '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:",
1449
2168
  'x-content-type-options': 'nosniff',
1450
2169
  'referrer-policy': 'no-referrer',
1451
2170
  });
@@ -1539,7 +2258,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1539
2258
  res.end();
1540
2259
  return;
1541
2260
  }
1542
- const dshHomeTerm = path.resolve(dir, '..', '..');
2261
+ const dshHomeTerm = path.resolve(dataDir(), '..', '..');
1543
2262
 
1544
2263
  const sendTerm = (pageHtml) => {
1545
2264
  res.writeHead(200, {
@@ -1721,7 +2440,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1721
2440
  'content-type': 'text/html; charset=utf-8',
1722
2441
  'cache-control': 'no-store',
1723
2442
  'x-frame-options': 'DENY',
1724
- '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:",
2443
+ '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:",
1725
2444
  'x-content-type-options': 'nosniff',
1726
2445
  'referrer-policy': 'no-referrer',
1727
2446
  });
@@ -1729,7 +2448,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1729
2448
  };
1730
2449
 
1731
2450
  if (url.pathname === '/git' && req.method === 'GET') {
1732
- const dshHome = path.resolve(dir, '..', '..');
2451
+ const dshHome = path.resolve(dataDir(), '..', '..');
1733
2452
  const index = filebrowse.workspaceIndex(dshHome);
1734
2453
  const asked = url.searchParams.get('path');
1735
2454
  const gitSession = url.searchParams.get('session');
@@ -1786,7 +2505,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1786
2505
  'content-type': 'text/html; charset=utf-8',
1787
2506
  'cache-control': 'no-store',
1788
2507
  'x-frame-options': 'DENY',
1789
- '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:",
2508
+ '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:",
1790
2509
  'x-content-type-options': 'nosniff',
1791
2510
  'referrer-policy': 'no-referrer',
1792
2511
  });
@@ -1794,7 +2513,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1794
2513
  };
1795
2514
 
1796
2515
  if (url.pathname === '/files' && req.method === 'GET') {
1797
- const dshHome = path.resolve(dir, '..', '..');
2516
+ const dshHome = path.resolve(dataDir(), '..', '..');
1798
2517
  const index = filebrowse.workspaceIndex(dshHome);
1799
2518
  const asked = url.searchParams.get('path');
1800
2519
  const sessionId = url.searchParams.get('session');
@@ -1832,6 +2551,40 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1832
2551
  return;
1833
2552
  }
1834
2553
 
2554
+ if (url.pathname === '/files/delete' && req.method === 'POST') {
2555
+ const form = new URLSearchParams(await readBody(req, 64 * 1024));
2556
+ const target = form.get('path') ?? '';
2557
+ const result = filebrowse.deleteEntry(target);
2558
+ appendAudit(dir, 'file-delete', { target, ok: result.ok, error: result.error ?? null });
2559
+ res.writeHead(303, { location: '/files?path=' + encodeURIComponent(path.dirname(target)), 'cache-control': 'no-store' });
2560
+ res.end();
2561
+ return;
2562
+ }
2563
+
2564
+ if (url.pathname === '/files/paste' && req.method === 'POST') {
2565
+ const form = new URLSearchParams(await readBody(req, 64 * 1024));
2566
+ const src = form.get('src') ?? '';
2567
+ const destDir = form.get('dir') ?? '';
2568
+ const op = form.get('op') === 'cut' ? 'cut' : 'copy';
2569
+ const result = op === 'cut' ? filebrowse.moveInto(src, destDir) : filebrowse.copyInto(src, destDir);
2570
+ appendAudit(dir, op === 'cut' ? 'file-move' : 'file-paste', { src, dir: destDir, ok: result.ok, target: result.path ?? null, error: result.error ?? null });
2571
+ res.writeHead(303, { location: '/files?path=' + encodeURIComponent(destDir), 'cache-control': 'no-store' });
2572
+ res.end();
2573
+ return;
2574
+ }
2575
+
2576
+ if ((url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') && req.method === 'POST') {
2577
+ const form = new URLSearchParams(await readBody(req, 64 * 1024));
2578
+ const targetDir = form.get('dir') ?? '';
2579
+ const name = form.get('name') ?? '';
2580
+ const isDir = url.pathname === '/files/mkdir';
2581
+ const result = filebrowse.createEntry(targetDir, name, isDir);
2582
+ appendAudit(dir, isDir ? 'file-mkdir' : 'file-newfile', { dir: targetDir, name, ok: result.ok, error: result.error ?? null });
2583
+ res.writeHead(303, { location: '/files?path=' + encodeURIComponent(targetDir), 'cache-control': 'no-store' });
2584
+ res.end();
2585
+ return;
2586
+ }
2587
+
1835
2588
  if (url.pathname === '/files/rename' && req.method === 'POST') {
1836
2589
  const form = new URLSearchParams(await readBody(req, 64 * 1024));
1837
2590
  const target = form.get('path') ?? '';
@@ -1909,10 +2662,12 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1909
2662
  'content-type': 'text/html; charset=utf-8',
1910
2663
  'cache-control': 'no-store',
1911
2664
  'x-frame-options': 'DENY',
1912
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
2665
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'self'; form-action 'self'; base-uri 'none'",
1913
2666
  'x-content-type-options': 'nosniff',
1914
2667
  'referrer-policy': 'no-referrer',
1915
2668
  });
2669
+ const inbox = inboxPaths(dataDir());
2670
+ const sessions = listSessionsForDebug(path.resolve(dataDir(), '..', '..'));
1916
2671
  res.end(DEBUG_HTML
1917
2672
  .replaceAll('{{message}}', message ? `<div class="msg">${escapeHtml(message)}</div>` : '')
1918
2673
  .replaceAll('{{version}}', escapeHtml(String(PLUGIN_VERSION)))
@@ -1925,6 +2680,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1925
2680
  .replaceAll('{{toggleAction}}', off ? 'mobile-on' : 'mobile-off')
1926
2681
  .replaceAll('{{toggleLabel}}', off ? '重新启用移动端样式' : '关闭移动端样式(回到原生布局)')
1927
2682
  .replaceAll('{{toggleClass}}', off ? '' : 'danger')
2683
+ .replaceAll('{{inbox}}', renderInbox(readJsonArray(inbox.messages).slice(-20).reverse(), sessions))
1928
2684
  .replaceAll('{{cssInfo}}', `${MOBILE_CSS.length} 字节`)
1929
2685
  .replaceAll('{{jsInfo}}', `${MOBILE_JS.length} 字节`)
1930
2686
  .replaceAll('{{errors}}', errors.length > 0 ? errors.map((line) => escapeHtml(line)).join('<br>') : '无')
@@ -2043,7 +2799,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2043
2799
  'content-type': 'text/html; charset=utf-8',
2044
2800
  'cache-control': 'no-store',
2045
2801
  'x-frame-options': 'DENY',
2046
- '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:",
2802
+ '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:",
2047
2803
  'x-content-type-options': 'nosniff',
2048
2804
  'referrer-policy': 'no-referrer',
2049
2805
  });
@@ -2441,7 +3197,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
2441
3197
  'content-type': 'text/html; charset=utf-8',
2442
3198
  'cache-control': 'no-store',
2443
3199
  'x-frame-options': 'DENY',
2444
- '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:",
3200
+ '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:",
2445
3201
  'x-content-type-options': 'nosniff',
2446
3202
  'referrer-policy': 'no-referrer',
2447
3203
  ...(deviceCookies.length > 0 ? { 'set-cookie': deviceCookies } : {}),
@@ -2744,8 +3500,8 @@ function createTunnel({ getConfig, dir }) {
2744
3500
  '-o', 'BatchMode=yes',
2745
3501
  '-o', 'PreferredAuthentications=publickey',
2746
3502
  '-o', 'ExitOnForwardFailure=yes',
2747
- '-o', 'ServerAliveInterval=30',
2748
- '-o', 'ServerAliveCountMax=3',
3503
+ '-o', 'ServerAliveInterval=15',
3504
+ '-o', 'ServerAliveCountMax=4',
2749
3505
  '-o', 'StrictHostKeyChecking=accept-new',
2750
3506
  '-R', `127.0.0.1:${config.remotePort}:127.0.0.1:${config.listenPort}`,
2751
3507
  `${config.sshUser}@${config.serverHost}`,