@andy.ian/dsh-homing 0.0.0-stage → 2.0.1

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 (230) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +71 -2
  3. package/bin/auth.mjs +159 -0
  4. package/bin/backup.mjs +118 -0
  5. package/bin/bootstrap-server.mjs +436 -0
  6. package/bin/entry-link.mjs +69 -0
  7. package/bin/nginx-dsh.template.conf +91 -0
  8. package/bin/nginx-gate.conf +9 -0
  9. package/bin/nginx-ws-map.conf +5 -0
  10. package/bin/renew-cert.mjs +127 -0
  11. package/bin/supervisor.mjs +488 -0
  12. package/bin/watchdog.mjs +163 -0
  13. package/client.js +79 -0
  14. package/cordis.patch.yml +30 -0
  15. package/icon.svg +9 -0
  16. package/index.js +3526 -0
  17. package/lib/csrf.mjs +60 -0
  18. package/lib/devices.mjs +221 -0
  19. package/lib/files-page.mjs +592 -0
  20. package/lib/files.mjs +551 -0
  21. package/lib/git.mjs +154 -0
  22. package/lib/limits.mjs +135 -0
  23. package/lib/pty.mjs +361 -0
  24. package/lib/session.mjs +216 -0
  25. package/lib/shell-page.mjs +430 -0
  26. package/lib/shell.mjs +274 -0
  27. package/lib/term-app.js +318 -0
  28. package/lib/term-page.mjs +117 -0
  29. package/lib/vendor/fonts/JetBrainsMono-Regular.ttf +0 -0
  30. package/lib/vendor/fonts/jetbrains-mono-400.woff2 +0 -0
  31. package/lib/vendor/fonts/jetbrains-mono-700.woff2 +0 -0
  32. package/lib/vendor/node_modules/@xterm/addon-fit/LICENSE +19 -0
  33. package/lib/vendor/node_modules/@xterm/addon-fit/README.md +24 -0
  34. package/lib/vendor/node_modules/@xterm/addon-fit/lib/addon-fit.js +2 -0
  35. package/lib/vendor/node_modules/@xterm/addon-fit/lib/addon-fit.js.map +1 -0
  36. package/lib/vendor/node_modules/@xterm/addon-fit/package.json +26 -0
  37. package/lib/vendor/node_modules/@xterm/addon-fit/src/FitAddon.ts +90 -0
  38. package/lib/vendor/node_modules/@xterm/addon-fit/typings/addon-fit.d.ts +55 -0
  39. package/lib/vendor/node_modules/asn1/Jenkinsfile +65 -0
  40. package/lib/vendor/node_modules/asn1/LICENSE +19 -0
  41. package/lib/vendor/node_modules/asn1/README.md +50 -0
  42. package/lib/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
  43. package/lib/vendor/node_modules/asn1/lib/ber/index.js +27 -0
  44. package/lib/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
  45. package/lib/vendor/node_modules/asn1/lib/ber/types.js +36 -0
  46. package/lib/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
  47. package/lib/vendor/node_modules/asn1/lib/index.js +20 -0
  48. package/lib/vendor/node_modules/asn1/package.json +31 -0
  49. package/lib/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
  50. package/lib/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
  51. package/lib/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
  52. package/lib/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
  53. package/lib/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
  54. package/lib/vendor/node_modules/safer-buffer/LICENSE +21 -0
  55. package/lib/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
  56. package/lib/vendor/node_modules/safer-buffer/Readme.md +156 -0
  57. package/lib/vendor/node_modules/safer-buffer/dangerous.js +58 -0
  58. package/lib/vendor/node_modules/safer-buffer/package.json +34 -0
  59. package/lib/vendor/node_modules/safer-buffer/safer.js +77 -0
  60. package/lib/vendor/node_modules/safer-buffer/tests.js +406 -0
  61. package/lib/vendor/node_modules/ssh2/.eslintignore +4 -0
  62. package/lib/vendor/node_modules/ssh2/.eslintrc.js +5 -0
  63. package/lib/vendor/node_modules/ssh2/.github/workflows/ci.yml +110 -0
  64. package/lib/vendor/node_modules/ssh2/.github/workflows/lint.yml +27 -0
  65. package/lib/vendor/node_modules/ssh2/LICENSE +19 -0
  66. package/lib/vendor/node_modules/ssh2/README.md +1529 -0
  67. package/lib/vendor/node_modules/ssh2/SFTP.md +413 -0
  68. package/lib/vendor/node_modules/ssh2/examples/server-chat.js +238 -0
  69. package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +134 -0
  70. package/lib/vendor/node_modules/ssh2/install.js +27 -0
  71. package/lib/vendor/node_modules/ssh2/lib/Channel.js +295 -0
  72. package/lib/vendor/node_modules/ssh2/lib/agent.js +1123 -0
  73. package/lib/vendor/node_modules/ssh2/lib/client.js +2176 -0
  74. package/lib/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
  75. package/lib/vendor/node_modules/ssh2/lib/index.js +44 -0
  76. package/lib/vendor/node_modules/ssh2/lib/keygen.js +582 -0
  77. package/lib/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
  78. package/lib/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
  79. package/lib/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
  80. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
  81. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
  82. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
  83. package/lib/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
  84. package/lib/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
  85. package/lib/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
  86. package/lib/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
  87. package/lib/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
  88. package/lib/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
  89. package/lib/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
  90. package/lib/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
  91. package/lib/vendor/node_modules/ssh2/lib/server.js +1380 -0
  92. package/lib/vendor/node_modules/ssh2/lib/utils.js +336 -0
  93. package/lib/vendor/node_modules/ssh2/package.json +49 -0
  94. package/lib/vendor/node_modules/ssh2/test/common.js +316 -0
  95. package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +26 -0
  96. package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +33 -0
  97. package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +52 -0
  98. package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +12 -0
  99. package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +5 -0
  100. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +15 -0
  101. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +26 -0
  102. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +30 -0
  103. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +21 -0
  104. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +1 -0
  105. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +7 -0
  106. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +7 -0
  107. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +22 -0
  108. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +1 -0
  109. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +7 -0
  110. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +7 -0
  111. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +23 -0
  112. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +1 -0
  113. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +7 -0
  114. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +7 -0
  115. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +9 -0
  116. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +1 -0
  117. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +7 -0
  118. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +7 -0
  119. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +10 -0
  120. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +1 -0
  121. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +8 -0
  122. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +7 -0
  123. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +10 -0
  124. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +1 -0
  125. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +8 -0
  126. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +7 -0
  127. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +7 -0
  128. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +1 -0
  129. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +7 -0
  130. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +7 -0
  131. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +27 -0
  132. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +1 -0
  133. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +7 -0
  134. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +7 -0
  135. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +28 -0
  136. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +1 -0
  137. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +8 -0
  138. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +7 -0
  139. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +29 -0
  140. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +1 -0
  141. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +8 -0
  142. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +7 -0
  143. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +12 -0
  144. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +1 -0
  145. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +7 -0
  146. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +7 -0
  147. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +15 -0
  148. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +1 -0
  149. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +8 -0
  150. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +7 -0
  151. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +5 -0
  152. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +1 -0
  153. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +7 -0
  154. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +7 -0
  155. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +8 -0
  156. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +1 -0
  157. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +8 -0
  158. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +7 -0
  159. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +27 -0
  160. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +1 -0
  161. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +7 -0
  162. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +7 -0
  163. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +30 -0
  164. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +1 -0
  165. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +8 -0
  166. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +7 -0
  167. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +54 -0
  168. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +1 -0
  169. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +6 -0
  170. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +6 -0
  171. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +17 -0
  172. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +7 -0
  173. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +26 -0
  174. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +7 -0
  175. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +18 -0
  176. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +7 -0
  177. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +9 -0
  178. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +7 -0
  179. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +10 -0
  180. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +7 -0
  181. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +11 -0
  182. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +7 -0
  183. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +11 -0
  184. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +7 -0
  185. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +8 -0
  186. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +7 -0
  187. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +13 -0
  188. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +7 -0
  189. package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +27 -0
  190. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +12 -0
  191. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +5 -0
  192. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +15 -0
  193. package/lib/vendor/node_modules/ssh2/test/test-exec.js +578 -0
  194. package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +486 -0
  195. package/lib/vendor/node_modules/ssh2/test/test-keygen.js +60 -0
  196. package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +1460 -0
  197. package/lib/vendor/node_modules/ssh2/test/test-openssh.js +261 -0
  198. package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +631 -0
  199. package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +177 -0
  200. package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +138 -0
  201. package/lib/vendor/node_modules/ssh2/test/test-sftp.js +842 -0
  202. package/lib/vendor/node_modules/ssh2/test/test-shell.js +109 -0
  203. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +110 -0
  204. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +171 -0
  205. package/lib/vendor/node_modules/ssh2/test/test-userauth.js +611 -0
  206. package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +25 -0
  207. package/lib/vendor/node_modules/ssh2/test/test.js +20 -0
  208. package/lib/vendor/node_modules/ssh2/util/build_pagent.bat +2 -0
  209. package/lib/vendor/node_modules/ssh2/util/pagent.c +88 -0
  210. package/lib/vendor/node_modules/ssh2/util/pagent.exe +0 -0
  211. package/lib/vendor/node_modules/tweetnacl/AUTHORS.md +27 -0
  212. package/lib/vendor/node_modules/tweetnacl/CHANGELOG.md +283 -0
  213. package/lib/vendor/node_modules/tweetnacl/LICENSE +24 -0
  214. package/lib/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
  215. package/lib/vendor/node_modules/tweetnacl/README.md +494 -0
  216. package/lib/vendor/node_modules/tweetnacl/nacl-fast.js +2391 -0
  217. package/lib/vendor/node_modules/tweetnacl/nacl-fast.min.js +1 -0
  218. package/lib/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
  219. package/lib/vendor/node_modules/tweetnacl/nacl.js +1178 -0
  220. package/lib/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
  221. package/lib/vendor/node_modules/tweetnacl/package.json +56 -0
  222. package/lib/vendor/xterm.css +218 -0
  223. package/lib/vendor/xterm.js +2 -0
  224. package/locale/en.json +6 -0
  225. package/locale/zh.json +6 -0
  226. package/ops/watchdog/dsh-watchdog.ps1 +105 -0
  227. package/ops/watchdog/restart-hidden.vbs +7 -0
  228. package/ops/watchdog/restart-now.ps1 +261 -0
  229. package/ops/watchdog/run-hidden.vbs +4 -0
  230. package/package.json +71 -4
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 续期公网证书(CSR 模式:私钥只在本机,服务器只负责走 ACME)。
4
+ *
5
+ * 用法:
6
+ * node bin/renew-cert.mjs 续期并安装
7
+ * node bin/renew-cert.mjs --dry-run 只生成 CSR,不请求证书
8
+ *
9
+ * 为什么这么做:TLS 在你这台电脑终止,服务器只做 TCP 透传。
10
+ * 用 CSR 模式可以把私钥永远留在本机,服务器上不存任何私钥。
11
+ */
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { spawn, spawnSync } from 'node:child_process';
16
+ import { fileURLToPath } from 'node:url';
17
+ import tls from 'node:tls';
18
+
19
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
20
+ const DIR = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'integrations', 'dsh-homing');
21
+ const SETTINGS = path.join(DIR, 'settings.json');
22
+ const CERTS = path.join(DIR, 'certs');
23
+ const dryRun = process.argv.includes('--dry-run');
24
+
25
+ const settings = (() => {
26
+ try { return JSON.parse(fs.readFileSync(SETTINGS, 'utf8')); } catch { return {}; }
27
+ })();
28
+ const publicUrl = settings.publicUrl || '';
29
+ const domain = publicUrl ? new URL(publicUrl).hostname : '';
30
+ if (!domain) {
31
+ console.error('settings.json 里没有 publicUrl,无法确定要续期的域名');
32
+ process.exit(2);
33
+ }
34
+ const serverHost = settings.serverHost;
35
+ const sshUser = settings.sshUser || 'ubuntu';
36
+ const sshPort = Number(settings.sshPort || 22);
37
+ const sshKey = settings.sshKey || path.join(os.homedir(), '.ssh', 'dsh_tunnel');
38
+
39
+ if (!serverHost) {
40
+ console.error('settings.json 里没有 serverHost,无法续期');
41
+ process.exit(2);
42
+ }
43
+
44
+ function findOpenssl() {
45
+ const candidates = process.platform === 'win32'
46
+ ? [
47
+ path.join(process.env['ProgramFiles'] ?? 'C:\\Program Files', 'Git', 'usr', 'bin', 'openssl.exe'),
48
+ path.join(process.env['ProgramFiles'] ?? 'C:\\Program Files', 'Git', 'mingw64', 'bin', 'openssl.exe'),
49
+ 'openssl.exe',
50
+ ]
51
+ : ['/usr/bin/openssl', '/usr/local/bin/openssl', '/opt/homebrew/bin/openssl', 'openssl'];
52
+ for (const candidate of candidates) {
53
+ if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
54
+ return candidate;
55
+ }
56
+ throw new Error('找不到 openssl');
57
+ }
58
+
59
+ const openssl = findOpenssl();
60
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'dsh-csr-'));
61
+ const keyPath = path.join(work, 'privkey.pem');
62
+ const csrPath = path.join(work, 'req.csr');
63
+
64
+ console.log(`==> 生成本机私钥 + CSR(${domain})`);
65
+ const gen = spawnSync(openssl, [
66
+ 'req', '-new', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:prime256v1', '-nodes',
67
+ '-keyout', keyPath, '-out', csrPath,
68
+ '-subj', `/CN=${domain}`, '-addext', `subjectAltName=DNS:${domain}`,
69
+ ], { stdio: 'ignore' });
70
+ if (gen.status !== 0 || !fs.existsSync(csrPath)) {
71
+ console.error('生成 CSR 失败');
72
+ process.exit(1);
73
+ }
74
+ console.log(` ${csrPath}`);
75
+
76
+ if (dryRun) {
77
+ console.log('DryRun:CSR 已生成,未请求证书');
78
+ process.exit(0);
79
+ }
80
+
81
+ const command = `set -e
82
+ cat > /tmp/dsh-renew.csr <<'CSREOF'
83
+ ${fs.readFileSync(csrPath, 'utf8').trim()}
84
+ CSREOF
85
+ sudo certbot certonly --webroot -w /var/www/html -d ${domain} --csr /tmp/dsh-renew.csr --cert-path /tmp/dsh-renew.crt --chain-path /tmp/dsh-renew.chain --fullchain-path /tmp/dsh-renew.fullchain.pem --non-interactive --agree-tos --register-unsafely-without-email >/dev/null 2>&1
86
+ sudo cat /tmp/dsh-renew.fullchain.pem
87
+ sudo rm -f /tmp/dsh-renew.csr /tmp/dsh-renew.crt /tmp/dsh-renew.chain /tmp/dsh-renew.fullchain.pem
88
+ `;
89
+
90
+ console.log('==> 请服务器走 ACME 签发');
91
+ const child = spawn('ssh', [
92
+ '-i', sshKey,
93
+ '-p', String(sshPort),
94
+ '-o', 'BatchMode=yes',
95
+ '-o', 'IdentitiesOnly=yes',
96
+ '-o', 'StrictHostKeyChecking=accept-new',
97
+ `${sshUser}@${serverHost}`,
98
+ 'bash -s',
99
+ ], { stdio: ['pipe', 'pipe', 'inherit'] });
100
+
101
+ let output = '';
102
+ child.stdout.on('data', (chunk) => { output += chunk; });
103
+ child.stdin.end(command);
104
+
105
+ const code = await new Promise((resolve) => child.on('close', resolve));
106
+ if (code !== 0 || !output.includes('BEGIN CERTIFICATE')) {
107
+ console.error('签发失败(服务器上可能有更详细的 certbot 日志)');
108
+ process.exit(1);
109
+ }
110
+
111
+ fs.mkdirSync(CERTS, { recursive: true });
112
+ fs.writeFileSync(path.join(CERTS, 'fullchain.pem'), `${output.trim()}\n`, { mode: 0o600 });
113
+ fs.writeFileSync(path.join(CERTS, 'privkey.pem'), fs.readFileSync(keyPath), { mode: 0o600 });
114
+ fs.chmodSync(keyPath, 0o600);
115
+
116
+ // 用私钥和证书对一次,防止装错
117
+ const certPub = spawnSync(openssl, ['x509', '-in', path.join(CERTS, 'fullchain.pem'), '-noout', '-pubkey']).stdout?.toString().trim();
118
+ const keyPub = spawnSync(openssl, ['pkey', '-in', path.join(CERTS, 'privkey.pem'), '-pubout']).stdout?.toString().trim();
119
+ if (!certPub || certPub !== keyPub) {
120
+ console.error('校验失败:证书与私钥不匹配,保持原文件不动');
121
+ process.exit(1);
122
+ }
123
+
124
+ const parsed = new tls.X509Certificate(fs.readFileSync(path.join(CERTS, 'fullchain.pem')));
125
+ console.log(`==> 已安装:${CERTS}`);
126
+ console.log(` 到期时间:${parsed.validTo}`);
127
+ console.log(' 重启插件(禁用→启用)或重启 DSH 后生效');
@@ -0,0 +1,488 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * DSH 常驻守护进程(模型 B)
4
+ *
5
+ * 为什么要独立进程:插件跑在 DSH 里,不能重启 DSH(会把自己杀掉)。
6
+ * 相比「系统定时任务每 5 分钟轮询」,常驻进程的优势:
7
+ * - 自己拉起的子进程:child.on('exit') 瞬时感知
8
+ * - 外部拉起的进程:2 秒轻量轮询(进程列表 + 端口),开销 < 0.05% CPU
9
+ * - 纯 Node,一份代码跨平台;只有「怎么开机启动它」分平台
10
+ * - 无控制台窗口,不存在闪黑窗
11
+ *
12
+ * 已修的关键缺陷:
13
+ * ① 单实例:控制端口被占用即退出,避免两个守护互相抢着拉起
14
+ * ② 重启互斥:并发请求只执行一次,避免双实例
15
+ * ③ 主动退出(退出码 0)不自动拉起,否则用户关不掉程序
16
+ * ④ default 模式等待空闲超时 → 放弃本次重启,不再硬打断用户
17
+ * ⑤ 稳定运行 60 秒后把退避计数归零
18
+ * ⑥ 找不到 exe 时只记一次日志并停止自动拉起
19
+ * ⑦ 用代际号忽略旧子进程的迟到 exit 事件
20
+ * ⑫ 空闲判定同时看 activity.json 与 sessions/*.json
21
+ *
22
+ * 用法:
23
+ * node bin/supervisor.mjs 前台运行(调试)
24
+ * node bin/supervisor.mjs --detach 后台常驻(配合启动项)
25
+ * node bin/supervisor.mjs --status 查看状态后退出
26
+ * node bin/supervisor.mjs --restart [--immediate] 请求重启
27
+ *
28
+ * 控制接口:
29
+ * GET http://127.0.0.1:8790/status
30
+ * POST http://127.0.0.1:8790/restart?mode=immediate|default
31
+ */
32
+ import fs from 'node:fs'
33
+ import net from 'node:net'
34
+ import os from 'node:os'
35
+ import path from 'node:path'
36
+ import http from 'node:http'
37
+ import { spawn, spawnSync } from 'node:child_process'
38
+
39
+ // ---------- 参数 ----------
40
+ function arg(name, fallback = '') {
41
+ const index = process.argv.indexOf('--' + name)
42
+ if (index < 0) return fallback
43
+ const next = process.argv[index + 1]
44
+ return next && !next.startsWith('--') ? next : 'true'
45
+ }
46
+ const has = (name) => process.argv.includes('--' + name)
47
+
48
+ const dshHome = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
49
+ const stateDir = arg('state', path.join(dshHome, 'watchdog'))
50
+ const controlPort = Number(arg('control', '8790'))
51
+ const idleSeconds = Number(arg('idle', '120'))
52
+ const bridgePort = Number(arg('bridge', '8787'))
53
+ const pollMs = Number(arg('poll', '2000'))
54
+ const logFile = path.join(stateDir, 'supervisor.log')
55
+ const stateFile = path.join(stateDir, 'supervisor.json')
56
+ const pidFile = path.join(stateDir, 'supervisor.pid')
57
+
58
+ fs.mkdirSync(stateDir, { recursive: true })
59
+
60
+ function log(message) {
61
+ const line = `${new Date().toISOString()} ${message}\n`
62
+ try { fs.appendFileSync(logFile, line) } catch { /* 日志写不了不影响主流程 */ }
63
+ if (!has('detach')) process.stdout.write(line)
64
+ }
65
+
66
+ // ---------- 找 DSH 可执行文件(唯一真正分平台的部分) ----------
67
+ function findDshExe() {
68
+ const fromArg = arg('exe')
69
+ if (fromArg && fromArg !== 'true' && fs.existsSync(fromArg)) return fromArg
70
+ if (process.platform === 'win32') {
71
+ const candidates = [
72
+ path.join(process.env.LOCALAPPDATA ?? '', 'Programs', 'DeepSeek Harness', 'DeepSeek Harness.exe'),
73
+ path.join(process.env.ProgramFiles ?? '', 'DeepSeek Harness', 'DeepSeek Harness.exe'),
74
+ path.join(process.env['ProgramFiles(x86)'] ?? '', 'DeepSeek Harness', 'DeepSeek Harness.exe'),
75
+ path.join(process.env.ProgramData ?? '', 'DeepSeek Harness', 'DeepSeek Harness.exe'),
76
+ ]
77
+ return candidates.find((item) => item && fs.existsSync(item)) ?? null
78
+ }
79
+ const candidates = process.platform === 'darwin'
80
+ ? ['/Applications/DeepSeek Harness.app/Contents/MacOS/DeepSeek Harness']
81
+ : ['/usr/local/bin/deepseek-harness', '/usr/bin/deepseek-harness']
82
+ return candidates.find((item) => fs.existsSync(item)) ?? null
83
+ }
84
+
85
+ const exePath = findDshExe()
86
+ const exeName = exePath ? path.basename(exePath) : 'DeepSeek Harness.exe'
87
+ const procName = path.basename(exeName, path.extname(exeName))
88
+
89
+ // ---------- 进程发现与探测 ----------
90
+ function listDshPids() {
91
+ try {
92
+ if (process.platform === 'win32') {
93
+ const out = spawnSync('tasklist', ['/FI', `IMAGENAME eq ${exeName}`, '/FO', 'CSV', '/NH'], {
94
+ encoding: 'utf8', windowsHide: true, timeout: 5000,
95
+ })
96
+ return String(out.stdout ?? '')
97
+ .split(/\r?\n/u)
98
+ .map((line) => line.match(/^"([^"]+)","(\d+)"/u))
99
+ .filter(Boolean)
100
+ .map((match) => Number(match[2]))
101
+ }
102
+ const out = spawnSync('ps', ['-eo', 'pid=,comm='], { encoding: 'utf8', timeout: 5000 })
103
+ return String(out.stdout ?? '')
104
+ .split(/\n/u)
105
+ .map((line) => line.trim().split(/\s+/u))
106
+ .filter((parts) => parts.length >= 2 && parts.slice(1).join(' ').includes(procName))
107
+ .map((parts) => Number(parts[0]))
108
+ } catch {
109
+ return []
110
+ }
111
+ }
112
+
113
+ function portOpen(port) {
114
+ return new Promise((resolve) => {
115
+ const socket = net.connect({ host: '127.0.0.1', port, timeout: 800 })
116
+ socket.once('connect', () => { socket.destroy(); resolve(true) })
117
+ socket.once('timeout', () => { socket.destroy(); resolve(false) })
118
+ socket.once('error', () => resolve(false))
119
+ })
120
+ }
121
+
122
+ async function probe() {
123
+ const pids = listDshPids()
124
+ return { pids, bridge: await portOpen(bridgePort), running: pids.length > 0 }
125
+ }
126
+
127
+ // ---------- 空闲判定:活动信标 + 会话文件 ----------
128
+ function idleAge() {
129
+ const files = [path.join(dshHome, 'integrations', 'dsh-homing', 'activity.json')]
130
+ try {
131
+ const sessions = path.join(dshHome, 'sessions')
132
+ for (const name of fs.readdirSync(sessions)) {
133
+ if (name.endsWith('.json')) files.push(path.join(sessions, name))
134
+ }
135
+ } catch { /* 没有 sessions 目录就只靠信标 */ }
136
+ let newest = 0
137
+ for (const file of files) {
138
+ try { newest = Math.max(newest, fs.statSync(file).mtimeMs) } catch { /* 跳过 */ }
139
+ }
140
+ return newest === 0 ? Infinity : (Date.now() - newest) / 1000
141
+ }
142
+
143
+ // ---------- 运行状态 ----------
144
+ let child = null
145
+ let childGeneration = 0
146
+ let restarts = 0
147
+ let stoppingForRestart = false
148
+ let restarting = false
149
+ let launchFailed = false
150
+ const startedAt = new Date()
151
+
152
+ function persist(extra = {}) {
153
+ try {
154
+ fs.writeFileSync(stateFile, JSON.stringify({
155
+ pid: process.pid,
156
+ exe: exePath,
157
+ controlPort,
158
+ bridgePort,
159
+ idleSeconds,
160
+ restarts,
161
+ childPid: child?.pid ?? null,
162
+ platform: process.platform,
163
+ startedAt: startedAt.toISOString(),
164
+ updatedAt: new Date().toISOString(),
165
+ ...extra,
166
+ }, null, 2))
167
+ } catch { /* 忽略 */ }
168
+ }
169
+
170
+ // ---------- 升级检测 ----------
171
+ // 规则:用户手动退出也要拉起;但 DSH 升级期间不能拉起(否则会拉起半装好的版本),
172
+ // 等升级完成后再拉起。三条信号联合判断「正在升级」:
173
+ // ① 更新器进程在跑 ② 可执行文件不存在 ③ 文件签名刚刚变过
174
+ const UPDATER_HINTS = ['setup', 'update', 'installer', 'squirrel', 'nsis']
175
+
176
+ /**
177
+ * 判断某个进程名是不是「DSH 的更新器」。
178
+ * 不能只看 installer/update 关键字——系统里 wslinstaller.exe 之类也会命中,
179
+ * 一旦误判就会永远认为"正在升级"、永远不拉起。
180
+ */
181
+ function isDshUpdater(name) {
182
+ const lower = name.toLowerCase()
183
+ if (lower.includes('deepseek')) {
184
+ return UPDATER_HINTS.some((hint) => lower.includes(hint)) || lower.includes('unins')
185
+ }
186
+ return /^(update|squirrel|electron-updater)\.exe$/u.test(lower)
187
+ }
188
+
189
+ function exeSignature() {
190
+ try {
191
+ const stat = fs.statSync(exePath)
192
+ return `${Math.round(stat.mtimeMs)}:${stat.size}`
193
+ } catch {
194
+ return ''
195
+ }
196
+ }
197
+
198
+ function updaterRunning() {
199
+ try {
200
+ if (process.platform === 'win32') {
201
+ const out = spawnSync('tasklist', ['/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true, timeout: 5000 })
202
+ return String(out.stdout ?? '')
203
+ .split(/\r?\n/u)
204
+ .map((line) => line.match(/^"([^"]+)"/u))
205
+ .filter(Boolean)
206
+ .map((match) => match[1])
207
+ .some((name) => isDshUpdater(name))
208
+ }
209
+ const out = spawnSync('ps', ['-eo', 'comm='], { encoding: 'utf8', timeout: 5000 })
210
+ return String(out.stdout ?? '')
211
+ .split(/\n/u)
212
+ .map((line) => line.trim())
213
+ .some((name) => isDshUpdater(name))
214
+ } catch {
215
+ return false
216
+ }
217
+ }
218
+
219
+ /**
220
+ * 等升级结束。返回 true 表示可以安全拉起。
221
+ * 判据:文件存在 + 没有更新器在跑 + 文件签名 8 秒内没变。
222
+ */
223
+ async function waitForUpgrade(maxMinutes = 30) {
224
+ const deadline = Date.now() + maxMinutes * 60_000
225
+ let signature = exeSignature()
226
+ let stableSince = Date.now()
227
+ let announced = false
228
+ while (Date.now() < deadline) {
229
+ const exists = signature !== ''
230
+ const updating = updaterRunning()
231
+ const current = exeSignature()
232
+ if (current !== signature) {
233
+ signature = current
234
+ stableSince = Date.now()
235
+ }
236
+ const stable = Date.now() - stableSince > 8000
237
+ if (!exists || updating || !stable) {
238
+ if (!announced) {
239
+ announced = true
240
+ log(`检测到升级中(存在=${exists} 更新器=${updating} 稳定=${stable}),等升级完成再拉起`)
241
+ }
242
+ await new Promise((resolve) => setTimeout(resolve, 2000))
243
+ continue
244
+ }
245
+ if (announced) log('升级已完成,开始拉起 DSH')
246
+ return true
247
+ }
248
+ log(`等待升级超时(${maxMinutes} 分钟),仍尝试拉起一次`)
249
+ return true
250
+ }
251
+
252
+ function launch() {
253
+ if (!exePath) {
254
+ if (!launchFailed) {
255
+ launchFailed = true
256
+ log('找不到 DSH 可执行文件,停止自动拉起(用 --exe 指定或检查安装位置)')
257
+ }
258
+ return null
259
+ }
260
+ launchFailed = false
261
+ log(`启动 DSH:${exePath}`)
262
+ const generation = ++childGeneration
263
+ const spawned = spawn(exePath, [], { stdio: 'ignore', windowsHide: false })
264
+ spawned.on('error', (error) => {
265
+ log(`启动失败:${error.code ?? error.message}`)
266
+ launchFailed = true
267
+ })
268
+ spawned.on('exit', (code, signal) => {
269
+ if (generation !== childGeneration) return // 旧子进程的迟到事件,忽略
270
+ log(`DSH 退出:code=${code} signal=${signal}${stoppingForRestart ? '(主动重启)' : ''}`)
271
+ child = null
272
+ if (stoppingForRestart) return
273
+ // 无论用户主动关闭还是崩溃都重新拉起;若检测到升级中,等升级完成再拉起
274
+ restarts += 1
275
+ const delay = Math.min(30_000, 1000 * restarts)
276
+ log(`${delay}ms 后重新拉起(第 ${restarts} 次)`)
277
+ setTimeout(async () => {
278
+ if (child) return
279
+ await waitForUpgrade()
280
+ if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH'); return }
281
+ if (!child) { child = launch(); persist() }
282
+ }, delay)
283
+ })
284
+ // 稳定运行 60 秒后把退避计数归零,避免一次崩溃永久 30 秒退避
285
+ const timer = setTimeout(() => {
286
+ if (generation === childGeneration && child) restarts = 0
287
+ }, 60_000)
288
+ timer.unref?.()
289
+ return spawned
290
+ }
291
+
292
+ async function killDsh() {
293
+ const pids = listDshPids()
294
+ if (pids.length === 0) return
295
+ log(`终止 DSH 进程:${pids.join(',')}`)
296
+ const parents = new Map()
297
+ try {
298
+ if (process.platform === 'win32') {
299
+ const script = `Get-CimInstance Win32_Process -Filter "Name='${exeName}'" | ForEach-Object { "$($_.ProcessId),$($_.ParentProcessId)" }`
300
+ const out = spawnSync('powershell', ['-NoProfile', '-Command', script], { encoding: 'utf8', windowsHide: true, timeout: 8000 })
301
+ for (const line of String(out.stdout ?? '').split(/\r?\n/u)) {
302
+ const [pid, ppid] = line.trim().split(',').map(Number)
303
+ if (pid) parents.set(pid, ppid)
304
+ }
305
+ }
306
+ } catch { /* 拿不到父子关系就全杀 */ }
307
+ // 先杀主进程(父进程不在集合内者),否则 Electron 会把 Host 退出当崩溃弹原生对话框
308
+ for (const pid of pids.filter((item) => !pids.includes(parents.get(item)))) {
309
+ try { process.kill(pid) } catch { /* 已退出 */ }
310
+ log(` 先终止主进程 ${pid}`)
311
+ }
312
+ const deadline = Date.now() + 10_000
313
+ while (Date.now() < deadline && listDshPids().length > 0) {
314
+ await new Promise((resolve) => setTimeout(resolve, 300))
315
+ }
316
+ for (const pid of listDshPids()) {
317
+ try {
318
+ if (process.platform === 'win32') spawnSync('taskkill', ['/F', '/PID', String(pid)], { windowsHide: true })
319
+ else process.kill(pid, 'SIGKILL')
320
+ } catch { /* 已退出 */ }
321
+ }
322
+ const portDeadline = Date.now() + 60_000
323
+ while (Date.now() < portDeadline && await portOpen(bridgePort)) {
324
+ await new Promise((resolve) => setTimeout(resolve, 500))
325
+ }
326
+ }
327
+
328
+ async function waitIdle(seconds) {
329
+ const deadline = Date.now() + seconds * 1000
330
+ while (Date.now() < deadline) {
331
+ if (idleAge() >= idleSeconds) return true
332
+ await new Promise((resolve) => setTimeout(resolve, 1000))
333
+ }
334
+ return false
335
+ }
336
+
337
+ async function restart(mode = 'default') {
338
+ if (restarting) { log('已有重启在进行,忽略本次请求'); return { skipped: true } }
339
+ restarting = true
340
+ try {
341
+ log(`收到重启请求(模式 ${mode})`)
342
+ if (mode !== 'immediate') {
343
+ const ok = await waitIdle(idleSeconds + 30)
344
+ if (!ok) {
345
+ log('用户仍在活跃,放弃本次重启(不再硬打断)')
346
+ return { ok: false, reason: 'busy' }
347
+ }
348
+ } else {
349
+ await new Promise((resolve) => setTimeout(resolve, 3000))
350
+ }
351
+ stoppingForRestart = true
352
+ await killDsh()
353
+ child = launch()
354
+ persist()
355
+ return { ok: true }
356
+ } finally {
357
+ stoppingForRestart = false
358
+ restarting = false
359
+ }
360
+ }
361
+
362
+ // ---------- 控制接口 ----------
363
+ // pausedUntil > 0 时暂停自动拉起(给用户关机/维护用)
364
+ let pausedUntil = 0
365
+
366
+ function cors(res) {
367
+ // 客户端插件运行在 DSH 页面里(http://127.0.0.1:<随机端口>),需要允许跨端口调用
368
+ res.setHeader('access-control-allow-origin', '*')
369
+ res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS')
370
+ res.setHeader('access-control-allow-headers', 'content-type')
371
+ }
372
+
373
+ function startControl() {
374
+ const server = http.createServer(async (req, res) => {
375
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
376
+ cors(res)
377
+ if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
378
+ const paused = pausedUntil > Date.now()
379
+ if (url.pathname === '/status') {
380
+ const info = await probe()
381
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
382
+ res.end(JSON.stringify({
383
+ supervisor: { pid: process.pid, restarts, restarting, exe: exePath },
384
+ ...info,
385
+ idleSeconds: Math.round(idleAge()),
386
+ paused,
387
+ pausedSecondsLeft: paused ? Math.round((pausedUntil - Date.now()) / 1000) : 0,
388
+ }, null, 2))
389
+ return
390
+ }
391
+ if (url.pathname === '/pause') {
392
+ const minutes = Number(url.searchParams.get('minutes') ?? '30')
393
+ pausedUntil = Date.now() + Math.max(1, minutes) * 60_000
394
+ log(`暂停自动拉起 ${minutes} 分钟(手动重启仍可用)`)
395
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
396
+ res.end(JSON.stringify({ paused: true, minutes }))
397
+ return
398
+ }
399
+ if (url.pathname === '/resume') {
400
+ pausedUntil = 0
401
+ log('恢复自动拉起')
402
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
403
+ res.end(JSON.stringify({ paused: false }))
404
+ return
405
+ }
406
+ if (url.pathname === '/stop') {
407
+ log('收到停止指令:守护进程退出,不再拉起 DSH')
408
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
409
+ res.end(JSON.stringify({ stopped: true }))
410
+ setTimeout(() => process.exit(0), 300)
411
+ return
412
+ }
413
+ if (url.pathname === '/restart') {
414
+ const mode = url.searchParams.get('mode') === 'immediate' ? 'immediate' : 'default'
415
+ res.writeHead(202, { 'content-type': 'application/json; charset=utf-8' })
416
+ res.end(JSON.stringify({ accepted: true, mode }))
417
+ void restart(mode)
418
+ return
419
+ }
420
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
421
+ res.end('not found\n')
422
+ })
423
+ server.on('error', (error) => {
424
+ if (error.code === 'EADDRINUSE') {
425
+ log('控制端口已被占用,说明已有守护进程在运行;本实例退出(单实例保护)')
426
+ process.exit(0)
427
+ }
428
+ log(`控制端口错误:${error.code}`)
429
+ process.exit(1)
430
+ })
431
+ server.listen(controlPort, '127.0.0.1', () => log(`控制接口:http://127.0.0.1:${controlPort}/status`))
432
+ return server
433
+ }
434
+
435
+ // ---------- 主流程 ----------
436
+ if (has('status')) {
437
+ const info = await probe()
438
+ console.log(JSON.stringify({
439
+ exe: exePath,
440
+ ...info,
441
+ idleSeconds: Math.round(idleAge()),
442
+ stateFile,
443
+ logFile,
444
+ }, null, 2))
445
+ process.exit(0)
446
+ }
447
+
448
+ if (has('restart')) {
449
+ const mode = has('immediate') ? 'immediate' : 'default'
450
+ const request = http.request({ host: '127.0.0.1', port: controlPort, path: `/restart?mode=${mode}`, method: 'POST' }, (res) => {
451
+ res.resume()
452
+ console.log(`守护进程已接受重启请求(${mode})→ 日志:${logFile}`)
453
+ process.exit(0)
454
+ })
455
+ request.on('error', () => {
456
+ console.error('守护进程没在运行(控制端口连不上)。先启动它,或直接重启 DSH。')
457
+ process.exit(1)
458
+ })
459
+ request.end()
460
+ } else {
461
+ fs.writeFileSync(pidFile, String(process.pid))
462
+ log(`守护进程启动:pid=${process.pid} 平台=${process.platform} exe=${exePath ?? '未找到'}`)
463
+ const cleanup = () => { try { fs.rmSync(pidFile, { force: true }) } catch { /* 忽略 */ } }
464
+ process.on('SIGINT', () => { log('收到 SIGINT,退出'); cleanup(); process.exit(0) })
465
+ process.on('SIGTERM', () => { log('收到 SIGTERM,退出'); cleanup(); process.exit(0) })
466
+ process.on('exit', cleanup)
467
+
468
+ startControl()
469
+ const info = await probe()
470
+ if (info.running) {
471
+ log(`DSH 已在运行(PID ${info.pids.join(',')}),接管监视(${pollMs / 1000} 秒轮询)`)
472
+ setInterval(async () => {
473
+ if (stoppingForRestart || restarting || launchFailed) return
474
+ const current = await probe()
475
+ if (!current.running) {
476
+ restarts += 1
477
+ log('检测到 DSH 已退出(外部拉起),准备拉起')
478
+ await waitForUpgrade()
479
+ if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH'); return }
480
+ if (!child) { child = launch(); persist() }
481
+ }
482
+ }, pollMs)
483
+ } else {
484
+ log('未发现运行中的 DSH,等待(可能是升级中)后拉起')
485
+ await waitForUpgrade()
486
+ if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH') } else { child = launch(); persist() }
487
+ }
488
+ }