@dsh-mobile/mobile-remote 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/FAQ.md +2 -2
  2. package/LICENSE +0 -0
  3. package/README.md +13 -8
  4. package/docs/PRIVACY-POLICY.en.md +26 -18
  5. package/docs/PRIVACY-POLICY.md +26 -18
  6. package/docs/SUPPORT.md +1 -1
  7. package/docs/TERMS-OF-SERVICE.en.md +5 -3
  8. package/docs/TERMS-OF-SERVICE.md +5 -3
  9. package/docs/USER-GUIDE.zh-CN.md +7 -6
  10. package/lib/account-usage-query.js +60 -60
  11. package/lib/account-usage.js +10 -10
  12. package/lib/api-helpers.js +114 -110
  13. package/lib/assistant-prefs.js +119 -76
  14. package/lib/auto-config.js +65 -65
  15. package/lib/backup.js +159 -123
  16. package/lib/break-reminder.js +45 -45
  17. package/lib/client.js +336 -138
  18. package/lib/config.js +234 -218
  19. package/lib/git-read-bundled-provider.js +27 -7
  20. package/lib/git-read-service.js +5 -5
  21. package/lib/host-compat.js +84 -84
  22. package/lib/http-util.js +17 -17
  23. package/lib/index.js +1670 -1511
  24. package/lib/memory/context.js +45 -40
  25. package/lib/memory/decay.js +93 -93
  26. package/lib/memory/extract.js +77 -77
  27. package/lib/memory/routes.js +33 -33
  28. package/lib/memory/store.js +239 -192
  29. package/lib/notify-copy.js +93 -93
  30. package/lib/permission-guide.js +86 -86
  31. package/lib/persona-cards.js +73 -61
  32. package/lib/phone-action-args.js +175 -0
  33. package/lib/phone-actions.js +227 -0
  34. package/lib/phone-announce.js +58 -0
  35. package/lib/proactive-material.js +42 -42
  36. package/lib/proactive.js +122 -119
  37. package/lib/protected-paths.js +205 -45
  38. package/lib/protocol.js +62 -23
  39. package/lib/push.js +29 -29
  40. package/lib/rate-limit.js +16 -16
  41. package/lib/relay/connector.js +334 -81
  42. package/lib/relay/crypto.js +15 -15
  43. package/lib/relay/devices.js +64 -32
  44. package/lib/relay/fingerprint.js +34 -34
  45. package/lib/relay/identity.js +26 -26
  46. package/lib/relay/mux.js +60 -46
  47. package/lib/relay/noise.js +40 -40
  48. package/lib/relay/on-demand.js +36 -31
  49. package/lib/relay/p2p.js +239 -0
  50. package/lib/relay/pairing.js +54 -15
  51. package/lib/relay/phone.js +63 -39
  52. package/lib/relay/serve.js +21 -21
  53. package/lib/relay/signal.js +69 -0
  54. package/lib/relay/ws-server.js +245 -0
  55. package/lib/reminders.js +15 -15
  56. package/lib/rpc-adapter.js +43 -43
  57. package/lib/session-list.js +31 -31
  58. package/lib/session-rotation.js +95 -95
  59. package/lib/session-title-cache.js +35 -35
  60. package/lib/session-title-refresh.js +51 -51
  61. package/lib/timeline.js +140 -140
  62. package/lib/turn-outline.js +104 -104
  63. package/package.json +11 -18
