@andy.ian/dsh-homing 2.1.4 → 2.1.6

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 (122) hide show
  1. package/README.md +42 -0
  2. package/SECURITY.md +90 -0
  3. package/bin/backup.mjs +3 -2
  4. package/bin/bootstrap-server.mjs +2 -1
  5. package/bin/inbox.mjs +46 -0
  6. package/bin/renew-cert.mjs +2 -1
  7. package/bin/window-agent-daemon.mjs +268 -0
  8. package/index.js +686 -87
  9. package/lib/compress.mjs +29 -5
  10. package/lib/exec-path.mjs +85 -0
  11. package/lib/files-page.mjs +27 -2
  12. package/lib/files.mjs +3 -2
  13. package/lib/git.mjs +5 -2
  14. package/lib/guard.mjs +43 -0
  15. package/lib/local-socket.mjs +50 -0
  16. package/lib/log-file.mjs +50 -0
  17. package/lib/node-runtime.mjs +44 -0
  18. package/lib/office.mjs +133 -0
  19. package/lib/orientation.mjs +158 -0
  20. package/lib/pty.mjs +6 -3
  21. package/lib/secret.mjs +46 -0
  22. package/lib/shells.mjs +2 -1
  23. package/lib/term-page.mjs +2 -0
  24. package/lib/vendor/des-vnc.mjs +266 -0
  25. package/lib/vendor/novnc/LICENSE.txt +62 -0
  26. package/lib/vendor/novnc/core/base64.js +104 -0
  27. package/lib/vendor/novnc/core/crypto/aes.js +178 -0
  28. package/lib/vendor/novnc/core/crypto/bigint.js +34 -0
  29. package/lib/vendor/novnc/core/crypto/crypto.js +90 -0
  30. package/lib/vendor/novnc/core/crypto/des.js +330 -0
  31. package/lib/vendor/novnc/core/crypto/dh.js +55 -0
  32. package/lib/vendor/novnc/core/crypto/md5.js +82 -0
  33. package/lib/vendor/novnc/core/crypto/rsa.js +132 -0
  34. package/lib/vendor/novnc/core/decoders/copyrect.js +27 -0
  35. package/lib/vendor/novnc/core/decoders/h264.js +321 -0
  36. package/lib/vendor/novnc/core/decoders/hextile.js +181 -0
  37. package/lib/vendor/novnc/core/decoders/jpeg.js +161 -0
  38. package/lib/vendor/novnc/core/decoders/raw.js +59 -0
  39. package/lib/vendor/novnc/core/decoders/rre.js +44 -0
  40. package/lib/vendor/novnc/core/decoders/tight.js +393 -0
  41. package/lib/vendor/novnc/core/decoders/tightpng.js +27 -0
  42. package/lib/vendor/novnc/core/decoders/zlib.js +51 -0
  43. package/lib/vendor/novnc/core/decoders/zrle.js +185 -0
  44. package/lib/vendor/novnc/core/deflator.js +84 -0
  45. package/lib/vendor/novnc/core/display.js +578 -0
  46. package/lib/vendor/novnc/core/encodings.js +54 -0
  47. package/lib/vendor/novnc/core/inflator.js +65 -0
  48. package/lib/vendor/novnc/core/input/domkeytable.js +311 -0
  49. package/lib/vendor/novnc/core/input/fixedkeys.js +129 -0
  50. package/lib/vendor/novnc/core/input/gesturehandler.js +567 -0
  51. package/lib/vendor/novnc/core/input/keyboard.js +294 -0
  52. package/lib/vendor/novnc/core/input/keysym.js +616 -0
  53. package/lib/vendor/novnc/core/input/keysymdef.js +688 -0
  54. package/lib/vendor/novnc/core/input/util.js +191 -0
  55. package/lib/vendor/novnc/core/input/vkeys.js +116 -0
  56. package/lib/vendor/novnc/core/input/xtscancodes.js +173 -0
  57. package/lib/vendor/novnc/core/ra2.js +312 -0
  58. package/lib/vendor/novnc/core/rfb.js +3420 -0
  59. package/lib/vendor/novnc/core/util/browser.js +233 -0
  60. package/lib/vendor/novnc/core/util/cursor.js +249 -0
  61. package/lib/vendor/novnc/core/util/element.js +32 -0
  62. package/lib/vendor/novnc/core/util/events.js +138 -0
  63. package/lib/vendor/novnc/core/util/eventtarget.js +35 -0
  64. package/lib/vendor/novnc/core/util/int.js +15 -0
  65. package/lib/vendor/novnc/core/util/logging.js +56 -0
  66. package/lib/vendor/novnc/core/util/strings.js +28 -0
  67. package/lib/vendor/novnc/core/websock.js +369 -0
  68. package/lib/vendor/novnc/vendor/pako/LICENSE +21 -0
  69. package/lib/vendor/novnc/vendor/pako/README.md +6 -0
  70. package/lib/vendor/novnc/vendor/pako/lib/utils/common.js +45 -0
  71. package/lib/vendor/novnc/vendor/pako/lib/zlib/adler32.js +27 -0
  72. package/lib/vendor/novnc/vendor/pako/lib/zlib/constants.js +47 -0
  73. package/lib/vendor/novnc/vendor/pako/lib/zlib/crc32.js +36 -0
  74. package/lib/vendor/novnc/vendor/pako/lib/zlib/deflate.js +1846 -0
  75. package/lib/vendor/novnc/vendor/pako/lib/zlib/gzheader.js +35 -0
  76. package/lib/vendor/novnc/vendor/pako/lib/zlib/inffast.js +324 -0
  77. package/lib/vendor/novnc/vendor/pako/lib/zlib/inflate.js +1527 -0
  78. package/lib/vendor/novnc/vendor/pako/lib/zlib/inftrees.js +322 -0
  79. package/lib/vendor/novnc/vendor/pako/lib/zlib/messages.js +11 -0
  80. package/lib/vendor/novnc/vendor/pako/lib/zlib/trees.js +1195 -0
  81. package/lib/vendor/novnc/vendor/pako/lib/zlib/zstream.js +24 -0
  82. package/lib/vendor/vnc.bundle.js +14592 -0
  83. package/lib/vendor/ws/LICENSE +20 -0
  84. package/lib/vendor/ws/index.js +22 -0
  85. package/lib/vendor/ws/lib/buffer-util.js +142 -0
  86. package/lib/vendor/ws/lib/constants.js +19 -0
  87. package/lib/vendor/ws/lib/event-target.js +292 -0
  88. package/lib/vendor/ws/lib/extension.js +203 -0
  89. package/lib/vendor/ws/lib/limiter.js +55 -0
  90. package/lib/vendor/ws/lib/permessage-deflate.js +530 -0
  91. package/lib/vendor/ws/lib/receiver.js +743 -0
  92. package/lib/vendor/ws/lib/sender.js +610 -0
  93. package/lib/vendor/ws/lib/stream.js +161 -0
  94. package/lib/vendor/ws/lib/subprotocol.js +62 -0
  95. package/lib/vendor/ws/lib/validation.js +152 -0
  96. package/lib/vendor/ws/lib/websocket-server.js +562 -0
  97. package/lib/vendor/ws/lib/websocket.js +1426 -0
  98. package/lib/vendor/ws/package.json +74 -0
  99. package/lib/vendor/ws/wrapper.mjs +21 -0
  100. package/lib/vnc-app.js +567 -0
  101. package/lib/vnc-auth-proxy.mjs +179 -0
  102. package/lib/vnc-boot.js +45 -0
  103. package/lib/vnc-page.mjs +77 -0
  104. package/lib/vnc-pointer.mjs +17 -0
  105. package/lib/vnc.mjs +75 -0
  106. package/lib/window-app.js +155 -0
  107. package/lib/window-page.mjs +111 -0
  108. package/lib/window-remote.mjs +227 -0
  109. package/lib/ws-bridge.mjs +130 -0
  110. package/package.json +6 -2
  111. package/permissions.json +91 -0
  112. package/restart/client.mjs +85 -19
  113. package/restart/daemon/cli.mjs +55 -13
  114. package/restart/daemon/lib/detach.mjs +3 -2
  115. package/restart/daemon/lib/process-tree.mjs +17 -3
  116. package/restart/daemon/lib/restart-flow.mjs +36 -0
  117. package/restart/daemon/main.mjs +299 -80
  118. package/restart/engine.mjs +24 -8
  119. package/restart/port.mjs +88 -0
  120. package/restart/runner.mjs +4 -3
  121. package/restart/service.mjs +8 -5
  122. package/restart/watchdog.mjs +134 -0
