@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,12 +1,18 @@
1
- /**
2
- * 已配对设备 + 一次性配对码。
3
- *
4
- * 取代「一个共享口令授权所有手机」:每台手机一把自己的 X25519 静态密钥,电脑只放行名单里的密钥,
5
- * 丢了手机在桌面上「撤销」即可,其它手机不受影响。口令不再经过网络。
6
- *
7
- * 配对:桌面生成一次性配对码(5 分钟内有效、只能用一次、最多同时 5 个),放进二维码。手机第一次握手时
8
- * 在加密负载里带上它;电脑核对通过就把这台手机的公钥登记进名单。以后重连只认公钥。
9
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
10
16
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
17
  import { join } from "node:path";
12
18
  import { b64u, equalBytes, hex, randomBytesU8, sha256 } from "./crypto.js";
@@ -30,7 +36,7 @@ export class DeviceStore {
30
36
  this.otpTtlMs = otpTtlMs;
31
37
  this.maxDevices = maxDevices;
32
38
  this.devices = [];
33
- this.otps = new Map(); // sha256(otp) hex -> { expiresAt, name }
39
+ this.otps = new Map();
34
40
  this.revokeListeners = new Set();
35
41
  this.lastPersist = 0;
36
42
  this.#load();
@@ -42,29 +48,33 @@ export class DeviceStore {
42
48
  const raw = JSON.parse(readFileSync(this.file, "utf8"));
43
49
  if (raw?.v !== 1 || !Array.isArray(raw.devices)) return;
44
50
  this.devices = raw.devices
45
- .map((d) => ({ id: String(d.id), name: cleanName(d.name), pub: b64u.dec(d.pub), createdAt: Number(d.createdAt) || 0, lastSeen: Number(d.lastSeen) || 0 }))
51
+ .map((d) => ({ id: String(d.id), name: cleanName(d.name), pub: b64u.dec(d.pub), createdAt: Number(d.createdAt) || 0, lastSeen: Number(d.lastSeen) || 0, relay: d.relay !== false }))
46
52
  .filter((d) => d.pub.length === 32 && d.id === fingerprint(d.pub));
47
53
  } catch {
48
- /* 损坏的名单 = 没有已配对设备(宁可让人重新配对,也不放行不认识的东西) */
54
+
49
55
  }
50
56
  }
51
57
  #persist() {
52
58
  mkdirSync(this.dir, { recursive: true, mode: 0o700 });
53
59
  const tmp = `${this.file}.${process.pid}.tmp`;
54
- const body = { v: 1, devices: this.devices.map((d) => ({ id: d.id, name: d.name, pub: b64u.enc(d.pub), createdAt: d.createdAt, lastSeen: d.lastSeen })) };
60
+ const body = { v: 1, devices: this.devices.map((d) => ({ id: d.id, name: d.name, pub: b64u.enc(d.pub), createdAt: d.createdAt, lastSeen: d.lastSeen, relay: d.relay !== false })) };
55
61
  writeFileSync(tmp, `${JSON.stringify(body)}\n`, { mode: 0o600 });
56
62
  renameSync(tmp, this.file);
57
63
  try {
58
64
  chmodSync(this.file, 0o600);
59
65
  } catch {
60
- /* Windows */
66
+
61
67
  }
62
68
  this.lastPersist = this.now();
63
69
  }
64
70
 
65
- /** 给 UI 看的列表:不含公钥全文,只有稳定的 id(公钥指纹)。 */
71
+
66
72
  list() {
67
- return this.devices.map(({ id, name, createdAt, lastSeen }) => ({ id, name, createdAt, lastSeen }));
73
+ return this.devices.map(({ id, name, createdAt, lastSeen, relay }) => ({ id, name, createdAt, lastSeen, via: relay === false ? "lan" : "relay" }));
74
+ }
75
+
76
+ relayPaired() {
77
+ return this.devices.filter((d) => d.relay !== false).length;
68
78
  }