@@ -1,26 +1,45 @@
1
- /**
2
- * 电脑端的中继连接器:常驻**出站**连接到中继(电脑不开任何入站端口),把中继转来的手机会话落地。
3
- *
4
- * 每个中继地址一条 WebSocket(断了按指数退避 + 抖动重连):
5
- * 1. 中继发来挑战 → 用 Ed25519 签名证明房间所有权 → 收到 `ready`;
6
- * 2. 手机来了(`guest{c}`)→ 为它建一个 GuestSession:Noise 响应方握手(消息 1 → 消息 2);
7
- * 3. 握手消息 1 里的静态公钥交给 DeviceStore 核对(已配对 / 带有效一次性配对码)→ 不认识就踢掉,**不回应**;
8
- * 4. 通过后告诉中继 `verified`(解除未确认限额),之后的传输消息解密后交给 MuxSession → serve() 回放给本机 HTTP。
9
- *
10
- * 防重放:握手之后 15 秒内必须收到一条能解密的传输数据,否则踢掉——重放者拿不到会话密钥,发不出来。
11
- *
12
- * 协议卫生(T-12)
13
- * · 接满了(会话数到上限)告诉中继 `kick{why:"busy"}`:手机收到的是 4430「电脑忙,稍后重试」,
14
- * 而不是 4401「这台手机没配对」。
15
- * · 同一台设备的新会话**收到第一条能解密的数据之后**,踢掉它的旧会话(why:"replaced" → 4409):
16
- * 手机切网络 / 切后台再回来时,旧连接往往还挂在中继上。必须等能解密的数据——握手消息 1 可以被重放,
17
- * 不能让重放者把真正在用的会话顶掉。
18
- * · 中继没动静的检测:每次心跳之后 pongMs 内收不到任何消息就认定连接已死、立刻重连
19
- * (以前要等 50 秒)。配合中继侧的宽限期,电脑闪断后手机不必重新连接中继。
20
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+ import { randomBytes } from "node:crypto";
21
39
  import { b64u, concat, ed25519Sign, hex } from "./crypto.js";
22
40
  import { MuxError, MuxSession } from "./mux.js";
23
41
  import { NoiseResponder } from "./noise.js";
42
+ import { SIGNAL_BUDGET, decodeSignal, encodeSignal } from "./signal.js";
24
43
 
25
44
  const enc = new TextEncoder();
26
45
  const dec = new TextDecoder();
@@ -28,12 +47,14 @@ const fromHex = (h) => Uint8Array.from(h.match(/../g) ?? [], (x) => parseInt(x,
28
47
 
29
48
  export const AUTH_CONTEXT = "dsh-relay-host-v1";
30
49
 
50
+ export const HOST_CAPS = Object.freeze(["signal"]);
51
+
31
52
  export class RelayConnector {
32
- /**
33
- * @param {{ identity:object, devices:object, urls:string[], serve:(stream:object, device:object)=>unknown,
34
- * serverName?:string, WebSocketImpl?:Function, log?:(m:string)=>void, now?:()=>number,
35
- * timing?:Partial<typeof RelayConnector.TIMING> }} o
36
- */
53
+
54
+
55
+
56
+
57
+
37
58
  constructor({ identity, devices, urls, serve, serverName = "dsh-mobile-remote", WebSocketImpl = globalThis.WebSocket, log = () => {}, timing = {} }) {
38
59
  if (typeof WebSocketImpl !== "function") throw new Error("需要全局 WebSocket(Node ≥ 22),或传入 WebSocketImpl");
39
60
  this.identity = identity;
@@ -44,15 +65,19 @@ export class RelayConnector {
44
65
  this.log = log;
45
66
  this.timing = { ...RelayConnector.TIMING, ...timing };
46
67
  this.links = urls.map((url) => new RelayLink(this, url.replace(/\/+$/, "")));
68
+
69
+ this.direct = new Set();
47
70
  this.stopped = true;
48
71
  this.unsubscribe = devices.onRevoke((id) => this.dropDevice(id));
72
+
73
+ this.signalHandlers = new Set();
49
74
  }
50
- static TIMING = Object.freeze({ handshakeMs: 15_000, pingMs: 20_000, pongMs: 10_000, firstFrameMs: 15_000, backoffMinMs: 1_000, backoffMaxMs: 30_000, maxSessionsPerLink: 16, kickAckMs: 2_000 });
75
+ static TIMING = Object.freeze({ handshakeMs: 15_000, pingMs: 20_000, pongMs: 10_000, firstFrameMs: 15_000, backoffMinMs: 1_000, backoffMaxMs: 30_000, maxSessionsPerLink: 16, kickAckMs: 2_000, maxDirect: 16, maxDirectPerIp: 4, directHelloMs: 3_000, directOpenMs: 5_000 });
51
76
 
52
77
  start() {
53
78
  if (!this.stopped) return;
54
79
  this.stopped = false;
55
- // stop() 取消了订阅;重新 start() 必须再订阅,否则撤销设备不再踢掉它的在线会话
80
+
56
81
  this.unsubscribe ??= this.devices.onRevoke((id) => this.dropDevice(id));
57
82
  for (const l of this.links) l.connect();
58
83
  }
@@ -62,15 +87,37 @@ export class RelayConnector {
62
87
  this.unsubscribe = null;
63
88
  for (const l of this.links) l.shutdown();
64
89
  }
90
+
91
+
92
+
93
+
94
+
95
+ acceptDirect(ws, { ip = "" } = {}) {
96
+ let fromIp = 0;
97
+ for (const l of this.direct) if (l.ip === ip) fromIp++;
98
+ if (this.direct.size >= this.timing.maxDirect || fromIp >= this.timing.maxDirectPerIp) {
99
+ ws.close(4430, "host busy");
100
+ return null;
101
+ }
102
+
103
+ this.unsubscribe ??= this.devices.onRevoke((id) => this.dropDevice(id));
104
+ const link = new DirectLink(this, ws, ip);
105
+ this.direct.add(link);
106
+ return link;
107
+ }
108
+
109
+ allLinks() {
110
+ return [...this.links, ...this.direct];
111
+ }
65
112
  status() {
66
- return this.links.map((l) => ({ url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: l.sessions.size }));
67
- }
68
- /**
69
- * Resolves once every kick sent to the relay has been acknowledged (`guest-close`) and every
70
- * link that was stopping has closed, or after `timeoutMs`. Returns whether it settled in time.
71
- * (T-62 fix: a revoke must not close the room before the relay has closed the phones with
72
- * 4401, or they see 4503 "PC offline" and keep retrying.)
73
- */
113
+ return this.links.map((l) => ({ url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: [...l.sessions.values()].filter((s) => !s.standby).length, standby: [...l.sessions.values()].filter((s) => s.standby).length }));
114
+ }
115
+
116
+
117
+
118
+
119
+
120
+
74
121
  async settled(timeoutMs = this.timing.kickAckMs + 500) {
75
122
  const deadline = Date.now() + timeoutMs;
76
123
  const busy = () => this.links.some((l) => l.pendingKicks.size > 0 || l.closing !== null);
@@ -80,9 +127,50 @@ export class RelayConnector {
80
127
  }
81
128
  return true;
82
129
  }
