@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,19 +1,19 @@
1
- /**
2
- * Noise_IK_25519_ChaChaPoly_SHA256(https://noiseprotocol.org/noise.html,rev 34)。
3
- *
4
- * 为什么是 IK:手机已经从配对二维码里知道电脑的静态公钥(预消息 `<- s`),第一条消息就能把自己的静态公钥
5
- * 加密后带过去——一个往返完成**双向认证 + 前向保密**;之后每次重连也是一个往返。
6
- *
7
- * <- s
8
- * ...
9
- * -> e, es, s, ss
10
- * <- e, ee, se
11
- *
12
- * 选 SHA-256(而不是 BLAKE2s)是为了让 Flutter 端除了 X25519 与 ChaCha20-Poly1305 之外只需要它已有的 `crypto` 包。
13
- *
14
- * ⚠ 一致性:本实现按规范逐步实现,并做了往返 / 篡改 / 重放 / 身份冒充等性质测试,但**尚未对照官方测试向量**
15
- * (本环境不联网,拿不到)。`test/vectors/` 里留了接入点;上线前必须用官方向量(cacophony / snow)核对。
16
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
17
  import { EMPTY, aeadDecrypt, aeadEncrypt, concat, equalBytes, hkdf, sha256, x25519Dh, x25519Generate, x25519PublicOf } from "./crypto.js";
18
18
 
19
19
  export const PROTOCOL_NAME = "Noise_IK_25519_ChaChaPoly_SHA256";
@@ -21,7 +21,7 @@ export const MAX_MESSAGE = 65535;
21
21
  const DHLEN = 32;
22
22
  const TAGLEN = 16;
23
23
 
24
- /** 传输阶段的单向加密状态。n 是 64 位计数器;Noise 规定 2^64-1 保留给 rekey,这里直接当上限。 */
24
+
25
25
  export class CipherState {
26
26
  constructor(key) {
27
27
  this.k = key ?? null;
@@ -40,7 +40,7 @@ export class CipherState {
40
40
  decrypt(ciphertext, ad = EMPTY) {
41
41
  if (this.k === null) return ciphertext;
42
42
  if (this.n >= 0xffffffffffffffffn) throw new Error("nonce exhausted");
43
- const out = aeadDecrypt(this.k, this.n, ad, ciphertext); // 认证失败抛错,n 不前进
43
+ const out = aeadDecrypt(this.k, this.n, ad, ciphertext);
44
44
  this.n += 1n;
45
45
  return out;
46
46
  }
@@ -87,10 +87,10 @@ const checkKeyPair = (kp, name) => {
87
87
  if (!kp || kp.priv?.length !== 32 || kp.pub?.length !== 32) throw new Error(`${name} must be an x25519 keypair`);
88
88
  };
89
89
 
90
- /**
91
- * 发起方(手机)。`rs` 是电脑的静态公钥(来自二维码)。
92
- * `ephemeral` 仅供测试注入固定临时密钥(生成固定向量);生产里不要传。
93
- */
90
+
91
+
92
+
93
+
94
94
  export class NoiseInitiator {
95
95
  constructor({ s, rs, prologue = EMPTY, ephemeral } = {}) {
96
96
  checkKeyPair(s, "s");
@@ -101,32 +101,32 @@ export class NoiseInitiator {
101
101
  this.re = null;
102
102
  this.sym = new SymmetricState(PROTOCOL_NAME);
103
103
  this.sym.mixHash(prologue);
104
- this.sym.mixHash(rs); // 预消息 `<- s`
104
+ this.sym.mixHash(rs);
105
105
  this.state = "start";
106
106
  }
107
- /** -> e, es, s, ss,附带加密负载。 */
107
+
108
108
  writeMessage1(payload = EMPTY) {
109
109
  if (this.state !== "start") throw new Error("bad state");
110
110
  this.e = this.e ?? x25519Generate();
111
111
  const parts = [this.e.pub];
112
112
  this.sym.mixHash(this.e.pub);
113
- this.sym.mixKey(x25519Dh(this.e.priv, this.rs)); // es
114
- parts.push(this.sym.encryptAndHash(this.s.pub)); // s
115
- this.sym.mixKey(x25519Dh(this.s.priv, this.rs)); // ss
113
+ this.sym.mixKey(x25519Dh(this.e.priv, this.rs));
114
+ parts.push(this.sym.encryptAndHash(this.s.pub));
115
+ this.sym.mixKey(x25519Dh(this.s.priv, this.rs));
116
116
  parts.push(this.sym.encryptAndHash(payload));
117
117
  const msg = concat(...parts);
118
118
  if (msg.length > MAX_MESSAGE) throw new Error("message too large");
119
119
  this.state = "sent1";
120
120
  return msg;
121
121
  }
122
- /** <- e, ee, se;成功后返回 { payload, send, recv, handshakeHash }。 */
122
+
123
123
  readMessage2(msg) {
124
124
  if (this.state !== "sent1") throw new Error("bad state");
125
125
  if (msg.length < DHLEN + TAGLEN || msg.length > MAX_MESSAGE) throw new Error("bad handshake message");
126
126
  this.re = msg.subarray(0, DHLEN);
127
127
  this.sym.mixHash(this.re);
128
- this.sym.mixKey(x25519Dh(this.e.priv, this.re)); // ee
129
- this.sym.mixKey(x25519Dh(this.s.priv, this.re)); // se
128
+ this.sym.mixKey(x25519Dh(this.e.priv, this.re));
129
+ this.sym.mixKey(x25519Dh(this.s.priv, this.re));
130
130
  const payload = this.sym.decryptAndHash(msg.subarray(DHLEN));
131
131
  const [c1, c2] = this.sym.split();
132
132
  this.state = "done";
@@ -134,7 +134,7 @@ export class NoiseInitiator {
134
134
  }
135
135
  }
136
136
 
137
- /** 响应方(电脑)。用 `s` 解密;对端静态公钥由消息 1 带来,调用方据此决定放不放行。 */
137
+
138
138
  export class NoiseResponder {
139
139
  constructor({ s, prologue = EMPTY, ephemeral } = {}) {
140
140
  checkKeyPair(s, "s");
@@ -144,33 +144,33 @@ export class NoiseResponder {
144
144
  this.rs = null;
145
145
  this.sym = new SymmetricState(PROTOCOL_NAME);
146
146
  this.sym.mixHash(prologue);
147
- this.sym.mixHash(s.pub); // 预消息 `<- s`
147
+ this.sym.mixHash(s.pub);
148
148
  this.state = "start";
149
149
  }
150
- /** 解消息 1。返回 { payload, rs }:rs 是发起方(手机)的静态公钥,**必须由调用方核对授权**。 */
150
+
151
151
  readMessage1(msg) {
152
152
  if (this.state !== "start") throw new Error("bad state");
153
153
  if (msg.length < DHLEN + DHLEN + TAGLEN + TAGLEN || msg.length > MAX_MESSAGE) throw new Error("bad handshake message");
154
154
  this.re = msg.subarray(0, DHLEN);
155
155
  this.sym.mixHash(this.re);
156
- this.sym.mixKey(x25519Dh(this.s.priv, this.re)); // es
157
- this.rs = this.sym.decryptAndHash(msg.subarray(DHLEN, DHLEN + DHLEN + TAGLEN)); // s
158
- this.sym.mixKey(x25519Dh(this.s.priv, this.rs)); // ss
156
+ this.sym.mixKey(x25519Dh(this.s.priv, this.re));
157
+ this.rs = this.sym.decryptAndHash(msg.subarray(DHLEN, DHLEN + DHLEN + TAGLEN));
158
+ this.sym.mixKey(x25519Dh(this.s.priv, this.rs));
159
159
  const payload = this.sym.decryptAndHash(msg.subarray(DHLEN + DHLEN + TAGLEN));
160
160
  this.state = "read1";
161
161
  return { payload, rs: this.rs };
162
162
  }
163
- /** <- e, ee, se,附带加密负载;返回 { msg, send, recv, handshakeHash }。 */
163
+
164
164
  writeMessage2(payload = EMPTY) {
165
165
  if (this.state !== "read1") throw new Error("bad state");
166
166
  this.e = this.e ?? x25519Generate();
167
167
  this.sym.mixHash(this.e.pub);
168
- this.sym.mixKey(x25519Dh(this.e.priv, this.re)); // ee
169
- this.sym.mixKey(x25519Dh(this.e.priv, this.rs)); // se
168
+ this.sym.mixKey(x25519Dh(this.e.priv, this.re));
169
+ this.sym.mixKey(x25519Dh(this.e.priv, this.rs));
170
170
  const msg = concat(this.e.pub, this.sym.encryptAndHash(payload));
171
171
  const [c1, c2] = this.sym.split();
172
172
  this.state = "done";
173
- // 响应方:c1 用于接收(发起方→响应方),c2 用于发送
173
+
174
174
  return { msg, send: c2, recv: c1, handshakeHash: this.sym.h };
175
175
  }
176
176
  }
@@ -1,32 +1,32 @@
1
- /**
2
- * 按需连接中继(T-11)。
3
- *
4
- * 以前只要 relay.enabled 为 true(默认),插件一启动就连上公共中继——哪怕这台电脑从来没配对过手机。
5
- * 那条连接没有任何用处(没有已配对设备、也没有有效的配对码时,谁都进不来),却让每一台装了插件的
6
- * 电脑都常驻一条到我们服务器的连接:成本随安装量增长,隐私文本也没法说「不配对就不联网」。
7
- *
8
- * 现在的规则:**只有在「有人可能进得来」的时候才连**——
9
- * · 已经有至少一台经中继配对的手机;或
10
- * · 用户刚在桌面上要了一个配对码(5 分钟内有效)。
11
- * 两个条件都不成立就断开:全新安装不产生任何中继连接;撤销最后一台设备、配对码过期没人用,也会断开。
12
- *
13
- * T-71 (C-04): only phones and codes **for remote access** count. A phone paired with the desktop's
14
- * default QR (encrypted LAN only, no relay in the link) never uses the relay, so it must not keep
15
- * this PC on our relay around the clock (cost, and the PC's IP and uptime seen by us for a user
16
- * who never asked for remote access). See `relay` in ./devices.js.
17
- *
18
- * 这个模块只做「该不该连」的判断,连接本身仍由 RelayConnector 负责(重连、心跳、会话)。
19
- */
20
-
21
- /**
22
- * @param {{ connector: { start():void, stop():void },
23
- * devices: { list():unknown[], pendingPairings():number, pairingExpiry():number, onRevoke(fn:()=>void):()=>void },
24
- * log?: (m:string)=>void, now?: ()=>number,
25
- * setTimer?: typeof setTimeout, clearTimer?: typeof clearTimeout }} o
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
27
  export function createRelayDemand({ connector, devices, log = () => {}, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
28
- let enabled = false; // 插件是否在运行(effect 生效期间)
29
- let active = false; // 连接器是否被我们启动了
28
+ let enabled = false;
29
+ let active = false;
30
30
  let timer = null;
31
31
 
32
32
  const paired = () => (typeof devices.relayPaired === "function" ? devices.relayPaired() : devices.list().length) > 0;
@@ -36,7 +36,7 @@ export function createRelayDemand({ connector, devices, log = () => {}, now = Da
36
36
  timer = null;
37
37
  };
38
38
 
39
- /** 对一下表:该连就连,不该连就断。可以随便多调。返回当前是否在连。 */
39
+
40
40
  const sync = () => {
41
41
  disarm();
42
42
  if (!enabled) return active;
@@ -50,7 +50,7 @@ export function createRelayDemand({ connector, devices, log = () => {}, now = Da
50
50
  connector.stop();
51
51
  log("relay: 没有已配对的手机,也没有有效的配对码,已断开中继");
52
52
  }
53
- // 只靠配对码撑着的连接:最后一个码过期后再对一次表(码被用掉 → 有设备了 → 继续连着)
53
+
54
54
  if (active && !paired()) {
55
55
  timer = setTimer(sync, Math.max(1_000, devices.pairingExpiry({ relay: true }) - now() + 1_000));
56
56
  timer.unref?.();
@@ -58,7 +58,7 @@ export function createRelayDemand({ connector, devices, log = () => {}, now = Da
58
58
  return active;
59
59
  };
60
60
 
61
- // 撤销设备:连接器先踢掉它的会话(它的监听器注册在前),这里再看还需不需要连着
61
+
62
62
  const unsubscribe = devices.onRevoke(() => sync());
63
63
 
64
64
  return {
@@ -67,12 +67,12 @@ export function createRelayDemand({ connector, devices, log = () => {}, now = Da
67
67
  get active() {
68
68
  return active;
69
69
  },
70
- /** 插件启动:开始按需连接。 */
70
+
71
71
  start() {
72
72
  enabled = true;
73
73
  return sync();
74
74
  },
75
- /** 插件停止 / 重载:断开,并且在下一次 start() 之前不再连接。 */
75
+
76
76
  stop() {
77
77
  enabled = false;
78
78
  disarm();
@@ -0,0 +1,239 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ import { registerFeature } from "../protocol.js";
23
+
24
+ export const P2P_LABEL = "dsh";
25
+ export const DEFAULT_STUN = Object.freeze(["stun:stun.cloudflare.com:3478"]);
26
+
27
+ export const MAX_LOCAL_CANDIDATES = 24;
28
+ export const P2P_TIMING = Object.freeze({ openMs: 15_000, maxPeers: 4, stunGatherSec: 3 });
29
+
30
+ const loadWerift = () => import("werift");
31
+
32
+
33
+ export class ChannelSocket {
34
+ constructor(channel, { onClose } = {}) {
35
+ this.channel = channel;
36
+ this.readyState = 1;
37
+ this.handlers = { message: [], close: [] };
38
+ this.onClose = onClose;
39
+ channel.onMessage.subscribe((data) => {
40
+ if (this.readyState === 1) for (const h of this.handlers.message) h(typeof data === "string" ? data : new Uint8Array(data));
41
+ });
42
+ channel.stateChanged.subscribe((s) => {
43
+ if (s === "closed" || s === "closing") this.#closed(1006);
44
+ });
45
+ }
46
+ on(type, fn) {
47
+ this.handlers[type]?.push(fn);
48
+ }
49
+ send(data) {
50
+ if (this.readyState !== 1) return false;
51
+ try {
52
+ this.channel.send(typeof data === "string" ? data : Buffer.from(data));
53
+ return true;
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+ close(code = 1000) {
59
+ if (this.readyState !== 1) return;
60
+ this.#closed(code);
61
+ try {
62
+ this.channel.close();
63
+ } catch {
64
+
65
+ }
66
+ }
67
+ #closed(code) {
68
+ if (this.readyState === 3) return;
69
+ this.readyState = 3;
70
+ for (const h of this.handlers.close) h(code);
71
+ this.onClose?.(code);
72
+ }
73
+ }
74
+
75
+ class Attempt {
76
+ constructor(host, peer) {
77
+ this.host = host;
78
+ this.peer = peer;
79
+ this.deviceId = peer.deviceId;
80
+ this.pc = null;
81
+ this.opened = false;
82
+ this.disposed = false;
83
+ this.answerSent = false;
84
+ this.pending = [];
85
+ this.sent = 0;
86
+ this.chain = Promise.resolve();
87
+ this.timer = setTimeout(() => {
88
+ if (!this.opened) this.dispose("no data channel in time");
89
+ }, host.timing.openMs);
90
+ this.timer.unref?.();
91
+ }
92
+
93
+ run(fn) {
94
+ this.chain = this.chain.then(() => (this.disposed ? undefined : fn())).catch((err) => this.fail(err));
95
+ return this.chain;
96
+ }
97
+ fail(err) {
98
+ this.host.log(`p2p: 失败(${err?.name ?? "error"})`);
99
+ this.bye();
100
+ this.dispose("error");
101
+ }
102
+ bye() {
103
+ try {
104
+ this.peer.send({ k: "bye" });
105
+ } catch {
106
+
107
+ }
108
+ }
109
+ async offer(sdp, werift) {
110
+ const { RTCPeerConnection } = werift;
111
+ const pc = (this.pc = new RTCPeerConnection({ iceServers: this.host.iceServers, stunGatherTimeout: this.host.timing.stunGatherSec, iceUseDefaultStunServer: false }));
112
+ pc.onIceCandidate.subscribe((c) => this.#local(c));
113
+ pc.connectionStateChange.subscribe((s) => {
114
+ if (s === "failed" || s === "closed") this.dispose(`connection ${s}`);
115
+ });
116
+ pc.onDataChannel.subscribe((ch) => this.#channel(ch));
117
+ await pc.setRemoteDescription({ type: "offer", sdp });
118
+ const answer = await pc.createAnswer();
119
+ pc.setLocalDescription(answer).catch((err) => this.fail(err));
120
+ this.peer.send({ k: "answer", sdp: answer.sdp });
121
+ this.answerSent = true;
122
+ for (const c of this.pending.splice(0)) this.#local(c);
123
+ }
124
+ async remoteCandidate(cand) {
125
+ if (!this.pc || cand === null) return;
126
+ await this.pc.addIceCandidate(cand);
127
+ }
128
+ #local(c) {
129
+ if (this.disposed) return;
130
+ if (!this.answerSent) return void this.pending.push(c);
131
+ if (c === undefined || c === null) return void this.peer.send({ k: "ice", cand: null });
132
+ if (this.sent >= MAX_LOCAL_CANDIDATES) return;
133
+ this.sent++;
134
+ const { candidate, sdpMid, sdpMLineIndex } = c.toJSON ? c.toJSON() : c;
135
+ this.peer.send({ k: "ice", cand: { candidate, sdpMid, sdpMLineIndex } });
136
+ }
137
+ #channel(ch) {
138
+ if (ch.label !== P2P_LABEL || this.channel) return void ch.close();
139
+ this.channel = ch;
140
+ const start = () => {
141
+ if (this.opened || this.disposed) return;
142
+ this.opened = true;
143
+ clearTimeout(this.timer);
144
+ const sock = new ChannelSocket(ch, { onClose: () => this.dispose("channel closed") });
145
+ const link = this.host.connector.acceptDirect(sock, { ip: "p2p" });
146
+ if (!link) this.dispose("busy");
147
+ else this.host.log("p2p: 数据通道已建立,开始 Noise 握手");
148
+ };
149
+ if (ch.readyState === "open") start();
150
+ else ch.stateChanged.subscribe((s) => s === "open" && start());
151
+ }
152
+ dispose(reason = "closed") {
153
+ if (this.disposed) return;
154
+ this.disposed = true;
155
+ clearTimeout(this.timer);
156
+ if (this.host.attempts.get(this.deviceId) === this) this.host.attempts.delete(this.deviceId);
157
+ const pc = this.pc;
158
+ this.pc = null;
159
+ Promise.resolve(pc?.close()).catch(() => {});
160
+ this.host.log(`p2p: 结束(${reason})`);
161
+ }
162
+ }
163
+
164
+ export class P2pHost {
165
+
166
+
167
+
168
+
169
+ constructor({ connector, importer = loadWerift, stun = DEFAULT_STUN, log = () => {}, timing = {}, feature = true }) {
170
+ this.connector = connector;
171
+ this.importer = importer;
172
+ this.iceServers = stun.length > 0 ? [{ urls: [...stun] }] : [];
173
+ this.log = log;
174
+ this.timing = { ...P2P_TIMING, ...timing };
175
+ this.useFeature = feature;
176
+ this.werift = null;
177
+ this.attempts = new Map();
178
+ this.unsubscribe = null;
179
+ this.unregister = null;
180
+ this.loading = null;
181
+ }
182
+
183
+ start() {
184
+ if (this.unsubscribe) return this.loading;
185
+ this.unsubscribe = this.connector.onSignal((e) => this.#event(e));
186
+ this.loading = this.#load().then((ok) => {
187
+ if (ok && this.unsubscribe && this.useFeature && !this.unregister) this.unregister = registerFeature("p2p");
188
+ return ok;
189
+ });
190
+ return this.loading;
191
+ }
192
+ stop() {
193
+ this.unsubscribe?.();
194
+ this.unsubscribe = null;
195
+ this.unregister?.();
196
+ this.unregister = null;
197
+ for (const a of [...this.attempts.values()]) a.dispose("stopped");
198
+ }
199
+ get available() {
200
+ return this.werift !== null;
201
+ }
202
+ async #load() {
203
+ if (this.werift) return true;
204
+ try {
205
+ const mod = await this.importer();
206
+ if (typeof mod?.RTCPeerConnection !== "function") throw new Error("no RTCPeerConnection");
207
+ this.werift = mod;
208
+ return true;
209
+ } catch (err) {
210
+ this.log(`p2p: werift 不可用,P2P 关闭:${err?.code ?? err?.message ?? err}`);
211
+ return false;
212
+ }
213
+ }
214
+ #event(e) {
215
+ if (e.type === "close") {
216
+ const a = this.attempts.get(e.deviceId);
217
+ if (a && !a.opened) a.dispose("signal closed");
218
+ return;
219
+ }
220
+ if (e.type !== "message") return;
221
+ const { msg, peer, deviceId } = e;
222
+ if (msg.k === "offer") return void this.#offer(deviceId, peer, msg.sdp);
223
+ const a = this.attempts.get(deviceId);
224
+ if (!a) return;
225
+ if (msg.k === "ice") a.run(() => a.remoteCandidate(msg.cand));
226
+ else if (msg.k === "bye" && !a.opened) a.dispose("bye");
227
+ }
228
+ async #offer(deviceId, peer, sdp) {
229
+ this.attempts.get(deviceId)?.dispose("replaced by a new offer");
230
+ if (this.attempts.size >= this.timing.maxPeers) return void peer.send({ k: "bye" });
231
+ const a = new Attempt(this, { ...peer, deviceId });
232
+ this.attempts.set(deviceId, a);
233
+ if (!(await this.#load())) {
234
+ a.bye();
235
+ return a.dispose("werift unavailable");
236
+ }
237
+ a.run(() => a.offer(sdp, this.werift));
238
+ }
239
+ }
@@ -1,24 +1,24 @@
1
- /**
2
- * 配对链接:二维码里编码的内容。
3
- *
4
- * dsh://pair?v=1&room=<32 位十六进制>&pk=<电脑 X25519 公钥 base64url>&otp=<一次性配对码>
5
- * &r=<中继 wss 地址>(可多个)&lan=<局域网地址>(可多个,可选)&n=<电脑名称>(可选)
6
- *
7
- * 手机只需要这些:去哪个中继、哪个房间、认哪把公钥、拿什么码证明「我是被邀请的」。
8
- * 解析是严格的:中继必须是 wss://(回环地址的 ws:// 仅供本机测试),其它一律拒绝。
9
- *
10
- * lan=(T-25)是电脑 LAN 桥上的局域网加密通道:`ws://<局域网 IPv4>:<端口>`。不用 TLS,因为
11
- * 通道本身就是 Noise 加密、认电脑的公钥;但只接受局域网地址(10/8、172.16/12、192.168/16、
12
- * 100.64/10、回环),一个被篡改的二维码不能把手机引去连公网上的任意主机。不合规的 lan 地址丢弃,不报错。
13
- *
14
- * T-71 (D-01, C-15): an invite may carry no relay at all, only `lan=`. That is the desktop's
15
- * default QR: an encrypted pairing on the local network that needs no relay room, no account and
16
- * no subscription (D5: the LAN is free). It needs 1-4 relays **or** at least one valid LAN
17
- * address. Such a link is `v=2`: apps before T-71 accept only `v=1`, and they answer an unknown
18
- * version with "this QR code comes from a newer DSH, please update the app" (their own text), which
19
- * is the right advice. Links with a relay stay `v=1`, readable by every app. The desktop panel keeps
20
- * the old token QR for apps that cannot be updated yet, labelled as unencrypted.
21
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
22
  import { b64u } from "./crypto.js";
23
23
 
24
24
  const ROOM_RE = /^[0-9a-f]{32}$/;
@@ -37,7 +37,7 @@ export function isAllowedRelayUrl(s) {
37
37
  }
38
38
  }
39
39
 
40
- /** 局域网 IPv4(含组网常用的 100.64/10 与回环)。 */
40
+
41
41
  function isLanIPv4(host) {
42
42
  const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
43
43
  if (!m) return false;
@@ -46,13 +46,13 @@ function isLanIPv4(host) {
46
46
  return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
47
47
  }
48
48
 
49
- /** 局域网加密通道的地址是否可接受:`ws://<局域网 IPv4>:<端口>`,不带账号、路径、查询串、片段。 */
49
+
50
50
  export function isAllowedLanUrl(s) {
51
51
  try {
52
52
  const u = new URL(s);
53
53
  if (u.protocol !== "ws:" || u.username || u.password || u.search || u.hash) return false;
54
54
  if (u.pathname !== "/" && u.pathname !== "") return false;
55
- if (!/^ws:\/\/[^/]+\/?$/.test(s)) return false; // URL 会把空路径补成 "/",原文里不能有路径
55
+ if (!/^ws:\/\/[^/]+\/?$/.test(s)) return false;
56
56
  return isLanIPv4(u.hostname) && u.port !== "";
57
57
  } catch {
58
58
  return false;