@dsh-mobile/mobile-remote 3.3.1 → 3.4.1-beta.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 (58) hide show
  1. package/README.md +9 -5
  2. package/docs/PRIVACY-POLICY.en.md +10 -3
  3. package/docs/PRIVACY-POLICY.md +10 -3
  4. package/docs/USER-GUIDE.zh-CN.md +1 -0
  5. package/lib/account-usage-query.js +60 -60
  6. package/lib/account-usage.js +10 -10
  7. package/lib/api-helpers.js +109 -109
  8. package/lib/assistant-prefs.js +82 -59
  9. package/lib/auto-config.js +65 -65
  10. package/lib/backup.js +117 -117
  11. package/lib/break-reminder.js +45 -45
  12. package/lib/client.js +93 -93
  13. package/lib/config.js +234 -218
  14. package/lib/git-read-bundled-provider.js +12 -12
  15. package/lib/git-read-service.js +5 -5
  16. package/lib/host-compat.js +84 -84
  17. package/lib/http-util.js +17 -17
  18. package/lib/index.js +1534 -1534
  19. package/lib/memory/context.js +44 -44
  20. package/lib/memory/decay.js +93 -93
  21. package/lib/memory/extract.js +77 -77
  22. package/lib/memory/routes.js +33 -33
  23. package/lib/memory/store.js +196 -196
  24. package/lib/notify-copy.js +93 -93
  25. package/lib/permission-guide.js +86 -86
  26. package/lib/persona-cards.js +73 -65
  27. package/lib/phone-action-args.js +175 -0
  28. package/lib/phone-actions.js +227 -0
  29. package/lib/phone-announce.js +58 -0
  30. package/lib/proactive-material.js +42 -42
  31. package/lib/proactive.js +121 -121
  32. package/lib/protected-paths.js +79 -79
  33. package/lib/protocol.js +61 -26
  34. package/lib/push.js +29 -29
  35. package/lib/rate-limit.js +16 -16
  36. package/lib/relay/connector.js +246 -102
  37. package/lib/relay/crypto.js +15 -15
  38. package/lib/relay/devices.js +36 -36
  39. package/lib/relay/fingerprint.js +34 -34
  40. package/lib/relay/identity.js +26 -26
  41. package/lib/relay/mux.js +60 -46
  42. package/lib/relay/noise.js +40 -40
  43. package/lib/relay/on-demand.js +33 -33
  44. package/lib/relay/p2p.js +239 -0
  45. package/lib/relay/pairing.js +24 -24
  46. package/lib/relay/phone.js +62 -40
  47. package/lib/relay/serve.js +21 -21
  48. package/lib/relay/signal.js +69 -0
  49. package/lib/relay/ws-server.js +32 -32
  50. package/lib/reminders.js +15 -15
  51. package/lib/rpc-adapter.js +43 -43
  52. package/lib/session-list.js +31 -31
  53. package/lib/session-rotation.js +95 -95
  54. package/lib/session-title-cache.js +35 -35
  55. package/lib/session-title-refresh.js +51 -51
  56. package/lib/timeline.js +140 -140
  57. package/lib/turn-outline.js +104 -104
  58. package/package.json +3 -13
@@ -1,33 +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
- *
21
- * 局域网加密通道(T-25):手机也可以不经中继,直接连电脑 LAN 桥端口上的 `/v1/lan`
22
- * (见 lib/index.js 的 upgrade 处理与 ./ws-server.js)。路径里不带房间号:局域网上是明文 WebSocket,
23
- * 房间号是这台电脑的长期标识,不该在咖啡馆的 Wi-Fi 里被同一个 IP 上的陌生主机看到。那条 WebSocket 由 [acceptDirect] 接过来,
24
- * 跑的是同一个 GuestSession:同样的 Noise IK、同样的设备核对、同样的多路复用与回放——
25
- * 访问口令从头到尾不出现在局域网上。
26
- */
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
+
27
38
  import { randomBytes } from "node:crypto";
28
39
  import { b64u, concat, ed25519Sign, hex } from "./crypto.js";
29
40
  import { MuxError, MuxSession } from "./mux.js";
30
41
  import { NoiseResponder } from "./noise.js";
42
+ import { SIGNAL_BUDGET, decodeSignal, encodeSignal } from "./signal.js";
31
43
 
32
44
  const enc = new TextEncoder();