83
- /** 设备被撤销:立刻踢掉它所有在线的会话。 */
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+ onSignal(handler) {
139
+ if (typeof handler !== "function") throw new TypeError("handler");
140
+ this.signalHandlers.add(handler);
141
+ return () => this.signalHandlers.delete(handler);
142
+ }
143
+ _emitSignal(event) {
144
+ for (const h of [...this.signalHandlers]) {
145
+ try {
146
+ h(event);
147
+ } catch (err) {
148
+ this.log(`relay: 信令监听者出错:${err?.message ?? err}`);
149
+ }
150
+ }
151
+ }
152
+
153
+ signalSession(deviceId) {
154
+ let found = null;
155
+ for (const l of this.allLinks()) for (const s of l.sessions.values()) if (s.signal && s.state === "open" && s.device?.id === deviceId) found = s;
156
+ return found;
157
+ }
158
+
159
+
160
+
161
+
162
+
163
+ sendSignal(deviceId, msg) {
164
+ return this.signalSession(deviceId)?.sendSignal(msg) ?? false;
165
+ }
166
+
167
+ closeSignal(deviceId) {
168
+ this.signalSession(deviceId)?.endSignal("closed by the computer", true);
169
+ }
170
+
171
+
84
172
  dropDevice(deviceId) {
85
- for (const l of this.links) for (const s of [...l.sessions.values()]) if (s.device?.id === deviceId) s.kick("device revoked");
173
+ for (const l of this.allLinks()) for (const s of [...l.sessions.values()]) if (s.device?.id === deviceId) s.kick("device revoked");
86
174
  }
87
175
  }
88
176
 
@@ -99,9 +187,9 @@ class RelayLink {
99
187
  this.timers = new Set();
100
188
  this.lastHeard = 0;
101
189
  this.heardSincePing = true;
102
- /** Guests we kicked whose close the relay has not confirmed yet (`guest-close`). */
190
+
103
191
  this.pendingKicks = new Set();
104
- /** While stopping: the timer that closes the link if the relay does not confirm the kicks. */
192
+
105
193
  this.closing = null;
106
194
  }
107
195
  #set(state) {
@@ -119,12 +207,13 @@ class RelayLink {
119
207
  }
120
208
 
