@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,741 @@
1
+ // lib/relay-client.mjs — 中继 WebSocket 客户端(契约 §4 / §3.4.1)。
2
+ //
3
+ // DSH 插件以 host 角色**出站连接**中继(无需端口映射);中继只转发
4
+ // AES-256-GCM 密文帧(frame.data)。本模块职责:
5
+ // - 连接 / hello(10s 内发出,带 §3.4.1 v2 握手证明与可选 RELAY_TOKEN)
6
+ // - 指数退避重连:1s → 60s 封顶,带 ±50% 抖动
7
+ // - 应用层心跳:30s 无帧即发 ping;90s 无任何消息判死重连
8
+ // - 发送 seq 单调递增(从 1 开始);接收按对端 seq 去重(同一 seq 只处理一次)
9
+ // - 解密后把明文业务消息交给 onMessage
10
+ //
11
+ // **v1.1.3 会话纪元(契约 §3.4.1 / §7)**:
12
+ // - hello 带 e/ts/pv/sid,sig 用 v2 证明串("hello2|role|channel|e|ts|pv|sid")。
13
+ // - 对端证明由中继在 welcome.peer / peer-joined.peer 里**原样透传**(中继无密钥)。
14
+ // - 模式判定:双方 pv≥2 → 加固模式(AAD 绑定发送方 sid + 钉扎对端 sid);
15
+ // 任一方 pv<2(或对端没带证明)→ 兼容模式(旧 AAD)。
16
+ // - 纪元单调性:对端 e ≤ 已接受值 → 拒绝连接(疑似重放);同一证明重复 → 幂等接受。
17
+ // - **收到 welcome 之前不发业务帧**(否则不知道对端 pv → AAD 会选错)。
18
+ //
19
+ // 传输层帧语义见契约 §4;加解密复用 lib/protocol.mjs。
20
+ import { randomBytes } from "node:crypto";
21
+ import {
22
+ acceptPeerEpoch,
23
+ deriveKey,
24
+ helloSig2,
25
+ HELLO_PROTO_VERSION,
26
+ MODE_COMPAT,
27
+ MODE_HARDENED,
28
+ negotiateMode,
29
+ open,
30
+ seal,
31
+ verifyHelloSig2,
32
+ } from "./protocol.mjs";
33
+
34
+ const HELLO_TIMEOUT_MS = 10_000; // 契约 §4:连接后 10s 内必须 hello
35
+ const HEARTBEAT_INTERVAL_MS = 30_000; // 30s 无帧即发 ping
36
+ const DEAD_TIMEOUT_MS = 90_000; // 90s 无任何消息判死
37
+ const BACKOFF_BASE_MS = 1_000;
38
+ const BACKOFF_MAX_MS = 60_000;
39
+ const SEEN_SET_TRIM = 2_048; // 去重集合超量时裁剪窗口
40
+ const PENDING_STASH_MAX = 16; // 模式切换竞态下暂存的帧数上限
41
+ const PENDING_STASH_TTL_MS = 15_000; // 暂存帧的最长存活时间
42
+
43
+ /**
44
+ * @typedef {"connecting"|"handshaking"|"ready"|"disconnected"|"error"} RelayStatus
45
+ * @typedef {{
46
+ * relayUrl: string, channel: string, secret: string,
47
+ * relayToken?: string,
48
+ * role?: "host"|"client",
49
+ * // v1.1.3 会话纪元的持久化钩子(契约 §3.4.1)。
50
+ * // 不传时退化为纯内存(进程内单调,跨重启不保留——只用于测试)。
51
+ * epoch?: {
52
+ * // 取下一个自纪元(实现方必须先落盘再返回;失败应抛错)。
53
+ * nextSelfEpoch?: () => number,
54
+ * // 读已接受的对端纪元锚点 {peer, peerSid}。
55
+ * peerState?: () => {peer?: number, peerSid?: string},
56
+ * // 持久化已接受的对端纪元锚点。
57
+ * savePeerEpoch?: (peer: number, peerSid: string) => void,
58
+ * },
59
+ * onStatus?: (s: RelayStatus, detail?: string) => void,
60
+ * onPeer?: (joined: boolean, role: "host"|"client") => void,
61
+ * onMessage: (m: object) => void,
62
+ * onFatal?: (code: string, message: string) => void,
63
+ * log?: (level: "info"|"warn"|"error", message: string, extra?: object) => void,
64
+ * }} RelayClientOptions
65
+ */
66
+
67
+ export class RelayClient {
68
+ #opts;
69
+ #key;
70
+ #ws = null;
71
+ #closed = false;
72
+ #seq = 0; // 本端发送序号(每条连接从 1 开始,契约 §4)
73
+ #sid = ""; // 发送端实例 id(每条连接生成一次;去重键 = sid:seq,契约 §4 v1.0.2)
74
+ #seen = new Map(); // 对端去重:sid -> Set<seq>
75
+ #tries = 0; // 连续失败次数(退避指数)
76
+ #reconnectTimer = null;
77
+ #heartbeatTimer = null;
78
+ #helloTimer = null;
79
+ #lastTrafficAt = 0;
80
+ #handshaken = false; // 本端 hello 已被中继接受(收到 welcome)
81
+
82
+ // ---- v1.1.3 会话纪元(契约 §3.4.1)--------------------------------------
83
+ #selfEpoch = 0; // 本连接的自纪元(每条新连接 +1,先落盘再使用)
84
+ #lastPeerEpoch = 0; // 已接受的对端纪元(回退检测的锚点,跨重启保留)
85
+ #lastPeerSid = ""; // 已接受的对端纪元对应的 sid(锚点的一部分)
86
+ #pinnedPeerSid = ""; // **本连接**钉扎的对端 sid(加固模式用于校验 frame.sid)
87
+ #peerPv = 1; // 对端协议版本(1 = 旧端 / 未知)
88
+ #peerProof = null; // 对端证明原文(welcome.peer / peer-joined.peer)
89
+ #mode = MODE_COMPAT; // 当前握手模式(compat | hardened)
90
+ #peerRejected = false; // 对端证明非法 → 拒绝连接(不发业务帧)
91
+ #pendingFrames = []; // 兼容模式下解不开的帧(模式切换后按加固 AAD 重试)
92
+
93
+ /**
94
+ * 对端在线状态。只跟踪**对端**:host 角色实例只读写 peers.client,
95
+ * client 角色实例只读写 peers.host。本端的可发送性由 #handshaken 决定
96
+ * (welcome.peers 自己那一项是中继快照,时序上可能落后,不可当作凭据)。
97
+ */
98
+ peers = { host: false, client: false };
99
+
100
+ /**
101
+ * @param {RelayClientOptions} opts
102
+ */
103
+ constructor(opts) {
104
+ this.#opts = opts;
105
+ this.#key = deriveKey(opts.secret, opts.channel);
106
+ }
107
+
108
+ get key() {
109
+ return this.#key;
110
+ }
111
+
112
+ /** 当前握手模式:"compat"(旧 AAD)或 "hardened"(AAD 绑定 sid)。 */
113
+ get mode() {
114
+ return this.#mode;
115
+ }
116
+
117
+ /** 本连接的自纪元号(契约 §3.4.1)。 */
118
+ get selfEpoch() {
119
+ return this.#selfEpoch;
120
+ }
121
+
122
+ /** 已钉扎的对端 sid(加固模式才有值;空串 = 还没接受对端证明)。 */
123
+ get pinnedPeerSid() {
124
+ return this.#pinnedPeerSid;
125
+ }
126
+
127
+ /** 对端协议版本(1 = 旧端/未知,2 = v1.1.3)。 */
128
+ get peerProtocolVersion() {
129
+ return this.#peerPv;
130
+ }
131
+
132
+ /** 手机端(client 角色)是否在线——审批拦截的前置条件之一(契约 §5.5)。 */
133
+ get clientOnline() {
134
+ return this.#handshaken && this.peers.client === true;
135
+ }
136
+
137
+ /** welcome 已收到(hello 被接受)且 socket 仍开着。 */
138
+ get ready() {
139
+ return this.#ws !== null && this.#ws.readyState === 1 /* OPEN */ && this.#handshaken;
140
+ }
141
+
142
+ /** 启动连接(幂等)。 */
143
+ start() {
144
+ if (this.#closed) return;
145
+ if (this.#ws !== null) return;
146
+ this.#connect();
147
+ this.#heartbeatTimer = setInterval(() => this.#tick(), HEARTBEAT_INTERVAL_MS);
148
+ }
149
+
150
+ /** 停止并释放全部资源(插件卸载 / 配置变更时调用)。 */
151
+ close() {
152
+ this.#closed = true;
153
+ if (this.#heartbeatTimer !== null) {
154
+ clearInterval(this.#heartbeatTimer);
155
+ this.#heartbeatTimer = null;
156
+ }
157
+ if (this.#reconnectTimer !== null) {
158
+ clearTimeout(this.#reconnectTimer);
159
+ this.#reconnectTimer = null;
160
+ }
161
+ this.#clearHelloTimer();
162
+ const ws = this.#ws;
163
+ this.#ws = null;
164
+ this.#handshaken = false;
165
+ this.peers = { host: false, client: false };
166
+ this.#resetPeerState();
167
+ if (ws !== null) {
168
+ try {
169
+ ws.close();
170
+ } catch {
171
+ /* 已关闭 */
172
+ }
173
+ }
174
+ this.#setStatus("disconnected", "closed");
175
+ }
176
+
177
+ /**
178
+ * 强制断开当前连接以触发自动重连(网络切换、手动重连、测试断线场景)。
179
+ * 与 close() 的区别:不置 #closed,因此 ws 的 close 事件会照常走指数退避重连。
180
+ * 空闲时(无连接)是 no-op。
181
+ */
182
+ dropConnection() {
183
+ if (this.#closed) return;
184
+ const ws = this.#ws;
185
+ if (ws === null) return;
186
+ try {
187
+ ws.close();
188
+ } catch {
189
+ /* 已关闭;close 事件仍会触发 */
190
+ }
191
+ }
192
+
193
+ /**
194
+ * 以新的配对信息热更换(/remote-pairing rotate,契约 §3.5):换 channel/secret
195
+ * 后立即用新密钥重连;旧密钥、旧连接、去重表即刻作废(旧二维码/旧口述失效)。
196
+ * 未传的字段保持原值;close() 之后调用是 no-op。
197
+ * @param {{channel?:string, secret?:string, relayToken?:string, relayUrl?:string}} next
198
+ */
199
+ reload(next) {
200
+ if (this.#closed) return;
201
+ const n = next ?? {};
202
+ if (typeof n.channel === "string" && n.channel !== "") this.#opts.channel = n.channel;
203
+ if (typeof n.secret === "string" && n.secret !== "") this.#opts.secret = n.secret;
204
+ if (n.relayToken !== undefined) this.#opts.relayToken = n.relayToken;
205
+ if (typeof n.relayUrl === "string" && n.relayUrl !== "") this.#opts.relayUrl = n.relayUrl;
206
+ this.#key = deriveKey(this.#opts.secret, this.#opts.channel);
207
+ this.#tries = 0;
208
+ this.#seen.clear();
209
+ this.#seq = 0;
210
+ this.#sid = "";
211
+ this.#handshaken = false;
212
+ this.peers = { host: false, client: false };
213
+ // 换了对端身份 → 之前的对端证明/钉扎一律作废(新连接重新握手)。
214
+ this.#resetPeerState();
215
+ // 摘除旧 socket:先置空,close 事件里的 #ws !== ws 守卫会忽略它(不触发退避重连)
216
+ const ws = this.#ws;
217
+ this.#ws = null;
218
+ this.#clearHelloTimer();
219
+ if (ws !== null) {
220
+ try {
221
+ ws.close();
222
+ } catch {
223
+ /* 已关闭 */
224
+ }
225
+ }
226
+ this.#opts.log?.("info", "pairing identity reloaded; reconnecting", { channel: this.#opts.channel });
227
+ this.#connect();
228
+ }
229
+
230
+ /**
231
+ * 发送一条明文业务消息:加密 → {t:"frame", seq, data, urgent?}。
232
+ * 未就绪时返回 false(调用方决定是否缓存或丢弃;中继另有离线缓存)。
233
+ *
234
+ * **AAD 两模式(契约 §7)**:兼容模式 "dshrc|role|seq";加固模式再绑定**发送方**的
235
+ * 连接实例 id("dshrc|role|seq|sid")。因此**必须等到 welcome 之后**才发
236
+ * (welcome 才知道对端 pv → 才知道该用哪种 AAD)。
237
+ * @param {object} message 明文业务消息
238
+ * @param {boolean} [urgent] 审批/提问帧标记优先补发(契约 §4)
239
+ * @returns {boolean}
240
+ */
241
+ send(message, urgent = false) {
242
+ const ws = this.#ws;
243
+ if (this.#closed || ws === null || ws.readyState !== 1 /* OPEN */) return false;
244
+ if (!this.#handshaken) return false; // hello 握手完成前不发业务帧
245
+ if (this.#peerRejected) return false; // 对端证明非法 → 拒绝连接,不发业务帧
246
+ this.#seq += 1;
247
+ const aadSid = this.#mode === MODE_HARDENED ? this.#sid : undefined;
248
+ const frame = {
249
+ t: "frame",
250
+ sid: this.#sid,
251
+ seq: this.#seq,
252
+ data: seal(this.#key, "host", this.#seq, message, undefined, aadSid),
253
+ };
254
+ if (urgent) frame.urgent = true;
255
+ try {
256
+ ws.send(JSON.stringify(frame));
257
+ return true;
258
+ } catch (e) {
259
+ this.#opts.log?.("warn", "frame send failed", { error: String(e && e.message) });
260
+ return false;
261
+ }
262
+ }
263
+
264
+ // ---- 内部 ----------------------------------------------------------------
265
+
266
+ #setStatus(s, detail) {
267
+ try {
268
+ this.#opts.onStatus?.(s, detail);
269
+ } catch {
270
+ /* 回调异常不影响链路 */
271
+ }
272
+ }
273
+
274
+ #clearHelloTimer() {
275
+ if (this.#helloTimer !== null) {
276
+ clearTimeout(this.#helloTimer);
277
+ this.#helloTimer = null;
278
+ }
279
+ }
280
+
281
+ #connect() {
282
+ if (this.#closed) return;
283
+ const { relayUrl } = this.#opts;
284
+ this.#setStatus("connecting");
285
+ let ws;
286
+ try {
287
+ ws = new WebSocket(relayUrl);
288
+ } catch (e) {
289
+ this.#opts.log?.("error", "WebSocket construct failed", { relayUrl, error: String(e && e.message) });
290
+ this.#scheduleReconnect();
291
+ return;
292
+ }
293
+ this.#ws = ws;
294
+ this.#lastTrafficAt = Date.now();
295
+
296
+ ws.addEventListener("open", () => {
297
+ if (this.#ws !== ws) return;
298
+ // v1.0.2:每条连接生成新 sid 并重置 seq——旧连接的去重状态不得误伤新连接的 seq。
299
+ this.#sid = randomBytes(4).toString("hex");
300
+ this.#seq = 0;
301
+ // v1.1.3:每条新连接自纪元 +1,**先落盘再使用**(崩溃也不能复用纪元)。
302
+ // 落盘失败 → 拒绝开链路(纪元不可持久化 = 重放窗口,宁可不连)。
303
+ const epoch = this.#nextSelfEpoch();
304
+ if (epoch === null) {
305
+ this.#opts.log?.("error", "session epoch persistence failed — refusing to open an unauthenticated link");
306
+ this.#setStatus("error", "epoch-persist-failed");
307
+ try {
308
+ ws.close();
309
+ } catch {
310
+ /* ignore */
311
+ }
312
+ return;
313
+ }
314
+ this.#selfEpoch = epoch;
315
+ // 新连接 → 对端状态重新协商(钉扎/证明作废;纪元锚点从持久化里读)。
316
+ this.#resetPeerState();
317
+ this.#loadPeerState();
318
+ this.#setStatus("handshaking");
319
+ // 契约 §4:hello 必须是连接后第一条消息,10s 内未发出即断开重试。
320
+ // v1.1.3:带 e/ts/pv/sid,sig 用 v2 证明串(§3.4.1)。
321
+ const ts = Date.now();
322
+ const pv = HELLO_PROTO_VERSION;
323
+ const hello = {
324
+ t: "hello",
325
+ role: "host",
326
+ ch: this.#opts.channel,
327
+ e: this.#selfEpoch,
328
+ ts,
329
+ pv,
330
+ sid: this.#sid,
331
+ sig: helloSig2(this.#key, "host", this.#opts.channel, this.#selfEpoch, ts, pv, this.#sid),
332
+ };
333
+ if (this.#opts.relayToken) hello.token = this.#opts.relayToken;
334
+ try {
335
+ ws.send(JSON.stringify(hello));
336
+ } catch (e) {
337
+ this.#opts.log?.("warn", "hello send failed", { error: String(e && e.message) });
338
+ }
339
+ this.#clearHelloTimer();
340
+ this.#helloTimer = setTimeout(() => {
341
+ // hello 未被接受(无 welcome)→ 判死重连
342
+ if (this.#ws === ws) {
343
+ this.#opts.log?.("warn", "hello timed out (no welcome)");
344
+ try {
345
+ ws.close();
346
+ } catch {
347
+ /* ignore */
348
+ }
349
+ }
350
+ }, HELLO_TIMEOUT_MS);
351
+ });
352
+
353
+ ws.addEventListener("message", (ev) => {
354
+ if (this.#ws !== ws) return;
355
+ this.#lastTrafficAt = Date.now();
356
+ this.#onRaw(String(ev.data));
357
+ });
358
+
359
+ ws.addEventListener("close", () => {
360
+ if (this.#ws !== ws) return;
361
+ this.#ws = null;
362
+ this.#clearHelloTimer();
363
+ this.#handshaken = false;
364
+ this.peers = { host: false, client: false };
365
+ this.#resetPeerState();
366
+ if (this.#closed) return;
367
+ this.#setStatus("disconnected");
368
+ this.#scheduleReconnect();
369
+ });
370
+
371
+ ws.addEventListener("error", () => {
372
+ // error 后必然跟随 close;这里只记日志,重连由 close 驱动。
373
+ this.#opts.log?.("warn", "websocket error event");
374
+ try {
375
+ ws.close();
376
+ } catch {
377
+ /* 已经在关闭 */
378
+ }
379
+ });
380
+ }
381
+
382
+ #scheduleReconnect() {
383
+ if (this.#closed || this.#reconnectTimer !== null) return;
384
+ this.#tries += 1;
385
+ const base = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.min(this.#tries - 1, 6));
386
+ const delay = Math.round(base * (0.5 + Math.random() * 0.5)); // ±50% 抖动
387
+ this.#opts.log?.("info", "reconnect scheduled", { attempt: this.#tries, delayMs: delay });
388
+ this.#reconnectTimer = setTimeout(() => {
389
+ this.#reconnectTimer = null;
390
+ this.#connect();
391
+ }, delay);
392
+ }
393
+
394
+ #tick() {
395
+ if (this.#ws === null) return;
396
+ const idle = Date.now() - this.#lastTrafficAt;
397
+ if (idle > DEAD_TIMEOUT_MS) {
398
+ this.#opts.log?.("warn", "no traffic for 90s; reconnecting");
399
+ try {
400
+ this.#ws.close();
401
+ } catch {
402
+ /* close 事件驱动重连 */
403
+ }
404
+ return;
405
+ }
406
+ this.#sendRelay({ t: "ping" });
407
+ }
408
+
409
+ #sendRelay(obj) {
410
+ const ws = this.#ws;
411
+ if (ws === null || ws.readyState !== 1 /* OPEN */) return;
412
+ try {
413
+ ws.send(JSON.stringify(obj));
414
+ } catch {
415
+ /* close 事件驱动重连 */
416
+ }
417
+ }
418
+
419
+ /** 解析并分发一条中继明文帧。任何解析/解密失败只丢帧,不打断链路。 */
420
+ #onRaw(raw) {
421
+ let f;
422
+ try {
423
+ f = JSON.parse(raw);
424
+ } catch {
425
+ return;
426
+ }
427
+ if (f === null || typeof f !== "object") return;
428
+ switch (f.t) {
429
+ case "welcome": {
430
+ this.#clearHelloTimer();
431
+ this.#tries = 0; // 握手成功,退避归零
432
+ this.#handshaken = true;
433
+ // welcome.peers 是中继的当前快照,只取**对端**那一项;本端项不可靠
434
+ // (中继登记本端连接与计算快照之间存在竞态,可能短暂回报 false)。
435
+ this.peers = this.#opts.role === "host"
436
+ ? { host: false, client: !!(f.peers && f.peers.client) }
437
+ : { host: !!(f.peers && f.peers.host), client: false };
438
+ // v1.1.3:对端证明(中继原样透传 welcome.peer);没有 → 兼容模式。
439
+ if (f.peer) this.#applyPeerProof(f.peer, "welcome");
440
+ else this.#setCompatMode("peer proof absent");
441
+ this.#setStatus("ready");
442
+ if (this.peers.client) this.#notifyPeer(true, "client");
443
+ else if (this.peers.host) this.#notifyPeer(true, "host");
444
+ break;
445
+ }
446
+ case "peer-joined":
447
+ case "peer-left": {
448
+ const role = f.role === "client" ? "client" : "host";
449
+ const joined = f.t === "peer-joined";
450
+ const was = this.peers[role];
451
+ this.peers[role] = joined;
452
+ if (was !== joined) this.#notifyPeer(joined, role);
453
+ if (joined) {
454
+ // v1.1.3:peer-joined 带**新上线方**的证明(§4:中继逐字复制)。
455
+ if (f.peer) this.#applyPeerProof(f.peer, "peer-joined");
456
+ } else {
457
+ // 对端下线 → 钉扎作废(重新上线时会有新的证明与新的 sid)。
458
+ this.#resetPeerState();
459
+ }
460
+ break;
461
+ }
462
+ case "ping":
463
+ this.#sendRelay({ t: "pong" });
464
+ break;
465
+ case "pong":
466
+ break;
467
+ case "error": {
468
+ const code = typeof f.code === "string" ? f.code : "unknown";
469
+ const message = typeof f.message === "string" ? f.message : "";
470
+ this.#opts.log?.("error", "relay error", { code, message });
471
+ if (code === "bad-hello" || code === "channel-full") {
472
+ // 协议级拒绝:重连无意义,交给上层决定(fatal:禁用并提示配置问题)。
473
+ try {
474
+ this.#opts.onFatal?.(code, message);
475
+ } catch {
476
+ /* ignore */
477
+ }
478
+ }
479
+ this.#setStatus("error", code + " " + message);
480
+ break;
481
+ }
482
+ case "frame":
483
+ this.#onFrame(f);
484
+ break;
485
+ default:
486
+ break; // 未知帧类型:前向兼容,忽略
487
+ }
488
+ }
489
+
490
+ #notifyPeer(joined, role) {
491
+ try {
492
+ this.#opts.onPeer?.(joined, role);
493
+ } catch {
494
+ /* 回调异常不影响链路 */
495
+ }
496
+ }
497
+
498
+ // ---- v1.1.3 会话纪元(契约 §3.4.1)--------------------------------------
499
+
500
+ /**
501
+ * 复位**本连接**的对端协商状态(证明/钉扎/模式)。
502
+ * 注意:**不动** #lastPeerEpoch/#lastPeerSid —— 那是跨重启的抗重放锚点。
503
+ */
504
+ #resetPeerState() {
505
+ this.#pinnedPeerSid = "";
506
+ this.#peerPv = 1;
507
+ this.#peerProof = null;
508
+ this.#mode = MODE_COMPAT;
509
+ this.#peerRejected = false;
510
+ this.#pendingFrames = [];
511
+ }
512
+
513
+ /** 从持久化里读「已接受的对端纪元」锚点(回退检测用)。 */
514
+ #loadPeerState() {
515
+ const state = this.#readPeerState();
516
+ this.#lastPeerEpoch = state.peer;
517
+ this.#lastPeerSid = state.peerSid;
518
+ }
519
+
520
+ /** 读持久化的对端纪元锚点(无钩子时用内存态)。 */
521
+ #readPeerState() {
522
+ const fn = this.#opts.epoch?.peerState;
523
+ if (typeof fn === "function") {
524
+ try {
525
+ const raw = fn() ?? {};
526
+ const peer = Number.isInteger(raw.peer) ? raw.peer : 0;
527
+ const peerSid = typeof raw.peerSid === "string" ? raw.peerSid : "";
528
+ return { peer, peerSid };
529
+ } catch (e) {
530
+ this.#opts.log?.("error", "peer epoch state read failed", { error: String(e && e.message) });
531
+ }
532
+ }
533
+ return { peer: this.#lastPeerEpoch, peerSid: this.#lastPeerSid };
534
+ }
535
+
536
+ /** 持久化「已接受的对端纪元 + 钉扎 sid」(跨重启有效)。 */
537
+ #savePeerState(peer, peerSid) {
538
+ const fn = this.#opts.epoch?.savePeerEpoch;
539
+ if (typeof fn !== "function") return;
540
+ try {
541
+ fn(peer, peerSid);
542
+ } catch (e) {
543
+ this.#opts.log?.("error", "peer epoch persistence failed", { error: String(e && e.message) });
544
+ }
545
+ }
546
+
547
+ /**
548
+ * 取下一个自纪元(**先落盘再使用**;契约 §3.4.1)。
549
+ * 落盘失败 → 返回 null(调用方拒绝开链路:纪元不可持久化 = 重放窗口)。
550
+ * @returns {number|null}
551
+ */
552
+ #nextSelfEpoch() {
553
+ const fn = this.#opts.epoch?.nextSelfEpoch;
554
+ if (typeof fn === "function") {
555
+ try {
556
+ const n = fn();
557
+ if (Number.isInteger(n) && n >= 0) return n;
558
+ this.#opts.log?.("error", "session epoch provider returned an invalid value");
559
+ return null;
560
+ } catch (e) {
561
+ this.#opts.log?.("error", "session epoch persistence failed", { error: String(e && e.message) });
562
+ return null;
563
+ }
564
+ }
565
+ // 无持久化钩子(仅测试用):内存里单调递增。
566
+ this.#selfEpoch += 1;
567
+ return this.#selfEpoch;
568
+ }
569
+
570
+ /** 退到兼容模式(对端是旧端 / 没有证明)。 */
571
+ #setCompatMode(reason) {
572
+ this.#mode = MODE_COMPAT;
573
+ this.#peerPv = 1;
574
+ this.#pinnedPeerSid = "";
575
+ this.#opts.log?.("info", "handshake in compatibility mode", { reason });
576
+ }
577
+
578
+ /**
579
+ * 处理中继透传的对端证明(welcome.peer / peer-joined.peer,契约 §3.4.1):
580
+ * ① pv≥2 → 先验签(不过 → 拒绝连接);再查纪元单调性(回退 → 拒绝连接);
581
+ * 通过 → 钉扎 (e, sid) 并持久化 → 切加固模式。
582
+ * ② pv<2(旧端)→ 兼容模式(不钉扎、不记纪元)。
583
+ * @param {unknown} proof 中继原样复制过来的对端 hello 证明
584
+ * @param {string} source 来源(诊断用)
585
+ */
586
+ #applyPeerProof(proof, source) {
587
+ if (proof === null || typeof proof !== "object") {
588
+ this.#setCompatMode("peer proof malformed");
589
+ return;
590
+ }
591
+ const p = /** @type {Record<string, unknown>} */ (proof);
592
+ const role = p.role === "client" ? "client" : "host";
593
+ if (role === this.#opts.role) {
594
+ // 不是对端的证明(对端 role 与自己相同 = 中继串台)→ 忽略。
595
+ this.#opts.log?.("warn", "ignoring peer proof with our own role", { role, source });
596
+ return;
597
+ }
598
+ const pv = Number.isInteger(p.pv) ? /** @type {number} */ (p.pv) : 1;
599
+ if (pv < 2) {
600
+ // 旧端:没有纪元也没有证明 → 兼容模式。
601
+ this.#peerProof = p;
602
+ this.#setCompatMode("peer protocol version < 2");
603
+ return;
604
+ }
605
+ const e = /** @type {number} */ (p.e);
606
+ const ts = /** @type {number} */ (p.ts);
607
+ const sid = /** @type {string} */ (p.sid);
608
+ // ① 验签(恒定时间比较;中继无密钥、只能复制 → 验签通过即可信任)。
609
+ if (!verifyHelloSig2(this.#key, role, this.#opts.channel, e, ts, pv, sid, /** @type {string} */ (p.sig))) {
610
+ this.#opts.log?.("error", "peer handshake proof v2 verification failed — connection rejected", { role, source });
611
+ this.#rejectPeer("peer-proof-invalid");
612
+ return;
613
+ }
614
+ // ② 纪元单调性(回退 = 疑似重放 → 拒绝连接)。
615
+ const verdict = acceptPeerEpoch({ peerEpoch: this.#lastPeerEpoch, peerSid: this.#lastPeerSid }, { e, sid });
616
+ if (!verdict.ok) {
617
+ this.#opts.log?.("error", "peer session epoch rejected — connection rejected", {
618
+ role,
619
+ source,
620
+ reason: verdict.reason,
621
+ });
622
+ this.#rejectPeer(verdict.reason ?? "epoch-rejected");
623
+ return;
624
+ }
625
+ if (!verdict.duplicate) {
626
+ this.#lastPeerEpoch = verdict.peerEpoch;
627
+ this.#lastPeerSid = verdict.peerSid;
628
+ this.#savePeerState(verdict.peerEpoch, verdict.peerSid);
629
+ }
630
+ this.#peerProof = p;
631
+ this.#peerPv = pv;
632
+ this.#pinnedPeerSid = sid;
633
+ this.#mode = negotiateMode(HELLO_PROTO_VERSION, pv);
634
+ this.#opts.log?.("info", "handshake in hardened mode", { role, source, duplicate: verdict.duplicate === true });
635
+ // 模式切换竞态:之前用兼容 AAD 解不开的帧,按加固 AAD 重试一次。
636
+ this.#retryPendingFrames();
637
+ }
638
+
639
+ /** 拒绝连接:断开 socket、不发业务帧(对端证明非法 / 纪元回退)。 */
640
+ #rejectPeer(reason) {
641
+ this.#peerRejected = true;
642
+ this.#handshaken = false;
643
+ this.#pendingFrames = [];
644
+ this.#setStatus("error", reason);
645
+ this.#opts.log?.("error", "rejecting relay connection", { reason });
646
+ const ws = this.#ws;
647
+ if (ws !== null) {
648
+ try {
649
+ ws.close();
650
+ } catch {
651
+ /* 已关闭 */
652
+ }
653
+ }
654
+ }
655
+
656
+ /** 处理转发帧:去重(sid:seq)→ sid 钉扎校验 → 解密(role 用发送方的 role)→ 上交。 */
657
+ #onFrame(f) {
658
+ const seq = f.seq;
659
+ if (typeof seq !== "number" || !Number.isInteger(seq) || seq < 1) return;
660
+ // 契约 §4 v1.0.2:去重键 = sid:seq(缺 sid 按 legacy),按 sid 分桶淘汰。
661
+ const sid = typeof f.sid === "string" && f.sid !== "" ? f.sid : "legacy";
662
+ let bucket = this.#seen.get(sid);
663
+ if (bucket === undefined) {
664
+ bucket = new Set();
665
+ this.#seen.set(sid, bucket);
666
+ if (this.#seen.size > 64) {
667
+ const oldest = this.#seen.keys().next().value;
668
+ if (oldest !== undefined) this.#seen.delete(oldest);
669
+ }
670
+ }
671
+ if (bucket.has(seq)) return; // 同一 sid 的同一 seq 只处理一次
672
+ bucket.add(seq);
673
+ if (bucket.size > SEEN_SET_TRIM * 2) {
674
+ const arr = [...bucket].sort((a, b) => a - b);
675
+ this.#seen.set(sid, new Set(arr.slice(-SEEN_SET_TRIM)));
676
+ }
677
+ if (typeof f.data !== "string") return;
678
+ const from = f.from === "host" ? "host" : "client";
679
+ // v1.1.3 加固模式:**钉扎**对端 sid——收到的帧 sid 不符 → 丢弃(跨会话重放)。
680
+ let aadSid;
681
+ if (this.#mode === MODE_HARDENED) {
682
+ if (this.#pinnedPeerSid === "") {
683
+ this.#opts.log?.("warn", "hardened mode without pinned peer sid; frame dropped", { seq });
684
+ return;
685
+ }
686
+ if (sid !== this.#pinnedPeerSid) {
687
+ this.#opts.log?.("warn", "frame sid mismatch; frame dropped", { seq });
688
+ return;
689
+ }
690
+ aadSid = sid;
691
+ }
692
+ let m;
693
+ try {
694
+ m = open(this.#key, from, seq, f.data, aadSid);
695
+ } catch (e) {
696
+ // 兼容模式下、**还不知道对端 pv** 时解不开 → 可能是对端已经切到加固模式
697
+ // (模式切换竞态:welcome 与 peer-joined 落在不同 socket 上)→ 暂存,
698
+ // 等对端证明到达、模式切到加固后按加固 AAD 重试一次。
699
+ if (this.#mode === MODE_COMPAT && this.#peerProof === null && this.#pendingFrames.length < PENDING_STASH_MAX) {
700
+ this.#pendingFrames.push({ seq, sid, from, data: f.data, at: Date.now() });
701
+ return;
702
+ }
703
+ // 密钥不匹配或帧损坏:丢帧并节流告警(避免刷屏)。
704
+ this.#opts.log?.("warn", "decrypt failed; frame dropped", { seq, error: String(e && e.message) });
705
+ return;
706
+ }
707
+ this.#deliver(m);
708
+ }
709
+
710
+ /**
711
+ * 模式切到加固模式后,把暂存的帧按加固 AAD 重试一次。
712
+ * 只接受**能按加固 AAD 解开且 sid 与钉扎值一致**的帧(安全性等价于加固模式)。
713
+ */
714
+ #retryPendingFrames() {
715
+ if (this.#pendingFrames.length === 0) return;
716
+ const list = this.#pendingFrames;
717
+ this.#pendingFrames = [];
718
+ const now = Date.now();
719
+ for (const item of list) {
720
+ if (now - item.at > PENDING_STASH_TTL_MS) continue; // 过期丢弃
721
+ if (this.#mode !== MODE_HARDENED) continue;
722
+ if (item.sid !== this.#pinnedPeerSid) continue;
723
+ let m;
724
+ try {
725
+ m = open(this.#key, item.from, item.seq, item.data, item.sid);
726
+ } catch {
727
+ continue;
728
+ }
729
+ this.#deliver(m);
730
+ }
731
+ }
732
+
733
+ /** 把解密后的业务消息交给上层(异常不许打断链路)。 */
734
+ #deliver(m) {
735
+ try {
736
+ this.#opts.onMessage(m);
737
+ } catch (e) {
738
+ this.#opts.log?.("error", "message handler threw", { type: m && m.type, error: String(e && e.message) });
739
+ }
740
+ }
741
+ }