33
45
  const dec = new TextDecoder();
@@ -35,12 +47,14 @@ const fromHex = (h) => Uint8Array.from(h.match(/../g) ?? [], (x) => parseInt(x,
35
47
 
36
48
  export const AUTH_CONTEXT = "dsh-relay-host-v1";
37
49
 
50
+ export const HOST_CAPS = Object.freeze(["signal"]);
51
+
38
52
  export class RelayConnector {
39
- /**
40
- * @param {{ identity:object, devices:object, urls:string[], serve:(stream:object, device:object)=>unknown,
41
- * serverName?:string, WebSocketImpl?:Function, log?:(m:string)=>void, now?:()=>number,
42
- * timing?:Partial<typeof RelayConnector.TIMING> }} o
43
- */
53
+
54
+
55
+
56
+
57
+
44
58
  constructor({ identity, devices, urls, serve, serverName = "dsh-mobile-remote", WebSocketImpl = globalThis.WebSocket, log = () => {}, timing = {} }) {
45
59
  if (typeof WebSocketImpl !== "function") throw new Error("需要全局 WebSocket(Node ≥ 22),或传入 WebSocketImpl");
46
60
  this.identity = identity;
@@ -51,17 +65,19 @@ export class RelayConnector {
51
65
  this.log = log;
52
66
  this.timing = { ...RelayConnector.TIMING, ...timing };
53
67
  this.links = urls.map((url) => new RelayLink(this, url.replace(/\/+$/, "")));
54
- /** 局域网直连的会话(每条一个 DirectLink)。与中继无关:中继停着也照常接。 */
68
+
55
69
  this.direct = new Set();
56
70
  this.stopped = true;
57
71
  this.unsubscribe = devices.onRevoke((id) => this.dropDevice(id));
72
+
73
+ this.signalHandlers = new Set();
58
74
  }
59
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 });
60
76
 
61
77
  start() {
62
78
  if (!this.stopped) return;
63
79
  this.stopped = false;
64
- // stop() 取消了订阅;重新 start() 必须再订阅,否则撤销设备不再踢掉它的在线会话
80
+
65
81
  this.unsubscribe ??= this.devices.onRevoke((id) => this.dropDevice(id));
66
82
  for (const l of this.links) l.connect();
67
83
  }
@@ -71,11 +87,11 @@ export class RelayConnector {
71
87
  this.unsubscribe = null;
72
88
  for (const l of this.links) l.shutdown();
73
89
  }
74
- /**
75
- * 接过一条局域网直连的 WebSocket(已完成 HTTP 升级,见 ./ws-server.js)。
76
- * 接满了(总数 maxDirect,或同一个来源地址 maxDirectPerIp)回 4430,和中继上「电脑忙」一样,手机会稍后重试。
77
- * 每个来源地址的上限是为了让局域网里的别的设备占不满全部名额,把真正的手机挤到收费的中继上去。
78
- */
90
+
91
+
92
+
93
+
94
+
79
95
  acceptDirect(ws, { ip = "" } = {}) {
80
96
  let fromIp = 0;
81
97
  for (const l of this.direct) if (l.ip === ip) fromIp++;
@@ -83,25 +99,25 @@ export class RelayConnector {
83
99
  ws.close(4430, "host busy");
84
100
  return null;
85
101
  }
86
- // 撤销设备要能踢掉直连会话:中继停着(stop 取消了订阅)时也一样
102
+
87
103
  this.unsubscribe ??= this.devices.onRevoke((id) => this.dropDevice(id));
88
104
  const link = new DirectLink(this, ws, ip);
89
105
  this.direct.add(link);
90
106
  return link;
91
107
  }
92
- /** 所有在线会话所在的连接:各条中继 + 各条局域网直连。 */
108
+
93
109
  allLinks() {
94
110
  return [...this.links, ...this.direct];
95
111
  }
96
112
  status() {
97
- return this.links.map((l) => ({ url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: l.sessions.size }));
98
- }
99
- /**
100
- * Resolves once every kick sent to the relay has been acknowledged (`guest-close`) and every
101
- * link that was stopping has closed, or after `timeoutMs`. Returns whether it settled in time.
102
- * (T-62 fix: a revoke must not close the room before the relay has closed the phones with
103
- * 4401, or they see 4503 "PC offline" and keep retrying.)
104
- */
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
+
105
121
  async settled(timeoutMs = this.timing.kickAckMs + 500) {
106
122
  const deadline = Date.now() + timeoutMs;
107
123
  const busy = () => this.links.some((l) => l.pendingKicks.size > 0 || l.closing !== null);
@@ -111,7 +127,48 @@ export class RelayConnector {
111
127
  }
112
128
  return true;
113
129
  }
114
- /** 设备被撤销:立刻踢掉它所有在线的会话(中继上的与局域网直连的)。 */
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
+
115
172
  dropDevice(deviceId) {
116
173
  for (const l of this.allLinks()) for (const s of [...l.sessions.values()]) if (s.device?.id === deviceId) s.kick("device revoked");
117
174
  }
@@ -130,9 +187,9 @@ class RelayLink {
130
187
  this.timers = new Set();
131
188
  this.lastHeard = 0;
132
189
  this.heardSincePing = true;
133
- /** Guests we kicked whose close the relay has not confirmed yet (`guest-close`). */
190
+
134
191
  this.pendingKicks = new Set();
135
- /** While stopping: the timer that closes the link if the relay does not confirm the kicks. */
192
+
136
193
  this.closing = null;
137
194
  }
138
195
  #set(state) {
@@ -150,12 +207,13 @@ class RelayLink {
150
207
  }
151
208
 
152
209
  connect() {
153
- if (this.closing !== null) this.#finishShutdown(); // a restart while still stopping: finish first
210
+ if (this.closing !== null) this.#finishShutdown();
154
211
  if (this.o.stopped) return;
155
212
  this.#set("connecting");
156
213
  let ws;
157
214
  try {
158
- 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(",")}`);
159
217
  } catch (err) {
160
218
  this.lastError = String(err?.message ?? err);
161
219
  return this.#scheduleReconnect();
@@ -168,12 +226,12 @@ class RelayLink {
168
226
  ws.addEventListener("error", () => {
169
227
  if (ws === this.ws) this.lastError = "connection error";
170
228
  });
171
- // HTTP 升级成功不代表房间认证完成;ready 前也必须有截止时间。
229
+
172
230
  this.handshakeTimer = this.after(this.o.timing.handshakeMs, () => {
173
231
  if (ws !== this.ws || this.state !== "connecting") return;
174
232
  this.lastError = "relay handshake timeout";
175
233
  ws.close();
176
- // 不等对端确认关闭:失联的中继可能连 close 也不回。
234
+
177
235
  this.#onClose(ws, {});
178
236
  });
179
237
  }
@@ -209,14 +267,16 @@ class RelayLink {
209
267
  return this.o.log(`relay: 已连上 ${this.url}`);
210
268
  case "guest":
211
269
  if (typeof msg.c !== "string" || !/^[0-9a-f]{16}$/.test(msg.c)) return;
212
- // Stopping (waiting only for kick acknowledgements): take no new phones.
270
+
213
271
  if (this.closing !== null || this.o.stopped) return this.control({ t: "kick", c: msg.c, why: "busy" });
214
- // 接满了:不是「不认识这台手机」,让中继用 4430 关它,手机会稍后重试
272
+
215
273
  if (this.sessions.size >= this.o.timing.maxSessionsPerLink) return this.control({ t: "kick", c: msg.c, why: "busy" });
216
- 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" }));
217
277
  return;
218
278
  case "guest-close":
219
- this.sessions.get(msg.c)?.dispose();
279
+ this.sessions.get(msg.c)?.dispose("phone disconnected");
220
280
  this.pendingKicks.delete(msg.c);
221
281
  if (this.closing !== null && this.pendingKicks.size === 0) this.#finishShutdown();
222
282
  return;
@@ -233,17 +293,17 @@ class RelayLink {
233
293
  if (this.o.stopped || this.state !== "online" || !ws) return;
234
294
  this.heardSincePing = false;
235
295
  this.send(JSON.stringify({ t: "ping" }));
236
- // 中继对心跳必有回应(pong)。pongMs 内什么都没收到 = 这条连接已经死了(半开的 TCP、
237
- // 电脑刚从睡眠醒来……):不等系统自己发现,立刻断开重连。
296
+
297
+
238
298
  this.after(Math.min(pongMs, pingMs), () => {
239
299
  if (ws !== this.ws || this.state !== "online" || this.heardSincePing) return;
240
300
  this.lastError = "relay went silent";
241
301
  try {
242
302
  ws.close();
243
303
  } catch {
244
- /* 已断开 */
304
+
245
305
  }
246
- // 不等对端确认关闭:失联的中继可能连 close 也不回。
306
+
247
307
  this.#onClose(ws, {});
248
308
  });
249
309
  this.after(pingMs, tick);
@@ -270,21 +330,21 @@ class RelayLink {
270
330
  const { backoffMinMs, backoffMaxMs } = this.o.timing;
271
331
  const base = Math.min(backoffMaxMs, backoffMinMs * 2 ** Math.min(this.attempt, 10));
272
332
  this.attempt++;
273
- this.after(base / 2 + Math.random() * (base / 2), () => this.connect()); // 抖动:避免大家同时重连
333
+ this.after(base / 2 + Math.random() * (base / 2), () => this.connect());
274
334
  }
275
335
  shutdown() {
276
336
  for (const t of this.timers) clearTimeout(t);
277
337
  this.timers.clear();
278
338
  for (const s of [...this.sessions.values()]) s.dispose();
279
- // T-62 fix: kicks still in flight (a revoked phone) must reach the relay before the room
280
- // closes, or the phone sees 4503 "PC offline" instead of 4401 "revoked". Keep the socket
281
- // until the relay confirms them (guest-close), for at most kickAckMs.
339
+
340
+
341
+
282
342
  if (this.pendingKicks.size > 0 && this.ws && this.ws.readyState === 1) {
283
343
  if (this.closing === null) {
284
344
  this.closing = setTimeout(() => this.#finishShutdown(), this.o.timing.kickAckMs);
285
345
  this.closing.unref?.();
286
346
  }
287
- this.#set("idle"); // no longer serving; the socket only waits for the acknowledgements
347
+ this.#set("idle");
288
348
  return;
289
349
  }
290
350
  this.#finishShutdown();
@@ -298,7 +358,7 @@ class RelayLink {
298
358
  try {
299
359
  ws?.close(1000, "shutdown");
300
360
  } catch {
301
- /* 已断开 */
361
+
302
362
  }
303
363
  this.#set("idle");
304
364
  }
@@ -310,7 +370,7 @@ class RelayLink {
310
370
  return true;
311
371
  }
312
372
  } catch {
313
- /* 连接正在断开 */
373
+
314
374
  }
315
375
  return false;
316
376
  }
@@ -319,10 +379,12 @@ class RelayLink {
319
379
  }
320
380
  }
321
381
 
322
- /** 一台手机在一条中继连接上的会话。 */
382
+
323
383
  class GuestSession {
324
- constructor(link, connId) {
384
+ constructor(link, connId, { relaySignal = false } = {}) {
325
385
  this.link = link;
386
+
387
+ this.relaySignal = relaySignal;
326
388
  this.connId = connId;
327
389
  this.idBytes = fromHex(connId);
328
390
  this.state = "handshake";
@@ -331,6 +393,14 @@ class GuestSession {
331
393
  this.mux = null;
332
394
  this.cipherOut = null;
333
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;
334
404
  this.timer = link.after(link.o.timing.firstFrameMs, () => {
335
405
  if (this.state !== "open") this.kick("handshake timeout");
336
406
  });
@@ -340,11 +410,15 @@ class GuestSession {
340
410
  try {
341
411
  if (this.state === "handshake") return this.#handshake(bytes);
342
412
  if (this.state === "closed") return;
343
- const plain = this.cipherIn.decrypt(bytes); // 认证失败抛错
413
+ const plain = this.cipherIn.decrypt(bytes);
344
414
  if (this.state === "await-first") {
345
415
  this.state = "open";
346
416
  clearTimeout(this.timer);
347
417
  this.#replaceOlder();
418
+ if (this.signal) {
419
+ this.signalOpen = true;
420
+ this.link.o._emitSignal({ type: "open", ...this.#signalWho() });
421
+ }
348
422
  }
349
423
  this.mux.receive(plain);
350
424
  } catch (err) {
@@ -362,67 +436,137 @@ class GuestSession {
362
436
  return this.kick("bad handshake payload");
363
437
  }
364
438
  if (info?.v !== 1) return this.kick("unsupported version");
365
- const result = devices.authorize(rs, info);
366
- 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");
367
451
  this.device = result.device;
368
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 })));
369
453
  this.cipherOut = reply.send;
370
454
  this.cipherIn = reply.recv;
371
- this.mux = new MuxSession({
372
- role: "server",
373
- send: (frame) => this.#sendPlain(frame),
374
- onRequest: (stream) => this.link.o.serve(stream, this.device),
375
- });
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
+ });
376
466
  this.link.send(concat(this.idBytes, reply.msg));
467
+ this.framesOut++;
377
468
  this.link.control({ t: "verified", c: this.connId });
378
469
  this.state = "await-first";
379
- 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 ? "完成配对" : "已连接"}`);
380
471
  }
381
472
  #sendPlain(frame) {
382
473
  if (this.state === "closed") return;
474
+ this.framesOut++;
383
475
  this.link.send(concat(this.idBytes, this.cipherOut.encrypt(frame)));
384
476
  }
