@dsh-mobile/mobile-remote 0.0.0-stage → 3.2.5

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 (73) hide show
  1. package/CHANGELOG.md +1273 -0
  2. package/CONTRIBUTING.md +59 -0
  3. package/FAQ.md +115 -0
  4. package/LICENSE +21 -0
  5. package/README.md +293 -2
  6. package/cordis.patch.yml +22 -0
  7. package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +121 -0
  8. package/docs/01-PRD.md +148 -0
  9. package/docs/02-architecture.md +249 -0
  10. package/docs/03-api.md +882 -0
  11. package/docs/04-security.md +109 -0
  12. package/docs/05-test-cases.md +376 -0
  13. package/docs/06-install-run.md +349 -0
  14. package/docs/07-user-manual.md +92 -0
  15. package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +86 -0
  16. package/docs/09-compatibility.md +201 -0
  17. package/docs/10-remote-access-and-launch-plan.md +216 -0
  18. package/docs/11-remote-relay-guide.md +82 -0
  19. package/docs/APP-ENCRYPTION-DESCRIPTION.md +50 -0
  20. package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
  21. package/docs/ARCHITECTURE-CURRENT.md +229 -0
  22. package/docs/AUDIT-2026-11-node.md +181 -0
  23. package/docs/AUDIT-2026-11.md +167 -0
  24. package/docs/BRAND-ASSETS.md +142 -0
  25. package/docs/BUILD-ENVIRONMENT.md +180 -0
  26. package/docs/FEATURE-PARITY.md +195 -0
  27. package/docs/PRIVACY-POLICY.en.md +143 -0
  28. package/docs/PRIVACY-POLICY.md +143 -0
  29. package/docs/REA-UNDERSTANDING.md +246 -0
  30. package/docs/STORE-LAUNCH.md +278 -0
  31. package/docs/STORE-LISTING.md +150 -0
  32. package/docs/SUPPORT.md +43 -0
  33. package/docs/TERMS-OF-SERVICE.en.md +70 -0
  34. package/docs/TERMS-OF-SERVICE.md +70 -0
  35. package/docs/screenshots/01-home.png +0 -0
  36. package/docs/screenshots/02-notifications.png +0 -0
  37. package/docs/screenshots/03-sessions.png +0 -0
  38. package/docs/screenshots/04-chat.png +0 -0
  39. package/docs/screenshots/05-settings.png +0 -0
  40. package/docs/screenshots/06-new-session.png +0 -0
  41. package/docs/screenshots/07-connect.png +0 -0
  42. package/docs/screenshots/pgy-appstore.jpg +0 -0
  43. package/docs/screenshots/pgy-mobile-app.jpg +0 -0
  44. package/docs/screenshots/pgy-pc-client.jpg +0 -0
  45. package/lib/account-usage-query.js +278 -0
  46. package/lib/account-usage.js +145 -0
  47. package/lib/api-helpers.js +333 -0
  48. package/lib/auto-config.js +107 -0
  49. package/lib/client.js +586 -0
  50. package/lib/config.js +211 -0
  51. package/lib/git-read-bundled-provider.js +255 -0
  52. package/lib/git-read-service.js +322 -0
  53. package/lib/host-compat.js +133 -0
  54. package/lib/http-util.js +69 -0
  55. package/lib/index.js +5729 -0
  56. package/lib/push.js +73 -0
  57. package/lib/rate-limit.js +46 -0
  58. package/lib/relay/connector.js +300 -0
  59. package/lib/relay/crypto.js +117 -0
  60. package/lib/relay/devices.js +138 -0
  61. package/lib/relay/identity.js +60 -0
  62. package/lib/relay/mux.js +411 -0
  63. package/lib/relay/noise.js +178 -0
  64. package/lib/relay/pairing.js +64 -0
  65. package/lib/relay/phone.js +114 -0
  66. package/lib/relay/serve.js +105 -0
  67. package/lib/rpc-adapter.js +88 -0
  68. package/lib/session-list.js +77 -0
  69. package/lib/session-title-cache.js +123 -0
  70. package/lib/session-title-refresh.js +261 -0
  71. package/lib/timeline.js +476 -0
  72. package/lib/turn-outline.js +289 -0
  73. package/package.json +62 -4
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 电脑的长期身份:两把密钥,各司其职。
3
+ * * X25519 静态密钥 —— Noise 握手里证明「我是这台电脑」,公钥放进配对二维码,手机据此认人。
4
+ * * Ed25519 密钥 —— 只对中继证明「这个房间是我的」。房间号 = SHA-256(Ed25519 公钥) 的前 16 字节。
5
+ * 存在 `<状态目录>/relay/identity.json`(0600,原子写)。私钥只在本机,永不上传、永不进日志。
6
+ */
7
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { b64u, ed25519Generate, equalBytes, hex, sha256, x25519Generate, x25519PublicOf } from "./crypto.js";
10
+
11
+ export const roomIdOf = (edPublicKey) => hex(sha256(edPublicKey).subarray(0, 16));
12
+
13
+ const valid = (raw) => {
14
+ try {
15
+ if (raw?.v !== 1) return null;
16
+ const ed = { pub: b64u.dec(raw.ed25519.pub), priv: b64u.dec(raw.ed25519.priv) };
17
+ const x = { pub: b64u.dec(raw.x25519.pub), priv: b64u.dec(raw.x25519.priv) };
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; // 公私钥必须配对,否则这份文件已损坏
20
+ return { ed, x };
21
+ } catch {
22
+ return null;
23
+ }
24
+ };
25
+
26
+ /**
27
+ * 读取身份;没有就生成并落盘。文件存在但损坏时**不覆盖**:改名留档后再生成(旧文件已不可用,
28
+ * 但留着方便排查,也不会因为一次读失败就悄悄销毁一个有效身份)。
29
+ */
30
+ export function loadOrCreateIdentity(dir, { log = () => {} } = {}) {
31
+ const file = join(dir, "identity.json");
32
+ if (existsSync(file)) {
33
+ let parsed = null;
34
+ try {
35
+ parsed = valid(JSON.parse(readFileSync(file, "utf8")));
36
+ } catch {
37
+ parsed = null;
38
+ }
39
+ if (parsed) return { ...parsed, roomId: roomIdOf(parsed.ed.pub), file, created: false };
40
+ const backup = `${file}.corrupt-${Date.now()}`;
41
+ renameSync(file, backup);
42
+ log(`relay: 身份文件损坏,已改名为 ${backup} 并重新生成——已配对的手机需要重新配对`);
43
+ }
44
+ const ed = ed25519Generate();
45
+ const x = x25519Generate();
46
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
47
+ const tmp = `${file}.${process.pid}.tmp`;
48
+ writeFileSync(
49
+ tmp,
50
+ `${JSON.stringify({ v: 1, ed25519: { pub: b64u.enc(ed.pub), priv: b64u.enc(ed.priv) }, x25519: { pub: b64u.enc(x.pub), priv: b64u.enc(x.priv) } })}\n`,
51
+ { mode: 0o600 },
52
+ );
53
+ renameSync(tmp, file);
54
+ try {
55
+ chmodSync(file, 0o600);
56
+ } catch {
57
+ /* Windows 上无意义 */
58
+ }
59
+ return { ed, x, roomId: roomIdOf(ed.pub), file, created: true };
60
+ }
@@ -0,0 +1,411 @@
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 });
21
+ export const MAX_FRAME_PAYLOAD = 16 * 1024;
22
+ export const INITIAL_WINDOW = 256 * 1024;
23
+ export const MAX_HEAD_BYTES = 16 * 1024;
24
+ export const RST = Object.freeze({ CANCEL: 1, PROTOCOL: 2, TOO_MANY: 3, REFUSED: 4, INTERNAL: 5, FLOW: 6, TIMEOUT: 7 });
25
+
26
+ const enc = new TextEncoder();
27
+ const dec = new TextDecoder();
28
+
29
+ export class MuxError extends Error {
30
+ constructor(message, code = RST.PROTOCOL) {
31
+ super(message);
32
+ this.name = "MuxError";
33
+ this.code = code;
34
+ }
35
+ }
36
+
37
+ export function encodeFrame(type, streamId, payload = new Uint8Array(0)) {
38
+ const out = new Uint8Array(5 + payload.length);
39
+ const view = new DataView(out.buffer);
40
+ view.setUint8(0, type);
41
+ view.setUint32(1, streamId, false);
42
+ out.set(payload, 5);
43
+ return out;
44
+ }
45
+ export function decodeFrame(bytes) {
46
+ if (!(bytes instanceof Uint8Array) || bytes.length < 5) throw new MuxError("short frame");
47
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
48
+ return { type: view.getUint8(0), streamId: view.getUint32(1, false), payload: bytes.subarray(5) };
49
+ }
50
+ const u32 = (n) => {
51
+ const b = new Uint8Array(4);
52
+ new DataView(b.buffer).setUint32(0, n, false);
53
+ return b;
54
+ };
55
+ const u16 = (n) => {
56
+ const b = new Uint8Array(2);
57
+ new DataView(b.buffer).setUint16(0, n, false);
58
+ return b;
59
+ };
60
+ const readU32 = (p) => (p.length === 4 ? new DataView(p.buffer, p.byteOffset, 4).getUint32(0, false) : null);
61
+ const toBytes = (chunk) => (typeof chunk === "string" ? enc.encode(chunk) : chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk));
62
+ const parseHead = (payload) => {
63
+ if (payload.length > MAX_HEAD_BYTES) throw new MuxError("head too large");
64
+ try {
65
+ const v = JSON.parse(dec.decode(payload));
66
+ if (v === null || typeof v !== "object") throw new Error("not an object");
67
+ return v;
68
+ } catch {
69
+ throw new MuxError("bad head");
70
+ }
71
+ };
72
+ const cleanHeaders = (h) => {
73
+ const out = {};
74
+ if (h && typeof h === "object") {
75
+ for (const [k, v] of Object.entries(h)) {
76
+ if (typeof v === "string") out[String(k).toLowerCase()] = v;
77
+ else if (Array.isArray(v)) out[String(k).toLowerCase()] = v.join(", ");
78
+ }
79
+ }
80
+ return out;
81
+ };
82
+
83
+ /** 接收缓冲:把收到的分片变成一个带反压的 ReadableStream;读走一片才归还一片的额度。 */
84
+ class Inbound {
85
+ constructor(onConsumed, onCancel) {
86
+ this.queue = [];
87
+ this.ended = false;
88
+ this.error = null;
89
+ this.wake = null;
90
+ this.stream = new ReadableStream(
91
+ {
92
+ pull: async (controller) => {
93
+ for (;;) {
94
+ if (this.error) return controller.error(this.error);
95
+ if (this.queue.length > 0) {
96
+ const chunk = this.queue.shift();
97
+ controller.enqueue(chunk);
98
+ onConsumed(chunk.length);
99
+ return;
100
+ }
101
+ if (this.ended) return controller.close();
102
+ await new Promise((resolve) => (this.wake = resolve));
103
+ }
104
+ },
105
+ cancel: () => {
106
+ this.queue = [];
107
+ this.ended = true;
108
+ onCancel?.(); // 读者放弃(例如 SSE 连接被关闭)→ 通知对端停止,别继续发
109
+ },
110
+ },
111
+ { highWaterMark: 0 },
112
+ );
113
+ }
114
+ push(chunk) {
115
+ this.queue.push(chunk);
116
+ this.#poke();
117
+ }
118
+ end() {
119
+ this.ended = true;
120
+ this.#poke();
121
+ }
122
+ fail(err) {
123
+ this.error = err;
124
+ this.#poke();
125
+ }
126
+ #poke() {
127
+ const w = this.wake;
128
+ this.wake = null;
129
+ w?.();
130
+ }
131
+ }
132
+
133
+ class StreamState {
134
+ constructor(id, session) {
135
+ this.id = id;
136
+ this.session = session;
137
+ this.sendWindow = session.window;
138
+ this.credits = []; // 等额度的发送方
139
+ this.recvOutstanding = 0; // 已收到、应用还没读走的字节
140
+ this.inbound = new Inbound(
141
+ (n) => {
142
+ this.recvOutstanding -= n;
143
+ if (!this.closed && n > 0) session._sendFrame(T.WINDOW, id, u32(n));
144
+ },
145
+ () => this.reset(RST.CANCEL),
146
+ );
147
+ this.localEnded = false; // 我方向已发 END
148
+ this.remoteEnded = false;
149
+ this.closed = false;
150
+ this.abort = new AbortController();
151
+ }
152
+ /** 发送 DATA:切片、等额度。 */
153
+ async write(chunk) {
154
+ const bytes = toBytes(chunk);
155
+ for (let off = 0; off < bytes.length; ) {
156
+ if (this.closed) throw new MuxError("stream closed", RST.CANCEL);
157
+ const room = Math.min(this.sendWindow, MAX_FRAME_PAYLOAD, bytes.length - off);
158
+ if (room <= 0) {
159
+ await new Promise((resolve) => this.credits.push(resolve));
160
+ continue;
161
+ }
162
+ this.sendWindow -= room;
163
+ this.session._sendFrame(T.DATA, this.id, bytes.subarray(off, off + room));
164
+ off += room;
165
+ }
166
+ }
167
+ end() {
168
+ if (this.localEnded || this.closed) return;
169
+ this.localEnded = true;
170
+ this.session._sendFrame(T.END, this.id);
171
+ this.session._maybeRetire(this);
172
+ }
173
+ addCredit(n) {
174
+ this.sendWindow += n;
175
+ const waiting = this.credits.splice(0);
176
+ for (const w of waiting) w();
177
+ }
178
+ /** 本地中止:通知对端并释放。 */
179
+ reset(code = RST.CANCEL) {
180
+ if (this.closed) return;
181
+ this.session._sendFrame(T.RST, this.id, u16(code));
182
+ this.teardown(new MuxError("reset", code));
183
+ }
184
+ /** err 为空 = 双方都正常结束:不能让还没读完的正文报错,也不是「被取消」。 */
185
+ teardown(err) {
186
+ if (this.closed) return;
187
+ this.closed = true;
188
+ if (err) {
189
+ this.onHeadFail?.(err); // 响应头还没到就被取消 / 重置:request() 必须结束,不能永远挂着(已 resolve 时无副作用)
190
+ this.inbound.fail(err);
191
+ this.abort.abort(err);
192
+ }
193
+ for (const w of this.credits.splice(0)) w();
194
+ this.session.streams.delete(this.id);
195
+ }
196
+ }
197
+
198
+ export class MuxSession {
199
+ /**
200
+ * @param {{send:(b:Uint8Array)=>void, role:'client'|'server', onRequest?:(s:object)=>unknown,
201
+ * maxStreams?:number, window?:number}} opts
202
+ */
203
+ constructor({ send, role, onRequest, maxStreams = 32, window = INITIAL_WINDOW }) {
204
+ if (role !== "client" && role !== "server") throw new Error("role");
205
+ this.send = send;
206
+ this.role = role;
207
+ this.onRequest = onRequest;
208
+ this.maxStreams = maxStreams;
209
+ this.window = window;
210
+ this.streams = new Map();
211
+ this.nextId = 1;
212
+ this.closed = false;
213
+ this.pings = new Map();
214
+ }
215
+
216
+ _sendFrame(type, streamId, payload) {
217
+ if (this.closed) return;
218
+ this.send(encodeFrame(type, streamId, payload));
219
+ }
220
+ _maybeRetire(s) {
221
+ if (s.localEnded && s.remoteEnded) s.teardown(null);
222
+ }
223
+
224
+ /** 客户端:发起一条请求。返回 { status, headers, body: ReadableStream }。 */
225
+ async request({ method = "GET", path, headers = {}, body, signal }) {
226
+ if (this.role !== "client") throw new Error("only the client opens streams");
227
+ if (this.closed) throw new MuxError("session closed", RST.CANCEL);
228
+ if (this.streams.size >= this.maxStreams) throw new MuxError("too many streams", RST.TOO_MANY);
229
+ const id = this.nextId;
230
+ this.nextId += 2;
231
+ const s = new StreamState(id, this);
232
+ this.streams.set(id, s);
233
+ const head = new Promise((resolve, reject) => {
234
+ s.onHead = resolve;
235
+ s.onHeadFail = reject;
236
+ });
237
+ head.catch(() => {}); // 避免未处理拒绝:真正的调用方会 await 它
238
+ const open = enc.encode(JSON.stringify({ m: method, p: path, h: cleanHeaders(headers) }));
239
+ if (open.length > MAX_HEAD_BYTES) {
240
+ s.teardown(new MuxError("head too large"));
241
+ throw new MuxError("head too large");
242
+ }
243
+ this._sendFrame(T.OPEN, id, open);
244
+ signal?.addEventListener("abort", () => s.reset(RST.CANCEL), { once: true });
245
+ if (signal?.aborted) s.reset(RST.CANCEL);
246
+
247
+ // 请求正文在后台发送(受流控);失败 → 中止这条流
248
+ (async () => {
249
+ try {
250
+ if (body != null) {
251
+ if (typeof body === "string" || body instanceof Uint8Array) await s.write(body);
252
+ else if (typeof body[Symbol.asyncIterator] === "function") for await (const c of body) await s.write(c);
253
+ else if (typeof body.getReader === "function") {
254
+ const r = body.getReader();
255
+ for (;;) {
256
+ const { value, done } = await r.read();
257
+ if (done) break;
258
+ await s.write(value);
259
+ }
260
+ }
261
+ }
262
+ s.end();
263
+ } catch {
264
+ s.reset(RST.CANCEL);
265
+ }
266
+ })();
267
+
268
+ const res = await head;
269
+ return { status: res.s, headers: cleanHeaders(res.h), body: s.inbound.stream, cancel: () => s.reset(RST.CANCEL) };
270
+ }
271
+
272
+ /** 往对端发 PING,返回往返毫秒。 */
273
+ ping(timeoutMs = 10_000) {
274
+ const nonce = (this.nextId + Math.floor(Math.random() * 1e9)) >>> 0;
275
+ return new Promise((resolve, reject) => {
276
+ const t0 = Date.now();
277
+ const timer = setTimeout(() => {
278
+ this.pings.delete(nonce);
279
+ reject(new MuxError("ping timeout", RST.TIMEOUT));
280
+ }, timeoutMs);
281
+ timer.unref?.();
282
+ this.pings.set(nonce, {
283
+ ok: () => {
284
+ clearTimeout(timer);
285
+ resolve(Date.now() - t0);
286
+ },
287
+ fail: (err) => {
288
+ clearTimeout(timer);
289
+ reject(err);
290
+ },
291
+ });
292
+ this._sendFrame(T.PING, 0, u32(nonce));
293
+ });
294
+ }
295
+
296
+ /** 收进一帧明文。协议错误抛 MuxError——调用方应当关闭整个会话(对端有 bug 或在攻击)。 */
297
+ receive(bytes) {
298
+ if (this.closed) return;
299
+ const { type, streamId, payload } = decodeFrame(bytes);
300
+ switch (type) {
301
+ case T.PING:
302
+ return this._sendFrame(T.PONG, 0, payload);
303
+ case T.PONG: {
304
+ const n = readU32(payload);
305
+ const p = n === null ? undefined : this.pings.get(n);
306
+ if (p) {
307
+ this.pings.delete(n);
308
+ p.ok();
309
+ }
310
+ return;
311
+ }
312
+ case T.OPEN:
313
+ return this.#onOpen(streamId, payload);
314
+ case T.RESP:
315
+ return this.#onResp(streamId, payload);
316
+ case T.DATA:
317
+ return this.#onData(streamId, payload);
318
+ case T.END:
319
+ return this.#onEnd(streamId);
320
+ case T.WINDOW: {
321
+ const n = readU32(payload);
322
+ if (n === null || n === 0) throw new MuxError("bad window");
323
+ this.streams.get(streamId)?.addCredit(n);
324
+ return;
325
+ }
326
+ case T.RST: {
327
+ const s = this.streams.get(streamId);
328
+ if (!s) return;
329
+ const code = payload.length === 2 ? new DataView(payload.buffer, payload.byteOffset, 2).getUint16(0, false) : RST.CANCEL;
330
+ const err = new MuxError("reset by peer", code);
331
+ s.onHeadFail?.(err);
332
+ s.teardown(err);
333
+ return;
334
+ }
335
+ default:
336
+ throw new MuxError(`unknown frame type ${type}`);
337
+ }
338
+ }
339
+
340
+ #onOpen(id, payload) {
341
+ if (this.role !== "server") throw new MuxError("OPEN sent to a client");
342
+ if (id === 0 || id % 2 === 0) throw new MuxError("bad stream id");
343
+ if (this.streams.has(id)) throw new MuxError("duplicate stream id");
344
+ if (this.streams.size >= this.maxStreams) return this._sendFrame(T.RST, id, u16(RST.TOO_MANY));
345
+ const head = parseHead(payload);
346
+ if (typeof head.m !== "string" || typeof head.p !== "string") throw new MuxError("bad request head");
347
+ const s = new StreamState(id, this);
348
+ this.streams.set(id, s);
349
+ const stream = {
350
+ id,
351
+ method: head.m,
352
+ path: head.p,
353
+ headers: cleanHeaders(head.h),
354
+ body: s.inbound.stream,
355
+ signal: s.abort.signal,
356
+ respond: (status, headers = {}) => {
357
+ if (s.closed) throw new MuxError("stream closed", RST.CANCEL);
358
+ if (s.responded) throw new Error("already responded");
359
+ s.responded = true;
360
+ this._sendFrame(T.RESP, id, enc.encode(JSON.stringify({ s: status, h: cleanHeaders(headers) })));
361
+ },
362
+ write: (chunk) => s.write(chunk),
363
+ end: () => s.end(),
364
+ reset: (code = RST.INTERNAL) => s.reset(code),
365
+ };
366
+ Promise.resolve()
367
+ .then(() => this.onRequest?.(stream))
368
+ .catch(() => s.reset(RST.INTERNAL));
369
+ if (!this.onRequest) s.reset(RST.REFUSED);
370
+ }
371
+ #onResp(id, payload) {
372
+ const s = this.streams.get(id);
373
+ if (!s || !s.onHead) throw new MuxError("unexpected RESP");
374
+ const head = parseHead(payload);
375
+ if (!Number.isInteger(head.s) || head.s < 100 || head.s > 599) throw new MuxError("bad status");
376
+ const cb = s.onHead;
377
+ s.onHead = null;
378
+ cb(head);
379
+ }
380
+ #onData(id, payload) {
381
+ const s = this.streams.get(id);
382
+ if (!s) return; // 对端在我们已中止之后还在发:忽略
383
+ if (s.remoteEnded) throw new MuxError("DATA after END");
384
+ s.recvOutstanding += payload.length;
385
+ if (s.recvOutstanding > this.window) {
386
+ s.reset(RST.FLOW);
387
+ return;
388
+ }
389
+ s.inbound.push(payload.slice()); // 拷贝:底层 buffer 会被复用
390
+ }
391
+ #onEnd(id) {
392
+ const s = this.streams.get(id);
393
+ if (!s) return;
394
+ s.remoteEnded = true;
395
+ s.inbound.end();
396
+ this._maybeRetire(s);
397
+ }
398
+
399
+ /** 关闭整个会话:所有进行中的流以错误结束。幂等。 */
400
+ close(reason = "closed") {
401
+ if (this.closed) return;
402
+ this.closed = true;
403
+ const err = new MuxError(reason, RST.CANCEL);
404
+ for (const s of [...this.streams.values()]) {
405
+ s.onHeadFail?.(err);
406
+ s.teardown(err);
407
+ }
408
+ for (const p of this.pings.values()) p.fail(err);
409
+ this.pings.clear();
410
+ }
411
+ }
@@ -0,0 +1,178 @@
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
+ */
17
+ import { EMPTY, aeadDecrypt, aeadEncrypt, concat, equalBytes, hkdf, sha256, x25519Dh, x25519Generate, x25519PublicOf } from "./crypto.js";
18
+
19
+ export const PROTOCOL_NAME = "Noise_IK_25519_ChaChaPoly_SHA256";
20
+ export const MAX_MESSAGE = 65535;
21
+ const DHLEN = 32;
22
+ const TAGLEN = 16;
23
+
24
+ /** 传输阶段的单向加密状态。n 是 64 位计数器;Noise 规定 2^64-1 保留给 rekey,这里直接当上限。 */
25
+ export class CipherState {
26
+ constructor(key) {
27
+ this.k = key ?? null;
28
+ this.n = 0n;
29
+ }
30
+ hasKey() {
31
+ return this.k !== null;
32
+ }
33
+ encrypt(plaintext, ad = EMPTY) {
34
+ if (this.k === null) return plaintext;
35
+ if (this.n >= 0xffffffffffffffffn) throw new Error("nonce exhausted");
36
+ const out = aeadEncrypt(this.k, this.n, ad, plaintext);
37
+ this.n += 1n;
38
+ return out;
39
+ }
40
+ decrypt(ciphertext, ad = EMPTY) {
41
+ if (this.k === null) return ciphertext;
42
+ if (this.n >= 0xffffffffffffffffn) throw new Error("nonce exhausted");
43
+ const out = aeadDecrypt(this.k, this.n, ad, ciphertext); // 认证失败抛错,n 不前进
44
+ this.n += 1n;
45
+ return out;
46
+ }
47
+ }
48
+
49
+ class SymmetricState {
50
+ constructor(protocolName) {
51
+ const name = new TextEncoder().encode(protocolName);
52
+ if (name.length <= 32) {
53
+ const h = new Uint8Array(32);
54
+ h.set(name);
55
+ this.h = h;
56
+ } else {
57
+ this.h = sha256(name);
58
+ }
59
+ this.ck = this.h;
60
+ this.cipher = new CipherState(null);
61
+ }
62
+ mixHash(data) {
63
+ this.h = sha256(this.h, data);
64
+ }
65
+ mixKey(ikm) {
66
+ const [ck, tempK] = hkdf(this.ck, ikm, 2);
67
+ this.ck = ck;
68
+ this.cipher = new CipherState(tempK);
69
+ }
70
+ encryptAndHash(plaintext) {
71
+ const ct = this.cipher.encrypt(plaintext, this.h);
72
+ this.mixHash(ct);
73
+ return ct;
74
+ }
75
+ decryptAndHash(ciphertext) {
76
+ const pt = this.cipher.decrypt(ciphertext, this.h);
77
+ this.mixHash(ciphertext);
78
+ return pt;
79
+ }
80
+ split() {
81
+ const [k1, k2] = hkdf(this.ck, EMPTY, 2);
82
+ return [new CipherState(k1), new CipherState(k2)];
83
+ }
84
+ }
85
+
86
+ const checkKeyPair = (kp, name) => {
87
+ if (!kp || kp.priv?.length !== 32 || kp.pub?.length !== 32) throw new Error(`${name} must be an x25519 keypair`);
88
+ };
89
+
90
+ /**
91
+ * 发起方(手机)。`rs` 是电脑的静态公钥(来自二维码)。
92
+ * `ephemeral` 仅供测试注入固定临时密钥(生成固定向量);生产里不要传。
93
+ */
94
+ export class NoiseInitiator {
95
+ constructor({ s, rs, prologue = EMPTY, ephemeral } = {}) {
96
+ checkKeyPair(s, "s");
97
+ if (rs?.length !== 32) throw new Error("rs must be 32 bytes");
98
+ this.s = s;
99
+ this.rs = rs;
100
+ this.e = ephemeral ?? null;
101
+ this.re = null;
102
+ this.sym = new SymmetricState(PROTOCOL_NAME);
103
+ this.sym.mixHash(prologue);
104
+ this.sym.mixHash(rs); // 预消息 `<- s`
105
+ this.state = "start";
106
+ }
107
+ /** -> e, es, s, ss,附带加密负载。 */
108
+ writeMessage1(payload = EMPTY) {
109
+ if (this.state !== "start") throw new Error("bad state");
110
+ this.e = this.e ?? x25519Generate();
111
+ const parts = [this.e.pub];
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
116
+ parts.push(this.sym.encryptAndHash(payload));
117
+ const msg = concat(...parts);
118
+ if (msg.length > MAX_MESSAGE) throw new Error("message too large");
119
+ this.state = "sent1";
120
+ return msg;
121
+ }
122
+ /** <- e, ee, se;成功后返回 { payload, send, recv, handshakeHash }。 */
123
+ readMessage2(msg) {
124
+ if (this.state !== "sent1") throw new Error("bad state");
125
+ if (msg.length < DHLEN + TAGLEN || msg.length > MAX_MESSAGE) throw new Error("bad handshake message");
126
+ this.re = msg.subarray(0, DHLEN);
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
130
+ const payload = this.sym.decryptAndHash(msg.subarray(DHLEN));
131
+ const [c1, c2] = this.sym.split();
132
+ this.state = "done";
133
+ return { payload, send: c1, recv: c2, handshakeHash: this.sym.h };
134
+ }
135
+ }
136
+
137
+ /** 响应方(电脑)。用 `s` 解密;对端静态公钥由消息 1 带来,调用方据此决定放不放行。 */
138
+ export class NoiseResponder {
139
+ constructor({ s, prologue = EMPTY, ephemeral } = {}) {
140
+ checkKeyPair(s, "s");
141
+ this.s = s;
142
+ this.e = ephemeral ?? null;
143
+ this.re = null;
144
+ this.rs = null;
145
+ this.sym = new SymmetricState(PROTOCOL_NAME);
146
+ this.sym.mixHash(prologue);
147
+ this.sym.mixHash(s.pub); // 预消息 `<- s`
148
+ this.state = "start";
149
+ }
150
+ /** 解消息 1。返回 { payload, rs }:rs 是发起方(手机)的静态公钥,**必须由调用方核对授权**。 */
151
+ readMessage1(msg) {
152
+ if (this.state !== "start") throw new Error("bad state");
153
+ if (msg.length < DHLEN + DHLEN + TAGLEN + TAGLEN || msg.length > MAX_MESSAGE) throw new Error("bad handshake message");
154
+ this.re = msg.subarray(0, DHLEN);
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
159
+ const payload = this.sym.decryptAndHash(msg.subarray(DHLEN + DHLEN + TAGLEN));
160
+ this.state = "read1";
161
+ return { payload, rs: this.rs };
162
+ }
163
+ /** <- e, ee, se,附带加密负载;返回 { msg, send, recv, handshakeHash }。 */
164
+ writeMessage2(payload = EMPTY) {
165
+ if (this.state !== "read1") throw new Error("bad state");
166
+ this.e = this.e ?? x25519Generate();
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
170
+ const msg = concat(this.e.pub, this.sym.encryptAndHash(payload));
171
+ const [c1, c2] = this.sym.split();
172
+ this.state = "done";
173
+ // 响应方:c1 用于接收(发起方→响应方),c2 用于发送
174
+ return { msg, send: c2, recv: c1, handshakeHash: this.sym.h };
175
+ }
176
+ }
177
+
178
+ export { x25519Generate as generateStaticKey, x25519PublicOf as publicKeyOf, equalBytes };