package/index.js CHANGED
@@ -19,7 +19,10 @@ 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
+ import { createRestartService } from './restart/service.mjs';
23
+ import { resolveRestartPort, isValidRestartPort, writePortOverride, isPortAvailable } from './restart/port.mjs';
24
+ import { findNodeRuntime } from './lib/node-runtime.mjs';
25
+ import { createRestartDaemonWatchdog } from './restart/watchdog.mjs';
23
26
  import zlib from 'node:zlib';
24
27
  import * as deviceStore from './lib/devices.mjs';
25
28
  import * as filebrowse from './lib/files.mjs';
@@ -28,9 +31,21 @@ import { createRestartPolicy } from './restart/face.mjs';
28
31
  import * as ptyrun from './lib/pty.mjs';
29
32
  import { renderTermPage } from './lib/term-page.mjs';
30
33
  import * as compress from './lib/compress.mjs';
34
+ import * as office from './lib/office.mjs';
35
+ import * as windowRemote from './lib/window-remote.mjs';
36
+ import { setOrientation, ensureLandscape } from './lib/orientation.mjs';
37
+ import { protectSecret, unprotectSecret } from './lib/secret.mjs';
38
+ import { startVncAuthProxy } from './lib/vnc-auth-proxy.mjs';
39
+ import { renderWindowPage } from './lib/window-page.mjs';
40
+ import * as vnc from './lib/vnc.mjs';
41
+ import { bridge as bridgeWebSocketToTcp } from './lib/ws-bridge.mjs';
42
+ import { WebSocketServer } from './lib/vendor/ws/wrapper.mjs';
43
+ import { renderVncPage } from './lib/vnc-page.mjs';
31
44
  import { customShells, detectShells, resolveShell, DEFAULT_SHELL } from './lib/shells.mjs';
32
45
  import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage } from './lib/files-page.mjs';
33
46
  import { checkUnsafeOrigin } from './lib/csrf.mjs';
47
+ import { validateOpenPath } from './lib/guard.mjs';
48
+ import { opensslExe, sshExe } from './lib/exec-path.mjs';
34
49
  import * as limits from './lib/limits.mjs';
35
50
 
36
51
  export const name = 'dsh-homing';
@@ -699,92 +714,201 @@ function policyAuthorized(req, fields) {
699
714
  }
700
715
 
701
716
  // 守护进程客户端:具体实现在 restart/service.mjs(唯一出口)
717
+ // 端口可配置:环境变量 > settings.json restartDaemon.port > 8790
718
+ let restartDaemonPort = resolveRestartPort();
702
719
  const restartService = createRestartService({
703
- port: RESTART_DAEMON_PORT,
720
+ port: () => restartDaemonPort,
704
721
  statusTimeoutMs: 3000,
705
722
  postTimeoutMs: 5000,
706
723
  });
707
724
 
725
+ function restartDaemonStateDir() {
726
+ return path.join(process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'), 'restart-daemon');
727
+ }
728
+
729
+ function restartDaemonDisabled() {
730
+ try { return fs.existsSync(path.join(restartDaemonStateDir(), 'disabled.json')) } catch { return false }
731
+ }
732
+
733
+ function readPortConflictMarker() {
734
+ try {
735
+ const data = JSON.parse(fs.readFileSync(path.join(restartDaemonStateDir(), 'port-conflict.json'), 'utf8'));
736
+ if (Date.now() - Date.parse(data.at ?? 0) > 10 * 60_000) return null;
737
+ return data;
738
+ } catch {
739
+ return null;
740
+ }
741
+ }
742
+
743
+ /** 探测"守护进程起不来且端口被别的程序占用" */
744
+ async function detectRestartPortConflict() {
745
+ if (restartDaemonDisabled()) return null;
746
+ const health = await restartService.health();
747
+ if (health && health.ok !== false) return null;
748
+ const marker = readPortConflictMarker();
749
+ if (marker) return { port: Number(marker.port) || restartDaemonPort, occupantPid: marker.occupantPid ?? null };
750
+ // 端口有响应但不是我们的 /health ⇒ 被占用(连接被拒则只是没启动)
751
+ const occupied = await new Promise((resolve) => {
752
+ const request = http.request({ host: '127.0.0.1', port: restartDaemonPort, path: '/health', method: 'GET', timeout: 1500, agent: false }, (res) => {
753
+ res.resume();
754
+ res.on('end', () => resolve(true));
755
+ });
756
+ request.on('timeout', () => { request.destroy(); resolve(false); });
757
+ request.on('error', () => resolve(false));
758
+ request.end();
759
+ });
760
+ return occupied ? { port: restartDaemonPort, occupantPid: null } : null;
761
+ }
762
+
763
+ async function waitRestartDaemonHealthy(timeoutMs = 5000) {
764
+ const deadline = Date.now() + timeoutMs;
765
+ while (Date.now() < deadline) {
766
+ const health = await restartService.health();
767
+ if (health && health.ok !== false) return true;
768
+ await new Promise((resolve) => setTimeout(resolve, 300));
769
+ }
770
+ return false;
771
+ }
772
+
773
+ function restartDaemonCliPath() {
774
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), 'restart', 'daemon', 'cli.mjs');
775
+ }
776
+
777
+ function startRestartDaemonDetached() {
778
+ try {
779
+ const cli = restartDaemonCliPath();
780
+ if (!fs.existsSync(cli)) {
781
+ appendAudit(dataDir(), 'restart-daemon-cli-missing', { cli });
782
+ return false;
783
+ }
784
+ const child = spawn(findNodeRuntime(), [cli, 'start'], { detached: true, stdio: 'ignore', windowsHide: true });
785
+ child.on('error', (error) => { try { appendAudit(dataDir(), 'restart-daemon-spawn-error', { error: String(error?.message ?? error).slice(0, 200) }); } catch { /* 忽略 */ } });
786
+ child.unref();
787
+ return true;
788
+ } catch {
789
+ return false;
790
+ }
791
+ }
792
+
793
+ // 看门狗:守护进程运行中崩溃/被杀后自动拉起(尊重用户主动停止)
794
+ const restartDaemonWatchdog = createRestartDaemonWatchdog({
795
+ service: restartService,
796
+ pluginRoot: path.dirname(fileURLToPath(import.meta.url)),
797
+ dshHome: process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'),
798
+ audit: (event, extra) => {
799
+ try { appendAudit(dataDir(), event, extra ?? {}); } catch { /* 忽略 */ }
800
+ },
801
+ });
802
+ void restartDaemonWatchdog;
803
+
708
804
 
709
805
  const LIVE_SCRIPT = `<div id="live" class="dim" style="margin-top:8px">脚本未加载</div>`
710
806
  + `<script src="/dsh_homing/restart.js"></script>`;
711
807
 