69
79
  find(pub) {
70
80
  return this.devices.find((d) => equalBytes(d.pub, pub)) ?? null;
@@ -74,14 +84,14 @@ export class DeviceStore {
74
84
  if (this.now() - this.lastPersist > 60_000) this.#persist();
75
85
  }
76
86
 
77
- /** Void every pairing code not yet used (T-62: codes shown with a key that is being replaced). */
87
+
78
88
  cancelPairings() {
79
89
  const n = this.otps.size;
80
90
  this.otps.clear();
81
91
  return n;
82
92
  }
83
93
 
84
- /** 撤销设备;返回是否真的删掉了。监听者(连接器)据此踢掉它正在用的连接。 */
94
+
85
95
  revoke(id) {
86
96
  const i = this.devices.findIndex((d) => d.id === id);
87
97
  if (i < 0) return false;
@@ -95,38 +105,59 @@ export class DeviceStore {
95
105
  return () => this.revokeListeners.delete(fn);
96
106
  }
97
107
 
98
- /** 生成一次性配对码。返回明文码(只此一次)与过期时间。 */
99
- createPairing(name) {
108
+
109
+
110
+
111
+
112
+ createPairing(name, { relay = true } = {}) {
100
113
  this.#sweep();
101
- while (this.otps.size >= MAX_PENDING_OTPS) this.otps.delete(this.otps.keys().next().value); // 最旧的让位
114
+ while (this.otps.size >= MAX_PENDING_OTPS) this.otps.delete(this.otps.keys().next().value);
102
115
  const otp = b64u.enc(randomBytesU8(16));
103
116
  const expiresAt = this.now() + this.otpTtlMs;
104
- this.otps.set(hex(sha256(otp)), { expiresAt, name: name ? cleanName(name) : undefined });
117
+ this.otps.set(hex(sha256(otp)), { expiresAt, name: name ? cleanName(name) : undefined, relay: relay !== false });
105
118
  return { otp, expiresAt };
106
119
  }
107
120
  #sweep() {
108
121
  const t = this.now();
109
122
  for (const [k, v] of this.otps) if (v.expiresAt <= t) this.otps.delete(k);
110
123
  }
111
- pendingPairings() {
124
+
125
+ pendingPairings({ relay } = {}) {
112
126
  this.#sweep();
113
- return this.otps.size;
127
+ if (relay === undefined) return this.otps.size;
128
+ let n = 0;
129
+ for (const v of this.otps.values()) if ((v.relay !== false) === relay) n++;
130
+ return n;
114
131
  }
115
- /** 最后一个还有效的配对码什么时候过期(毫秒时间戳);没有则 0。按需连接用它决定何时可以断开中继。 */
116
- pairingExpiry() {
132
+
133
+ pairingExpiry({ relay } = {}) {
117
134
  this.#sweep();
118
135
  let latest = 0;
119
- for (const v of this.otps.values()) if (v.expiresAt > latest) latest = v.expiresAt;
136
+ for (const v of this.otps.values()) {
137
+ if (relay !== undefined && (v.relay !== false) !== relay) continue;
138
+ if (v.expiresAt > latest) latest = v.expiresAt;
139
+ }
120
140
  return latest;
121
141
  }
122
142
 
123
- /**
124
- * 握手成功之后、放行之前的最后一道关:这把公钥是不是我们认的?
125
- * @returns {{ device, newlyPaired:boolean } | null} null = 拒绝(不要回应、直接踢掉)
126
- */
143
+
144
+
145
+
146
+
127
147
  authorize(pub, info = {}) {
128
148
  const known = this.find(pub);
129
149
  if (known) {
150
+
151
+
152
+ if (known.relay === false && typeof info.otp === "string" && info.otp !== "" && info.otp.length <= 64) {
153
+ this.#sweep();
154
+ const key = hex(sha256(info.otp));
155
+ if (this.otps.get(key)?.relay) {
156
+ this.otps.delete(key);
157
+ known.relay = true;
158
+ this.#persist();
159
+ }
160
+ }
130
161
  this.touch(known);
131
162
  return { device: known, newlyPaired: false };
132
163
  }
@@ -136,7 +167,7 @@ export class DeviceStore {
136
167
  const key = hex(sha256(otp));
137
168
  const entry = this.otps.get(key);
138
169
  if (!entry) return null;
139
- this.otps.delete(key); // 一次性:无论后面成不成功,这个码都作废
170
+ this.otps.delete(key);
140
171
  if (this.devices.length >= this.maxDevices) return null;
141
172
  const device = {
142
173
  id: fingerprint(pub),
@@ -144,6 +175,7 @@ export class DeviceStore {
144
175
  pub: pub.slice(),
145
176
  createdAt: this.now(),
146
177
  lastSeen: this.now(),
178
+ relay: entry.relay !== false,
147
179
  };
148
180
  this.devices.push(device);
149
181
  this.#persist();
@@ -1,30 +1,30 @@
1
- /**
2
- * 配对指纹的算法与显示格式——**电脑端与手机端共用这一份定义**。
3
- *
4
- * 为什么单独抽一个文件:手机(Dart)和电脑(JS)各自算一次指纹,只要算法或分组
5
- * 差一点,用户就会看到两个不同的字符串,然后合理地拒绝连接——一个安全功能
6
- * 变成「连不上」的元凶。把电脑侧的算法收在这里,测试可以直接对着它跑,
7
- * 而不是去 `lib/client.js` 那个需要完整 React/浏览器沙箱才能加载的模块里取。
8
- *
9
- * 手机侧的对应实现:`dsh-mobile-app/lib/relay/fingerprint.dart`。
10
- * 两边的测试(`test/pairing-fingerprint.test.mjs` 与
11
- * `dsh-mobile-app/test/relay_fingerprint_test.dart`)都用同一组向量对拍,
12
- * 改任何一边都必须同时改另一边。
13
- *
14
- * 算法与服务端设备列表 `lib/relay/devices.js` 的 `fingerprint()` 一致:
15
- * sha256(公钥) 的十六进制前 16 个字符。
16
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
17
  import { createHash } from "node:crypto";
18
18
 
19
- /** 指纹的十六进制长度。 */
19
+
20
20
  export const FINGERPRINT_HEX_LEN = 16;
21
21
 
22
- /**
23
- * 算一把 X25519 公钥的指纹。
24
- *
25
- * @param {Buffer|Uint8Array} publicKey 32 字节公钥
26
- * @returns {string} 16 位小写十六进制
27
- */
22
+
23
+
24
+
25
+
26
+
27
+
28
28
  export function pairingFingerprint(publicKey) {
29
29
  if (!publicKey || publicKey.length !== 32) {
30
30
  throw new Error(`公钥必须是 32 字节(X25519),实际 ${publicKey?.length ?? 0}`);
@@ -32,17 +32,17 @@ export function pairingFingerprint(publicKey) {
32
32
  return createHash("sha256").update(publicKey).digest("hex").slice(0, FINGERPRINT_HEX_LEN);
33
33
  }
34
34
 
35
- /**
36
- * 把 16 位十六进制拆成 4 组 4 位,供界面显示。
37
- *
38
- * 分组是为了能一眼念出来、也方便和另一块屏幕逐段比。一整串 16 位连着写,
39
- * 眼睛会串行——而这一串的意义正是让人认真核对。
40
- *
41
- * 非法输入原样返回(不抛):这是展示层,不该因为一个坏字符串把面板弄崩。
42
- *
43
- * @param {string} hex
44
- * @returns {string}
45
- */
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
46
  export function formatPairingFingerprint(hex) {
47
47
  const clean = String(hex ?? "").toLowerCase().replace(/[^0-9a-f]/g, "");
48
48
  if (clean.length !== FINGERPRINT_HEX_LEN) return String(hex ?? "");
@@ -1,9 +1,9 @@
1
- /**
2
- * 电脑的长期身份:两把密钥,各司其职。
3
- * * X25519 静态密钥 —— Noise 握手里证明「我是这台电脑」,公钥放进配对二维码,手机据此认人。
4
- * * Ed25519 密钥 —— 只对中继证明「这个房间是我的」。房间号 = SHA-256(Ed25519 公钥) 的前 16 字节。
5
- * 存在 `<状态目录>/relay/identity.json`(0600,原子写)。私钥只在本机,永不上传、永不进日志。
6
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
7
  import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { b64u, ed25519Generate, equalBytes, hex, sha256, x25519Generate, x25519PublicOf } from "./crypto.js";
@@ -16,22 +16,22 @@ const valid = (raw) => {
16
16
  const ed = { pub: b64u.dec(raw.ed25519.pub), priv: b64u.dec(raw.ed25519.priv) };
17
17
  const x = { pub: b64u.dec(raw.x25519.pub), priv: b64u.dec(raw.x25519.priv) };
18
18
  if (ed.pub.length !== 32 || ed.priv.length !== 32 || x.pub.length !== 32 || x.priv.length !== 32) return null;
19
- if (!equalBytes(x25519PublicOf(x.priv), x.pub)) return null; // 公私钥必须配对,否则这份文件已损坏
19
+ if (!equalBytes(x25519PublicOf(x.priv), x.pub)) return null;
20
20
  return { ed, x };
21
21
  } catch {
22
22
  return null;
23
23
  }
24
24
  };
25
25
 
26
- /**
27
- * 读取身份;没有就生成并落盘。文件存在但损坏时**不覆盖**:改名留档后再生成(旧文件已不可用,
28
- * 但留着方便排查,也不会因为一次读失败就悄悄销毁一个有效身份)。
29
- */
30
- /**
31
- * Replace the PC's identity with a fresh one (T-62: after a device is revoked). The old private
32
- * keys are overwritten, not kept: a revoked phone must not be able to talk to this PC again.
33
- * Every phone pinned the old public key and room, so all of them have to pair again.
34
- */
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
35
  export function rotateIdentity(dir) {
36
36
  const file = join(dir, "identity.json");
37
37
  const ed = ed25519Generate();
@@ -47,22 +47,22 @@ export function rotateIdentity(dir) {
47
47
  try {
48
48
  chmodSync(file, 0o600);
49
49
  } catch {
50
- /* Windows 上无意义 */
50
+
51
51
  }
52
52
  return { ed, x, roomId: roomIdOf(ed.pub), file, created: true };
53
53
  }
54
54
 
55
- /** How long an old room keeps answering after a rotation (T-62 fix). */
55
+
56
56
  export const RETIRED_ROOM_MS = 7 * 24 * 60 * 60_000;
57
57
  const MAX_RETIRED = 4;
58
58
  const encodeIdentity = (id) => ({ v: 1, ed25519: { pub: b64u.enc(id.ed.pub), priv: b64u.enc(id.ed.priv) }, x25519: { pub: b64u.enc(id.x.pub), priv: b64u.enc(id.x.priv) } });
59
59
 
60
- /**
61
- * Identities replaced by a rotation, still used for a while to answer their old room
62
- * (`<dir>/retired.json`, 0600): phones that dial it get 4401 "revoked, pair again" instead of
63
- * waiting for a computer that never comes. Expired entries are dropped on every read.
64
- * @returns {{ identity: object, until: number }[]}
65
- */
60
+
61
+
62
+
63
+
64
+
65
+
66
66
  export function loadRetiredIdentities(dir, now = Date.now()) {
67
67
  const file = join(dir, "retired.json");
68
68
  if (!existsSync(file)) return [];
@@ -89,7 +89,7 @@ function saveRetired(dir, items) {
89
89
  renameSync(tmp, file);
90
90
  }
91
91
 
92
- /** Keep `identity` answering its old room until `until`. Returns the live list. */
92
+
93
93
  export function retireIdentity(dir, identity, until) {
94
94
  const items = [...loadRetiredIdentities(dir), { identity, until }].slice(-MAX_RETIRED);
95
95
  saveRetired(dir, items);
@@ -123,7 +123,7 @@ export function loadOrCreateIdentity(dir, { log = () => {} } = {}) {
123
123
  try {
124
124
  chmodSync(file, 0o600);
125
125
  } catch {
126
- /* Windows 上无意义 */
126
+
127
127
  }
128
128
  return { ed, x, roomId: roomIdOf(ed.pub), file, created: true };
129
129
  }
package/lib/relay/mux.js CHANGED
@@ -1,23 +1,26 @@
1
- /**
2
- * 一条加密通道里的多路复用:把很多条 HTTP 请求 / SSE 长连接装进同一个字节管道。
3
- *
4
- * 通道本身(Noise 之上的 WebSocket)由调用方提供:`send(bytes)` 发出一帧**明文**(外层负责加密),
5
- * `receive(bytes)` 收进一帧**明文**。所以这个模块两端通用,也不依赖任何网络库,能用内存管道做确定性测试。
6
- *
7
- * 帧:`[type:u8][streamId:u32 BE][payload]`(一帧装进一条 Noise 传输消息,≤ 64 KiB)
8
- * OPEN (客户端→服务端) JSON {m:方法, p:路径, h:头}
9
- * RESP (服务端→客户端) JSON {s:状态码, h:头}
10
- * DATA 两个方向的正文分片(≤ 16 KiB)
11
- * END 该方向正文结束
12
- * RST 中止这条流,payload = u16 BE 错误码
13
- * WINDOW 流控:payload = u32 BE,授权对端再发这么多字节的 DATA
14
- * PING / PONG (streamId = 0)存活探测
15
- *
16
- * 流控按流、按方向:初始窗口 256 KiB,接收方在**应用真正读走**之后才归还额度,所以慢速读者会
17
- * 反压发送方,一个 20 MB 的图片上传不会把心跳与 SSE 帧挤死,也不会无界占内存。
18
- */
19
-
20
- export const T = Object.freeze({ OPEN: 1, DATA: 2, END: 3, RST: 4, RESP: 5, WINDOW: 6, PING: 7, PONG: 8 });
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ export const T = Object.freeze({ OPEN: 1, DATA: 2, END: 3, RST: 4, RESP: 5, WINDOW: 6, PING: 7, PONG: 8, SIGNAL: 9 });
21
24
  export const MAX_FRAME_PAYLOAD = 16 * 1024;
22
25
  export const INITIAL_WINDOW = 256 * 1024;
23
26
  export const MAX_HEAD_BYTES = 16 * 1024;
@@ -80,7 +83,7 @@ const cleanHeaders = (h) => {
80
83
  return out;
81
84
  };
82
85
 
83
- /** 接收缓冲:把收到的分片变成一个带反压的 ReadableStream;读走一片才归还一片的额度。 */
86
+
84
87
  class Inbound {
85
88
  constructor(onConsumed, onCancel) {
86
89
  this.queue = [];
@@ -105,7 +108,7 @@ class Inbound {
105
108
  cancel: () => {
106
109
  this.queue = [];
107
110
  this.ended = true;
108
- onCancel?.(); // 读者放弃(例如 SSE 连接被关闭)→ 通知对端停止,别继续发
111
+ onCancel?.();
109
112
  },
110
113
  },
111
114
  { highWaterMark: 0 },
@@ -135,8 +138,8 @@ class StreamState {
135
138
  this.id = id;
136
139
  this.session = session;
137
140
  this.sendWindow = session.window;
138
- this.credits = []; // 等额度的发送方
139
- this.recvOutstanding = 0; // 已收到、应用还没读走的字节
141
+ this.credits = [];
142
+ this.recvOutstanding = 0;
140
143
  this.inbound = new Inbound(
141
144
  (n) => {
142
145
  this.recvOutstanding -= n;
@@ -144,12 +147,12 @@ class StreamState {
144
147
  },
145
148
  () => this.reset(RST.CANCEL),
146
149
  );
147
- this.localEnded = false; // 我方向已发 END
150
+ this.localEnded = false;
148
151
  this.remoteEnded = false;
149
152
  this.closed = false;
150
153
  this.abort = new AbortController();
151
154
  }
152
- /** 发送 DATA:切片、等额度。 */
155
+
153
156
  async write(chunk) {
154
157
  const bytes = toBytes(chunk);
155
158
  for (let off = 0; off < bytes.length; ) {
@@ -175,22 +178,22 @@ class StreamState {
175
178
  const waiting = this.credits.splice(0);
176
179
  for (const w of waiting) w();
177
180
  }
178
- /** 本地中止:通知对端并释放。 */
181
+
179
182
  reset(code = RST.CANCEL) {
180
183
  if (this.closed) return;
181
184
  this.session._sendFrame(T.RST, this.id, u16(code));
182
185
  this.teardown(new MuxError("reset", code));
183
186
  }
184
- /** err 为空 = 双方都正常结束:不能让还没读完的正文报错,也不是「被取消」。 */
187
+
185
188
  teardown(err) {
186
189
  if (this.closed) return;
187
190
  this.closed = true;
188
- // 审计 S8:监听在调用方 signal 上的回调随流结束一起摘掉(信号往往活得比单条请求长)。
191
+
189
192
  try {
190
193
  this.onTeardown?.();
191
- } catch { /* 清理失败不影响流关闭 */ }
194
+ } catch { }
192
195
  if (err) {
193
- this.onHeadFail?.(err); // 响应头还没到就被取消 / 重置:request() 必须结束,不能永远挂着(已 resolve 时无副作用)
196
+ this.onHeadFail?.(err);
194
197
  this.inbound.fail(err);
195
198
  this.abort.abort(err);
196
199
  }
@@ -200,15 +203,17 @@ class StreamState {
200
203
  }
201
204
 
202
205
  export class MuxSession {
203
- /**
204
- * @param {{send:(b:Uint8Array)=>void, role:'client'|'server', onRequest?:(s:object)=>unknown,
205
- * maxStreams?:number, window?:number}} opts
206
- */
207
- constructor({ send, role, onRequest, maxStreams = 32, window = INITIAL_WINDOW }) {
206
+
207
+
208
+
209
+
210
+ constructor({ send, role, onRequest, onSignal, maxStreams = 32, window = INITIAL_WINDOW }) {
208
211
  if (role !== "client" && role !== "server") throw new Error("role");
209
212
  this.send = send;
210
213
  this.role = role;
211
214
  this.onRequest = onRequest;
215
+
216
+ this.onSignal = typeof onSignal === "function" ? onSignal : null;
212
217
  this.maxStreams = maxStreams;
213
218
  this.window = window;
214
219
  this.streams = new Map();
@@ -225,7 +230,7 @@ export class MuxSession {
225
230
  if (s.localEnded && s.remoteEnded) s.teardown(null);
226
231
  }
227
232
 
228
- /** 客户端:发起一条请求。返回 { status, headers, body: ReadableStream }。 */
233
+
229
234
  async request({ method = "GET", path, headers = {}, body, signal }) {
230
235
  if (this.role !== "client") throw new Error("only the client opens streams");
231
236
  if (this.closed) throw new MuxError("session closed", RST.CANCEL);
@@ -238,21 +243,21 @@ export class MuxSession {
238
243
  s.onHead = resolve;
239
244
  s.onHeadFail = reject;
240
245
  });
241
- head.catch(() => {}); // 避免未处理拒绝:真正的调用方会 await 它
246
+ head.catch(() => {});
242
247
  const open = enc.encode(JSON.stringify({ m: method, p: path, h: cleanHeaders(headers) }));
243
248
  if (open.length > MAX_HEAD_BYTES) {
244
249
  s.teardown(new MuxError("head too large"));
245
250
  throw new MuxError("head too large");
246
251
  }
247
252
  this._sendFrame(T.OPEN, id, open);
248
- // 监听器必须随请求结束摘掉(审计 S8):调用方传入的 signal 往往活得比单条请求长
249
- // (整段连接一个 AbortController),不摘就是每请求一个永久监听器。
253
+
254
+
250
255
  const onAbort = () => s.reset(RST.CANCEL);
251
256
  s.onTeardown = () => signal?.removeEventListener("abort", onAbort);
252
257
  signal?.addEventListener("abort", onAbort, { once: true });
253
258
  if (signal?.aborted) s.reset(RST.CANCEL);
254
259
 
255
- // 请求正文在后台发送(受流控);失败 → 中止这条流
260
+
256
261
  (async () => {
257
262
  try {
258
263
  if (body != null) {
@@ -277,7 +282,13 @@ export class MuxSession {
277
282
  return { status: res.s, headers: cleanHeaders(res.h), body: s.inbound.stream, cancel: () => s.reset(RST.CANCEL) };
278
283
  }
279
284
 
280
- /** 往对端发 PING,返回往返毫秒。 */
285
+
286
+ sendSignal(payload) {
287
+ if (this.closed) throw new MuxError("session closed", RST.CANCEL);
288
+ this._sendFrame(T.SIGNAL, 0, payload);
289
+ }
290
+
291
+
281
292
  ping(timeoutMs = 10_000) {
282
293
  const nonce = (this.nextId + Math.floor(Math.random() * 1e9)) >>> 0;
283
294
  return new Promise((resolve, reject) => {
@@ -301,7 +312,7 @@ export class MuxSession {
301
312
  });
302
313
  }
303
314
 
304
- /** 收进一帧明文。协议错误抛 MuxError——调用方应当关闭整个会话(对端有 bug 或在攻击)。 */
315
+
305
316
  receive(bytes) {
306
317
  if (this.closed) return;
307
318
  const { type, streamId, payload } = decodeFrame(bytes);
@@ -317,6 +328,9 @@ export class MuxSession {
317
328
  }
318
329
  return;
319
330
  }
331
+ case T.SIGNAL:
332
+ if (!this.onSignal || streamId !== 0) throw new MuxError("unexpected SIGNAL");
333
+ return void this.onSignal(payload);
320
334
  case T.OPEN:
321
335
  return this.#onOpen(streamId, payload);
322
336
  case T.RESP:
@@ -387,14 +401,14 @@ export class MuxSession {
387
401
  }
388
402
  #onData(id, payload) {
389
403
  const s = this.streams.get(id);
390
- if (!s) return; // 对端在我们已中止之后还在发:忽略
404
+ if (!s) return;
391
405
  if (s.remoteEnded) throw new MuxError("DATA after END");
392
406
  s.recvOutstanding += payload.length;
393
407
  if (s.recvOutstanding > this.window) {
394
408
  s.reset(RST.FLOW);
395
409
  return;
396
410
  }
397
- s.inbound.push(payload.slice()); // 拷贝:底层 buffer 会被复用
411
+ s.inbound.push(payload.slice());
398
412
  }
399
413
  #onEnd(id) {
400
414
  const s = this.streams.get(id);
@@ -404,7 +418,7 @@ export class MuxSession {
404
418
  this._maybeRetire(s);
405
419
  }
406
420
 
407
- /** 关闭整个会话:所有进行中的流以错误结束。幂等。 */
421
+
408
422
  close(reason = "closed") {
409
423
  if (this.closed) return;
410
424
  this.closed = true;