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

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,777 @@
1
+ #!/usr/bin/env node
2
+ // ⚠️ 自动生成,请勿手改 —— 源文件:../relay/server.js
3
+ // 生成方式:node scripts/vendor-relay.mjs
4
+ // 改动源文件后必须重新生成(门禁 scripts/verify-relay-supervisor.mjs 会校验同步)。
5
+ // source-sha256:bfab1839b8d109ce
6
+ /**
7
+ * dsh-remote-control-relay —— 公网 WebSocket 中继服务器(哑管道)
8
+ *
9
+ * 严格实现协议契约 §4「传输层:中继帧协议」:
10
+ * docs/plans/2026-10-20-dsh-remote-control-protocol.md
11
+ *
12
+ * 中继只理解 hello / welcome / peer-joined / peer-left / frame / ping / pong / error;
13
+ * frame.data 是端到端密文(base64),中继不解析、不理解、原样转发。
14
+ *
15
+ * 环境变量:
16
+ * PORT 监听端口(默认 8787)
17
+ * RELAY_TOKEN 可选;配置后 hello 必须带匹配 token
18
+ * LOG_LEVEL debug | info | warn | error | silent(默认 info)
19
+ * RELAY_HELLO_TIMEOUT_MS hello 超时(默认 10000)
20
+ * RELAY_PING_INTERVAL_MS 无消息多久发一次心跳(默认 30000)
21
+ * RELAY_DEAD_TIMEOUT_MS 多久无任何消息判死(默认 90000)
22
+ * RELAY_HELLO_RATE_LIMIT 每 IP 每窗口最多 hello 数(默认 60)
23
+ * RELAY_HELLO_RATE_WINDOW_MS 限速窗口(默认 60000)
24
+ * RELAY_CACHE_LIMIT 离线缓存条数上限(默认 256,契约值)
25
+ * RELAY_CACHE_TTL_MS 离线缓存 TTL(默认 86400000 = 24h,契约值)
26
+ * RELAY_MAX_PAYLOAD 单帧最大字节(默认 1048576 = 1MiB)
27
+ * RELAY_TLS_CERT 可选;PEM 证书链**文件路径**(与 RELAY_TLS_KEY 同时设置才生效)
28
+ * RELAY_TLS_KEY 可选;PEM 私钥**文件路径**(与 RELAY_TLS_CERT 同时设置才生效)
29
+ *
30
+ * 监听地址:**IPv4/IPv6 双栈**(默认绑定 '::',Node 默认 ipv6Only=false)——
31
+ * 同一端口同时接受 ws://<IPv4>:port 与 ws://[<IPv6>]:port;
32
+ * 系统禁用 IPv6 时自动回落到 '0.0.0.0'(仅 IPv4,旧版行为)。
33
+ *
34
+ * TLS(契约 §3.4.2):两个 TLS 环境变量都配置 → 以 **wss://**(HTTPS)提供服务;
35
+ * 都没配置 → 维持明文 ws://(默认行为不变)。
36
+ * 证书/私钥**读不到或非法 → 启动即失败**(绝不静默降级成明文)。
37
+ */
38
+
39
+ import { WebSocketServer, WebSocket } from 'ws';
40
+ import { pathToFileURL } from 'node:url';
41
+ import { readFileSync } from 'node:fs';
42
+ import { createServer as createHttpsServer } from 'node:https';
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // 常量(契约 §4)
46
+ // ---------------------------------------------------------------------------
47
+
48
+ /** ch 必须匹配 ^[A-Z2-7]{16,64}$ */
49
+ export const CHANNEL_RE = /^[A-Z2-7]{16,64}$/;
50
+ export const ROLES = /** @type {const} */ (['host', 'client']);
51
+
52
+ const DEFAULTS = {
53
+ port: 8787,
54
+ token: null,
55
+ logLevel: 'info',
56
+ helloTimeoutMs: 10_000, // 连接后 10s 内必须 hello,否则断开
57
+ pingIntervalMs: 30_000, // 30s 无帧发 ping
58
+ deadTimeoutMs: 90_000, // 90s 无任何消息判死
59
+ helloRateLimit: 60, // 每 IP 每分钟 ≤60 个 hello
60
+ helloRateWindowMs: 60_000,
61
+ cacheLimit: 256, // 离线缓存 256 条
62
+ cacheTtlMs: 24 * 3600 * 1000, // 24h
63
+ maxPayload: 1024 * 1024, // 1MiB(密文帧一般很小;防御性上限)
64
+ /**
65
+ * 监听地址候选(按顺序尝试):'::' = IPv6/IPv4 双栈;'0.0.0.0' = 仅 IPv4 回落。
66
+ * 仅 IPv6 不可用(EAFNOSUPPORT/EADDRNOTAVAIL/…)时才自动回落到下一个候选。
67
+ */
68
+ listenHosts: ['::', '0.0.0.0'],
69
+ };
70
+
71
+ // ---------------------------------------------------------------------------
72
+ // 小工具
73
+ // ---------------------------------------------------------------------------
74
+
75
+ const LEVELS = { debug: 10, info: 20, warn: 30, error: 40, silent: 99 };
76
+
77
+ function makeLogger(levelName) {
78
+ const level = LEVELS[String(levelName).toLowerCase()] ?? LEVELS.info;
79
+ const fmt = (tag, args) => {
80
+ const ts = new Date().toISOString();
81
+ // eslint-disable-next-line no-console
82
+ console.log(`${ts} ${tag} ${args.map((a) => (typeof a === 'string' ? a : JSON.stringify(a))).join(' ')}`);
83
+ };
84
+ return {
85
+ level,
86
+ debug: (...a) => level <= LEVELS.debug && fmt('DEBUG', a),
87
+ info: (...a) => level <= LEVELS.info && fmt('INFO ', a),
88
+ warn: (...a) => level <= LEVELS.warn && fmt('WARN ', a),
89
+ error: (...a) => level <= LEVELS.error && fmt('ERROR', a),
90
+ };
91
+ }
92
+
93
+ function intFromEnv(env, name, def) {
94
+ const v = env[name];
95
+ if (v === undefined || v === '') return def;
96
+ const n = Number(v);
97
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : def;
98
+ }
99
+
100
+ /** PORT 专用解析:允许 0(内核分配临时端口,测试用) */
101
+ function portFromEnv(env) {
102
+ const v = env.PORT;
103
+ if (v === undefined || v === '') return DEFAULTS.port;
104
+ const n = Number(v);
105
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : DEFAULTS.port;
106
+ }
107
+
108
+ /**
109
+ * TLS 配置(契约 §3.4.2):RELAY_TLS_CERT / RELAY_TLS_KEY 是 **PEM 文件路径**。
110
+ *
111
+ * 返回 null = 不启用 TLS(默认,明文 ws://)。
112
+ * 抛错 = 配置有问题(只配了一个 / 文件读不到)——**启动即失败,不静默降级**。
113
+ */
114
+ export function loadTlsConfig(env = process.env) {
115
+ const rawCert = typeof env.RELAY_TLS_CERT === 'string' ? env.RELAY_TLS_CERT.trim() : '';
116
+ const rawKey = typeof env.RELAY_TLS_KEY === 'string' ? env.RELAY_TLS_KEY.trim() : '';
117
+ if (rawCert === '' && rawKey === '') return null; // 默认:明文
118
+ if (rawCert === '' || rawKey === '') {
119
+ const missing = rawCert === '' ? 'RELAY_TLS_CERT' : 'RELAY_TLS_KEY';
120
+ const present = rawCert === '' ? 'RELAY_TLS_KEY' : 'RELAY_TLS_CERT';
121
+ throw new Error(
122
+ `TLS 配置不完整:${present} 已设置但 ${missing} 缺失。` +
123
+ '两个变量必须同时指向 PEM 文件(契约 §3.4.2);如需明文 ws:// 请把两者都清空。',
124
+ );
125
+ }
126
+ let cert;
127
+ let key;
128
+ try {
129
+ cert = readFileSync(rawCert);
130
+ } catch (err) {
131
+ throw new Error(`读取 RELAY_TLS_CERT 失败(${rawCert}):${err && err.message ? err.message : String(err)}`);
132
+ }
133
+ try {
134
+ key = readFileSync(rawKey);
135
+ } catch (err) {
136
+ throw new Error(`读取 RELAY_TLS_KEY 失败(${rawKey}):${err && err.message ? err.message : String(err)}`);
137
+ }
138
+ return { cert, key, certPath: rawCert, keyPath: rawKey };
139
+ }
140
+
141
+ /** 从环境变量读配置(测试可直接传对象覆盖) */
142
+ export function loadConfig(env = process.env) {
143
+ return {
144
+ port: portFromEnv(env),
145
+ token: env.RELAY_TOKEN || DEFAULTS.token,
146
+ logLevel: env.LOG_LEVEL || DEFAULTS.logLevel,
147
+ helloTimeoutMs: intFromEnv(env, 'RELAY_HELLO_TIMEOUT_MS', DEFAULTS.helloTimeoutMs),
148
+ pingIntervalMs: intFromEnv(env, 'RELAY_PING_INTERVAL_MS', DEFAULTS.pingIntervalMs),
149
+ deadTimeoutMs: intFromEnv(env, 'RELAY_DEAD_TIMEOUT_MS', DEFAULTS.deadTimeoutMs),
150
+ helloRateLimit: intFromEnv(env, 'RELAY_HELLO_RATE_LIMIT', DEFAULTS.helloRateLimit),
151
+ helloRateWindowMs: intFromEnv(env, 'RELAY_HELLO_RATE_WINDOW_MS', DEFAULTS.helloRateWindowMs),
152
+ cacheLimit: intFromEnv(env, 'RELAY_CACHE_LIMIT', DEFAULTS.cacheLimit),
153
+ cacheTtlMs: intFromEnv(env, 'RELAY_CACHE_TTL_MS', DEFAULTS.cacheTtlMs),
154
+ maxPayload: intFromEnv(env, 'RELAY_MAX_PAYLOAD', DEFAULTS.maxPayload),
155
+ listenHosts: [...DEFAULTS.listenHosts],
156
+ /** TLS 配置:null = 明文 ws://;{cert,key} = wss://(契约 §3.4.2) */
157
+ tls: loadTlsConfig(env),
158
+ };
159
+ }
160
+
161
+ const otherRole = (role) => (role === 'host' ? 'client' : 'host');
162
+
163
+ /**
164
+ * 握手证明字段(契约 §3.4.1):`e`(纪元)/ `ts` / `pv`(协议版本)/ `sid` / `sig`。
165
+ *
166
+ * 中继是**哑管道**:它没有密钥,**不校验 sig、不改数值、不补默认值、不重排**——
167
+ * 只把对端 hello 里**出现的**字段逐字复制到 welcome.peer / peer-joined.peer。
168
+ * 旧端(v1.1.2 及以前)不带 e/ts/pv/sid → 复制结果里也就没有这些字段。
169
+ */
170
+ const PROOF_FIELDS = ['e', 'ts', 'pv', 'sid', 'sig'];
171
+
172
+ /** 逐字抽取对端 hello 里的证明字段(只取存在的;值原样保留,不做类型转换) */
173
+ export function extractProof(msg) {
174
+ const proof = {};
175
+ if (!msg || typeof msg !== 'object') return proof;
176
+ for (const f of PROOF_FIELDS) {
177
+ if (msg[f] !== undefined) proof[f] = msg[f];
178
+ }
179
+ return proof;
180
+ }
181
+
182
+ /** 组成发往对端的 peer 证明对象:role + 对端 hello 里的证明字段(原样) */
183
+ export function peerProofOf(role, proof) {
184
+ return { role, ...(proof ?? {}) };
185
+ }
186
+
187
+ /**
188
+ * 监听地址候选见 DEFAULTS.listenHosts:
189
+ * '::' —— IPv6 通配地址。Node 默认 ipv6Only=false → **一次绑定同时接收
190
+ * IPv6 与 IPv4**(IPv4 以 ::ffff:a.b.c.d 映射形式进来)。
191
+ * '0.0.0.0' —— 回落:系统禁用 IPv6 时保持旧版(仅 IPv4)行为。
192
+ */
193
+
194
+ /** 只有「IPv6 不可用」这类错误才允许回落 IPv4;端口占用等错误照旧直接抛出 */
195
+ const IPV6_UNAVAILABLE_CODES = new Set(['EAFNOSUPPORT', 'EADDRNOTAVAIL', 'EINVAL', 'EPROTONOSUPPORT']);
196
+
197
+ /**
198
+ * 双栈下 IPv4 连接的对端地址形如 '::ffff:127.0.0.1',
199
+ * 归一为 '127.0.0.1' —— 限速分桶与日志与旧版(IPv4-only 监听)保持一致,
200
+ * 纯 IPv6 地址(::1 等)原样保留。
201
+ */
202
+ function normalizeIp(addr) {
203
+ if (typeof addr !== 'string' || addr === '') return 'unknown';
204
+ const m = addr.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
205
+ return m ? m[1] : addr;
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // 中继核心
210
+ // ---------------------------------------------------------------------------
211
+
212
+ /**
213
+ * 创建中继(不监听端口,由 start() 启动)。测试可注入 config 覆盖默认值。
214
+ *
215
+ * 连接表结构:
216
+ * channels: Map<ch, Channel>
217
+ * Channel = { conns: { host: Conn|null, client: Conn|null },
218
+ * cache: { host: CachedFrame[], client: CachedFrame[] },
219
+ * cleanupTimer }
220
+ * Conn = { ws, ip, role, ch, helloDone, lastRecvAt, lastSentAt, helloTimer }
221
+ * CachedFrame = { seq, data, urgent, at }
222
+ */
223
+ export function createRelay(overrides = {}) {
224
+ const cfg = { ...loadConfig(), ...overrides };
225
+ const log = makeLogger(cfg.logLevel);
226
+
227
+ /** @type {Map<string, any>} */
228
+ const channels = new Map();
229
+ /** @type {Set<any>} */
230
+ const conns = new Set();
231
+ /** ip -> { start, count } */
232
+ const rateBuckets = new Map();
233
+
234
+ // ---- 限速:每 IP 每窗口 ≤ helloRateLimit 个 hello -------------------------
235
+ function takeHelloSlot(ip) {
236
+ const now = Date.now();
237
+ let b = rateBuckets.get(ip);
238
+ if (!b || now - b.start >= cfg.helloRateWindowMs) {
239
+ b = { start: now, count: 0 };
240
+ rateBuckets.set(ip, b);
241
+ }
242
+ b.count += 1;
243
+ return b.count <= cfg.helloRateLimit;
244
+ }
245
+
246
+ // ---- 发送 -----------------------------------------------------------------
247
+ function sendJson(conn, obj) {
248
+ if (conn.ws.readyState !== WebSocket.OPEN) return false;
249
+ try {
250
+ conn.ws.send(JSON.stringify(obj));
251
+ conn.lastSentAt = Date.now();
252
+ return true;
253
+ } catch (err) {
254
+ log.warn('send failed', { err: String(err && err.message) });
255
+ return false;
256
+ }
257
+ }
258
+
259
+ function sendErrorClose(conn, code, message, closeCode = 1008) {
260
+ sendJson(conn, { t: 'error', code, message });
261
+ try {
262
+ conn.ws.close(closeCode, `${code}: ${message}`);
263
+ } catch {
264
+ /* ignore */
265
+ }
266
+ }
267
+
268
+ // ---- 通道 -----------------------------------------------------------------
269
+ function getChannel(ch) {
270
+ let c = channels.get(ch);
271
+ if (!c) {
272
+ c = { conns: { host: null, client: null }, cache: { host: [], client: [] }, cleanupTimer: null };
273
+ channels.set(ch, c);
274
+ }
275
+ if (c.cleanupTimer) {
276
+ clearTimeout(c.cleanupTimer);
277
+ c.cleanupTimer = null;
278
+ }
279
+ return c;
280
+ }
281
+
282
+ /** 把发往 targetRole 的帧转发或缓存 */
283
+ function deliverFrame(channel, targetRole, out) {
284
+ const target = channel.conns[targetRole];
285
+ if (target && target.ws.readyState === WebSocket.OPEN) {
286
+ sendJson(target, out);
287
+ return true;
288
+ }
289
+ // 对端不在线 → 离线缓存:256 条 / 24h,FIFO 丢旧
290
+ const q = channel.cache[targetRole];
291
+ q.push({ sid: out.sid, seq: out.seq, data: out.data, urgent: out.urgent === true, at: Date.now() });
292
+ while (q.length > cfg.cacheLimit) q.shift(); // FIFO 丢最旧
293
+ while (q.length && Date.now() - q[0].at > cfg.cacheTtlMs) q.shift(); // 过期清理(队首最旧)
294
+ log.debug('cached frame', { targetRole, seq: out.seq, queued: q.length });
295
+ return false;
296
+ }
297
+
298
+ /** 对端重连后补发缓存:urgent 优先,其余按 seq 升序 */
299
+ function flushCache(channel, targetRole, targetConn) {
300
+ const q = channel.cache[targetRole];
301
+ if (!q.length) return 0;
302
+ channel.cache[targetRole] = [];
303
+ const now = Date.now();
304
+ const live = q.filter((f) => now - f.at <= cfg.cacheTtlMs);
305
+ live.sort((a, b) => (b.urgent ? 1 : 0) - (a.urgent ? 1 : 0) || a.seq - b.seq);
306
+ const from = otherRole(targetRole);
307
+ for (const f of live) {
308
+ const out = { t: 'frame', from, seq: f.seq, data: f.data };
309
+ if (typeof f.sid === 'string' && f.sid !== '') out.sid = f.sid;
310
+ if (f.urgent) out.urgent = true;
311
+ sendJson(targetConn, out);
312
+ }
313
+ if (live.length) log.info('flushed offline cache', { role: targetRole, count: live.length });
314
+ return live.length;
315
+ }
316
+
317
+ // ---- hello ----------------------------------------------------------------
318
+ function handleHello(conn, msg) {
319
+ const ip = conn.ip;
320
+ if (!takeHelloSlot(ip)) {
321
+ log.warn('hello rate limited', { ip });
322
+ sendErrorClose(conn, 'rate-limited', `too many hello from ${ip}`, 1008);
323
+ return;
324
+ }
325
+ const role = msg && msg.role;
326
+ const ch = msg && msg.ch;
327
+ if (role !== 'host' && role !== 'client') {
328
+ log.warn('bad hello: role', { ip, role });
329
+ sendErrorClose(conn, 'bad-hello', 'role must be "host" or "client"');
330
+ return;
331
+ }
332
+ if (typeof ch !== 'string' || !CHANNEL_RE.test(ch)) {
333
+ log.warn('bad hello: ch', { ip, ch });
334
+ sendErrorClose(conn, 'bad-hello', 'ch must match ^[A-Z2-7]{16,64}$');
335
+ return;
336
+ }
337
+ if (cfg.token !== null && (!msg || msg.token !== cfg.token)) {
338
+ log.warn('bad hello: token', { ip, ch });
339
+ sendErrorClose(conn, 'bad-hello', 'invalid or missing token');
340
+ return;
341
+ }
342
+ // 注:sig 字段是端到端 HMAC 握手证明(契约 §3.4),中继无密钥材料,只透传不校验。
343
+
344
+ clearTimeout(conn.helloTimer);
345
+ conn.helloDone = true;
346
+ conn.role = role;
347
+ conn.ch = ch;
348
+ // v1.1.3:原样留存对端 hello 的证明字段(只复制,不校验——中继无密钥)
349
+ conn.proof = extractProof(msg);
350
+
351
+ const channel = getChannel(ch);
352
+ // 同 channel 同 role 单活跃连接:新顶旧
353
+ const old = channel.conns[role];
354
+ channel.conns[role] = conn;
355
+ if (old && old !== conn && old.ws.readyState === WebSocket.OPEN) {
356
+ log.info('replacing existing connection', { ch, role, oldIp: old.ip, newIp: conn.ip });
357
+ sendJson(old, { t: 'error', code: 'replaced', message: `a new ${role} connection took over this channel` });
358
+ try {
359
+ old.ws.close(4001, 'replaced by a newer connection');
360
+ } catch {
361
+ /* ignore */
362
+ }
363
+ old.role = null;
364
+ old.ch = null; // 防止它的 close 清理逻辑误删新连接 / 误发 peer-left(detachFromChannel 幂等跳过)
365
+ }
366
+
367
+ // v1.1.3:welcome.peer = 对端**已在线**时,把对端 hello 的证明逐字复制过来;
368
+ // 对端不在线 → 不带 peer 字段(不补默认值)。
369
+ const peerRole = otherRole(role);
370
+ const peerConn = channel.conns[peerRole];
371
+ const welcome = {
372
+ t: 'welcome',
373
+ peers: { host: channel.conns.host !== null, client: channel.conns.client !== null },
374
+ };
375
+ if (peerConn) welcome.peer = peerProofOf(peerRole, peerConn.proof);
376
+ sendJson(conn, welcome);
377
+
378
+ // v1.1.3:**顶替场景也要通知对端**(v1.1.2 时顶替对对端无影响,因为 sid 只用于
379
+ // 去重分桶;加固模式下对端**钉扎**了对端的 sid/纪元,顶替换了新连接(sid 与纪元
380
+ // 都变)→ 对端必须重新钉扎,否则新连接的帧全被当成「sid 不符」丢弃 → 链路死到
381
+ // 双方重连为止)。故这里**无条件**给在线的对端发 peer-joined(带新证明)。
382
+ // (peer-joined.peer = 新上线方自己的证明;顶替时是「新顶替者」的证明。)
383
+ if (peerConn) {
384
+ sendJson(peerConn, { t: 'peer-joined', role, peer: peerProofOf(role, conn.proof) });
385
+ }
386
+
387
+ flushCache(channel, role, conn);
388
+ log.info('hello ok', { ch, role, ip: conn.ip, peers: { host: channel.conns.host !== null, client: channel.conns.client !== null } });
389
+ }
390
+
391
+ // ---- 帧分发 ---------------------------------------------------------------
392
+ function handleMessage(conn, raw, isBinary) {
393
+ conn.lastRecvAt = Date.now();
394
+ if (isBinary) return; // 协议只用文本帧;二进制帧忽略(哑管道不做猜测)
395
+
396
+ let msg;
397
+ try {
398
+ msg = JSON.parse(raw.toString('utf8'));
399
+ } catch {
400
+ if (!conn.helloDone) {
401
+ log.warn('first message not JSON', { ip: conn.ip });
402
+ sendErrorClose(conn, 'bad-hello', 'first message must be a hello JSON object');
403
+ } else {
404
+ log.debug('ignoring non-JSON message', { ip: conn.ip });
405
+ }
406
+ return;
407
+ }
408
+ if (!msg || typeof msg !== 'object' || typeof msg.t !== 'string') {
409
+ if (!conn.helloDone) {
410
+ log.warn('first message malformed', { ip: conn.ip });
411
+ sendErrorClose(conn, 'bad-hello', 'first message must be a hello JSON object');
412
+ }
413
+ return;
414
+ }
415
+
416
+ if (!conn.helloDone) {
417
+ if (msg.t === 'hello') handleHello(conn, msg);
418
+ else {
419
+ log.warn('first message not hello', { ip: conn.ip, t: msg.t });
420
+ sendErrorClose(conn, 'bad-hello', 'first message must be hello');
421
+ }
422
+ return;
423
+ }
424
+
425
+ switch (msg.t) {
426
+ case 'hello':
427
+ // 已经 hello 过 → 忽略(哑管道,不升级为错误)
428
+ return;
429
+ case 'frame': {
430
+ const { seq, data, urgent, sid } = msg;
431
+ // 只做传输层形状校验;不解析 base64 内容(端到端密文)
432
+ if (typeof seq !== 'number' || !Number.isFinite(seq) || typeof data !== 'string') {
433
+ log.debug('ignoring malformed frame', { ip: conn.ip, seq: typeof seq });
434
+ return;
435
+ }
436
+ const channel = channels.get(conn.ch);
437
+ if (!channel) return;
438
+ const out = { t: 'frame', from: conn.role, seq, data };
439
+ // v1.0.2:sid(发送端实例 id)不透明透传,接收端做 sid:seq 去重
440
+ if (typeof sid === 'string' && sid !== '') out.sid = sid;
441
+ if (urgent === true) out.urgent = true;
442
+ deliverFrame(channel, otherRole(conn.role), out);
443
+ return;
444
+ }
445
+ case 'ping':
446
+ sendJson(conn, { t: 'pong' });
447
+ return;
448
+ case 'pong':
449
+ return; // 仅作为活性证据(lastRecvAt 已更新)
450
+ default:
451
+ log.debug('ignoring unknown message type', { ip: conn.ip, t: msg.t });
452
+ return;
453
+ }
454
+ }
455
+
456
+ // ---- 连接生命周期 ---------------------------------------------------------
457
+ /** 从通道连接表摘除(幂等);对端在线则通知 peer-left;空通道挂 TTL 清理 */
458
+ function detachFromChannel(conn, closeCode, closeReason) {
459
+ if (!conn.ch) return;
460
+ const ch = conn.ch;
461
+ const role = conn.role;
462
+ conn.ch = null;
463
+ conn.role = null;
464
+ const channel = channels.get(ch);
465
+ if (!channel) return;
466
+ if (channel.conns[role] !== conn) return; // 已被新连接顶掉
467
+ channel.conns[role] = null;
468
+ const peerConn = channel.conns[otherRole(role)];
469
+ if (peerConn) sendJson(peerConn, { t: 'peer-left', role });
470
+ log.info('peer left', { ch, role, ip: conn.ip, code: closeCode, reason: closeReason });
471
+ if (!channel.conns.host && !channel.conns.client) {
472
+ // 双方都下线:保留缓存至 TTL,到期后删除整个通道
473
+ channel.cleanupTimer = setTimeout(() => {
474
+ const c = channels.get(ch);
475
+ if (c && !c.conns.host && !c.conns.client) channels.delete(ch);
476
+ }, cfg.cacheTtlMs);
477
+ channel.cleanupTimer.unref?.();
478
+ }
479
+ }
480
+
481
+ function onConnection(ws, req) {
482
+ const ip = normalizeIp(req.socket && req.socket.remoteAddress);
483
+ const conn = {
484
+ ws,
485
+ ip,
486
+ role: null,
487
+ ch: null,
488
+ helloDone: false,
489
+ lastRecvAt: Date.now(),
490
+ lastSentAt: Date.now(),
491
+ helloTimer: null,
492
+ /** v1.1.3:本连接 hello 里的证明字段(原样留存,供对端读取) */
493
+ proof: {},
494
+ };
495
+ conns.add(conn);
496
+ log.info('connection open', { ip, conns: conns.size });
497
+
498
+ conn.helloTimer = setTimeout(() => {
499
+ if (!conn.helloDone) {
500
+ log.warn('hello timeout', { ip });
501
+ try {
502
+ conn.ws.close(4008, 'hello timeout');
503
+ } catch {
504
+ /* ignore */
505
+ }
506
+ }
507
+ }, cfg.helloTimeoutMs);
508
+ conn.helloTimer.unref?.();
509
+
510
+ ws.on('message', (data, isBinary) => handleMessage(conn, data, isBinary));
511
+ ws.on('pong', () => {
512
+ conn.lastRecvAt = Date.now(); // ws 协议层 pong 也是活性证据
513
+ });
514
+ ws.on('ping', () => {
515
+ conn.lastRecvAt = Date.now();
516
+ if (ws.readyState === WebSocket.OPEN) {
517
+ try {
518
+ ws.pong();
519
+ } catch {
520
+ /* ignore */
521
+ }
522
+ }
523
+ });
524
+ ws.on('error', (err) => log.debug('socket error', { ip, err: String(err && err.message) }));
525
+ ws.on('close', (code, reasonBuf) => {
526
+ clearTimeout(conn.helloTimer);
527
+ conns.delete(conn);
528
+ detachFromChannel(conn, code, reasonBuf?.toString());
529
+ });
530
+ }
531
+
532
+ // ---- 心跳巡检 -------------------------------------------------------------
533
+ const sweepEveryMs = Math.max(50, Math.min(cfg.pingIntervalMs, cfg.deadTimeoutMs) / 2);
534
+ const sweepTimer = setInterval(() => {
535
+ const now = Date.now();
536
+ for (const conn of [...conns]) {
537
+ if (now - conn.lastRecvAt > cfg.deadTimeoutMs) {
538
+ log.warn('peer dead (no message within timeout)', { ip: conn.ip, role: conn.role, ch: conn.ch, deadTimeoutMs: cfg.deadTimeoutMs });
539
+ // 立即从连接表摘除(不等异步 close 事件),保证快速重连看到干净状态
540
+ clearTimeout(conn.helloTimer);
541
+ detachFromChannel(conn, 4002, 'heartbeat timeout');
542
+ conns.delete(conn);
543
+ try {
544
+ conn.ws.terminate();
545
+ } catch {
546
+ /* ignore */
547
+ }
548
+ continue;
549
+ }
550
+ if (now - conn.lastSentAt >= cfg.pingIntervalMs) {
551
+ sendJson(conn, { t: 'ping' }); // 应用层心跳
552
+ try {
553
+ conn.ws.ping(); // ws 协议层 ping 同步发,穿透中间设备
554
+ conn.lastSentAt = now;
555
+ } catch {
556
+ /* ignore */
557
+ }
558
+ }
559
+ }
560
+ // 限速桶回收,防 Map 泄漏
561
+ for (const [ip, b] of rateBuckets) {
562
+ if (now - b.start >= cfg.helloRateWindowMs * 2) rateBuckets.delete(ip);
563
+ }
564
+ }, sweepEveryMs);
565
+ sweepTimer.unref?.();
566
+
567
+ // ---- 启停 -----------------------------------------------------------------
568
+ let wss = null;
569
+ /** TLS 模式下由我们创建的 https server(明文模式为 null) */
570
+ let httpServer = null;
571
+ /** 实际生效的监听地址('::' = 双栈,'0.0.0.0' = 仅 IPv4) */
572
+ let listenHost = null;
573
+
574
+ /**
575
+ * 在指定 host 上监听一次;成功 resolve {wss, httpServer},失败 reject(error)。
576
+ * 失败时把 server 关掉,避免残留半开句柄。
577
+ *
578
+ * TLS 模式(契约 §3.4.2):RELAY_TLS_CERT + RELAY_TLS_KEY 都配置时,
579
+ * 用 node:https 起 HTTPS 服务并把 upgrade 交给 ws —— 对外即 **wss://**。
580
+ * 证书/私钥非法 → createHttpsServer 直接抛错 → 启动失败(不降级明文)。
581
+ */
582
+ function listenOnce(host) {
583
+ return new Promise((resolve, reject) => {
584
+ let srv = null;
585
+ let server = null;
586
+ try {
587
+ if (cfg.tls) {
588
+ server = createHttpsServer({ cert: cfg.tls.cert, key: cfg.tls.key });
589
+ srv = new WebSocketServer({ server, maxPayload: cfg.maxPayload });
590
+ } else {
591
+ srv = new WebSocketServer({ port: cfg.port, host, maxPayload: cfg.maxPayload });
592
+ }
593
+ } catch (err) {
594
+ reject(
595
+ cfg.tls
596
+ ? new Error(
597
+ `TLS 证书/私钥非法(${cfg.tls.certPath} / ${cfg.tls.keyPath}):${err && err.message ? err.message : String(err)}`,
598
+ )
599
+ : err,
600
+ );
601
+ return;
602
+ }
603
+ const target = server ?? srv; // 错误/监听事件来自底层 server
604
+ // 常驻的兜底 error 监听:避免 close 过程中的二次 error 变成 unhandled 'error'
605
+ target.on('error', () => {});
606
+ const onError = (err) => {
607
+ try {
608
+ srv.close(() => {});
609
+ } catch {
610
+ /* ignore */
611
+ }
612
+ try {
613
+ server?.close(() => {});
614
+ } catch {
615
+ /* ignore */
616
+ }
617
+ reject(err);
618
+ };
619
+ target.once('error', onError);
620
+ target.once('listening', () => {
621
+ target.off('error', onError);
622
+ resolve({ wss: srv, httpServer: server });
623
+ });
624
+ if (server) server.listen(cfg.port, host);
625
+ });
626
+ }
627
+
628
+ async function start() {
629
+ let lastErr = null;
630
+ const candidates = Array.isArray(cfg.listenHosts) && cfg.listenHosts.length ? cfg.listenHosts : DEFAULTS.listenHosts;
631
+ for (const host of candidates) {
632
+ let res;
633
+ try {
634
+ res = await listenOnce(host);
635
+ } catch (err) {
636
+ lastErr = err;
637
+ if (!IPV6_UNAVAILABLE_CODES.has(err && err.code)) throw err;
638
+ log.warn('ipv6 listen unavailable, falling back to ipv4-only', { err: String(err && err.message) });
639
+ continue;
640
+ }
641
+ wss = res.wss;
642
+ httpServer = res.httpServer;
643
+ listenHost = host;
644
+ wss.on('connection', onConnection);
645
+ wss.on('error', (err) => log.error('server error', { err: String(err && err.message) }));
646
+ const addr = (httpServer ?? wss).address();
647
+ // 机器可读启动行(测试脚本依赖此行解析实际端口)
648
+ console.log(`relay listening port=${addr.port}`);
649
+ log.info('relay started', {
650
+ port: addr.port,
651
+ host,
652
+ dualStack: host === '::',
653
+ tokenRequired: cfg.token !== null,
654
+ tls: cfg.tls !== null && cfg.tls !== undefined,
655
+ });
656
+ return addr.port;
657
+ }
658
+ throw lastErr;
659
+ }
660
+
661
+ function stop() {
662
+ clearInterval(sweepTimer);
663
+ for (const conn of [...conns]) {
664
+ clearTimeout(conn.helloTimer);
665
+ try {
666
+ conn.ws.terminate();
667
+ } catch {
668
+ /* ignore */
669
+ }
670
+ }
671
+ conns.clear();
672
+ channels.clear();
673
+ rateBuckets.clear();
674
+ return new Promise((resolve) => {
675
+ if (!wss) return resolve();
676
+ wss.close(() => {
677
+ // TLS 模式:https server 是我们自己起的,wss.close() 不会关它 → 显式关掉
678
+ if (httpServer) {
679
+ try {
680
+ httpServer.close(() => resolve());
681
+ return;
682
+ } catch {
683
+ /* ignore */
684
+ }
685
+ }
686
+ resolve();
687
+ });
688
+ });
689
+ }
690
+
691
+ return {
692
+ cfg,
693
+ log,
694
+ channels,
695
+ conns,
696
+ rateBuckets,
697
+ start,
698
+ stop,
699
+ /** 实际生效的监听地址(start() 之后才有值) */
700
+ get listenHost() {
701
+ return listenHost;
702
+ },
703
+ /** 是否启用了原生 TLS(契约 §3.4.2) */
704
+ get tlsEnabled() {
705
+ return Boolean(cfg.tls);
706
+ },
707
+ };
708
+ }
709
+
710
+ // ---------------------------------------------------------------------------
711
+ // 入口
712
+ // ---------------------------------------------------------------------------
713
+ const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
714
+ if (isMain) {
715
+ let relay;
716
+ try {
717
+ relay = createRelay();
718
+ } catch (err) {
719
+ // TLS 配置有问题(证书读不到 / 非法 / 只配了一个变量)→ 启动即失败,
720
+ // 绝不静默降级成明文 ws://
721
+ console.error(`dsh-remote-control-relay failed to start: ${err && err.message ? err.message : String(err)}`);
722
+ process.exit(1);
723
+ }
724
+ relay
725
+ .start()
726
+ .then((port) => {
727
+ const h = relay.listenHost === '0.0.0.0' ? '0.0.0.0' : '[::]';
728
+ const dual = relay.listenHost === '::' ? 'IPv4+IPv6 双栈' : '仅 IPv4';
729
+ const scheme = relay.tlsEnabled ? 'wss' : 'ws';
730
+ relay.log.info(`dsh-remote-control-relay listening on ${scheme}://${h}:${port} (${dual}) (pid ${process.pid})`);
731
+ })
732
+ .catch((err) => {
733
+ relay.log.error('failed to start', { err: String(err && err.message) });
734
+ process.exit(1);
735
+ });
736
+ // 停止是**幂等**的:POSIX 上父进程可能同时发 SIGTERM 与 stdin 的 shutdown 命令,
737
+ // 两条路径都会走到这里 → 只执行一次真正的 stop()。
738
+ let stopping = false;
739
+ const shutdown = (sig) => {
740
+ if (stopping) return;
741
+ stopping = true;
742
+ relay.log.info(`received ${sig}, shutting down`);
743
+ relay.stop().then(() => process.exit(0));
744
+ };
745
+ process.on('SIGINT', () => shutdown('SIGINT'));
746
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
747
+
748
+ // 父进程看门狗(仅当插件以 DSHRC_RELAY_PARENT_WATCHDOG=1 托管本进程时启用):
749
+ // 父进程用 stdio 的 stdin 管道 spawn 本进程,父进程一旦退出管道即 EOF →
750
+ // 这里收到 'end' 就优雅关停,避免 DSH 崩溃/被杀后留下孤儿中继。
751
+ // 手工 `node server.js` 启动时该变量不存在,行为完全不变。
752
+ //
753
+ // 另支持父进程经 stdin 下 `shutdown` 命令做**优雅停止**:
754
+ // Windows 上 child.kill('SIGTERM') 是硬杀(不走 signal handler),
755
+ // 所以插件优先走这条命令通道,让中继自己 close 掉 ws 连接(手机端看到正常 close 而非 RST)。
756
+ if (process.env.DSHRC_RELAY_PARENT_WATCHDOG === '1' && process.stdin) {
757
+ let buf = '';
758
+ process.stdin.on('data', (chunk) => {
759
+ buf += String(chunk);
760
+ let idx = buf.indexOf('\n');
761
+ while (idx >= 0) {
762
+ const line = buf.slice(0, idx).trim();
763
+ buf = buf.slice(idx + 1);
764
+ if (line === 'shutdown') {
765
+ shutdown('shutdown command');
766
+ return;
767
+ }
768
+ idx = buf.indexOf('\n');
769
+ }
770
+ });
771
+ process.stdin.on('end', () => {
772
+ shutdown('parent process gone');
773
+ });
774
+ // 不让 stdin 保持活跃引用拖住事件循环退出
775
+ process.stdin.resume();
776
+ }
777
+ }