@duke-dsh-plugins/dsh-remote-control 0.0.0-stage → 1.1.4

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.
@@ -0,0 +1,798 @@
1
+ // lib/relay-supervisor.mjs — 中继进程托管(v1.1.1,2026-10-25)
2
+ //
3
+ // 目的:中继是这套方案的「服务端」,不该靠人手 `node server.js` 起。
4
+ // 插件启动时把本机中继拉起来,插件卸载/DSH 退出时收掉。
5
+ //
6
+ // 进程安全铁律(曾因误杀 DSH 后端被固化为全局规则):
7
+ // - **只操作自己 spawn 出来的子进程**(按 child handle 停),绝不按进程名/端口批量杀;
8
+ // - 端口探测只做 TCP connect(不发送数据),探测到占用就**不抢**(外部中继优先);
9
+ // - 远端中继(relayUrl 指向别的机器)**不托管**——那是别人机器上的服务。
10
+ //
11
+ // 父子绑定:中继子进程以 DSHRC_RELAY_PARENT_WATCHDOG=1 启动,
12
+ // 它监听 stdin ——收到 "shutdown" 命令则优雅停止;stdin EOF(父进程死了)也优雅退出。
13
+ // 不留孤儿进程。
14
+ //
15
+ // 审计修复要点(2026-10-25,独立审计发现):
16
+ // S1 改端口 → 必须先停旧进程再起新的(原来只判「子进程活着」就 return,端口换了不换进程);
17
+ // S2 状态必须由 supervisor 实时持有并回调(原来只在 ensure() 时拍快照,看门狗读到旧值永不重拉);
18
+ // S3 ensure 加 in-flight 锁 + exit 回调按归属判断(原来并发会双 spawn,且败者的 exit 回调
19
+ // 把胜者的句柄一起清掉 → 孤儿);
20
+ // S4 dispose 标志:卸载后不再启动(原来在途 ensure 会在卸载后把中继拉起来);
21
+ // S5 spawn 后 unref child 与三条 stdio(原来 pipe 句柄吊住 DSH 事件循环,导致优雅退出挂住);
22
+ // S6 Windows 上 child.kill('SIGTERM') 是硬杀(不走 signal handler)→ 改用 stdin 管道下命令,
23
+ // 让中继自己走 relay.stop() 优雅关闭。
24
+ import { spawn } from "node:child_process";
25
+ import { existsSync } from "node:fs";
26
+ import { lookup } from "node:dns/promises";
27
+ import { connect } from "node:net";
28
+ import { networkInterfaces } from "node:os";
29
+ import { dirname, join, resolve } from "node:path";
30
+ import { fileURLToPath } from "node:url";
31
+
32
+ /** 本模块所在目录(plugin/lib)→ 插件根目录(plugin/)。 */
33
+ const LIB_DIR = dirname(fileURLToPath(import.meta.url));
34
+ /** 插件根目录(plugin/)。 */
35
+ export const PLUGIN_DIR = resolve(LIB_DIR, "..");
36
+
37
+ /** 优雅停止命令(父进程 → 子进程,经 stdin 管道)。 */
38
+ const SHUTDOWN_COMMAND = "shutdown";
39
+ /** 优雅停止的宽限期(毫秒);超时才硬杀。 */
40
+ const STOP_GRACE_MS = 3000;
41
+
42
+ /**
43
+ * 中继入口的候选位置(按优先级):
44
+ * 1. 环境变量 DSHRC_RELAY_ENTRY 显式指定
45
+ * 2. <plugin>/../relay/server.js —— 仓库布局(link 安装/开发时是活源码,优先)
46
+ * 3. <plugin>/vendor/relay/server.js —— **打包进插件的中继副本**(bundle 安装时唯一可用的)
47
+ * (由 scripts/vendor-relay.mjs 从 relay/server.js 生成,门禁校验同步)
48
+ * 4. <plugin>/node_modules/@duke-dsh-plugins/dsh-remote-control-relay/server.js —— npm 包形态
49
+ * (v1.1.3 起中继发布为 scoped npm 包;scoped 包装在 node_modules/@duke-dsh-plugins/ 下)
50
+ */
51
+ export function resolveRelayEntry(pluginDir = PLUGIN_DIR, env = process.env) {
52
+ const candidates = [];
53
+ if (typeof env.DSHRC_RELAY_ENTRY === "string" && env.DSHRC_RELAY_ENTRY !== "") {
54
+ candidates.push(resolve(env.DSHRC_RELAY_ENTRY));
55
+ }
56
+ candidates.push(resolve(pluginDir, "..", "relay", "server.js"));
57
+ candidates.push(resolve(pluginDir, "vendor", "relay", "server.js"));
58
+ candidates.push(resolve(pluginDir, "node_modules", "@duke-dsh-plugins", "dsh-remote-control-relay", "server.js"));
59
+ for (const c of candidates) {
60
+ if (existsSync(c)) return c;
61
+ }
62
+ return "";
63
+ }
64
+
65
+ /**
66
+ * 解析 relayUrl → { host, port };不是 ws/wss 或 URL 非法时返回 null。
67
+ * @param {string} url
68
+ * @returns {{host:string, port:number}|null}
69
+ */
70
+ export function parseRelayTarget(url) {
71
+ if (typeof url !== "string" || url.trim() === "") return null;
72
+ let u;
73
+ try {
74
+ u = new URL(url.trim());
75
+ } catch {
76
+ return null;
77
+ }
78
+ if (u.protocol !== "ws:" && u.protocol !== "wss:") return null;
79
+ const port = u.port !== "" ? Number(u.port) : u.protocol === "wss:" ? 443 : 80;
80
+ if (!Number.isFinite(port) || port <= 0 || port > 65535) return null;
81
+ // URL.hostname 对 IPv6 带方括号([::1])——去掉,判定与比较都用裸地址
82
+ const host = u.hostname.toLowerCase().replace(/^\[|\]$/g, "");
83
+ return { host, port };
84
+ }
85
+
86
+ /**
87
+ * host 是否指向**本机**(含本机所有网卡地址)。
88
+ * 只有本机中继才该由插件托管;远端(VPS / 另一台机器)不碰。
89
+ * @param {string} host
90
+ * @param {Record<string, Array<{address:string, family:string, internal:boolean}>>} [ifaces]
91
+ */
92
+ export function isLocalHost(host, ifaces = networkInterfaces()) {
93
+ if (typeof host !== "string" || host === "") return false;
94
+ const h = host.toLowerCase().replace(/^\[|\]$/g, "");
95
+ if (h === "localhost" || h === "::1" || h === "0.0.0.0" || h === "::") return true;
96
+ for (const list of Object.values(ifaces || {})) {
97
+ for (const ni of list || []) {
98
+ if (ni && typeof ni.address === "string" && ni.address.toLowerCase() === h) return true;
99
+ }
100
+ }
101
+ return false;
102
+ }
103
+
104
+ /** 当前生效的 DNS lookup(N10 门禁注入点;生产恒为 node:dns/promises 的 lookup)。 */
105
+ let dnsLookup = lookup;
106
+
107
+ /**
108
+ * 替换/复位 DNS lookup 实现——**仅限单测注入**(生产代码不得调用)。
109
+ * @param {Function|null} fn 传 null 复位为真实 lookup
110
+ */
111
+ export function setDnsLookup(fn) {
112
+ dnsLookup = typeof fn === "function" ? fn : lookup;
113
+ }
114
+
115
+ /**
116
+ * host 是否指向本机(**含 DNS 解析**:本机名/本机别名也认)。
117
+ * 解析失败一律按「非本机」处理(保守:宁可不管,也不误托管别人的服务)。
118
+ * @param {string} host
119
+ * @returns {Promise<boolean>}
120
+ */
121
+ export async function isLocalHostResolved(host) {
122
+ if (typeof host !== "string" || host === "") return false;
123
+ const h = host.toLowerCase().replace(/^\[|\]$/g, "");
124
+ if (isLocalHost(h)) return true;
125
+ // **N10:DNS 解析必须有超时**——异常 DNS 会让每轮看门狗阻塞数秒。
126
+ try {
127
+ const res = await Promise.race([
128
+ dnsLookup(h),
129
+ new Promise((_, reject) => {
130
+ const t = setTimeout(() => reject(new Error("dns timeout")), 2000);
131
+ if (typeof t.unref === "function") t.unref();
132
+ }),
133
+ ]);
134
+ const addrs = Array.isArray(res) ? res : [res];
135
+ return addrs.some((a) => isLocalHost(a.address));
136
+ } catch {
137
+ return false;
138
+ }
139
+ }
140
+
141
+ /**
142
+ * 端口上是否已有服务在监听(纯 TCP connect 探测,不发数据)。
143
+ * @param {number} port
144
+ * @param {string} [host]
145
+ * @param {number} [timeoutMs]
146
+ * @returns {Promise<boolean>}
147
+ */
148
+ export function isPortListening(port, host = "127.0.0.1", timeoutMs = 400) {
149
+ return new Promise((resolve) => {
150
+ let settled = false;
151
+ const done = (v) => {
152
+ if (settled) return;
153
+ settled = true;
154
+ try {
155
+ sock.destroy();
156
+ } catch {
157
+ /* ignore */
158
+ }
159
+ resolve(v);
160
+ };
161
+ const sock = connect({ port, host });
162
+ sock.setTimeout(timeoutMs);
163
+ sock.once("connect", () => done(true));
164
+ sock.once("timeout", () => done(false));
165
+ sock.once("error", () => done(false));
166
+ });
167
+ }
168
+
169
+ /**
170
+ * 目标端口是否已被占用——**同时探 127.0.0.1 与目标 host**。
171
+ * 只探 127.0.0.1 会漏判「只绑了 LAN IP 的外部服务」→ 起一个影子中继(审计 M1)。
172
+ * @param {number} port
173
+ * @param {string} host 目标 host
174
+ * @returns {Promise<boolean>}
175
+ */
176
+ export async function isRelayPortBusy(port, host) {
177
+ if (await isPortListening(port, "127.0.0.1")) return true;
178
+ const h = (host || "").toLowerCase().replace(/^\[|\]$/g, "");
179
+ // **N4:IPv6 也要探**——原来把 "::1" 跳过了,但只绑 [::1]:P 的服务是真实存在的
180
+ // → 漏判 → 起一个影子中继 → EADDRINUSE → 崩溃循环。
181
+ if (h === "::1") {
182
+ if (await isPortListening(port, "::1")) return true;
183
+ } else if (h !== "" && h !== "127.0.0.1" && h !== "localhost" && h !== "0.0.0.0" && h !== "::") {
184
+ if (await isPortListening(port, h)) return true;
185
+ }
186
+ return false;
187
+ }
188
+
189
+ /** 托管状态快照。 */
190
+ export function emptyStatus() {
191
+ return {
192
+ /** 是否由插件托管(配置允许且 relayUrl 指向本机)。 */
193
+ managed: false,
194
+ /** 中继是否在跑(托管的子进程活着,或端口上已有服务)。 */
195
+ running: false,
196
+ /** 子进程 pid(未运行时为 0)。 */
197
+ pid: 0,
198
+ /** 监听端口(未托管时为 0)。 */
199
+ port: 0,
200
+ /** 最近一次状态说明(中文,直接可展示)。 */
201
+ detail: "",
202
+ /** 端口上是不是**别人**的服务(外部中继)。 */
203
+ external: false,
204
+ /**
205
+ * 状态原因(看门狗据此决定要不要再探一次端口):
206
+ * 'not-configured' 未配置地址 / 'disabled' 关掉了自动启动 / 'remote' 远端中继 /
207
+ * 'no-entry' 找不到中继程序 / 'external' 端口上是别人的服务 / 'managed' 我们托管的
208
+ */
209
+ reason: "not-configured",
210
+ };
211
+ }
212
+
213
+ /**
214
+ * 中继进程托管器。
215
+ *
216
+ * 生命周期:ensure()(幂等,按需拉起)→ stop()(只停自己起的进程)/ dispose()(永久)。
217
+ * 所有 spawn/kill 都针对本对象持有的 child handle——**不按名字或端口杀任何进程**。
218
+ */
219
+ export class RelaySupervisor {
220
+ /**
221
+ * @param {object} opts
222
+ * @param {string} [opts.entry] 中继入口(server.js);缺省自动解析,空串 = 显式没有
223
+ * @param {string} [opts.nodePath] 用来起子进程的 node 可执行文件(默认 process.execPath)
224
+ * @param {(level:string, msg:string, extra?:object)=>void} [opts.log]
225
+ * @param {(state:object)=>void} [opts.onStatus] 状态变化回调(宿主用它刷新设置页快照)
226
+ * @param {(file:string, args:string[], env:object, opts:object)=>object} [opts.spawnFn] 单测注入点
227
+ */
228
+ constructor(opts = {}) {
229
+ // 注意:**空串是显式的「没有入口」**(测试与「禁用托管」场景用),
230
+ // 不能用 || ——否则 "" 会被当成「没传」而自动解析出真入口。
231
+ this.entry = opts.entry === undefined ? resolveRelayEntry() : opts.entry;
232
+ this.nodePath = opts.nodePath || process.execPath;
233
+ this.log = typeof opts.log === "function" ? opts.log : () => {};
234
+ this.onStatus = typeof opts.onStatus === "function" ? opts.onStatus : null;
235
+ this.spawnFn = typeof opts.spawnFn === "function" ? opts.spawnFn : spawn;
236
+ /** @type {import('node:child_process').ChildProcess|null} */
237
+ this.child = null;
238
+ /** 子进程**实际**监听的端口(改端口时用它判断是否要换进程)。 */
239
+ this.childPort = 0;
240
+ /** @type {object} */
241
+ this.status = emptyStatus();
242
+ /** 在途 ensure 的 promise(并发去重锁)。 */
243
+ this.pending = null;
244
+ /** 永久停用标志(dispose 后不再启动任何进程)。 */
245
+ this.disposed = false;
246
+ /**
247
+ * 停止世代号(第三轮审计 #1):每次 stop() 自增。
248
+ * 在途的 ensure() 用它判断「我探测端口期间,世界有没有人喊停」——
249
+ * 有就放弃 spawn,否则设置页刚清空地址、中继却又被拉起来(孤儿)。
250
+ */
251
+ this.epoch = 0;
252
+ /** 当前子进程是否**曾确认过监听**(第三轮审计 #2:区分「还在启动」和「僵尸」)。 */
253
+ this.childReady = false;
254
+ }
255
+
256
+ /** 更新状态并通知宿主(宿主据此刷新设置页快照——S2:不能只在 ensure 时拍快照)。 */
257
+ #publish(patch) {
258
+ this.status = { ...this.status, ...patch };
259
+ try {
260
+ this.onStatus?.(this.status);
261
+ } catch {
262
+ /* 回调失败不影响托管 */
263
+ }
264
+ }
265
+
266
+ /** 子进程是否还活着(真的活着,不是「调过 kill」)。 */
267
+ isChildAlive() {
268
+ const c = this.child;
269
+ if (!c) return false;
270
+ return c.exitCode === null && c.signalCode === null;
271
+ }
272
+
273
+ /**
274
+ * 确保本机中继在跑(幂等,并发安全)。
275
+ *
276
+ * 判定顺序:
277
+ * 1. 没配 relayUrl / autoStartRelay=false → 不托管
278
+ * 2. relayUrl 指向远端 → 不托管(别人的服务)
279
+ * 3. 找不到中继入口 → 不托管(给出提示)
280
+ * 4. 端口已被占用 → 不托管(外部中继在跑),但标记 running
281
+ * 5. 已在托管且**端口一致** → 直接返回
282
+ * 6. 已在托管但**端口变了** → 先停旧进程,再起新的(S1)
283
+ * 7. 否则 spawn 一个(并等它打印「relay listening」)
284
+ *
285
+ * @param {string} relayUrl
286
+ * @param {object} [opts]
287
+ * @param {boolean} [opts.autoStart] 默认 true
288
+ * @param {string} [opts.relayToken] 中继自身 token(配置了才带)
289
+ * @param {{cert?:string,key?:string}} [opts.tls] 中继 TLS 证书/私钥**文件路径**(契约 §3.4.2)
290
+ * @returns {Promise<object>} 状态快照
291
+ */
292
+ async ensure(relayUrl, opts = {}) {
293
+ // 串行化:等在途的跑完,然后**每次都亲自跑一遍** #ensureInner。
294
+ // (S3 并发去重 + N8:不能把「别人那一次」的结果当成自己的返回值——
295
+ // 目标可能不同,也可能在等待期间世界已经变了(比如我们等的那次
296
+ // 又被第三次 ensure 顶掉)。已托管且一致时 #ensureInner 是廉价的
297
+ // (一次端口探测就返回),串行化没有性能问题。)
298
+ while (this.pending) {
299
+ await this.pending.catch(() => {});
300
+ }
301
+ this.pending = this.#ensureInner(relayUrl, opts).finally(() => {
302
+ this.pending = null;
303
+ });
304
+ return await this.pending;
305
+ }
306
+
307
+ async #ensureInner(relayUrl, opts) {
308
+ const autoStart = opts.autoStart !== false;
309
+ const target = parseRelayTarget(relayUrl);
310
+ if (!target) {
311
+ this.#publish({
312
+ ...emptyStatus(),
313
+ reason: "not-configured",
314
+ detail: "未配置中继地址,暂不托管中继进程。",
315
+ });
316
+ return this.status;
317
+ }
318
+ if (!autoStart) {
319
+ this.#publish({
320
+ ...emptyStatus(),
321
+ port: target.port,
322
+ reason: "disabled",
323
+ detail: "已关闭「随插件启动中继」。",
324
+ });
325
+ return this.status;
326
+ }
327
+ if (!(await isLocalHostResolved(target.host))) {
328
+ this.#publish({
329
+ ...emptyStatus(),
330
+ port: target.port,
331
+ reason: "remote",
332
+ detail: "中继地址不在本机(远程中继),插件不托管进程。",
333
+ });
334
+ return this.status;
335
+ }
336
+ if (this.entry === "" || !existsSync(this.entry)) {
337
+ this.#publish({
338
+ ...emptyStatus(),
339
+ port: target.port,
340
+ reason: "no-entry",
341
+ detail:
342
+ "未找到中继程序(relay/server.js);非仓库布局的安装请设置 DSHRC_RELAY_ENTRY," +
343
+ "或把 autoStartRelay 设为 false 自行启动中继。",
344
+ });
345
+ return this.status;
346
+ }
347
+ // 已在托管:端口一致才复用;端口变了必须换进程(S1:原来只判「活着」就 return)
348
+ let baseEpoch = this.epoch;
349
+ if (this.isChildAlive()) {
350
+ if (this.childPort === target.port) {
351
+ // **N6:不能只看「进程活着」就说 running**——中继可能还没监听
352
+ // (启动慢/端口被占后重试)→ running:true 会让看门狗从此失明。
353
+ // 端口确实在监听才算真的在跑。
354
+ const listening = await isRelayPortBusy(target.port, target.host);
355
+ // **僵尸替换(第三轮审计 #2)**:曾确认过监听、现在探不到了 →
356
+ // 进程活着但已经不服务(真中继的 wss 'error' 只记日志不退出)→ 换掉它。
357
+ // 从未确认过监听 → 还在启动等待期,别急着换(8s 内会再探)。
358
+ if (!listening && this.childReady) {
359
+ this.log("warn", "managed relay alive but no longer listening; replacing it", {
360
+ pid: this.child?.pid || 0,
361
+ port: this.childPort,
362
+ });
363
+ await this.stop();
364
+ baseEpoch = this.epoch;
365
+ // 落到下面的端口占用检查 / 重新 spawn
366
+ } else {
367
+ this.#publish({
368
+ managed: true,
369
+ running: listening,
370
+ pid: this.child?.pid || 0,
371
+ port: this.childPort,
372
+ reason: "managed",
373
+ detail: listening
374
+ ? `中继进程由插件托管(pid ${this.child?.pid || 0},端口 ${this.childPort})。`
375
+ : `中继进程已启动(pid ${this.child?.pid || 0}),但端口 ${this.childPort} 尚未监听,稍后重试。`,
376
+ });
377
+ return this.status;
378
+ }
379
+ } else {
380
+ this.log("info", "relay port changed; restarting managed relay", {
381
+ from: this.childPort,
382
+ to: target.port,
383
+ });
384
+ await this.stop();
385
+ baseEpoch = this.epoch;
386
+ }
387
+ }
388
+ if (await isRelayPortBusy(target.port, target.host)) {
389
+ // 外部已有中继在监听:不抢、不杀,只如实报告(external → 看门狗**仍会再探一次端口**,
390
+ // 因为占用者随时可能消失——插件热重载时旧实例的中继就是这种情况)
391
+ this.#publish({
392
+ ...emptyStatus(),
393
+ running: true,
394
+ port: target.port,
395
+ external: true,
396
+ reason: "external",
397
+ detail: `端口 ${target.port} 已有服务监听(中继可能已由外部启动),插件不重复启动。`,
398
+ });
399
+ return this.status;
400
+ }
401
+ if (this.disposed) {
402
+ this.#publish({
403
+ ...emptyStatus(),
404
+ port: target.port,
405
+ reason: "not-configured",
406
+ detail: "插件已卸载,不再启动中继进程。",
407
+ });
408
+ return this.status;
409
+ }
410
+ // **世代号守卫(第三轮审计 #1)**:上面的端口探测是 await——期间可能有人喊停
411
+ // (设置页清空中继地址走 stop()、插件卸载走 dispose())。
412
+ // 世代变了就放弃启动,否则刚清空的地址下中继又被拉起来(孤儿)。
413
+ if (this.epoch !== baseEpoch) {
414
+ this.#publish({
415
+ ...emptyStatus(),
416
+ port: target.port,
417
+ reason: "not-configured",
418
+ detail: "托管在启动前被停止,已取消本次启动。",
419
+ });
420
+ return this.status;
421
+ }
422
+ return await this.start(target.port, opts.relayToken, opts.tls);
423
+ }
424
+
425
+ /**
426
+ * 真正 spawn 中继子进程。
427
+ * @param {number} port
428
+ * @param {string} [relayToken]
429
+ * @param {{cert?:string,key?:string}} [tls] TLS 证书/私钥**文件路径**(契约 §3.4.2)
430
+ * @returns {Promise<object>} 状态快照
431
+ */
432
+ async start(port, relayToken = "", tls = null) {
433
+ const env = {
434
+ ...process.env,
435
+ PORT: String(port),
436
+ LOG_LEVEL: process.env.DSHRC_RELAY_LOG_LEVEL || "info",
437
+ // 父子绑定:父进程(DSH)一死,stdin 管道 EOF,中继自己优雅退出
438
+ DSHRC_RELAY_PARENT_WATCHDOG: "1",
439
+ };
440
+ // **跨平台**:宿主若是 Electron(macOS 的 DSH 常见是 .app 打包),process.execPath
441
+ // 是 Electron 可执行文件,直接跑脚本会再开一个应用实例 → 必须让它以 Node 模式运行。
442
+ // Windows 版 DSH 的后端是独立 node.exe(process.versions.electron 为空),不受影响。
443
+ if (process.versions && process.versions.electron) {
444
+ env.ELECTRON_RUN_AS_NODE = "1";
445
+ }
446
+ if (typeof relayToken === "string" && relayToken !== "") {
447
+ env.RELAY_TOKEN = relayToken;
448
+ }
449
+ // v1.1.3:TLS(契约 §3.4.2)——两个都配了才让中继起 wss://;
450
+ // 只配一个 → 中继启动即失败(不静默降级明文),这里提前拒绝,别白等。
451
+ const tlsCert = typeof tls?.cert === "string" ? tls.cert.trim() : "";
452
+ const tlsKey = typeof tls?.key === "string" ? tls.key.trim() : "";
453
+ if (tlsCert !== "" || tlsKey !== "") {
454
+ if (tlsCert === "" || tlsKey === "") {
455
+ throw new Error("TLS 配置不完整:证书与私钥路径必须同时提供(契约 §3.4.2)。");
456
+ }
457
+ env.RELAY_TLS_CERT = tlsCert;
458
+ env.RELAY_TLS_KEY = tlsKey;
459
+ }
460
+ let child;
461
+ try {
462
+ child = this.spawnFn(this.nodePath, [this.entry], {
463
+ cwd: dirname(this.entry),
464
+ env,
465
+ stdio: ["pipe", "pipe", "pipe"],
466
+ windowsHide: true,
467
+ });
468
+ } catch (e) {
469
+ this.#publish({ ...emptyStatus(), port, detail: "启动中继进程失败:" + String(e && e.message) });
470
+ this.log("error", "relay spawn failed", { error: String(e && e.message) });
471
+ return this.status;
472
+ }
473
+ this.child = child;
474
+ this.childPort = port;
475
+ this.childReady = false;
476
+ // 输出缓冲是**每个子进程一份**(第三轮审计 #6:共用 this.output 会让
477
+ // 新进程的崩溃日志夹带旧进程的输出)
478
+ let output = "";
479
+ // **确认监听之前不报 running**(第三轮审计 #4:spawn 到确认之间有最长 8s 窗口,
480
+ // 期间谎报「运行中」,启动失败时设置页会先显示运行中再翻转)
481
+ this.#publish({
482
+ managed: true,
483
+ running: false,
484
+ pid: child.pid || 0,
485
+ port,
486
+ reason: "managed",
487
+ detail: `正在启动中继进程(pid ${child.pid || 0},端口 ${port})…`,
488
+ });
489
+
490
+ // 收集子进程输出:启动失败/崩溃时把原因带给宿主日志(M2:原来全被吞掉;
491
+ // N3:崩溃时 stderr 也要进日志,否则崩溃循环的根因 100% 不可见)
492
+ const onData = (buf) => {
493
+ output += String(buf);
494
+ if (output.length > 4096) output = output.slice(-4096);
495
+ };
496
+ if (child.stdout) child.stdout.on("data", onData);
497
+ if (child.stderr) child.stderr.on("data", onData);
498
+
499
+ /** 取输出尾部(多行合并成一行,便于日志阅读;不含 base64 之类的大块内容)。 */
500
+ const outputTail = () =>
501
+ output
502
+ .trim()
503
+ .split("\n")
504
+ .filter((l) => l.trim() !== "")
505
+ .slice(-6)
506
+ .join(" | ")
507
+ .slice(0, 600);
508
+
509
+ child.on("exit", (code, signal) => {
510
+ // 归属判断:只有「当前持有的那个」退出才清句柄(S3:败者的 exit 回调
511
+ // 曾把胜者的句柄一起清掉 → 变成孤儿,再也管不到)
512
+ if (this.child === child) {
513
+ this.child = null;
514
+ this.childPort = 0;
515
+ // **managed 保持 true**(审计 S2):子进程崩了不代表「不归我管」——
516
+ // 仍是我们负责的那个中继,只是没在跑 → 看门狗据此重拉。
517
+ this.#publish({
518
+ managed: true,
519
+ running: false,
520
+ pid: 0,
521
+ port,
522
+ external: false,
523
+ reason: "managed",
524
+ detail: `托管的中继进程已退出(code=${String(code)} signal=${String(signal)}),将自动重拉。`,
525
+ });
526
+ // **N3:崩溃原因必须进日志**(原来只在 output 缓冲里,没人读 → 崩溃循环无痕)
527
+ const tail = outputTail();
528
+ this.log("error", "managed relay exited", {
529
+ code,
530
+ signal,
531
+ port,
532
+ output: tail || undefined,
533
+ });
534
+ return;
535
+ }
536
+ // 已被取代的子进程(N12):只记 info,不刷 warn 噪声
537
+ this.log("info", "superseded relay process exited", { code, signal, port });
538
+ });
539
+ child.on("error", (e) => {
540
+ if (this.child !== child) return;
541
+ // **N7**:spawn 失败时 Node **不发 exit**(exitCode 恒 null)→ 必须自己清句柄,
542
+ // 否则 isChildAlive() 恒为 true → 状态永远卡在「运行中(pid 0)」。
543
+ this.child = null;
544
+ this.childPort = 0;
545
+ this.#publish({
546
+ ...emptyStatus(),
547
+ port,
548
+ reason: "managed",
549
+ detail: "中继进程出错:" + String(e && e.message),
550
+ });
551
+ this.log("error", "managed relay error", {
552
+ error: String(e && e.message),
553
+ output: outputTail() || undefined,
554
+ });
555
+ });
556
+
557
+ // S5:子进程的三条 stdio 管道 + child 本身都是 ref 句柄,会吊住 DSH 事件循环
558
+ // (DSH 走「排空事件循环」式退出时会一直挂住)。unref 只解除「保持事件循环存活」,
559
+ // 不影响管道本身——stdin EOF 看门狗照常工作。
560
+ // **必须在启动确认之后才 unref**:unref 后若父进程没有别的 ref 句柄,事件循环会空,
561
+ // 正在 await 的 promise 永远不落定(门禁实测踩到:unsettled top-level await)。
562
+ const unrefAll = () => {
563
+ try {
564
+ child.unref?.();
565
+ child.stdin?.unref?.();
566
+ child.stdout?.unref?.();
567
+ child.stderr?.unref?.();
568
+ } catch {
569
+ /* 某些平台不支持 unref,忽略 */
570
+ }
571
+ };
572
+
573
+ // 等「listening」确认真的起来了(最多 8s)
574
+ const ready = await this.waitForListening(child, 8000);
575
+ // **N3:启动没确认成功时,输出必须进日志**(原来被下面的早退跳过 →
576
+ // 崩溃循环的根因完全不可见)。早退之前先记日志。
577
+ if (!ready) {
578
+ const tail = output
579
+ .trim()
580
+ .split("\n")
581
+ .filter((l) => l.trim() !== "")
582
+ .slice(-6)
583
+ .join(" | ")
584
+ .slice(0, 600);
585
+ this.log("error", "managed relay did not confirm listening", {
586
+ pid: child.pid || 0,
587
+ port,
588
+ output: tail || undefined,
589
+ });
590
+ }
591
+ // 等待期间可能已被 stop()/dispose() 收掉 → 句柄不再属于我们,别再发布「运行中」
592
+ if (this.child !== child) {
593
+ this.log("info", "managed relay was stopped while starting", { pid: child.pid || 0, port });
594
+ unrefAll();
595
+ return this.status;
596
+ }
597
+ // 只有我们**自己确认过监听**才记 childReady(僵尸替换的依据)
598
+ this.childReady = ready;
599
+ // **N6:running 只在「真的监听着」时为 true**——
600
+ // 活着但没监听(如中继启动慢)时报 running:true 会让看门狗从此失明。
601
+ this.#publish({
602
+ managed: true,
603
+ running: ready,
604
+ pid: child.pid || 0,
605
+ port,
606
+ reason: "managed",
607
+ detail: ready
608
+ ? `中继进程由插件托管(pid ${child.pid || 0},端口 ${port})。`
609
+ : `中继进程已启动(pid ${child.pid || 0}),但暂未确认监听成功,稍后自动重试。`,
610
+ });
611
+ this.log(ready ? "info" : "warn", ready ? "managed relay ready" : "managed relay starting", {
612
+ pid: child.pid || 0,
613
+ port,
614
+ });
615
+ // 启动确认后再解除 ref(见上面的 S5 说明)
616
+ unrefAll();
617
+ return this.status;
618
+ }
619
+
620
+ /**
621
+ * 等子进程打印出「relay listening」/「listening on」——中继启动成功的唯一可靠信号。
622
+ * @param {import('node:child_process').ChildProcess} child
623
+ * @param {number} timeoutMs
624
+ * @returns {Promise<boolean>}
625
+ */
626
+ waitForListening(child, timeoutMs) {
627
+ return new Promise((resolve) => {
628
+ let done = false;
629
+ const cleanup = [];
630
+ const finish = (v) => {
631
+ if (done) return;
632
+ done = true;
633
+ for (const fn of cleanup) {
634
+ try {
635
+ fn();
636
+ } catch {
637
+ /* ignore */
638
+ }
639
+ }
640
+ resolve(v);
641
+ };
642
+ const timer = setTimeout(() => finish(false), timeoutMs);
643
+ if (typeof timer.unref === "function") timer.unref();
644
+ const check = (buf) => {
645
+ const s = String(buf);
646
+ if (s.includes("relay listening") || s.includes("listening on ws://")) {
647
+ finish(true);
648
+ }
649
+ };
650
+ if (child.stdout) {
651
+ child.stdout.on("data", check);
652
+ cleanup.push(() => child.stdout.removeListener("data", check));
653
+ }
654
+ if (child.stderr) {
655
+ child.stderr.on("data", check);
656
+ cleanup.push(() => child.stderr.removeListener("data", check));
657
+ }
658
+ cleanup.push(() => clearTimeout(timer));
659
+ child.once("exit", () => finish(false));
660
+ });
661
+ }
662
+
663
+ /**
664
+ * 停止自己托管的中继(**只停这个 child handle**)。
665
+ *
666
+ * 跨平台差异(实测):
667
+ * - **POSIX(Linux/macOS)**:`child.kill('SIGTERM')` 会触发子进程的 signal handler
668
+ * → 中继走 relay.stop() 优雅关闭(手机端看到正常 close)。
669
+ * - **Windows**:`child.kill('SIGTERM')` 直接 TerminateProcess(**硬杀,不走 handler**),
670
+ * 所以只发 stdin 的 `shutdown` 命令让中继自己优雅关停;宽限期内没退出才硬杀。
671
+ * 两条路径都等真实退出;「调过 kill」不等于「已退出」(M5:原来据此提前丢句柄)。
672
+ * @returns {Promise<void>}
673
+ */
674
+ async stop() {
675
+ const child = this.child;
676
+ this.child = null;
677
+ this.childPort = 0;
678
+ // **世代号自增(第三轮审计 #1)**:任何 stop 都让「在途的 ensure」作废——
679
+ // 它探测端口回来后发现世代变了,就不会再把中继 spawn 出来
680
+ // (否则设置页刚清空地址,中继却又被拉起来,成了没人管的孤儿)。
681
+ this.epoch++;
682
+ this.childReady = false;
683
+ if (!child) return;
684
+ // 只有「进程真的结束了」才算停完;killed 只说明调过 kill
685
+ if (child.exitCode !== null || child.signalCode !== null) {
686
+ this.#publish({ ...emptyStatus(), detail: "已停止托管的中继进程。" });
687
+ return;
688
+ }
689
+ await new Promise((resolve) => {
690
+ let done = false;
691
+ const finish = () => {
692
+ if (done) return;
693
+ done = true;
694
+ clearTimeout(killTimer);
695
+ clearTimeout(waitTimer);
696
+ resolve();
697
+ };
698
+ const killTimer = setTimeout(() => {
699
+ try {
700
+ child.kill("SIGKILL");
701
+ } catch {
702
+ /* 已退出 */
703
+ }
704
+ // 硬杀后**等进程真的退出**再返回:否则调用方紧接着探测端口仍会看到占用
705
+ waitTimer = setTimeout(finish, 2000);
706
+ if (typeof waitTimer.unref === "function") waitTimer.unref();
707
+ }, STOP_GRACE_MS);
708
+ if (typeof killTimer.unref === "function") killTimer.unref();
709
+ let waitTimer = null;
710
+ child.once("exit", finish);
711
+ // 等待退出期间临时 ref 住子进程:unref 后父进程可能没有别的 ref 句柄,
712
+ // 事件循环一空,这个 await 永远不落定(stop() 会挂住)。
713
+ try {
714
+ child.ref?.();
715
+ } catch {
716
+ /* ignore */
717
+ }
718
+ // 优雅停止(所有平台都走这条):写 shutdown 命令,子进程读到就自己 relay.stop()
719
+ try {
720
+ if (child.stdin && !child.stdin.destroyed) {
721
+ child.stdin.write(SHUTDOWN_COMMAND + "\n");
722
+ }
723
+ } catch {
724
+ /* 管道已断 → 走下面的硬杀分支 */
725
+ }
726
+ // POSIX 额外补一发 SIGTERM(真优雅信号);Windows 上跳过——那里 SIGTERM 是硬杀,
727
+ // 会抢在上面的 shutdown 命令之前把进程打死。
728
+ if (process.platform !== "win32") {
729
+ try {
730
+ child.kill("SIGTERM");
731
+ } catch {
732
+ /* ignore */
733
+ }
734
+ }
735
+ });
736
+ this.#publish({ ...emptyStatus(), detail: "已停止托管的中继进程。" });
737
+ }
738
+
739
+ /**
740
+ * 永久停用(插件卸载时调用):置位 disposed,之后的 ensure 不会再启动任何进程,
741
+ * 并收掉当前托管的进程(S4:原来在途 ensure 会在卸载后把中继拉起来 → 孤儿)。
742
+ * @returns {Promise<void>}
743
+ */
744
+ async dispose() {
745
+ this.disposed = true;
746
+ await this.stop();
747
+ }
748
+ }
749
+
750
+ /**
751
+ * 看门狗判定:现在**要不要**再跑一次 ensure()?(纯函数,便于单测——审计指出接线逻辑零覆盖)
752
+ *
753
+ * 规则(**N1:丢了 managed 判定会让「已关插件」反而把中继拉起来**,务必保留):
754
+ * - 我们托管的进程在跑 → 不用管;
755
+ * - 未配置 / 关了自动启动 / 远端中继 / 找不到中继程序 → 不用管(再探也没意义);
756
+ * - 我们托管的进程崩了 → 要重拉;
757
+ * - 端口上是**别人**的服务 → **要再探一次端口**!
758
+ * 占用者随时可能消失:插件热重载时旧实例的中继就是这样——
759
+ * 新实例启动时看到端口被占(判 external),随后旧实例被卸载把中继杀了,
760
+ * 若看门狗被 external 挡住,中继就永远起不来(实测过的设计漏洞)。
761
+ *
762
+ * @param {object} status supervisor 的**实时**状态
763
+ * @returns {boolean}
764
+ */
765
+ export function shouldRestartRelay(status) {
766
+ if (!status || typeof status !== "object") return false;
767
+ const reason = typeof status.reason === "string" ? status.reason : "";
768
+ if (reason === "managed") return status.running !== true;
769
+ if (reason === "external") return true;
770
+ // 其余原因(not-configured / disabled / remote / no-entry)一律**不重拉**:
771
+ // 否则「用户关了插件」会被看门狗反复 ensure → 反而把中继拉起来(审计 N1 实测复现)。
772
+ if (reason !== "") return false;
773
+ // 旧版本没有 reason 字段时的兼容判断(与 b6adbd2 的行为一致)
774
+ if (status.managed !== true) return false;
775
+ if (status.running === true) return false;
776
+ return true;
777
+ }
778
+
779
+ /**
780
+ * 看门狗**接线**判定:这一轮要不要动?(纯函数——审计指出 index.js 的接线
781
+ * 是唯一没被测到、又已经出过事的地方:丢了 enabled 判定时,
782
+ * 「用户把插件关掉」反而会把中继拉起来。)
783
+ *
784
+ * @param {object} status supervisor 的实时状态
785
+ * @param {{enabled?:boolean, autoStartRelay?:boolean}} cfg 插件配置
786
+ * @returns {boolean}
787
+ */
788
+ export function shouldTickWatchdog(status, cfg) {
789
+ // 插件被禁用 → 一律不碰中继(N1)
790
+ if (!cfg || cfg.enabled !== true) return false;
791
+ if (cfg.autoStartRelay === false) return false;
792
+ return shouldRestartRelay(status);
793
+ }
794
+
795
+ /** 插件根目录(导出以便测试与其它模块引用)。 */
796
+ export function pluginDir() {
797
+ return PLUGIN_DIR;
798
+ }