385
- /**
386
- * 这台设备已经用新连接证明了自己(发来了能解密的数据):它的旧会话让位。
387
- * 一台手机同一时间只该有一条会话;旧的那条多半是切网络 / 切后台留下的死连接。
388
- */
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
+
389
518
  #replaceOlder() {
390
519
  const id = this.device?.id;
391
520
  if (!id) return;
521
+
522
+ const standby = this.standby;
392
523
  for (const link of this.link.o.allLinks()) {
393
524
  for (const other of [...link.sessions.values()]) {
394
- 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");
395
527
  }
396
528
  }
397
529
  }
398
530
 
399
- /**
400
- * 拒绝并断开这个访客(同时让中继关掉它)。
401
- * `why` 告诉中继用哪个关闭码:缺省 4401(不认识 / 不合规);"replaced" → 4409;"busy" → 4430。
402
- */
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
+
403
543
  kick(reason = "kicked", why = "") {
404
544
  if (this.state === "closed") return;
405
545
  this.link.o.log(`relay: 断开访客 ${this.connId.slice(0, 6)}…(${reason})`);
406
546
  if (this.link.control(why ? { t: "kick", c: this.connId, why } : { t: "kick", c: this.connId })) this.link.pendingKicks.add(this.connId);
407
- this.dispose();
547
+ this.dispose(reason);
408
548
  }