712
- function renderRestartPage({ status, sessions, message, confirmForce }) {
713
- const running = status?.running ?? false;
714
- const paused = status?.paused ?? false;
715
- const left = status?.pausedSecondsLeft ?? 0;
716
- const busyList = sessions.length
717
- ? '<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>'
718
- : '<p class="dim" style="margin:6px 0 0">无</p>';
808
+ function renderRestartPage({ status, sessions, message, confirmForce, portState }) {
809
+ const running = status?.running ?? false
810
+ const paused = status?.paused ?? false
811
+ const left = status?.pausedSecondsLeft ?? 0
812
+ const busy = sessions.length > 0
813
+ const busyItems = sessions.map((s) => '<li><b>' + escapeHtml(s.title || '(未命名会话)') + '</b> · ' + s.age + ' 秒前' + (s.cwd ? ' · ' + escapeHtml(s.cwd) : '') + '</li>').join('')
719
814
 
720
815
  const confirmBlock = confirmForce
721
- ? '<div class="card warn"><div class="row"><span class="k">确认强制重启</span></div>'
722
- + '<p class="dim">以下 ' + sessions.length + ' 个会话正在运行,强制重启会立即中断它们:</p>' + busyList
723
- + '<form method="post" action="/dsh_homing/restart/do">'
816
+ ? '<div class="card warn"><div class="line"><span class="k">确认强制重启</span><span class="v">' + sessions.length + ' 个会话运行中</span></div>'
817
+ + '<ul>' + busyItems + '</ul>'
818
+ + '<div class="grid"><form method="post" action="/dsh_homing/restart/do">'
724
819
  + '<input type="hidden" name="action" value="force"><input type="hidden" name="confirm" value="1">'
725
820
  + '<button class="danger" type="submit">确认中断并强制重启</button></form>'
726
- + '<form method="get" action="/dsh_homing/restart"><button class="ghost" type="submit">取消</button></form></div>'
727
- : '';
821
+ + '<form method="get" action="/dsh_homing/restart"><button class="ghost" type="submit">取消</button></form></div></div>'
822
+ : ''
823
+
824
+ const portCard = (() => {
825
+ if (portState?.conflict) {
826
+ const conflict = portState.conflict
827
+ const next = Number(portState.port) + 1
828
+ const suggested = isValidRestartPort(next) && next !== 8787 ? next : 8791
829
+ return '<div class="card warn"><div class="line"><span class="k">端口冲突</span><span class="v">127.0.0.1:' + escapeHtml(String(conflict.port)) + ' 已被占用' + (conflict.occupantPid ? '(PID ' + escapeHtml(String(conflict.occupantPid)) + ')' : '') + '</span></div>'
830
+ + '<p class="sub" style="margin:4px 0 0">守护进程无法启动。换端口,或关闭重启守护进程。</p>'
831
+ + '<form method="post" action="/dsh_homing/restart/port" class="inline">'
832
+ + '<input name="port" type="number" min="1024" max="65535" value="' + suggested + '" placeholder="新端口" required>'
833
+ + '<button class="primary" type="submit" name="action" value="save">保存并重试</button></form>'
834
+ + '<form method="post" action="/dsh_homing/restart/port" style="margin-top:8px">'
835
+ + '<button class="ghost" type="submit" name="action" value="disable">关闭重启守护进程</button></form></div>'
836
+ }
837
+ if (portState?.disabled) {
838
+ return '<div class="card"><div class="line"><span class="k">重启守护进程</span><span class="v">已关闭</span></div>'
839
+ + '<p class="sub" style="margin:4px 0 0">已关闭:DSH 崩溃后不会被自动拉起。</p>'
840
+ + '<form method="post" action="/dsh_homing/restart/port" style="margin-top:8px">'
841
+ + '<button class="primary" type="submit" name="action" value="enable">重新启用</button></form></div>'
842
+ }
843
+ return ''
844
+ })()
845
+
846
+ const policy = restartPolicy.status()
847
+ const cfg = policy?.config ?? {}
848
+ const nav = '<div class="nav"><a href="/">← 返回 DSH</a><a href="/files">文件</a><a href="/git">Git</a><a href="/term">终端</a><a href="/debug">调试</a></div>'
728
849
 
729
850
  return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
730
851
  + '<meta name="viewport" content="width=device-width,initial-scale=1">'
731
852
  + '<title>重启 DSH</title><style>'
732
- + 'body{background:#12161d;color:#dbe2ea;font:15px/1.55 system-ui;margin:0;padding:16px}'
733
- + 'h1{font-size:19px;margin:0 0 6px}.dim{color:#8b93a1;font-size:13px}'
734
- + '.card{background:#1a1f27;border:1px solid #2b3340;border-radius:10px;padding:14px;margin-bottom:12px}'
735
- + '.warn{border-color:#7a5a2c}.k{color:#8b93a1;font-size:12px;margin-right:8px}.v{font-weight:600}'
736
- + 'button{width:100%;margin-top:10px;padding:12px;border-radius:8px;border:0;font-size:15px;font-weight:600}'
737
- + '.primary{background:#4f7cff;color:#fff}.ghost{background:#2a2f3a;color:#c7cdd8}'
738
- + '.danger{background:#7a2c34;color:#ffd7dc}'
739
- + '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}'
740
- + 'ul{margin:8px 0 0;padding-left:18px;color:#ffcdd2;font-size:13px}li{margin-bottom:6px}'
741
- + 'a{color:#8ab4f8}.msg{background:#243447;border-radius:8px;padding:10px;margin-bottom:12px;font-size:14px}'
853
+ + 'body{background:#12161d;color:#dbe2ea;font:14px/1.45 system-ui,-apple-system,"Noto Sans SC",sans-serif;margin:0 auto;padding:10px 12px 20px;max-width:620px}'
854
+ + 'h1{font-size:17px;margin:0}.sub{color:#8b93a1;font-size:12px;margin:2px 0 8px}'
855
+ + '.nav{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 10px}'
856
+ + '.nav a{color:#c7cdd8;text-decoration:none;font-size:12px;padding:4px 9px;background:#1a1f27;border:1px solid #2b3340;border-radius:6px}'
857
+ + '.card{background:#1a1f27;border:1px solid #2b3340;border-radius:9px;padding:9px 11px;margin-bottom:8px}'
858
+ + '.warn{border-color:#7a5a2c}'
859
+ + '.line{display:flex;justify-content:space-between;gap:10px;align-items:baseline;padding:2px 0;font-size:13px}'
860
+ + '.k{color:#8b93a1;font-size:12px;white-space:nowrap}.v{font-weight:600;text-align:right;word-break:break-word}'
861
+ + '.grid{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:8px}.grid button{margin:0}'
862
+ + 'button{width:100%;padding:9px 10px;border-radius:7px;border:0;font-size:14px;font-weight:600}'
863
+ + '.primary{background:#4f7cff;color:#fff}.ghost{background:#2a2f3a;color:#c7cdd8}.danger{background:#7a2c34;color:#ffd7dc}'
864
+ + 'form{margin:0}'
865
+ + '.inline{display:flex;gap:8px;margin-top:8px}.inline input{flex:1;min-width:0}.inline button{flex:0 0 auto;width:auto}'
866
+ + 'input{width:100%;box-sizing:border-box;padding:9px;border-radius:7px;border:1px solid #39424f;background:#0f1319;color:#e6edf5;font-size:14px}'
867
+ + '.check{display:flex;align-items:center;gap:8px;font-size:13px;color:#c7cdd8;margin:2px 0 8px}'
868
+ + '.check input{width:auto;margin:0;padding:0;transform:scale(1.15)}'
869
+ + 'ul{margin:6px 0 0;padding-left:16px;color:#ffcdd2;font-size:12px}li{margin-bottom:3px}'
870
+ + 'a{color:#8ab4f8}.msg{background:#243447;border-radius:7px;padding:8px 10px;margin-bottom:8px;font-size:13px}'
871
+ + '#live{font-size:12px;margin:4px 0 0}'
742
872
  + '</style></head><body>'
743
873
  + '<meta name="restart-state" content="/dsh_homing/restart/state" id="restart-state-url">'
744
- + '<h1>重启 DSH</h1><p class="dim">普通重启会等到所有会话结束、且安静满 5 秒;强制重启立即中断。</p>'
745
- + (message ? '<div class="msg">' + escapeHtml(message) + '</div>' : '')
874
+ + '<meta name="restart-pending" content="' + (policy?.active ? '1' : '0') + '">'
875
+ + '<h1>重启 DSH</h1><p class="sub">普通重启等会话结束且安静 5 秒;强制重启立即中断。</p>'
876
+ + nav
877
+ + (message ? '<div class="msg" id="restart-msg">' + escapeHtml(message) + '</div>' : '')
746
878
  + confirmBlock
747
- + '<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>'
748
- + '<div style="margin-top:8px"><span class="k">重启队列</span><span class="v" id="queue-state">'
749
- + (() => { const p = restartPolicy.status(); return p.active ? ('排队中 · ' + escapeHtml(p.reason || '等待空闲')) : '未排队'; })()
750
- + '</span></div>'
751
- + '<div style="margin-top:8px"><span class="k">当前策略</span><span class="v" id="policy-state">'
752
- + (() => { const c = restartPolicy.status()?.config ?? {}; return escapeHtml((c.name || 'default') + ' · 安静 ' + Math.round((c.quietMs ?? 0) / 1000) + ' 秒 · 轮询 ' + Math.round((c.pollMs ?? 0) / 1000) + ' 秒'); })()
753
- + '</span></div>'
754
- + '<div style="margin-top:8px"><span class="k">繁忙</span><span class="v" id="busy-state">' + (sessions.length ? ('是(' + sessions.length + ' 个会话运行中)') : '否(空闲)') + '</span></div>'
755
- + '<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>'
756
- + '<div class="card"><form method="post" action="/dsh_homing/restart/do">'
757
- + '<input type="hidden" name="action" value="normal">'
758
- + '<button class="primary" type="submit" id="btn-normal">重启(等空闲)</button></form>'
759
- + '<form method="post" action="/dsh_homing/restart/do" id="force-form">'
760
- + '<input type="hidden" name="action" value="force"><input type="hidden" name="token" value="' + escapeHtml(policyToken()) + '"><input type="hidden" name="confirm" value="1">'
761
- + '<button class="danger" type="submit" id="btn-force">立即强制重启</button>'
762
- + '<div id="force-confirm" style="display:none">'
763
- + '<p class="dim" style="margin:6px 0">强制重启会立即中断正在运行的会话。5 秒内不确认将自动取消。</p>'
764
- + '<button class="danger" type="submit" id="btn-force-confirm">确认重启</button>'
765
- + '<button class="ghost" type="button" id="btn-force-cancel">取消</button>'
766
- + '</div>'
767
- + '</form>'
768
- + '<p class="dim" style="margin-top:8px">点「立即强制重启」后,需在 5 秒内再次确认才会真正重启。</p></div>'
769
- + '<div class="card"><form method="post" action="/dsh_homing/restart/do">'
770
- + '<input type="hidden" name="action" value="pause">'
771
- + '<input id="pause-min" name="minutes" type="number" min="1" step="1" placeholder="暂停分钟数(必填)" required>'
772
- + '<button class="ghost" type="submit">暂停自动拉起</button></form>'
773
- + '<form method="post" action="/dsh_homing/restart/do">'
774
- + '<input type="hidden" name="action" value="resume">'
775
- + '<button class="ghost" type="submit">恢复自动拉起</button></form></div>'
879
+ + '<div class="card">'
880
+ + '<div class="line"><span class="k">守护进程</span><span class="v" id="sup-state">' + (running ? ('运行中 · 重启 ' + (status?.daemon?.restarts ?? 0) + ' 次' + (paused ? (' · 暂停剩 ' + left + ' 秒') : '') + (policy?.active ? (' · 排队已等 ' + (policy.waitedSeconds ?? 0) + ' 秒') : '')) : '未运行') + '</span></div>'
881
+ + '<div class="line"><span class="k">重启队列</span><span class="v" id="queue-state">' + (policy?.active ? ('排队中 · ' + escapeHtml(policy.reason || '等待空闲')) : '未排队') + '</span></div>'
882
+ + '<div class="line"><span class="k">当前策略</span><span class="v" id="policy-state">' + escapeHtml((cfg.name || 'default') + ' · 安静 ' + Math.round((cfg.quietMs ?? 0) / 1000) + ' 秒 · 轮询 ' + Math.round((cfg.pollMs ?? 0) / 1000) + ' 秒') + '</span></div>'
883
+ + '<div class="line"><span class="k">繁忙</span><span class="v" id="busy-state">' + (busy ? ('是(' + sessions.length + ' 个会话运行中)') : '否(空闲)') + '</span></div>'
884
+ + '<ul id="busy-list">' + busyItems + '</ul>'
885
+ + LIVE_SCRIPT
886
+ + '<form method="post" action="/dsh_homing/restart/daemon" style="margin-top:8px"><button class="ghost" type="submit">重启守护进程</button></form>'
887
+ + '</div>'
888
+ + '<div class="card"><form method="post" action="/dsh_homing/restart/do" id="restart-form">'
889
+ + '<input type="hidden" name="action" id="restart-action" value="normal">'
890
+ + '<input type="hidden" name="token" id="restart-token" value="' + escapeHtml(policyToken()) + '">'
891
+ + '<input type="hidden" name="confirm" value="1">'
892
+ + '<label class="check"><input type="checkbox" id="opt-force">立即强制重启(中断正在运行的会话)</label>'
893
+ + '<button class="primary" type="submit" id="btn-restart">重启</button>'
894
+ + '</form>'
895
+ + '<div id="force-confirm" style="display:none">'
896
+ + '<p class="sub" style="margin:6px 0">强制重启会立即中断会话,5 秒内不确认将自动取消。</p>'
897
+ + '<button class="danger" type="button" id="btn-force-confirm">确认强制重启</button>'
898
+ + '<button class="ghost" type="button" id="btn-force-cancel">取消</button>'
899
+ + '</div></div>'
900
+ + '<div class="card"><form method="post" action="/dsh_homing/restart/do" class="inline" style="margin:0">'
901
+ + '<input id="pause-min" name="minutes" type="number" min="1" step="1" placeholder="分钟" required style="flex:0 0 92px">'
902
+ + '<button class="ghost" type="submit" name="action" value="pause">暂停自动拉起</button>'
903
+ + '<button class="ghost" type="submit" name="action" value="resume" formnovalidate>恢复</button></form></div>'
904
+ + portCard
776
905
  + (autostartState().configured || autostartState().dismissed ? ''
777
- : '<div class="card"><div class="row"><span class="k">开机自启</span><span class="v">未设置</span></div>'
778
- + '<p class="dim" style="margin:6px 0 0">设置后,登录系统时守护进程自动启动,DSH 崩溃可被自动拉起。</p>'
779
- + '<form method="post" action="/dsh_homing/autostart" style="display:inline">'
780
- + '<input type="hidden" name="action" value="install">'
906
+ : '<div class="card"><div class="line"><span class="k">开机自启</span><span class="v">未设置</span></div>'
907
+ + '<div class="grid"><form method="post" action="/dsh_homing/autostart"><input type="hidden" name="action" value="install">'
781
908
  + '<button class="primary" type="submit">启用开机自启</button></form>'
782
- + '<form method="post" action="/dsh_homing/autostart" style="display:inline">'
783
- + '<input type="hidden" name="action" value="dismiss">'
784
- + '<button class="ghost" type="submit">以后再说</button></form></div>')
785
- + LIVE_SCRIPT
786
- + '<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>'
787
- + '</body></html>';
909
+ + '<form method="post" action="/dsh_homing/autostart"><input type="hidden" name="action" value="dismiss">'
910
+ + '<button class="ghost" type="submit">以后再说</button></form></div></div>')
911
+ + '</body></html>'
788
912
  }