121
209
  connect() {
122
- if (this.closing !== null) this.#finishShutdown(); // a restart while still stopping: finish first
210
+ if (this.closing !== null) this.#finishShutdown();
123
211
  if (this.o.stopped) return;
124
212
  this.#set("connecting");
125
213
  let ws;
126
214
  try {
127
- ws = new this.o.WS(`${this.url}/v1/host/${this.o.identity.roomId}`);
215
+
216
+ ws = new this.o.WS(`${this.url}/v1/host/${this.o.identity.roomId}?caps=${HOST_CAPS.join(",")}`);
128
217
  } catch (err) {
129
218
  this.lastError = String(err?.message ?? err);
130
219
  return this.#scheduleReconnect();
@@ -137,12 +226,12 @@ class RelayLink {
137
226
  ws.addEventListener("error", () => {
138
227
  if (ws === this.ws) this.lastError = "connection error";
139
228
  });
140
- // HTTP 升级成功不代表房间认证完成;ready 前也必须有截止时间。
229
+
141
230
  this.handshakeTimer = this.after(this.o.timing.handshakeMs, () => {
142
231
  if (ws !== this.ws || this.state !== "connecting") return;
143
232
  this.lastError = "relay handshake timeout";
144
233
  ws.close();
145
- // 不等对端确认关闭:失联的中继可能连 close 也不回。
234
+
146
235
  this.#onClose(ws, {});
147
236
  });
148
237
  }
@@ -178,14 +267,16 @@ class RelayLink {
178
267
  return this.o.log(`relay: 已连上 ${this.url}`);
179
268
  case "guest":
180
269
  if (typeof msg.c !== "string" || !/^[0-9a-f]{16}$/.test(msg.c)) return;
181
- // Stopping (waiting only for kick acknowledgements): take no new phones.
270
+
182
271
  if (this.closing !== null || this.o.stopped) return this.control({ t: "kick", c: msg.c, why: "busy" });
183
- // 接满了:不是「不认识这台手机」,让中继用 4430 关它,手机会稍后重试
272
+
184
273
  if (this.sessions.size >= this.o.timing.maxSessionsPerLink) return this.control({ t: "kick", c: msg.c, why: "busy" });
185
- this.sessions.set(msg.c, new GuestSession(this, msg.c));
274
+
275
+
276
+ this.sessions.set(msg.c, new GuestSession(this, msg.c, { relaySignal: msg.m === "signal" }));
186
277
  return;
187
278
  case "guest-close":
188
- this.sessions.get(msg.c)?.dispose();
279
+ this.sessions.get(msg.c)?.dispose("phone disconnected");
189
280
  this.pendingKicks.delete(msg.c);
190
281
  if (this.closing !== null && this.pendingKicks.size === 0) this.#finishShutdown();
191
282
  return;
@@ -202,17 +293,17 @@ class RelayLink {
202
293
  if (this.o.stopped || this.state !== "online" || !ws) return;
203
294
  this.heardSincePing = false;
204
295
  this.send(JSON.stringify({ t: "ping" }));
205
- // 中继对心跳必有回应(pong)。pongMs 内什么都没收到 = 这条连接已经死了(半开的 TCP、
206
- // 电脑刚从睡眠醒来……):不等系统自己发现,立刻断开重连。
296
+
297
+
207
298
  this.after(Math.min(pongMs, pingMs), () => {
208
299
  if (ws !== this.ws || this.state !== "online" || this.heardSincePing) return;
209
300
  this.lastError = "relay went silent";
210
301
  try {
211
302
  ws.close();
212
303
  } catch {
213
- /* 已断开 */
304
+
214
305
  }
215
- // 不等对端确认关闭:失联的中继可能连 close 也不回。
306
+
216
307
  this.#onClose(ws, {});
217
308
  });
218
309
  this.after(pingMs, tick);
@@ -239,21 +330,21 @@ class RelayLink {
239
330
  const { backoffMinMs, backoffMaxMs } = this.o.timing;
240
331
  const base = Math.min(backoffMaxMs, backoffMinMs * 2 ** Math.min(this.attempt, 10));
241
332
  this.attempt++;
242
- this.after(base / 2 + Math.random() * (base / 2), () => this.connect()); // 抖动:避免大家同时重连
333
+ this.after(base / 2 + Math.random() * (base / 2), () => this.connect());
243
334
  }
244
335
  shutdown() {
245
336
  for (const t of this.timers) clearTimeout(t);
246
337
  this.timers.clear();
247
338
  for (const s of [...this.sessions.values()]) s.dispose();
248
- // T-62 fix: kicks still in flight (a revoked phone) must reach the relay before the room
249
- // closes, or the phone sees 4503 "PC offline" instead of 4401 "revoked". Keep the socket
250
- // until the relay confirms them (guest-close), for at most kickAckMs.
339
+
340
+
341
+
251
342
  if (this.pendingKicks.size > 0 && this.ws && this.ws.readyState === 1) {
252
343
  if (this.closing === null) {
253
344
  this.closing = setTimeout(() => this.#finishShutdown(), this.o.timing.kickAckMs);
254
345
  this.closing.unref?.();
255
346
  }
256
- this.#set("idle"); // no longer serving; the socket only waits for the acknowledgements
347
+ this.#set("idle");
257
348
  return;
258
349
  }
259
350
  this.#finishShutdown();
@@ -267,7 +358,7 @@ class RelayLink {
267
358
  try {
268
359
  ws?.close(1000, "shutdown");
269
360
  } catch {
270
- /* 已断开 */
361
+
271
362
  }
272
363
  this.#set("idle");
273
364
  }
@@ -279,7 +370,7 @@ class RelayLink {
279
370
  return true;
280
371
  }
281
372
  } catch {
282
- /* 连接正在断开 */
373
+
283
374
  }
284
375
  return false;
285
376
  }
@@ -288,10 +379,12 @@ class RelayLink {
288
379
  }
289
380
  }
290
381
 
291
- /** 一台手机在一条中继连接上的会话。 */
382
+
292
383
  class GuestSession {
293
- constructor(link, connId) {
384
+ constructor(link, connId, { relaySignal = false } = {}) {
294
385
  this.link = link;
386
+
387
+ this.relaySignal = relaySignal;
295
388
  this.connId = connId;
296
389
  this.idBytes = fromHex(connId);
297
390
  this.state = "handshake";
@@ -300,6 +393,14 @@ class GuestSession {
300
393
  this.mux = null;
301
394
  this.cipherOut = null;
302
395
  this.cipherIn = null;
396
+
397
+ this.signal = false;
398
+ this.signalOpen = false;
399
+ this.signalIdOut = 0;
400
+
401
+ this.standby = false;
402
+
403
+ this.framesOut = 0;
303
404
  this.timer = link.after(link.o.timing.firstFrameMs, () => {
304
405
  if (this.state !== "open") this.kick("handshake timeout");
305
406
  });
@@ -309,11 +410,15 @@ class GuestSession {
309
410
  try {
310
411
  if (this.state === "handshake") return this.#handshake(bytes);
311
412
  if (this.state === "closed") return;
312
- const plain = this.cipherIn.decrypt(bytes); // 认证失败抛错
413
+ const plain = this.cipherIn.decrypt(bytes);
313
414
  if (this.state === "await-first") {
314
415
  this.state = "open";
315
416
  clearTimeout(this.timer);
316
417
  this.#replaceOlder();
418
+ if (this.signal) {
419
+ this.signalOpen = true;
420
+ this.link.o._emitSignal({ type: "open", ...this.#signalWho() });
421
+ }
317
422
  }
318
423
  this.mux.receive(plain);
319
424
  } catch (err) {
@@ -331,55 +436,203 @@ class GuestSession {
331
436
  return this.kick("bad handshake payload");
332
437
  }
333
438
  if (info?.v !== 1) return this.kick("unsupported version");
334
- const result = devices.authorize(rs, info);
335
- if (!result) return this.kick("unauthorized device"); // 不回应:别给陌生人任何东西
439
+
440
+
441
+
442
+ if (this.relaySignal && info.mode !== "signal") {
443
+ this.link.o.log(`relay: 访客 ${this.connId.slice(0, 6)}… 由中继作为信令连接放入,握手却不是信令:拒绝`);
444
+ return this.kick("signal connection without signal handshake");
445
+ }
446
+ this.signal = this.relaySignal || info.mode === "signal";
447
+ this.standby = !this.signal && info.mode === "standby";
448
+
449
+ const result = devices.authorize(rs, this.signal || this.standby ? { ...info, otp: undefined } : info);
450
+ if (!result) return this.kick("unauthorized device");
336
451
  this.device = result.device;
337
452
  const reply = this.noise.writeMessage2(enc.encode(JSON.stringify({ v: 1, ok: true, server: serverName, device: { id: result.device.id, name: result.device.name }, newlyPaired: result.newlyPaired })));
338
453
  this.cipherOut = reply.send;
339
454
  this.cipherIn = reply.recv;
340
- this.mux = new MuxSession({
341
- role: "server",
342
- send: (frame) => this.#sendPlain(frame),
343
- onRequest: (stream) => this.link.o.serve(stream, this.device),
344
- });
455
+ this.mux = this.signal
456
+ ?
457
+ new MuxSession({ role: "server", send: (frame) => this.#sendPlain(frame), onSignal: (bytes) => this.#onSignal(bytes) })
458
+ : new MuxSession({
459
+ role: "server",
460
+ send: (frame) => this.#sendPlain(frame),
461
+ onRequest: (stream) => {
462
+ this.#promote();
463
+ return this.link.o.serve(stream, this.device);
464
+ },
465
+ });
345
466
  this.link.send(concat(this.idBytes, reply.msg));
467
+ this.framesOut++;
346
468
  this.link.control({ t: "verified", c: this.connId });
347
469
  this.state = "await-first";
348
- this.link.o.log(`relay: 设备「${this.device.name}」${result.newlyPaired ? "完成配对" : "已连接"}`);
470
+ this.link.o.log(`relay: 设备「${this.device.name}」${this.signal ? "打开信令连接" : this.standby ? "打开待命连接" : result.newlyPaired ? "完成配对" : "已连接"}`);
349
471
  }
350
472
  #sendPlain(frame) {
351
473
  if (this.state === "closed") return;
474
+ this.framesOut++;
352
475
  this.link.send(concat(this.idBytes, this.cipherOut.encrypt(frame)));
353
476
  }
354
- /**
355
- * 这台设备已经用新连接证明了自己(发来了能解密的数据):它的旧会话让位。
356
- * 一台手机同一时间只该有一条会话;旧的那条多半是切网络 / 切后台留下的死连接。
357
- */
477
+ #signalWho() {
478
+ const device = { id: this.device?.id, name: this.device?.name };
479
+ const peer = this.peer ??= { deviceId: device.id, send: (msg) => this.sendSignal(msg), close: () => this.endSignal("closed by the computer", true) };
480
+ return { deviceId: device.id, device, peer };
481
+ }
482
+
483
+ #onSignal(bytes) {
484
+ const msg = decodeSignal(bytes);
485
+ this.link.o._emitSignal({ type: "message", ...this.#signalWho(), msg });
486
+ if (msg.k === "bye") this.endSignal("bye");
487
+ }
488
+
489
+ sendSignal(msg) {
490
+ if (!this.signal || this.state !== "open" || !msg || typeof msg !== "object") return false;
491
+ const full = { ...msg, t: "sig", id: Number.isInteger(msg.id) ? msg.id : this.signalIdOut };
492
+ const payload = encodeSignal(full);
493
+ if (this.framesOut >= SIGNAL_BUDGET.frames) return false;
494
+ this.signalIdOut = Math.max(this.signalIdOut, full.id + 1);
495
+ this.mux.sendSignal(payload);
496
+ if (full.k === "bye") this.endSignal("bye");
497
+ return true;
498
+ }
499
+
500
+
501
+
502
+
503
+ endSignal(reason, sayBye = false) {
504
+ if (!this.signal || this.state === "closed") return;
505
+ if (sayBye && this.state === "open") {
506
+ try {
507
+ this.mux.sendSignal(encodeSignal({ t: "sig", k: "bye", id: this.signalIdOut++ }));
508
+ } catch {
509
+
510
+ }
511
+ }
512
+ this.dispose(reason);
513
+ }
514
+
515
+
516
+
517
+
358
518
  #replaceOlder() {
359
519
  const id = this.device?.id;
360
520
  if (!id) return;
361
- for (const link of this.link.o.links) {
521
+
522
+ const standby = this.standby;
523
+ for (const link of this.link.o.allLinks()) {
362
524
  for (const other of [...link.sessions.values()]) {
363
- if (other !== this && other.device?.id === id) other.kick("replaced by a newer connection from the same device", "replaced");
525
+
526
+ if (other !== this && other.device?.id === id && other.signal === this.signal && other.standby === standby) other.kick("replaced by a newer connection from the same device", "replaced");
364
527
  }
365
528
  }
366
529
  }
367
530
 
368
- /**
369
- * 拒绝并断开这个访客(同时让中继关掉它)。
370
- * `why` 告诉中继用哪个关闭码:缺省 4401(不认识 / 不合规);"replaced" → 4409;"busy" → 4430。
371
- */
531
+
532
+ #promote() {
533
+ if (!this.standby) return;
534
+ this.standby = false;
535
+ this.link.o.log(`relay: 设备「${this.device.name}」的待命连接开始承载请求`);
536
+ this.#replaceOlder();
537
+ }
538
+
539
+
540
+
541
+
542
+
372
543
  kick(reason = "kicked", why = "") {
373
544
  if (this.state === "closed") return;
374
545
  this.link.o.log(`relay: 断开访客 ${this.connId.slice(0, 6)}…(${reason})`);
375
546
  if (this.link.control(why ? { t: "kick", c: this.connId, why } : { t: "kick", c: this.connId })) this.link.pendingKicks.add(this.connId);
376
- this.dispose();
547
+ this.dispose(reason);
377
548
  }
378
- dispose() {
549
+ dispose(reason = "closed") {
379
550
  if (this.state === "closed") return;
380
551
  this.state = "closed";
381
552
  clearTimeout(this.timer);
382
553
  this.mux?.close("session closed");
383
554
  this.link.sessions.delete(this.connId);
555
+ if (this.signalOpen) {
556
+ this.signalOpen = false;
557
+ this.link.o._emitSignal({ type: "close", ...this.#signalWho(), reason: String(reason) });
558
+ }
559
+ }
560
+ }
561
+
562
+
563
+
564
+
565
+
566
+
567
+
568
+
569
+
570
+ class DirectLink {
571
+ constructor(owner, ws, ip = "") {
572
+ this.o = owner;
573
+ this.ws = ws;
574
+ this.ip = ip;
575
+ this.url = "lan";
576
+ this.sessions = new Map();
577
+ this.timers = new Set();
578
+ this.closed = false;
579
+ const connId = hex(randomBytes(8));
580
+ this.session = new GuestSession(this, connId);
581
+ this.sessions.set(connId, this.session);
582
+ ws.on("message", (data) => this.#onMessage(data));
583
+ ws.on("close", () => this.dispose());
584
+ this.control({ t: "hello", host: true });
585
+
586
+ const { directHelloMs, directOpenMs } = owner.timing;
587
+ this.after(directHelloMs, () => {
588
+ if (this.session.state === "handshake") this.ws.close(4408, "hello timeout");
589
+ });
590
+ this.after(directOpenMs, () => {
591
+ if (this.session.state !== "open" && this.session.state !== "closed") this.ws.close(4408, "handshake timeout");
592
+ });
593
+ }
594
+ after(ms, fn) {
595
+ const t = setTimeout(() => {
596
+ this.timers.delete(t);
597
+ fn();
598
+ }, ms);
599
+ t.unref?.();
600
+ this.timers.add(t);
601
+ return t;
602
+ }
603
+ #onMessage(data) {
604
+ if (this.closed) return;
605
+ if (typeof data !== "string") return void this.session.onFrame(data);
606
+ let msg = null;
607
+ try {
608
+ msg = data.length <= 256 ? JSON.parse(data) : null;
609
+ } catch {
610
+
611
+ }
612
+ if (msg?.t === "ping") return void this.ws.send(JSON.stringify({ t: "pong" }));
613
+ this.ws.close(4400, "unknown control");
614
+ }
615
+ send(bytes) {
616
+ if (this.closed || typeof bytes === "string" || bytes.length < 8) return false;
617
+ return this.ws.send(bytes.subarray(8));
618
+ }
619
+ control(obj) {
620
+ if (this.closed) return false;
621
+ if (obj?.t === "kick") {
622
+ const code = obj.why === "busy" ? 4430 : obj.why === "replaced" ? 4409 : 4401;
623
+ this.ws.close(code, obj.why || "kicked");
624
+ return true;
625
+ }
626
+ if (obj?.t === "verified") return true;
627
+ return this.ws.send(JSON.stringify(obj));
628
+ }
629
+ dispose() {
630
+ if (this.closed) return;
631
+ this.closed = true;
632
+ for (const t of this.timers) clearTimeout(t);
633
+ this.timers.clear();
634
+ this.session.dispose();
635
+ this.o.direct.delete(this);
636
+ if (this.ws.readyState === 1) this.ws.close(1001, "going away");
384
637
  }
385
638
  }
@@ -1,9 +1,9 @@
1
- /**
2
- * 中继用到的密码学原语,**只用 Node 内置的 crypto**(零依赖,插件包保持小)。
3
- * 这里不实现任何原语,只是把 Node 的 KeyObject 接口包成「裸 32 字节」的形态,供 Noise 与配对使用。
4
- *
5
- * 原语:X25519(DH)、Ed25519(中继侧证明房间所有权)、ChaCha20-Poly1305(AEAD)、SHA-256 / HMAC-SHA256。
6
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
7
  import {
8
8
  createCipheriv, createDecipheriv, createHash, createHmac, createPrivateKey, createPublicKey,
9
9
  diffieHellman, generateKeyPairSync, randomBytes, sign as edSign, verify as edVerify, timingSafeEqual,
@@ -29,10 +29,10 @@ export const hex = (bytes) => Buffer.from(bytes).toString("hex");
29
29
  export const concat = (...parts) => u8(Buffer.concat(parts.map((p) => Buffer.from(p))));
30
30
  export const randomBytesU8 = (n) => u8(randomBytes(n));
31
31
 
32
- /** 常量时间比较(长度不同直接 false)。 */
32
+
33
33
  export const equalBytes = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
34
34
 
35
- // ── X25519 ──────────────────────────────────────────────────────────────────
35
+
36
36
  const x25519Priv = (raw) => {
37
37
  if (raw.length !== 32) throw new Error("x25519 private key must be 32 bytes");
38
38
  return createPrivateKey({ key: Buffer.concat([X25519_PKCS8, Buffer.from(raw)]), format: "der", type: "pkcs8" });
@@ -41,7 +41,7 @@ const x25519Pub = (raw) => {
41
41
  if (raw.length !== 32) throw new Error("x25519 public key must be 32 bytes");
42
42
  return createPublicKey({ key: Buffer.concat([X25519_SPKI, Buffer.from(raw)]), format: "der", type: "spki" });
43
43
  };
44
- /** 由私钥算公钥。 */
44
+
45
45
  export const x25519PublicOf = (priv) => b64uToU8(createPublicKey(x25519Priv(priv)).export({ format: "jwk" }).x);
46
46
  const b64uToU8 = (s) => new Uint8Array(Buffer.from(s, "base64url"));
47
47
 
@@ -50,12 +50,12 @@ export function x25519Generate() {
50
50
  const jwk = privateKey.export({ format: "jwk" });
51
51
  return { priv: b64uToU8(jwk.d), pub: b64uToU8(jwk.x) };
52
52
  }
53
- /** 32 字节共享密钥;对端是低阶点时 OpenSSL 会抛错,调用方当握手失败处理。 */
53
+
54
54
  export function x25519Dh(priv, pub) {
55
55
  return u8(diffieHellman({ privateKey: x25519Priv(priv), publicKey: x25519Pub(pub) }));
56
56
  }
57
57
 
58
- // ── Ed25519(只用于中继侧证明「这个房间是我的」)──────────────────────────────────
58
+
59
59
  export function ed25519Generate() {
60
60
  const { privateKey } = generateKeyPairSync("ed25519");
61
61
  const jwk = privateKey.export({ format: "jwk" });
@@ -74,7 +74,7 @@ export function ed25519Verify(pub, message, signature) {
74
74
  }
75
75
  }
76
76
 
77
- // ── 哈希 / HMAC / HKDF(Noise 规范 §4.3 的 HKDF,基于 HMAC)──────────────────────
77
+
78
78
  export const sha256 = (...parts) => {
79
79
  const h = createHash("sha256");
80
80
  for (const p of parts) h.update(p);
@@ -85,7 +85,7 @@ const hmac = (key, ...parts) => {
85
85
  for (const p of parts) h.update(p);
86
86
  return u8(h.digest());
87
87
  };
88
- /** Noise HKDF:返回 n(2 或 3)个 32 字节输出。 */
88
+
89
89
  export function hkdf(chainingKey, inputKeyMaterial, n) {
90
90
  const tempKey = hmac(chainingKey, inputKeyMaterial);
91
91
  const out1 = hmac(tempKey, Uint8Array.of(1));
@@ -94,7 +94,7 @@ export function hkdf(chainingKey, inputKeyMaterial, n) {
94
94
  return [out1, out2, hmac(tempKey, out2, Uint8Array.of(3))];
95
95
  }
96
96
 
97
- // ── ChaCha20-Poly1305(Noise 的 nonce:4 字节 0 + 8 字节小端计数)──────────────────
97
+
98
98
  const nonceFor = (counter) => {
99
99
  const n = Buffer.alloc(12);
100
100
  n.writeBigUInt64LE(BigInt(counter), 4);
@@ -105,7 +105,7 @@ export function aeadEncrypt(key, counter, ad, plaintext) {
105
105
  c.setAAD(Buffer.from(ad), { plaintextLength: plaintext.length });
106
106
  return concat(c.update(Buffer.from(plaintext)), c.final(), c.getAuthTag());
107
107
  }
108
- /** 认证失败抛错(不泄漏原因)。 */
108
+
109
109
  export function aeadDecrypt(key, counter, ad, ciphertext) {
110
110
  if (ciphertext.length < 16) throw new Error("ciphertext too short");
111
111
  const body = ciphertext.subarray(0, ciphertext.length - 16);