@andy.ian/dsh-homing 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/bin/auth.mjs +2 -2
- package/bin/backup.mjs +4 -4
- package/bin/bootstrap-server.mjs +4 -4
- package/bin/entry-link.mjs +2 -2
- package/bin/renew-cert.mjs +1 -1
- package/bin/supervisor.mjs +488 -0
- package/bin/watchdog.mjs +99 -113
- package/cordis.patch.yml +4 -4
- package/index.js +197 -229
- package/lib/files-page.mjs +228 -138
- package/lib/files.mjs +89 -2
- package/lib/limits.mjs +1 -1
- package/lib/pty.mjs +10 -3
- package/package.json +4 -4
- package/lib/session.mjs +0 -216
- package/lib/shell-page.mjs +0 -430
- package/lib/shell.mjs +0 -274
- package/ops/watchdog/dsh-watchdog.ps1 +0 -105
- package/ops/watchdog/restart-now.ps1 +0 -247
package/README.md
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
> **v1.4.0 变更(务必先读)**
|
|
4
4
|
>
|
|
5
5
|
> - 入口从「常量暗号 `?func=dsh-view` + 可伪造的 `dshview=1` Cookie」改为 **HMAC 签名、带过期的入口令牌 `?k=`**。
|
|
6
|
-
> - 令牌打开一次后换成 **逐设备令牌** `dsh-device`(HttpOnly / SameSite=Lax / Secure,180 天),设备可在
|
|
7
|
-
> `/
|
|
6
|
+
> - 令牌打开一次后换成 **逐设备令牌** `dsh-homing-device`(HttpOnly / SameSite=Lax / Secure,180 天),设备可在
|
|
7
|
+
> `/dsh_homing/devices` 单独吊销,吊销即时生效。
|
|
8
8
|
> - 生成入口:`node bin/entry-link.mjs`(或 `dsh-homing-entry`),默认 30 天有效;书签只存 `https://域名/`。
|
|
9
9
|
> - 旧链接 `?func=dsh-view` **默认失效**;如确需兼容,配置 `legacyFunc: true`。
|
|
10
10
|
> - 新增:写操作来源校验(Origin + Sec-Fetch-Site,含 WebSocket)、登录失败分桶锁定 + 全局延迟、
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
| 找 DSH 端口 | `ctx.webServer.getOrigin()`,不扫进程、不依赖平台 |
|
|
26
26
|
| 注入登录态 | `ctx.credentials.readRecord('client-connection/browser-session')` 取签名密钥,签 `dsh-auth-*` Cookie |
|
|
27
27
|
| 账号登录 | 登录页 + scrypt 哈希 + 7 天签名 Cookie,失败限速 |
|
|
28
|
-
| 入口令牌 | 首次必须带 `?k=<签名令牌>`,之后靠 `dsh-device` Cookie;两者都没有则 `404` |
|
|
28
|
+
| 入口令牌 | 首次必须带 `?k=<签名令牌>`,之后靠 `dsh-homing-device` Cookie;两者都没有则 `404` |
|
|
29
29
|
| 移动端适配 | 注入 CSS/JS:窄屏隐藏右侧边栏、选完会话自动收起抽屉 |
|
|
30
30
|
| 反向隧道 | 调系统自带 `ssh -N -R`,断线 5 秒重连,日志写 `$DSH_HOME/integrations/dsh-homing/tunnel.log` |
|
|
31
31
|
| 生命周期 | 全部资源在 `ctx.effect()` 里注册,插件卸载时关闭监听并杀掉 ssh 子进程 |
|
package/bin/auth.mjs
CHANGED
|
@@ -15,8 +15,8 @@ import os from 'node:os';
|
|
|
15
15
|
import path from 'node:path';
|
|
16
16
|
import crypto from 'node:crypto';
|
|
17
17
|
|
|
18
|
-
const DATA_DIR = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'integrations', 'dsh-
|
|
19
|
-
const AUTH_FILE = process.env.
|
|
18
|
+
const DATA_DIR = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'integrations', 'dsh-homing');
|
|
19
|
+
const AUTH_FILE = process.env.DSH_HOMING_AUTH || path.join(DATA_DIR, 'auth.json');
|
|
20
20
|
fs.mkdirSync(path.dirname(AUTH_FILE), { recursive: true });
|
|
21
21
|
const SCRYPT_KEYLEN = 64;
|
|
22
22
|
|
package/bin/backup.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* 用法:
|
|
6
6
|
* node bin/backup.mjs 备份到 <dataDir>/backups/backup-<时间>/
|
|
7
|
-
*
|
|
7
|
+
* DSH_HOMING_BACKUP_PASS=xxx node ... 额外生成一个加密包(AES-256)
|
|
8
8
|
* node bin/backup.mjs --list 列出已有备份
|
|
9
9
|
* node bin/backup.mjs --restore <目录> 从备份恢复(覆盖前会先备份当前状态)
|
|
10
10
|
*
|
|
@@ -15,7 +15,7 @@ import os from 'node:os';
|
|
|
15
15
|
import path from 'node:path';
|
|
16
16
|
import { spawnSync } from 'node:child_process';
|
|
17
17
|
|
|
18
|
-
const DIR = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'integrations', 'dsh-
|
|
18
|
+
const DIR = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'integrations', 'dsh-homing');
|
|
19
19
|
const BACKUPS = path.join(DIR, 'backups');
|
|
20
20
|
const KEEP = 10;
|
|
21
21
|
const ITEMS = [
|
|
@@ -66,13 +66,13 @@ function backup() {
|
|
|
66
66
|
console.log(`已备份 ${copied.length} 个文件到 ${target}`);
|
|
67
67
|
|
|
68
68
|
// 可选加密包
|
|
69
|
-
const password = process.env.
|
|
69
|
+
const password = process.env.DSH_HOMING_BACKUP_PASS;
|
|
70
70
|
if (password) {
|
|
71
71
|
const openssl = process.platform === 'win32' ? 'openssl.exe' : 'openssl';
|
|
72
72
|
const archive = `${target}.enc.tgz`;
|
|
73
73
|
const tar = spawnSync('tar', ['-czf', '-', '-C', target, '.'], { maxBuffer: 64 * 1024 * 1024 });
|
|
74
74
|
if (tar.status === 0) {
|
|
75
|
-
const enc = spawnSync(openssl, ['enc', '-aes-256-cbc', '-pbkdf2', '-salt', '-pass', 'env:
|
|
75
|
+
const enc = spawnSync(openssl, ['enc', '-aes-256-cbc', '-pbkdf2', '-salt', '-pass', 'env:DSH_HOMING_BACKUP_PASS'], {
|
|
76
76
|
input: tar.stdout,
|
|
77
77
|
maxBuffer: 64 * 1024 * 1024,
|
|
78
78
|
});
|
package/bin/bootstrap-server.mjs
CHANGED
|
@@ -100,7 +100,7 @@ function ensureKeypair() {
|
|
|
100
100
|
const keygen = findKeygen();
|
|
101
101
|
if (!keygen) throw new Error('找不到 ssh-keygen,无法生成密钥');
|
|
102
102
|
fs.mkdirSync(path.dirname(keyFile), { recursive: true });
|
|
103
|
-
const result = spawnSync(keygen, ['-t', 'ed25519', '-N', '', '-C', 'dsh-
|
|
103
|
+
const result = spawnSync(keygen, ['-t', 'ed25519', '-N', '', '-C', 'dsh-homing', '-f', keyFile], { stdio: 'ignore', windowsHide: true });
|
|
104
104
|
if (result.status !== 0 || !fs.existsSync(pubFile)) throw new Error('ssh-keygen 生成密钥失败');
|
|
105
105
|
return fs.readFileSync(pubFile, 'utf8').trim();
|
|
106
106
|
}
|
|
@@ -376,8 +376,8 @@ if [ "${harden ? '1' : '0'}" = "1" ]; then
|
|
|
376
376
|
BK="/root/sshd-backup-$(date +%Y%m%d-%H%M%S)"
|
|
377
377
|
sudo mkdir -p "$BK"
|
|
378
378
|
sudo cp -a /etc/ssh/sshd_config "$BK/" 2>/dev/null || true
|
|
379
|
-
sudo tee /etc/ssh/sshd_config.d/00-dsh-
|
|
380
|
-
# 由 dsh-
|
|
379
|
+
sudo tee /etc/ssh/sshd_config.d/00-dsh-homing.conf >/dev/null <<'SSHD'
|
|
380
|
+
# 由 dsh-homing bootstrap 写入:只允许公钥登录
|
|
381
381
|
PasswordAuthentication no
|
|
382
382
|
KbdInteractiveAuthentication no
|
|
383
383
|
PubkeyAuthentication yes
|
|
@@ -389,7 +389,7 @@ SSHD
|
|
|
389
389
|
echo "sshd hardened (backup: $BK)"
|
|
390
390
|
else
|
|
391
391
|
echo 'SSHD-INVALID, rolling back'
|
|
392
|
-
sudo rm -f /etc/ssh/sshd_config.d/00-dsh-
|
|
392
|
+
sudo rm -f /etc/ssh/sshd_config.d/00-dsh-homing.conf
|
|
393
393
|
fi
|
|
394
394
|
# nginx 崩��时不把内存 dump 到磁盘(里面是解密后的明文)
|
|
395
395
|
sudo mkdir -p /etc/systemd/system/nginx.service.d
|
package/bin/entry-link.mjs
CHANGED
|
@@ -9,14 +9,14 @@
|
|
|
9
9
|
* 说明:链接里的令牌是 HMAC 签名 + 过期时间,服务端只认签名,没有共享口令。
|
|
10
10
|
* 打开一次后会换成 dsh-entry 签名 Cookie,之后书签只存 https://域名/ 即可。
|
|
11
11
|
* 想立刻作废所有已发出的链接和 Cookie:改 settings.json 里的 auth.json sessionKey
|
|
12
|
-
* (或用 /
|
|
12
|
+
* (或用 /dsh_homing/account 的重置功能重新生成),旧的全部失效。
|
|
13
13
|
*/
|
|
14
14
|
import fs from 'node:fs'
|
|
15
15
|
import os from 'node:os'
|
|
16
16
|
import path from 'node:path'
|
|
17
17
|
import crypto from 'node:crypto'
|
|
18
18
|
|
|
19
|
-
const DIR = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'integrations', 'dsh-
|
|
19
|
+
const DIR = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'integrations', 'dsh-homing')
|
|
20
20
|
const SETTINGS = path.join(DIR, 'settings.json')
|
|
21
21
|
const AUTH = path.join(DIR, 'auth.json')
|
|
22
22
|
|
package/bin/renew-cert.mjs
CHANGED
|
@@ -17,7 +17,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
17
17
|
import tls from 'node:tls';
|
|
18
18
|
|
|
19
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-
|
|
20
|
+
const DIR = path.join(process.env.DSH_HOME || path.join(os.homedir(), '.dsh'), 'integrations', 'dsh-homing');
|
|
21
21
|
const SETTINGS = path.join(DIR, 'settings.json');
|
|
22
22
|
const CERTS = path.join(DIR, 'certs');
|
|
23
23
|
const dryRun = process.argv.includes('--dry-run');
|
|
@@ -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
|
+
}
|