@andy.ian/dsh-homing 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/bin/restart-daemon.mjs +3 -0
  2. package/bin/restart.mjs +3 -0
  3. package/index.js +714 -21
  4. package/lib/devices.mjs +0 -1
  5. package/lib/files-page.mjs +0 -18
  6. package/lib/files.mjs +39 -27
  7. package/package.json +8 -9
  8. package/restart/client.mjs +184 -0
  9. package/restart/config.mjs +187 -0
  10. package/restart/engine.mjs +93 -0
  11. package/restart/face.mjs +62 -0
  12. package/restart/runner.mjs +184 -0
  13. package/restart/service.mjs +91 -0
  14. package/restart-daemon/README.md +66 -0
  15. package/restart-daemon/cli.mjs +321 -0
  16. package/restart-daemon/lib/detach.mjs +126 -0
  17. package/restart-daemon/lib/process-tree.mjs +69 -0
  18. package/restart-daemon/lib/restart-flow.mjs +111 -0
  19. package/restart-daemon/lib/update-state.mjs +72 -0
  20. package/restart-daemon/main.mjs +691 -0
  21. package/bin/supervisor.mjs +0 -488
  22. package/bin/watchdog.mjs +0 -144
  23. package/lib/vendor/node_modules/ssh2/examples/server-chat.js +0 -238
  24. package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +0 -134
  25. package/lib/vendor/node_modules/ssh2/test/common.js +0 -316
  26. package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +0 -26
  27. package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +0 -33
  28. package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +0 -52
  29. package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +0 -12
  30. package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +0 -5
  31. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +0 -15
  32. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +0 -26
  33. package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +0 -30
  34. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +0 -21
  35. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +0 -1
  36. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +0 -7
  37. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +0 -7
  38. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +0 -22
  39. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +0 -1
  40. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +0 -7
  41. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +0 -7
  42. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +0 -23
  43. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +0 -1
  44. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +0 -7
  45. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +0 -7
  46. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +0 -9
  47. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +0 -1
  48. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +0 -7
  49. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +0 -7
  50. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +0 -10
  51. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +0 -1
  52. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +0 -8
  53. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +0 -7
  54. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +0 -10
  55. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +0 -1
  56. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +0 -8
  57. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +0 -7
  58. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +0 -7
  59. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +0 -1
  60. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +0 -7
  61. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +0 -7
  62. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +0 -27
  63. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +0 -1
  64. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +0 -7
  65. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +0 -7
  66. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +0 -28
  67. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +0 -1
  68. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +0 -8
  69. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +0 -7
  70. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +0 -29
  71. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +0 -1
  72. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +0 -8
  73. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +0 -7
  74. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +0 -12
  75. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +0 -1
  76. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +0 -7
  77. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +0 -7
  78. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +0 -15
  79. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +0 -1
  80. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +0 -8
  81. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +0 -7
  82. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +0 -5
  83. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +0 -1
  84. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +0 -7
  85. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +0 -7
  86. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +0 -8
  87. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +0 -1
  88. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +0 -8
  89. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +0 -7
  90. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +0 -27
  91. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +0 -1
  92. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +0 -7
  93. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +0 -7
  94. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +0 -30
  95. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +0 -1
  96. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +0 -8
  97. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +0 -7
  98. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +0 -54
  99. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +0 -1
  100. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +0 -6
  101. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +0 -6
  102. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +0 -17
  103. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +0 -7
  104. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +0 -26
  105. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +0 -7
  106. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +0 -18
  107. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +0 -7
  108. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +0 -9
  109. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +0 -7
  110. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +0 -10
  111. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +0 -7
  112. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +0 -11
  113. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +0 -7
  114. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +0 -11
  115. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +0 -7
  116. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +0 -8
  117. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +0 -7
  118. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +0 -13
  119. package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +0 -7
  120. package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +0 -27
  121. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +0 -12
  122. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +0 -5
  123. package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +0 -15
  124. package/lib/vendor/node_modules/ssh2/test/test-exec.js +0 -578
  125. package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +0 -486
  126. package/lib/vendor/node_modules/ssh2/test/test-keygen.js +0 -60
  127. package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +0 -1460
  128. package/lib/vendor/node_modules/ssh2/test/test-openssh.js +0 -261
  129. package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +0 -631
  130. package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +0 -177
  131. package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +0 -138
  132. package/lib/vendor/node_modules/ssh2/test/test-sftp.js +0 -842
  133. package/lib/vendor/node_modules/ssh2/test/test-shell.js +0 -109
  134. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +0 -110
  135. package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +0 -171
  136. package/lib/vendor/node_modules/ssh2/test/test-userauth.js +0 -611
  137. package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +0 -25
  138. package/lib/vendor/node_modules/ssh2/test/test.js +0 -20