789
913
 
790
914
  const DEBUG_HTML = `<!doctype html>
@@ -1527,6 +1651,30 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1527
1651
 
1528
1652
  const touchActivity = createActivityRecorder(dir);
1529
1653
 
1654
+ const rateBuckets = new Map();
1655
+ const rateLimited = (key, limit, windowMs) => {
1656
+ const now = Date.now();
1657
+ const bucket = rateBuckets.get(key);
1658
+ if (!bucket || now >= bucket.reset) {
1659
+ rateBuckets.set(key, { count: 1, reset: now + windowMs });
1660
+ return false;
1661
+ }
1662
+ bucket.count += 1;
1663
+ return bucket.count > limit;
1664
+ };
1665
+ const clientKey = (req) => String((req.socket && req.socket.remoteAddress) || 'unknown');
1666
+ let vncPasswordCache = '';
1667
+ async function resolveVncPassword() {
1668
+ if (vncPasswordCache !== '') return vncPasswordCache;
1669
+ const vncConfig = (config && typeof config.vnc === 'object' && config.vnc !== null) ? config.vnc : {};
1670
+ if (typeof vncConfig.passwordEnc === 'string' && vncConfig.passwordEnc !== '') {
1671
+ vncPasswordCache = (await unprotectSecret(vncConfig.passwordEnc)) || '';
1672
+ } else if (typeof vncConfig.password === 'string') {
1673
+ vncPasswordCache = vncConfig.password;
1674
+ }
1675
+ return vncPasswordCache;
1676
+ }
1677
+
1530
1678
  const handler = async (req, res) => {
1531
1679
  // 每个响应生成一次性 nonce:内联脚本必须带 nonce 才能执行,
1532
1680
  // 攻击者注入的脚本没有 nonce,即使 HTML 转义出漏洞也跑不起来。
@@ -1565,10 +1713,10 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1565
1713
 
1566
1714
 
1567
1715
  const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
1568
- // 只有"人会做"的请求才算活跃。
1569
- // 排除:SSE 长连接与其 2 秒回执、状态轮询、静态资源、alive 信标——
1570
- // 否则页面开着就会不停刷新活动时间,安静窗口永远满足不了。
1571
- if (!/^\/(?:dsh_homing\/alive|dsh_homing\/restart(?:\/(?:ack|events|state)|\.js)|assets?\/|favicon)/u.test(url.pathname)) touchActivity('request');
1716
+ // 活跃时间只由"用户真实操作"刷新:手机端键盘/指针/输入事件会 POST /dsh_homing/alive。
1717
+ // 这里不再把任意请求(页面加载、图标、重定向、控制接口)算作用户输入,
1718
+ // 否则打开/刷新页面会不断重置安静窗口,排队等待还会被误报成"最近有用户输入"。
1719
+ ;
1572
1720
  // 写操作来源校验:
1573
1721
  // - 代理到 DSH 的请求必须严格校验(代理会改写 Origin/Referer,上游的同源检查形同虚设);
1574
1722
  // - 本插件自己的页面(登录/账户/设备)只记录不阻断:它的 Cookie 都是 SameSite=Lax,
@@ -1608,7 +1756,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1608
1756
  }
1609
1757
  const upstream = http.request({
1610
1758
  host: '127.0.0.1',
1611
- port: RESTART_DAEMON_PORT,
1759
+ port: restartDaemonPort,
1612
1760
  path: '/' + rest + (url.search ?? ''),
1613
1761
  method: req.method,
1614
1762
  timeout: 8000,
@@ -1649,8 +1797,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1649
1797
  const action = form.get('action') ?? '';
1650
1798
  let message = '';
1651
1799
  if (action === 'install') {
1652
- const cli = path.join(path.dirname(fileURLToPath(import.meta.url)), 'restart-daemon', 'cli.mjs');
1653
- const result = spawnSync(process.execPath, [cli, 'install'], { encoding: 'utf8', timeout: 60_000, windowsHide: true });
1800
+ const cli = restartDaemonCliPath();
1801
+ const result = spawnSync(findNodeRuntime(), [cli, 'install', '--control', String(restartDaemonPort)], { encoding: 'utf8', timeout: 60_000, windowsHide: true });
1654
1802
  const ok = result.status === 0;
1655
1803
  message = ok ? '已设置开机自启' : '设置失败:' + String(result.stderr ?? result.stdout ?? '').trim().split('\n').slice(-2).join(' ');
1656
1804
  appendAudit(dataDir(), 'autostart-install', { ok });
@@ -1820,7 +1968,77 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1820
1968
  'x-frame-options': 'DENY',
1821
1969
  'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'",
1822
1970
  });
1823
- res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1' }));
1971
+ const portState = { conflict: await detectRestartPortConflict(), disabled: restartDaemonDisabled(), port: restartDaemonPort };
1972
+ res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1', portState }));
1973
+ return;
1974
+ }
1975
+
1976
+ // 重启守护进程(用户手动触发)
1977
+ if (url.pathname === '/dsh_homing/restart/daemon' && req.method === 'POST') {
1978
+ let message = '';
1979
+ appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'stop-old' });
1980
+ try { await restartService.stop(); } catch { /* 忽略 */ }
1981
+ appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'stop-old-done' });
1982
+ await new Promise((resolve) => setTimeout(resolve, 600));
1983
+ const started = startRestartDaemonDetached();
1984
+ appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'spawn-new', started });
1985
+ const healthy = await waitRestartDaemonHealthy(6000);
1986
+ appendAudit(dataDir(), 'restart-daemon-manual-restart', { started, healthy });
1987
+ message = healthy ? '守护进程已重启' : '已请求重启守护进程,但未就绪,请查看日志';
1988
+ res.writeHead(303, { location: '/dsh_homing/restart?m=' + encodeURIComponent(message), 'cache-control': 'no-store' });
1989
+ res.end();
1990
+ return;
1991
+ }
1992
+
1993
+ // 守护进程端口配置:保存新端口 / 关闭 / 重新启用
1994
+ if (url.pathname === '/dsh_homing/restart/port' && req.method === 'POST') {
1995
+ const form = new URLSearchParams(await readBody(req, 4096));
1996
+ const action = form.get('action') ?? '';
1997
+ let message = '';
1998
+ if (action === 'save') {
1999
+ const port = Number(form.get('port'));
2000
+ const oldPort = restartDaemonPort;
2001
+ const oldHealth = await restartService.health();
2002
+ if (!isValidRestartPort(port)) {
2003
+ message = '端口无效:需 1024–65535,且不能是 8787';
2004
+ } else if (port === oldPort && oldHealth && oldHealth.ok !== false) {
2005
+ message = '守护进程已经在端口 ' + port + ' 上运行';
2006
+ } else if (!(await isPortAvailable(port))) {
2007
+ message = '端口 ' + port + ' 已被其它程序占用,请换一个端口';
2008
+ } else {
2009
+ // 旧端口上的守护进程用"授权停止"请求关掉,再切换(CLI 的停止请求会被鉴权拒绝)
2010
+ if (oldHealth && oldHealth.ok !== false) {
2011
+ try { await restartService.stop(); } catch { /* 忽略 */ }
2012
+ await new Promise((resolve) => setTimeout(resolve, 600));
2013
+ }
2014
+ writePortOverride(port);
2015
+ restartDaemonPort = port;
2016
+ try { fs.rmSync(path.join(restartDaemonStateDir(), 'port-conflict.json'), { force: true }); } catch { /* 忽略 */ }
2017
+ try { fs.rmSync(path.join(restartDaemonStateDir(), 'stopped.json'), { force: true }); } catch { /* 忽略 */ }
2018
+ const started = startRestartDaemonDetached();
2019
+ const healthy = await waitRestartDaemonHealthy(5000);
2020
+ appendAudit(dataDir(), 'restart-daemon-port-change', { from: oldPort, port, started, healthy });
2021
+ if (healthy) message = '已切换到端口 ' + port + ',守护进程运行正常';
2022
+ else if (started) message = '已保存端口 ' + port + ',但守护进程未就绪(端口可能刚被占用),请查看日志';
2023
+ else message = '已保存端口 ' + port + ',但启动失败,请查看日志';
2024
+ }
2025
+ } else if (action === 'disable') {
2026
+ try {
2027
+ fs.mkdirSync(restartDaemonStateDir(), { recursive: true });
2028
+ fs.writeFileSync(path.join(restartDaemonStateDir(), 'disabled.json'), JSON.stringify({ at: new Date().toISOString() }));
2029
+ } catch { /* 忽略 */ }
2030
+ try { await restartService.stop(); } catch { /* 忽略 */ }
2031
+ appendAudit(dataDir(), 'restart-daemon-disabled', {});
2032
+ message = '已关闭重启守护进程';
2033
+ } else if (action === 'enable') {
2034
+ try { fs.rmSync(path.join(restartDaemonStateDir(), 'disabled.json'), { force: true }); } catch { /* 忽略 */ }
2035
+ const started = startRestartDaemonDetached();
2036
+ const healthy = await waitRestartDaemonHealthy(5000);
2037
+ appendAudit(dataDir(), 'restart-daemon-enabled', { started, healthy });
2038
+ message = healthy ? '已重新启用,守护进程运行正常' : '已启用,但守护进程未就绪,请查看日志';
2039
+ }
2040
+ res.writeHead(303, { location: '/dsh_homing/restart?m=' + encodeURIComponent(message), 'cache-control': 'no-store' });
2041
+ res.end();
1824
2042
  return;
1825
2043
  }
1826
2044
 
@@ -1839,8 +2057,10 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1839
2057
  void broadcastRestartState(dataDir(), { event: 'restart-requested', action });
1840
2058
  if (action === 'normal') {
1841
2059
  const result = restartPolicy.queue(0);
1842
- message = result.accepted ? '已排队:等所有会话结束、且安静满 5 秒后重启' : '排队失败';
2060
+ // 排队信息已在下方状态行完整展示,不再重复横幅;只有失败才提示
2061
+ message = result.accepted ? '' : '排队失败';
1843
2062
  } else if (action === 'force') {
2063
+ const wantsJson = String(req.headers['x-dsh-fetch'] ?? '') === '1' || String(req.headers.accept ?? '').includes('application/json');
1844
2064
  if (sessions.length > 0 && form.get('confirm') !== '1') {
1845
2065
  // 繁忙:先渲染二次确认页,列出正在运行的会话
1846
2066
  const status = await restartService.status();
@@ -1854,7 +2074,22 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1854
2074
  return;
1855
2075
  }
1856
2076
  const result = await restartPolicy.force();
1857
- message = result.ok ? '已触发强制重启(策略层已放行)' : '提交失败:守护进程未运行';
2077
+ if (wantsJson) {
2078
+ const ok = result.ok === true;
2079
+ message = ok ? '已触发强制重启' : (result.status === 403
2080
+ ? '守护进程拒绝了请求(来源进程校验未通过)'
2081
+ : '守护进程未运行或未响应');
2082
+ res.writeHead(ok ? 200 : 409, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2083
+ res.end(JSON.stringify({ ok, status: result.status ?? 0, message }));
2084
+ return;
2085
+ }
2086
+ if (result.ok) {
2087
+ message = '已触发强制重启(策略层已放行)';
2088
+ } else if (result.status === 403) {
2089
+ message = '提交失败:守护进程拒绝了请求(来源进程校验未通过),请查看守护进程日志';
2090
+ } else {
2091
+ message = '提交失败:' + (result.error === 'restart-daemon down' || result.error === 'timeout' ? '守护进程未运行' : String(result.error ?? '未知原因'));
2092
+ }
1858
2093
  } else if (action === 'pause') {
1859
2094
  const minutes = Number(form.get('minutes'));
1860
2095
  if (!Number.isFinite(minutes) || minutes <= 0) {
@@ -2331,6 +2566,246 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2331
2566
  return;
2332
2567
  }
2333
2568
 
2569
+ // 窗口共享:手机上看/操作 PC 上的窗口(PowerShell 代理)
2570
+ if (url.pathname === '/remote' || url.pathname.startsWith('/remote/')) {
2571
+ if (!sessionValid(req) && currentDevice(req) === null) {
2572
+ res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
2573
+ res.end();
2574
+ return;
2575
+ }
2576
+ const sendRemote = (status, headers, body) => {
2577
+ res.writeHead(status, {
2578
+ 'cache-control': 'no-store',
2579
+ 'x-content-type-options': 'nosniff',
2580
+ ...headers,
2581
+ });
2582
+ res.end(body);
2583
+ };
2584
+ const sendRemoteJson = (status, payload) => sendRemote(status, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify(payload));
2585
+
2586
+ if (url.pathname === '/remote' && req.method === 'GET') {
2587
+ sendRemote(200, {
2588
+ 'content-type': 'text/html; charset=utf-8',
2589
+ 'x-frame-options': 'DENY',
2590
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self' " + (secureCookies ? 'wss://' : 'ws://') + String(req.headers.host ?? '') + "; img-src 'self' blob: data:; font-src 'self'; form-action 'self'; base-uri 'none'",
2591
+ 'referrer-policy': 'no-referrer',
2592
+ }, renderWindowPage({
2593
+ user: process.env.USERNAME ?? '',
2594
+ host: os.hostname(),
2595
+ supported: windowRemote.isSupported(),
2596
+ agent: windowRemote.stats().running,
2597
+ }));
2598
+ return;
2599
+ }
2600
+
2601
+ if (url.pathname === '/remote/app.js') {
2602
+ try {
2603
+ const body = fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'window-app.js'));
2604
+ sendRemote(200, { 'content-type': 'text/javascript; charset=utf-8' }, body);
2605
+ } catch {
2606
+ sendRemoteJson(500, { ok: false, error: '脚本缺失' });
2607
+ }
2608
+ return;
2609
+ }
2610
+
2611
+ if (url.pathname === '/remote/windows' && req.method === 'GET') {
2612
+ const result = await windowRemote.listWindows();
2613
+ appendAudit(dir, 'window-list', { ok: result.ok, count: result.windows.length, error: result.error ?? null });
2614
+ sendRemoteJson(result.ok ? 200 : 500, result);
2615
+ return;
2616
+ }
2617
+
2618
+ if (url.pathname === '/remote/frame' && req.method === 'GET') {
2619
+ const hwnd = url.searchParams.get('hwnd') ?? '';
2620
+ const maxWidth = Number(url.searchParams.get('maxWidth') ?? '1280') || 1280;
2621
+ const shot = await windowRemote.captureWindow(hwnd, maxWidth);
2622
+ if (!shot.ok) {
2623
+ appendAudit(dir, 'window-frame', { hwnd, ok: false, error: shot.error ?? null });
2624
+ sendRemoteJson(500, { ok: false, error: shot.error ?? '抓图失败' });
2625
+ return;
2626
+ }
2627
+ sendRemote(200, {
2628
+ 'content-type': 'image/jpeg',
2629
+ 'x-window-width': String(shot.width),
2630
+ 'x-window-height': String(shot.height),
2631
+ }, shot.buffer);
2632
+ return;
2633
+ }
2634
+
2635
+ if (url.pathname === '/remote/input' && req.method === 'POST') {
2636
+ let payload = {};
2637
+ try {
2638
+ payload = JSON.parse(await readBody(req, 64 * 1024));
2639
+ } catch {
2640
+ sendRemoteJson(400, { ok: false, error: '请求体不是 JSON' });
2641
+ return;
2642
+ }
2643
+ const hwnd = String(payload.hwnd ?? '');
2644
+ if (payload.kind === 'rotate') {
2645
+ const mode = payload.mode === 'landscape' ? 'landscape' : 'portrait';
2646
+ const rotated = await setOrientation(mode);
2647
+ appendAudit(dir, 'screen-rotate', { mode, ok: rotated.ok === true, detail: rotated.detail ?? null });
2648
+ sendRemoteJson(rotated.ok === true ? 200 : 500, { ok: rotated.ok === true, detail: rotated.detail ?? null, screen: rotated.screen ?? null });
2649
+ return;
2650
+ }
2651
+ if (payload.kind === 'cursor') {
2652
+ const pos = await windowRemote.cursorPos();
2653
+ sendRemoteJson(200, { ok: pos.ok === true, x: pos.x ?? null, y: pos.y ?? null });
2654
+ return;
2655
+ }
2656
+ if (payload.kind === 'open') {
2657
+ const check = validateOpenPath(String(payload.path ?? ''));
2658
+ if (!check.ok) {
2659
+ appendAudit(dir, 'file-open-rejected', { path: String(payload.path ?? '').slice(0, 300), reason: check.reason });
2660
+ sendRemoteJson(400, { ok: false, error: '不允许打开:' + check.reason });
2661
+ return;
2662
+ }
2663
+ const filePath = check.path;
2664
+ try {
2665
+ if (!fs.statSync(filePath).isFile()) throw new Error('not a file');
2666
+ } catch {
2667
+ appendAudit(dir, 'file-open-rejected', { path: filePath.slice(0, 300), reason: 'not-a-file' });
2668
+ sendRemoteJson(400, { ok: false, error: '文件不存在或不是普通文件' });
2669
+ return;
2670
+ }
2671
+ const opened = await windowRemote.openPath(filePath);
2672
+ appendAudit(dir, 'file-open-pc', { path: filePath, ok: opened.ok === true, hwnd: opened.hwnd ?? null, title: opened.title ?? null, isZoomed: opened.isZoomed ?? null, isForeground: opened.isForeground ?? null, x: opened.x ?? null, y: opened.y ?? null, width: opened.width ?? null, height: opened.height ?? null, error: opened.error ?? null });
2673
+ sendRemoteJson(opened.ok === true ? 200 : 500, { ok: opened.ok === true, hwnd: opened.hwnd ?? null, title: opened.title ?? null, error: opened.error ?? null });
2674
+ return;
2675
+ }
2676
+ if (payload.kind === 'kill') {
2677
+ if (hwnd === '') {
2678
+ sendRemoteJson(400, { ok: false, error: '缺少 hwnd' });
2679
+ return;
2680
+ }
2681
+ const killed = await windowRemote.killWindow(hwnd);
2682
+ appendAudit(dir, 'window-kill', { hwnd, ok: killed.ok === true, pid: killed.pid ?? null, error: killed.error ?? null });
2683
+ sendRemoteJson(killed.ok === true ? 200 : 500, { ok: killed.ok === true, pid: killed.pid ?? null, error: killed.error ?? null });
2684
+ return;
2685
+ }
2686
+ if (payload.kind === 'close') {
2687
+ const closed = await windowRemote.closeWindow(hwnd);
2688
+ appendAudit(dir, 'window-input', { hwnd: closed.hwnd ?? hwnd, kind: 'close', ok: closed.ok === true, error: closed.error ?? null });
2689
+ sendRemoteJson(closed.ok === true ? 200 : 500, { ok: closed.ok === true, hwnd: closed.hwnd ?? null, error: closed.error ?? null });
2690
+ return;
2691
+ }
2692
+ if (hwnd === '') {
2693
+ sendRemoteJson(400, { ok: false, error: '缺少 hwnd' });
2694
+ return;
2695
+ }
2696
+ let result = { ok: false, error: '未知操作' };
2697
+ if (payload.kind === 'click') result = await windowRemote.clickWindow(hwnd, payload.x, payload.y, payload.button === 'right' ? 'right' : 'left');
2698
+ else if (payload.kind === 'wheel') result = await windowRemote.wheelWindow(hwnd, payload.delta);
2699
+ else if (payload.kind === 'key') result = await windowRemote.keyWindow(hwnd, { text: payload.text, keys: payload.keys });
2700
+ else if (payload.kind === 'focus') result = await windowRemote.focusWindow(hwnd);
2701
+ appendAudit(dir, 'window-input', { hwnd, kind: payload.kind ?? null, ok: result.ok === true, error: result.error ?? null });
2702
+ sendRemoteJson(result.ok === true ? 200 : 500, { ok: result.ok === true, error: result.error ?? null });
2703
+ return;
2704
+ }
2705
+
2706
+ sendRemoteJson(404, { ok: false, error: 'not found' });
2707
+ return;
2708
+ }
2709
+
2710
+ // 桌面:VNC(noVNC 页面 + 同源 WebSocket 代理,跨平台)
2711
+ if (url.pathname === '/vnc' || url.pathname.startsWith('/vnc/')) {
2712
+ if (!sessionValid(req) && currentDevice(req) === null) {
2713
+ res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
2714
+ res.end();
2715
+ return;
2716
+ }
2717
+ const sendVnc = (status, headers, body) => {
2718
+ res.writeHead(status, { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...headers });
2719
+ res.end(body);
2720
+ };
2721
+
2722
+ if (url.pathname === '/vnc' && req.method === 'GET') {
2723
+ const target = vnc.vncTarget(config);
2724
+ sendVnc(200, {
2725
+ 'content-type': 'text/html; charset=utf-8',
2726
+ 'x-frame-options': 'DENY',
2727
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self' " + (secureCookies ? 'wss://' : 'ws://') + String(req.headers.host ?? '') + "; img-src 'self' blob: data:; font-src 'self'; form-action 'self'; base-uri 'none'",
2728
+ 'referrer-policy': 'no-referrer',
2729
+ }, renderVncPage({
2730
+ user: process.env.USERNAME ?? '',
2731
+ host: os.hostname(),
2732
+ target: target.host + ':' + target.port,
2733
+ ready: vnc.novncReady(),
2734
+ }));
2735
+ return;
2736
+ }
2737
+
2738
+ if (url.pathname === '/vnc/boot.js') {
2739
+ try {
2740
+ const body = fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'vnc-boot.js'));
2741
+ sendVnc(200, { 'content-type': 'text/javascript; charset=utf-8' }, body);
2742
+ } catch {
2743
+ sendVnc(404, { 'content-type': 'text/plain; charset=utf-8' }, 'not found');
2744
+ }
2745
+ return;
2746
+ }
2747
+
2748
+ if (url.pathname === '/vnc/report' && req.method === 'POST') {
2749
+ if (rateLimited('vnc-report:' + clientKey(req), 120, 60_000)) {
2750
+ sendVnc(429, {}, '');
2751
+ return;
2752
+ }
2753
+ let payload = {};
2754
+ try {
2755
+ payload = JSON.parse(await readBody(req, 16 * 1024));
2756
+ } catch {
2757
+ payload = { kind: 'parse-error' };
2758
+ }
2759
+ appendAudit(dir, 'vnc-client-error', {
2760
+ kind: String(payload.kind ?? '').slice(0, 40),
2761
+ message: String(payload.message ?? '').slice(0, 300),
2762
+ extra: payload.extra ?? null,
2763
+ });
2764
+ sendVnc(204, {}, '');
2765
+ return;
2766
+ }
2767
+
2768
+ if (url.pathname === '/vnc/bundle.js') {
2769
+ try {
2770
+ const body = fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'vendor', 'vnc.bundle.js'));
2771
+ sendVnc(200, { 'content-type': 'text/javascript; charset=utf-8' }, body);
2772
+ } catch {
2773
+ sendVnc(404, { 'content-type': 'text/plain; charset=utf-8' }, 'bundle not found');
2774
+ }
2775
+ return;
2776
+ }
2777
+
2778
+
2779
+ if (url.pathname === '/vnc/app.js') {
2780
+ try {
2781
+ const body = fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'vnc-app.js'));
2782
+ sendVnc(200, { 'content-type': 'text/javascript; charset=utf-8' }, body);
2783
+ } catch {
2784
+ sendVnc(404, { 'content-type': 'text/plain; charset=utf-8' }, 'not found');
2785
+ }
2786
+ return;
2787
+ }
2788
+
2789
+ if (url.pathname.startsWith('/vnc/static/')) {
2790
+ const file = vnc.resolveStatic(url.pathname);
2791
+ if (file === null) {
2792
+ sendVnc(404, { 'content-type': 'text/plain; charset=utf-8' }, 'not found');
2793
+ return;
2794
+ }
2795
+ res.writeHead(200, {
2796
+ 'content-type': vnc.mimeOf(file),
2797
+ // no-store:避免旧模块被缓存 24h 后与新版入口混用
2798
+ 'cache-control': 'no-store',
2799
+ 'x-content-type-options': 'nosniff',
2800
+ });
2801
+ fs.createReadStream(file).pipe(res);
2802
+ return;
2803
+ }
2804
+
2805
+ sendVnc(404, { 'content-type': 'text/plain; charset=utf-8' }, 'not found');
2806
+ return;
2807
+ }
2808
+
2334
2809
  // 终端:执行任意 shell 命令(手机端的 Git Bash)。需要登录。
2335
2810
  if (url.pathname === '/git' || url.pathname === '/git/run') {
2336
2811
  if (!sessionValid(req) && currentDevice(req) === null) {
@@ -2394,7 +2869,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2394
2869
  return;
2395
2870
  }
2396
2871
 
2397
- if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/download' || url.pathname === '/files/compress' || url.pathname === '/files/run'
2872
+ if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/pdf' || url.pathname === '/files/download' || url.pathname === '/files/compress' || url.pathname === '/files/run'
2398
2873
  || url.pathname === '/files/rename'
2399
2874
  || url.pathname === '/files/delete' || url.pathname === '/files/paste'
2400
2875
  || url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
@@ -2503,8 +2978,69 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2503
2978
  return;
2504
2979
  }
2505
2980
 
2981
+ // PDF / Office 在线预览:PDF 直接流式返回;Office 先转 PDF(带缓存)
2982
+ if (url.pathname === '/files/pdf' && req.method === 'GET') {
2983
+ const target = filebrowse.resolvePath(url.searchParams.get('path') ?? '');
2984
+ let stat = null;
2985
+ try { stat = fs.statSync(target); } catch { stat = null; }
2986
+ if (!stat || !stat.isFile()) {
2987
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
2988
+ res.end('文件不存在\n');
2989
+ return;
2990
+ }
2991
+ const name = path.basename(target);
2992
+ const sendPdf = (file, downloadName) => {
2993
+ let size = 0;
2994
+ try { size = fs.statSync(file).size; } catch { size = 0; }
2995
+ const ascii = downloadName.replace(/[^\x20-\x7E]/gu, '_').replace(/["\\]/gu, '_');
2996
+ res.writeHead(200, {
2997
+ 'content-type': 'application/pdf',
2998
+ 'content-length': String(size),
2999
+ 'content-disposition': `inline; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(downloadName)}`,
3000
+ 'cache-control': 'private, max-age=60',
3001
+ 'x-content-type-options': 'nosniff',
3002
+ });
3003
+ fs.createReadStream(file).pipe(res);
3004
+ };
3005
+ if (office.isPdfFile(name)) {
3006
+ appendAudit(dir, 'file-preview', { path: target, kind: 'pdf' });
3007
+ sendPdf(target, name);
3008
+ return;
3009
+ }
3010
+ if (!office.isOfficeFile(name)) {
3011
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
3012
+ res.end('这个文件不支持在线预览\n');
3013
+ return;
3014
+ }
3015
+ const result = await office.renderPdf(target);
3016
+ appendAudit(dir, 'file-preview', {
3017
+ path: target,
3018
+ kind: 'office',
3019
+ ok: result.ok,
3020
+ cached: result.cached === true,
3021
+ error: result.error ?? null,
3022
+ });
3023
+ if (!result.ok) {
3024
+ res.writeHead(500, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
3025
+ res.end(`<!doctype html><meta charset="utf-8"><title>预览失败</title><body style="background:#161a20;color:#e6e8ee;font-family:system-ui;padding:24px">
3026
+ <h1 style="font-size:18px">预览失败</h1>
3027
+ <p style="color:#9aa3b2">${escapeHtml(String(result.error ?? '未知原因'))}</p>
3028
+ <p><a style="color:#8ab4f8" href="/files/download?path=${encodeURIComponent(target)}">下载后用 WPS / Office 打开</a></p>
3029
+ </body>`);
3030
+ return;
3031
+ }
3032
+ sendPdf(result.path, name + '.pdf');
3033
+ return;
3034
+ }
3035
+
2506
3036
  if (url.pathname === '/files/view' && req.method === 'GET') {
2507
- const info = filebrowse.readTextFile(url.searchParams.get('path') ?? '');
3037
+ const asked = url.searchParams.get('path') ?? '';
3038
+ if (office.isOfficeFile(asked) || office.isPdfFile(asked)) {
3039
+ res.writeHead(303, { location: '/files/pdf?path=' + encodeURIComponent(asked), 'cache-control': 'no-store' });
3040
+ res.end();
3041
+ return;
3042
+ }
3043
+ const info = filebrowse.readTextFile(asked);
2508
3044
  appendAudit(dir, 'file-view', { path: info.path });
2509
3045
  sendHtml(renderFileView({ info }));
2510
3046
  return;
@@ -3271,8 +3807,39 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3271
3807
  req.on('aborted', () => upstream.destroy());
3272
3808
  };
3273
3809
 
3810
+ // VNC 的 WebSocket 服务端(noServer:握手交给它,帧解析/掩码/分片都由 ws 处理)
3811
+ const vncWss = new WebSocketServer({ noServer: true });
3812
+
3274
3813
  const onUpgrade = async (req, socket, head) => {
3275
3814
  const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
3815
+
3816
+ // 桌面 WebSocket:鉴权后通过 ws 库完成握手,再桥接本机 VNC 的 TCP
3817
+ if (url.pathname === '/vnc/ws') {
3818
+ if (!sessionValid(req) && currentDevice(req) === null) {
3819
+ socket.end('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\n\r\n');
3820
+ return;
3821
+ }
3822
+ const target = vnc.vncTarget(config);
3823
+ try {
3824
+ vncWss.handleUpgrade(req, socket, head, (ws) => {
3825
+ appendAudit(dir, 'vnc-connect', { host: target.host, port: target.port });
3826
+ startVncAuthProxy({
3827
+ ws,
3828
+ host: target.host,
3829
+ port: target.port,
3830
+ getPassword: resolveVncPassword,
3831
+ onError: (error) => {
3832
+ appendAudit(dir, 'vnc-auth-failed', { host: target.host, port: target.port, error: String(error?.message ?? error).slice(0, 200) });
3833
+ },
3834
+ });
3835
+ });
3836
+ } catch (error) {
3837
+ appendAudit(dir, 'vnc-connect-failed', { host: target.host, port: target.port, error: String(error?.message ?? error) });
3838
+ try { socket.end('HTTP/1.1 502 Bad Gateway\r\ncontent-length: 0\r\n\r\n'); } catch { /* 忽略 */ }
3839
+ }
3840
+ return;
3841
+ }
3842
+
3276
3843
  // WebSocket 握手同样校验来源:跨站页面可以发起带 Cookie 的 WS 连接
3277
3844
  if (!checkUnsafeOrigin({ method: 'POST', headers: req.headers }).ok) {
3278
3845
  socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
@@ -3282,7 +3849,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3282
3849
  socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
3283
3850
  return;
3284
3851
  }
3285
- if (config.login && !sessionValid(req)) {
3852
+ if (config.login && !sessionValid(req) && currentDevice(req) === null) {
3286
3853
  socket.end('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\n\r\n');
3287
3854
  return;
3288
3855
  }
@@ -3319,8 +3886,8 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3319
3886
 
3320
3887
  function findSsh() {
3321
3888
  const candidates = process.platform === 'win32'
3322
- ? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'), 'ssh.exe', 'ssh']
3323
- : ['/usr/bin/ssh', '/usr/local/bin/ssh', 'ssh'];
3889
+ ? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'), sshExe()]
3890
+ : ['/usr/bin/ssh', '/usr/local/bin/ssh', sshExe()];
3324
3891
  for (const candidate of candidates) {
3325
3892
  if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
3326
3893
  return candidate;
@@ -3554,10 +4121,9 @@ function findOpenssl() {
3554
4121
  ? [
3555
4122
  path.join(process.env['ProgramFiles'] ?? 'C:\\Program Files', 'Git', 'usr', 'bin', 'openssl.exe'),
3556
4123
  path.join(process.env['ProgramFiles'] ?? 'C:\\Program Files', 'Git', 'mingw64', 'bin', 'openssl.exe'),
3557
- 'openssl.exe',
3558
- 'openssl',
4124
+ opensslExe(),
3559
4125
  ]
3560
- : ['/usr/bin/openssl', '/usr/local/bin/openssl', '/opt/homebrew/bin/openssl', 'openssl'];
4126
+ : ['/usr/bin/openssl', '/usr/local/bin/openssl', '/opt/homebrew/bin/openssl', opensslExe()];
3561
4127
  for (const candidate of candidates) {
3562
4128
  if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
3563
4129
  return candidate;
@@ -3698,6 +4264,30 @@ export function apply(ctx, rawConfig) {
3698
4264
 
3699
4265
  const config = normalizeConfig({ ...rawConfig, ...readSettings() });
3700
4266
  const auth = loadAuth(dir);
4267
+ if (config.vnc && typeof config.vnc.password === 'string' && config.vnc.password !== '' && !config.vnc.passwordEnc) {
4268
+ protectSecret(config.vnc.password).then((enc) => {
4269
+ if (!enc) return;
4270
+ config.vnc.passwordEnc = enc;
4271
+ delete config.vnc.password;
4272
+ try {
4273
+ const current = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
4274
+ current.vnc = { ...(current.vnc || {}), passwordEnc: enc };
4275
+ delete current.vnc.password;
4276
+ fs.writeFileSync(settingsPath, JSON.stringify(current, null, 2) + '\n', 'utf8');
4277
+ appendAudit(dir, 'vnc-password-encrypted', { ok: true });
4278
+ console.log('[dsh-homing] VNC 密码已改用 DPAPI 加密存储');
4279
+ } catch (error) {
4280
+ warn('VNC 密码加密回写失败:' + error.message);
4281
+ }
4282
+ }).catch((error) => warn('VNC 密码加密失败:' + error.message));
4283
+ }
4284
+ setTimeout(() => {
4285
+ ensureLandscape().then((result) => {
4286
+ if (result && result.skipped !== true) {
4287
+ appendAudit(dir, 'screen-restore', { ok: result.ok === true, detail: result.detail || null });
4288
+ }
4289
+ }).catch(() => {});
4290
+ }, 3000);
3701
4291
  // mintCookie 需要知道上游端口才能探测 DSH 接受的 cookie 有效期;port 在下面才算出来,
3702
4292
  // 所以用闭包延迟读取。
3703
4293
  const mintCookie = createCookieMinter(ctx.credentials, () => port);
@@ -3740,8 +4330,17 @@ export function apply(ctx, rawConfig) {
3740
4330
  // publicUrl 不是合法 URL:只按本机证书提供服务
3741
4331
  }
3742
4332
  const localContext = tls.mode === 'off' ? undefined : nodeTls.createSecureContext(tls.options);
4333
+ const safeHandler = (req, res) => {
4334
+ Promise.resolve(handler(req, res)).catch((error) => {
4335
+ appendAudit(dir, 'request-error', { path: String(req.url ?? '').slice(0, 200), error: String(error?.message ?? error).slice(0, 300) });
4336
+ try {
4337
+ if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
4338
+ res.end('internal error');
4339
+ } catch { /* 忽略 */ }
4340
+ });
4341
+ };
3743
4342
  const server = tls.mode === 'off'
3744
- ? http.createServer(handler)
4343
+ ? http.createServer(safeHandler)
3745
4344
  : https.createServer({
3746
4345
  ...tls.options,
3747
4346
  // 按 SNI 选证书:公网域名用真证书,其余(局域网 IP)用本机 CA 签的证书
@@ -3752,7 +4351,7 @@ export function apply(ctx, rawConfig) {
3752
4351
  }
3753
4352
  callback(null, localContext);
3754
4353
  },
3755
- }, handler);
4354
+ }, safeHandler);
3756
4355
  server.on('upgrade', onUpgrade);
3757
4356
  server.requestTimeout = 0;
3758
4357
  server.headersTimeout = 0;
@@ -3861,7 +4460,7 @@ export function apply(ctx, rawConfig) {
3861
4460
  renewing = true;
3862
4461
  console.log(`[dsh-homing] 公网证书只剩 ${days} 天,开始自动续期`);
3863
4462
  const script = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'renew-cert.mjs');
3864
- const child = spawn(process.execPath, [script], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
4463
+ const child = spawn(findNodeRuntime(), [script], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
3865
4464
  let output = '';
3866
4465
  child.stdout?.on('data', (chunk) => { output += String(chunk); });
3867
4466
  child.stderr?.on('data', (chunk) => { output += String(chunk); });
@@ -3971,7 +4570,7 @@ export function apply(ctx, rawConfig) {
3971
4570
  // 每周自动备份一次(含私钥,只留在本机 backups/ 目录)
3972
4571
  const backupScript = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'backup.mjs');
3973
4572
  const backupOnce = () => {
3974
- const job = spawn(process.execPath, [backupScript], { stdio: 'ignore', windowsHide: true });
4573
+ const job = spawn(findNodeRuntime(), [backupScript], { stdio: 'ignore', windowsHide: true });
3975
4574
  job.on('error', () => {});
3976
4575
  };
3977
4576
  const backupTimer = setInterval(backupOnce, 7 * 24 * 60 * 60 * 1000);