409
- dispose() {
549
+ dispose(reason = "closed") {
410
550
  if (this.state === "closed") return;
411
551
  this.state = "closed";
412
552
  clearTimeout(this.timer);
413
553
  this.mux?.close("session closed");
414
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
+ }
415
559
  }
416
560
  }
417
561
 
418
- /**
419
- * 一条局域网直连(T-25)。对 GuestSession 来说它就是一条「只有一位访客的中继连接」:
420
- * · 中继会先发 `hello{host:true}`、回答心跳:这里照做,手机端不用区分走的是哪条路;
421
- * · GuestSession 发出的 `connId‖消息` → 去掉 8 字节 connId 直接发给手机;
422
- * · `verified` 只是告诉中继解除限额,这里没有中继,无事可做;
423
- * · `kick` → 按 why 用和中继相同的关闭码断开(4401 不认识 / 4409 被顶替 / 4430 忙)。
424
- * 握手时限、设备核对、防重放都在 GuestSession 里,与中继上完全相同。
425
- */
562
+
563
+
564
+
565
+
566
+
567
+
568
+
569
+
426
570
  class DirectLink {
427
571
  constructor(owner, ws, ip = "") {
428
572
  this.o = owner;
@@ -438,7 +582,7 @@ class DirectLink {
438
582
  ws.on("message", (data) => this.#onMessage(data));
439
583
  ws.on("close", () => this.dispose());
440
584
  this.control({ t: "hello", host: true });
441
- // 握手前的时限比中继上短:真手机在局域网上几十毫秒就发出消息 1、完成握手;占着不动的连接早点放掉
585
+
442
586
  const { directHelloMs, directOpenMs } = owner.timing;
443
587
  this.after(directHelloMs, () => {
444
588
  if (this.session.state === "handshake") this.ws.close(4408, "hello timeout");
@@ -463,7 +607,7 @@ class DirectLink {
463
607
  try {
464
608
  msg = data.length <= 256 ? JSON.parse(data) : null;
465
609
  } catch {
466
- /* 下面统一处理 */
610
+
467
611
  }
468
612
  if (msg?.t === "ping") return void this.ws.send(JSON.stringify({ t: "pong" }));
469
613
  this.ws.close(4400, "unknown control");
@@ -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);