package/lib/devices.mjs CHANGED
@@ -16,7 +16,6 @@ import crypto from 'node:crypto'
16
16
  const FILE = 'devices.json'
17
17
 
18
18
  /** 记录的最后活跃时间超过这个天数就不再参与「活跃设备」展示(但不自动吊销)。 */
19
- export const STALE_DAYS = 180
20
19
 
21
20
  const b64url = (buf) => Buffer.from(buf).toString('base64')
22
21
  .replaceAll('+', '-').replaceAll('/', '_').replaceAll(/=+$/gu, '')
@@ -333,24 +333,6 @@ export function renderFile({ info, message, isError }) {
333
333
  }
334
334
 
335
335
  /** 运行结果页 */
336
- export function renderRunResult({ file, result }) {
337
- const failed = !result.ok || result.timedOut || (typeof result.code === 'number' && result.code !== 0)
338
- const body = `
339
- <div class="bar">
340
- <h1>运行结果</h1>
341
- <div class="path">${escapeHtml(file)}</div>
342
- </div>
343
- ${failed
344
- ? `<div class="msg err">${escapeHtml(result.error ?? (result.timedOut ? '执行超时(15 秒),已终止' : `退出码 ${result.code}`))}</div>`
345
- : `<div class="msg">退出码 ${result.code}</div>`}
346
- <pre>${escapeHtml(result.output === '' ? '(无输出)' : result.output)}</pre>
347
- ${result.truncated ? '<p class="crumbs">输出过长,已截断到 64 KB</p>' : ''}
348
- <div class="row">
349
- <a class="btn ghost" href="/files?path=${encodeURIComponent(file.replace(/[\\/][^\\/]*$/u, '') || '/')}"
350
- style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">返回目录</a>
351
- </div>`
352
- return layout({ title: `运行 ${file}`, body })
353
- }
354
336
 
355
337
  /** 运行页:可填参数,结果同页显示,便于改参数重跑 */
356
338
  export function renderRunPage({ file, args = '', result = null }) {
package/lib/files.mjs CHANGED
@@ -10,7 +10,7 @@
10
10
  import fs from 'node:fs'
11
11
  import os from 'node:os'
12
12
  import path from 'node:path'
13
- import { spawn } from 'node:child_process'
13
+ import { spawn, spawnSync } from 'node:child_process'
14
14
 
15
15
  const MAX_READ = 512 * 1024
16
16
  const MAX_OUTPUT = 64 * 1024
@@ -212,21 +212,6 @@ export function workspaceIndex(dshHome) {
212
212
  }
213
213
 
214
214
  /** 从 DSH 的工作区注册表里读出「标题 + 路径」,给文件页做快捷入口。 */
215
- export function listWorkspaces(dshHome) {
216
- const file = path.join(dshHome, 'storages', 'workspace.json');
217
- try {
218
- const data = JSON.parse(fs.readFileSync(file, 'utf8'));
219
- const table = (data && data.tables && data.tables.workspaces) || {};
220
- return Object.values(table)
221
- .filter((item) => item && typeof item.path === 'string')
222
- .map((item) => ({
223
- title: typeof item.title === 'string' && item.title !== '' ? item.title : path.basename(item.path),
224
- path: item.path,
225
- }));
226
- } catch {
227
- return [];
228
- }
229
- }
230
215
 
231
216
  /** 列目录。不可读时返回 error 而不是抛错,页面好展示。 */
232
217
  export function listDirectory(absPath) {
@@ -360,6 +345,18 @@ export function writeTextFile(absPath, text, limit = MAX_READ) {
360
345
  }
361
346
  }
362
347
 
348
+ /** 判断命令是否可用(跨平台:Windows 查 where,其他查 PATH) */
349
+ function commandExists(name) {
350
+ try {
351
+ const checker = process.platform === 'win32' ? 'where' : 'sh';
352
+ const args = process.platform === 'win32' ? [name] : ['-c', 'command -v ' + JSON.stringify(name)];
353
+ const out = spawnSync(checker, args, { encoding: 'utf8', windowsHide: true, timeout: 4000 });
354
+ return out.status === 0 && String(out.stdout ?? '').trim().length > 0;
355
+ } catch {
356
+ return false;
357
+ }
358
+ }
359
+
363
360
  /** 按类型执行文件,收集输出。不经过 shell 拼接(bat/ps1/sh 由解释器接手)。 */
364
361
  export function runFile(absPath, args = '', { timeoutMs = 15_000, cwd } = {}) {
365
362
  const target = resolvePath(absPath);
@@ -374,24 +371,39 @@ export function runFile(absPath, args = '', { timeoutMs = 15_000, cwd } = {}) {
374
371
  // 再用 & 调用目标并透传参数。不能塞进 cmd /c 一行命令——路径的引号会被 cmd 吃掉。
375
372
  let command = target;
376
373
  let argv = argList;
374
+ const isWindows = process.platform === 'win32';
375
+
377
376
  if (kind === 'ps1') {
378
- const wrapper = path.join(os.tmpdir(), 'dsh-homing-run-ps1.ps1');
379
- fs.writeFileSync(wrapper, [
380
- '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
381
- '$target = $args[0]',
382
- '$rest = @($args | Select-Object -Skip 1)',
383
- '& $target @rest',
384
- 'exit $LASTEXITCODE',
385
- ].join('\r\n'), 'utf8');
386
- command = 'powershell.exe';
387
- argv = ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', wrapper, target, ...argList];
377
+ if (isWindows) {
378
+ // 中文 Windows 默认 GBK 输出:用包装脚本强制 UTF-8,同时保留 -File 的参数绑定
379
+ const wrapper = path.join(os.tmpdir(), 'dsh-homing-run-ps1.ps1');
380
+ fs.writeFileSync(wrapper, [
381
+ '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
382
+ '$target = $args[0]',
383
+ '$rest = @($args | Select-Object -Skip 1)',
384
+ '& $target @rest',
385
+ 'exit $LASTEXITCODE',
386
+ ].join('\r\n'), 'utf8');
387
+ command = 'powershell.exe';
388
+ argv = ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', wrapper, target, ...argList];
389
+ } else {
390
+ // macOS/Linux 上只有装了 PowerShell 7 才能跑 .ps1
391
+ if (!commandExists('pwsh')) return Promise.resolve({ ok: false, error: '当前平台没有 PowerShell(.ps1 需要 pwsh)' });
392
+ command = 'pwsh';
393
+ argv = ['-NoProfile', '-File', target, ...argList];
394
+ }
388
395
  } else if (kind === 'bat') {
396
+ if (!isWindows) return Promise.resolve({ ok: false, error: '.bat 只能在 Windows 上运行' });
389
397
  command = 'cmd.exe';
390
398
  const tail = argList.map((item) => ' "' + item.replace(/"/gu, '""') + '"').join('');
391
399
  argv = ['/d', '/c', 'chcp 65001>nul & call "' + target + '"' + tail];
392
400
  } else if (kind === 'sh') {
393
- command = 'bash';
401
+ const shell = isWindows ? 'bash' : '/bin/sh';
402
+ if (!commandExists(shell)) return Promise.resolve({ ok: false, error: '找不到可用的 shell(Windows 需要 Git Bash)' });
403
+ command = shell;
394
404
  argv = [target, ...argList];
405
+ } else if (kind === 'exe' && !isWindows) {
406
+ return Promise.resolve({ ok: false, error: '.exe 只能在 Windows 上运行' });
395
407
  }
396
408
 
397
409
  return new Promise((resolve) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.0.3",
3
+ "version": "2.1.0",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [
@@ -24,13 +24,8 @@
24
24
  },
25
25
  "icon": "./icon.svg",
26
26
  "bin": {
27
- "dsh-homing-bootstrap": "./bin/bootstrap-server.mjs",
28
- "dsh-homing-renew-cert": "./bin/renew-cert.mjs",
29
- "dsh-homing-auth": "./bin/auth.mjs",
30
- "dsh-homing-backup": "./bin/backup.mjs",
31
- "dsh-homing-entry": "./bin/entry-link.mjs",
32
- "dsh-homing-watchdog": "./bin/watchdog.mjs",
33
- "dsh-homing-supervisor": "./bin/supervisor.mjs"
27
+ "dsh-homing-restart-daemon": "./bin/restart-daemon.mjs",
28
+ "dsh-homing-restart": "./bin/restart.mjs"
34
29
  },
35
30
  "exports": {
36
31
  ".": "./index.js",
@@ -49,12 +44,16 @@
49
44
  "bin/nginx-ws-map.conf",
50
45
  "lib/*.mjs",
51
46
  "lib/*.js",
47
+ "restart-daemon/**",
52
48
  "cordis.patch.yml",
53
49
  "locale/*.json",
54
50
  "icon.svg",
55
51
  "README.md",
56
52
  "LICENSE",
57
- "lib/vendor/**"
53
+ "lib/vendor/**",
54
+ "restart/**",
55
+ "!lib/vendor/node_modules/ssh2/test/**",
56
+ "!lib/vendor/node_modules/ssh2/examples/**"
58
57
  ],
59
58
  "publishConfig": {
60
59
  "access": "public",
@@ -0,0 +1,184 @@
1
+ /**
2
+ * 重启页面客户端脚本(v2:带逐步诊断)
3
+ *
4
+ * 设计目标:不只做事,还要把"卡在哪一步"直接显示在页面上,
5
+ * 因为手机浏览器里看不到控制台。
6
+ *
7
+ * 底部 #live 会依次显示:脚本加载 → 元素就绪 → 创建连接 → 已连接 → 第 N 帧
8
+ * 任何 JS 错误都会以「脚本错误:…」的形式显示出来。
9
+ */
10
+ (function () {
11
+ function start() {
12
+ var steps = [];
13
+ var live = document.getElementById('live');
14
+
15
+ function mark(text) {
16
+ if (!live) live = document.getElementById('live');
17
+ if (!live) return;
18
+ steps.push(text);
19
+ if (steps.length > 5) steps.shift();
20
+ live.textContent = steps.join(' → ');
21
+ }
22
+
23
+ window.onerror = function (message, source, line) {
24
+ if (!live) live = document.getElementById('live');
25
+ if (live) live.textContent = '脚本错误:' + message + ' @' + line;
26
+ return false;
27
+ };
28
+ window.addEventListener('unhandledrejection', function (event) {
29
+ if (!live) live = document.getElementById('live');
30
+ if (live) live.textContent = '未处理的 Promise 错误:' + (event.reason && event.reason.message ? event.reason.message : String(event.reason));
31
+ });
32
+
33
+ // 一次性消息:把 ?m= 从地址栏去掉,刷新后不再重复显示"已触发强制重启"
34
+ if (location.search.includes('m=')) {
35
+ try { history.replaceState(null, '', location.pathname); } catch (error) {}
36
+ }
37
+
38
+ mark('脚本 v2 已加载');
39
+
40
+ var sup = document.getElementById('sup-state');
41
+ var busy = document.getElementById('busy-state');
42
+ var policyEl = document.getElementById('policy-state');
43
+ var queueEl = document.getElementById('queue-state');
44
+ var list = document.getElementById('busy-list');
45
+ if (!sup) {
46
+ mark('缺少 sup-state 元素');
47
+ return;
48
+ }
49
+ // 强制重启两步确认:首次点击只展开确认区,5 秒内不确认自动还原
50
+ (function setupForceConfirm() {
51
+ var btn = document.getElementById('btn-force');
52
+ var box = document.getElementById('force-confirm');
53
+ var cancel = document.getElementById('btn-force-cancel');
54
+ if (!btn || !box) return;
55
+ var timer = null;
56
+
57
+ function reset() {
58
+ if (timer) { clearTimeout(timer); timer = null; }
59
+ box.style.display = 'none';
60
+ btn.style.display = '';
61
+ btn.disabled = false;
62
+ }
63
+
64
+ function expand(event) {
65
+ if (event && event.preventDefault) event.preventDefault(); // 拦截提交,先确认
66
+ btn.style.display = 'none';
67
+ btn.disabled = true;
68
+ box.style.display = '';
69
+ if (timer) clearTimeout(timer);
70
+ timer = setTimeout(reset, 5000); // 5 秒不确认 → 还原
71
+ }
72
+
73
+ btn.addEventListener('click', expand);
74
+ if (cancel) cancel.addEventListener('click', reset);
75
+ })();
76
+
77
+ mark('元素就绪');
78
+
79
+ var lastFrame = Date.now();
80
+ var acks = 0;
81
+ var es = null;
82
+ var gotFirst = false;
83
+
84
+ function setBusy(state) {
85
+ if (busy) busy.textContent = state.busy
86
+ ? ('是(' + (state.sessions || []).length + ' 个会话运行中)')
87
+ : '否(空闲)';
88
+ if (!list) return;
89
+ list.innerHTML = (state.sessions || []).map(function (item) {
90
+ var line = '<li><b>' + (item.title || '(未命名)') + '</b> · ' + item.age + ' 秒前';
91
+ if (item.cwd) line += '<br><span class="dim">' + item.cwd + '</span>';
92
+ return line + '</li>';
93
+ }).join('');
94
+ }
95
+
96
+ function onFrame(evt) {
97
+ var state = null;
98
+ try {
99
+ state = JSON.parse(evt.data);
100
+ } catch (error) {
101
+ mark('帧解析失败');
102
+ return;
103
+ }
104
+ if (sup) {
105
+ sup.textContent = state.running
106
+ ? ('运行中 · 重启 ' + state.restarts + ' 次' + (state.paused ? (' · 暂停剩 ' + state.pausedSecondsLeft + ' 秒') : ''))
107
+ : '未运行';
108
+ }
109
+ if (policyEl && state.config) {
110
+ var cfg = state.config;
111
+ policyEl.textContent = (cfg.name || 'default')
112
+ + ' · 安静 ' + Math.round((cfg.quietMs || 0) / 1000) + ' 秒'
113
+ + ' · 轮询 ' + Math.round((cfg.pollMs || 0) / 1000) + ' 秒'
114
+ + (cfg.valid === false ? '(配置有误,已回退)' : '')
115
+ + (cfg.usedLastGood ? '(用上次有效配置)' : '');
116
+ }
117
+ if (queueEl) {
118
+ var p = state.policy;
119
+ queueEl.textContent = (p && p.active)
120
+ ? ('排队中 · ' + (p.reason || '等待空闲') + '(已等 ' + (p.waitedSeconds || 0) + ' 秒)')
121
+ : '未排队';
122
+ }
123
+ setBusy(state);
124
+ lastFrame = Date.now();
125
+ if (!gotFirst) {
126
+ gotFirst = true;
127
+ mark('收到第 1 帧');
128
+ }
129
+ acks += 1;
130
+ try {
131
+ fetch('/dsh_homing/restart/ack', {
132
+ method: 'POST',
133
+ headers: { 'content-type': 'application/json' },
134
+ body: JSON.stringify({ client: state.client, seq: state.seq, ts: state.ts }),
135
+ });
136
+ } catch (error) {}
137
+ if (live) live.textContent = '实时更新(SSE)· 已确认 ' + acks + ' 次';
138
+ }
139
+
140
+ function connect() {
141
+ try {
142
+ if (es) es.close();
143
+ } catch (error) {}
144
+ mark('创建 EventSource');
145
+ try {
146
+ es = new EventSource('/dsh_homing/restart/events');
147
+ } catch (error) {
148
+ mark('EventSource 创建失败');
149
+ return;
150
+ }
151
+ es.onopen = function () {
152
+ mark('SSE 已连接');
153
+ };
154
+ es.onerror = function () {
155
+ mark('SSE 出错(readyState=' + (es ? es.readyState : '?') + ')');
156
+ };
157
+ es.onmessage = onFrame;
158
+ }
159
+
160
+ connect();
161
+
162
+ // 看门狗:20 秒没帧就重建(不用轮询)
163
+ setInterval(function () {
164
+ if (Date.now() - lastFrame > 20000) {
165
+ lastFrame = Date.now();
166
+ mark('20 秒无帧,重建连接');
167
+ connect();
168
+ }
169
+ }, 5000);
170
+
171
+ document.addEventListener('visibilitychange', function () {
172
+ if (document.visibilityState !== 'visible') return;
173
+ if (Date.now() - lastFrame > 5000) {
174
+ mark('回到前台,重建连接');
175
+ connect();
176
+ }
177
+ });
178
+ }
179
+ if (document.readyState === 'loading') {
180
+ document.addEventListener('DOMContentLoaded', start);
181
+ } else {
182
+ start();
183
+ }
184
+ })();
@@ -0,0 +1,187 @@
1
+ /**
2
+ * 策略配置:把「策略」表达成一份可校验的配置
3
+ *
4
+ * 设计边界(很重要):
5
+ * 配置只描述"参数 + 允许的条件组合",不是任意脚本。
6
+ * 词汇表是封闭的:未知键直接拒绝并回退默认值(fail-closed),
7
+ * 以免配置文件变成第二套程序。
8
+ *
9
+ * 默认配置 = 当前线上的行为(3 秒轮询、5 秒安静窗口、失败重试 1 次)。
10
+ */
11
+ import fs from 'node:fs';
12
+
13
+ export const DEFAULT_SPEC = deepFreeze({
14
+ version: 1,
15
+ name: 'default',
16
+ schedule: { pollMs: 3000, earliestSeconds: 0 },
17
+ idle: { quietMs: 5000, requireNoBusySessions: true },
18
+ retry: { attempts: 1, delayMs: 3000 },
19
+ guard: { recheckBeforeTrigger: true, recheckBeforeRetry: true },
20
+ });
21
+
22
+ const LIMITS = {
23
+ pollMs: [500, 60_000],
24
+ earliestSeconds: [0, 24 * 3600],
25
+ quietMs: [0, 600_000],
26
+ attempts: [0, 5],
27
+ delayMs: [0, 60_000],
28
+ };
29
+
30
+ function deepFreeze(value) {
31
+ if (value && typeof value === 'object') {
32
+ for (const item of Object.values(value)) deepFreeze(item);
33
+ Object.freeze(value);
34
+ }
35
+ return value;
36
+ }
37
+
38
+ function within(name, value) {
39
+ const [min, max] = LIMITS[name];
40
+ if (!Number.isFinite(value)) return { ok: false, error: `${name} 必须是数字` };
41
+ if (value < min || value > max) return { ok: false, error: `${name} 超出范围 ${min}..${max}` };
42
+ return { ok: true, value: Math.round(value) };
43
+ }
44
+
45
+ function pickObject(raw, key, errors) {
46
+ const value = raw?.[key];
47
+ if (value === undefined) return {};
48
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
49
+ errors.push(`${key} 必须是对象`);
50
+ return {};
51
+ }
52
+ return value;
53
+ }
54
+
55
+ /**
56
+ * 校验并归一化配置。
57
+ * @returns {{ ok: boolean, spec: object, errors: string[], source: string }}
58
+ */
59
+ export function parseSpec(raw, source = 'default') {
60
+ const errors = [];
61
+ if (raw !== undefined && (raw === null || typeof raw !== 'object' || Array.isArray(raw))) {
62
+ return { ok: false, spec: DEFAULT_SPEC, errors: ['配置根必须是对象'], source };
63
+ }
64
+ const allowedRoot = new Set(['version', 'name', 'schedule', 'idle', 'retry', 'guard']);
65
+ for (const key of Object.keys(raw ?? {})) {
66
+ if (!allowedRoot.has(key)) errors.push(`未知配置项:${key}`);
67
+ }
68
+
69
+ // 嵌套键也做白名单校验(否则 config 里写错字段名会被静默忽略)
70
+ const nestedKeys = {
71
+ schedule: ['pollMs', 'earliestSeconds'],
72
+ idle: ['quietMs', 'requireNoBusySessions'],
73
+ retry: ['attempts', 'delayMs'],
74
+ guard: ['recheckBeforeTrigger', 'recheckBeforeRetry'],
75
+ };
76
+ for (const [section, allowed] of Object.entries(nestedKeys)) {
77
+ const value = raw?.[section];
78
+ if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value)) continue;
79
+ for (const key of Object.keys(value)) {
80
+ if (!allowed.includes(key)) errors.push('未知配置项:' + section + '.' + key);
81
+ }
82
+ }
83
+
84
+ const schedule = pickObject(raw, 'schedule', errors);
85
+ const idle = pickObject(raw, 'idle', errors);
86
+ const retry = pickObject(raw, 'retry', errors);
87
+ const guard = pickObject(raw, 'guard', errors);
88
+
89
+ const normalized = {
90
+ version: 1,
91
+ name: typeof raw?.name === 'string' && raw.name.trim() ? raw.name.trim().slice(0, 60) : 'custom',
92
+ schedule: {
93
+ pollMs: DEFAULT_SPEC.schedule.pollMs,
94
+ earliestSeconds: DEFAULT_SPEC.schedule.earliestSeconds,
95
+ },
96
+ idle: {
97
+ quietMs: DEFAULT_SPEC.idle.quietMs,
98
+ requireNoBusySessions: DEFAULT_SPEC.idle.requireNoBusySessions,
99
+ },
100
+ retry: { attempts: DEFAULT_SPEC.retry.attempts, delayMs: DEFAULT_SPEC.retry.delayMs },
101
+ guard: {
102
+ recheckBeforeTrigger: DEFAULT_SPEC.guard.recheckBeforeTrigger,
103
+ recheckBeforeRetry: DEFAULT_SPEC.guard.recheckBeforeRetry,
104
+ },
105
+ };
106
+
107
+ for (const [key, range] of [['pollMs', 'pollMs'], ['earliestSeconds', 'earliestSeconds']]) {
108
+ if (schedule[key] === undefined) continue;
109
+ const result = within(range, Number(schedule[key]));
110
+ if (result.ok) normalized.schedule[key] = result.value;
111
+ else errors.push('schedule.' + result.error);
112
+ }
113
+ if (idle.quietMs !== undefined) {
114
+ const result = within('quietMs', Number(idle.quietMs));
115
+ if (result.ok) normalized.idle.quietMs = result.value;
116
+ else errors.push('idle.' + result.error);
117
+ }
118
+ if (idle.requireNoBusySessions !== undefined) {
119
+ if (typeof idle.requireNoBusySessions !== 'boolean') errors.push('idle.requireNoBusySessions 必须是布尔值');
120
+ else normalized.idle.requireNoBusySessions = idle.requireNoBusySessions;
121
+ }
122
+ for (const [key, range] of [['attempts', 'attempts'], ['delayMs', 'delayMs']]) {
123
+ if (retry[key] === undefined) continue;
124
+ const result = within(range, Number(retry[key]));
125
+ if (result.ok) normalized.retry[key] = result.value;
126
+ else errors.push('retry.' + result.error);
127
+ }
128
+ for (const key of Object.keys(normalized.guard)) {
129
+ if (guard[key] === undefined) continue;
130
+ if (typeof guard[key] !== 'boolean') errors.push('guard.' + key + ' 必须是布尔值');
131
+ else normalized.guard[key] = guard[key];
132
+ }
133
+ if (raw?.version !== undefined && Number(raw.version) !== 1) errors.push('version 目前只支持 1');
134
+
135
+ return { ok: errors.length === 0, spec: errors.length === 0 ? deepFreeze(normalized) : DEFAULT_SPEC, errors, source };
136
+ }
137
+
138
+ /**
139
+ * 读取配置文件(不存在 → 默认配置)。
140
+ * 配置写坏时回退默认值,并把错误带出去给 status() 显示,绝不因此让策略崩掉。
141
+ * 注意:热加载路径(createSpecWatcher)会用「上一次有效配置」覆盖这里回退的默认值。
142
+ */
143
+ export function loadSpec(file) {
144
+ if (!file) return { ...parseSpec(undefined), source: 'default' };
145
+ let text;
146
+ try {
147
+ text = fs.readFileSync(file, 'utf8');
148
+ } catch (error) {
149
+ if (error.code === 'ENOENT') return { ...parseSpec(undefined), source: 'default' };
150
+ return { ok: false, spec: DEFAULT_SPEC, errors: ['读取配置失败:' + error.message], source: file };
151
+ }
152
+ try {
153
+ return parseSpec(JSON.parse(text), file);
154
+ } catch (error) {
155
+ return { ok: false, spec: DEFAULT_SPEC, errors: ['JSON 解析失败:' + error.message], source: file };
156
+ }
157
+ }
158
+
159
+ /** 文件 mtime 变了才重新加载(热更新用)
160
+ *
161
+ * 关键:配置写到一半/写坏时,保留「上一次有效配置」,而不是退回默认值——
162
+ * 否则一次手抖的编辑可能让安静窗口从 5 秒变回默认,行为悄悄改变。
163
+ * 只有首次加载就没有有效配置时,才用 DEFAULT_SPEC。
164
+ */
165
+ export function createSpecWatcher(file) {
166
+ let mtime = 0;
167
+ let cached = loadSpec(file);
168
+ let lastGood = cached.ok ? cached : { ok: true, spec: DEFAULT_SPEC, errors: [], source: 'default' };
169
+ return function current() {
170
+ if (!file) return lastGood;
171
+ try {
172
+ const stat = fs.statSync(file);
173
+ if (stat.mtimeMs !== mtime) {
174
+ mtime = stat.mtimeMs;
175
+ const loaded = loadSpec(file);
176
+ if (loaded.ok) {
177
+ cached = loaded;
178
+ lastGood = loaded;
179
+ } else {
180
+ // 无效配置:保留上次有效策略,但把错误暴露出去
181
+ cached = { ...loaded, spec: lastGood.spec, usedLastGood: true };
182
+ }
183
+ }
184
+ } catch { /* 文件暂时不存在:沿用上次结果 */ }
185
+ return cached;
186
+ };
187
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * 策略引擎:纯决策函数
3
+ *
4
+ * 输入:当前状态 + 这一轮的观测(是否繁忙、会话标题)+ 时间
5
+ * 输出:下一状态 + 该执行的动作
6
+ *
7
+ * 不碰定时器、不碰文件、不调守护进程 —— 因此可以用固定时间戳做单元测试。
8
+ */
9
+
10
+ export const ACTION = Object.freeze({
11
+ WAIT_EARLIEST: 'wait-earliest',
12
+ BUSY: 'busy',
13
+ START_QUIET: 'start-quiet',
14
+ WAIT_QUIET: 'wait-quiet',
15
+ TRIGGER: 'trigger',
16
+ });
17
+
18
+ /** 排队时的初始状态 */
19
+ export function initialState(now, earliestSeconds = 0) {
20
+ return {
21
+ active: true,
22
+ startedAt: now,
23
+ afterSeconds: earliestSeconds,
24
+ quietSince: null,
25
+ round: 0,
26
+ reason: '已排队,等待空闲',
27
+ };
28
+ }
29
+
30
+ export function idleState(reason = '未排队') {
31
+ return { active: false, startedAt: 0, afterSeconds: 0, quietSince: null, round: 0, reason };
32
+ }
33
+
34
+ /**
35
+ * 单步决策(纯函数,不修改入参)
36
+ *
37
+ * @param {object} state 上一轮状态
38
+ * @param {object} spec 已校验的策略配置
39
+ * @param {{ now: number, busyNow: boolean, busyTitles: string[], lastActivityAt: number }} input
40
+ * @returns {{ state: object, action: string, reason: string }}
41
+ */
42
+ export function decide(state, spec, input) {
43
+ const { now, busyNow, busyTitles = [] } = input;
44
+ const next = { ...state, round: state.round + 1 };
45
+ const quietMs = spec.idle.quietMs;
46
+
47
+ if (!next.active) {
48
+ return { state: next, action: ACTION.WAIT_QUIET, reason: next.reason || '未排队' };
49
+ }
50
+
51
+ const notBefore = next.startedAt + next.afterSeconds * 1000;
52
+ if (now < notBefore) {
53
+ next.reason = `等待最早重启时间(还差 ${Math.ceil((notBefore - now) / 1000)} 秒)`;
54
+ return { state: next, action: ACTION.WAIT_EARLIEST, reason: next.reason };
55
+ }
56
+
57
+ if (busyNow) {
58
+ next.quietSince = null;
59
+ next.reason = busyTitles.length
60
+ ? '有会话在运行:' + busyTitles.join('、')
61
+ : '最近有用户输入';
62
+ return { state: next, action: ACTION.BUSY, reason: next.reason };
63
+ }
64
+
65
+ if (next.quietSince === null) {
66
+ next.quietSince = now;
67
+ next.reason = `会话已结束,开始 ${Math.round(quietMs / 1000)} 秒安静窗口`;
68
+ return { state: next, action: ACTION.START_QUIET, reason: next.reason };
69
+ }
70
+
71
+ const waited = now - next.quietSince;
72
+ if (waited >= quietMs) {
73
+ next.reason = '满足重启条件,准备触发';
74
+ return { state: next, action: ACTION.TRIGGER, reason: next.reason };
75
+ }
76
+
77
+ next.reason = `安静窗口中(还差 ${Math.ceil((quietMs - waited) / 1000)} 秒)`;
78
+ return { state: next, action: ACTION.WAIT_QUIET, reason: next.reason };
79
+ }
80
+
81
+ /**
82
+ * 触发前的复查:忙则取消并重新计时
83
+ * @returns {{ state: object, cancelled: boolean, reason: string }}
84
+ */
85
+ export function recheckBeforeTrigger(state, spec, input, guardKey = 'recheckBeforeTrigger') {
86
+ if (!spec.guard[guardKey]) return { state, cancelled: false, reason: 'skipped' };
87
+ if (!input.busyNow) return { state, cancelled: false, reason: 'idle' };
88
+ return {
89
+ state: { ...state, quietSince: null, reason: '刚要重启时检测到新活动,已取消并重新计时' },
90
+ cancelled: true,
91
+ reason: 'became-busy-before-trigger',
92
+ };
93
+ }