@dsh-mobile/mobile-remote 3.3.1 → 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 (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 +232 -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 +6 -13
@@ -1,21 +1,22 @@
1
- /**
2
- * 手机端协议的参考实现(Node)。
3
- *
4
- * 用途:①测试里扮演手机,端到端验证中继 / 连接器 / 插件;②给 Flutter 端当「可执行的规格」——
5
- * Dart 实现必须与它逐字节互通(见 test/vectors/ 里的确定性转录)。
6
- *
7
- * 流程:连中继(访客身份)→ 等房主在线 → Noise 发起方握手(消息 1 里带上设备名与一次性配对码)→
8
- * 读消息 2 → 之后所有流量都是 Noise 传输消息,里面跑多路复用的 HTTP。
9
- *
10
- * 电脑闪断后在原连接上续用(`resume: true`,访客协议 v2,见 relay/hub.js「访客协议版本」)
11
- * 连接地址带 `?v=2`,告诉中继「我认得 host-down,也会在原连接上重新握手」。之后:
12
- * host-down → 这条 Noise 会话作废:在途请求立刻失败,停止发送,等中继的下一句话;
13
- * host-up → 用同一把设备密钥在**同一条连接**上重新握手(不带配对码——它已经用掉了),
14
- * 握手完成后换上新的密钥与新的多路复用会话,`phone.resumes` 加一;
15
- * 4503 → 电脑没在宽限期内回来,连接关闭,和以前一样重新连接。
16
- * 不带 `resume`(缺省)就是所有已发布旧版 App 的行为:收到 host-up 只把会话作废,由上层另开连接。
17
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
18
  import { MuxSession } from "./mux.js";
19
+ import { decodeSignal, encodeSignal } from "./signal.js";
19
20
  import { NoiseInitiator } from "./noise.js";
20
21
 
21
22
  const enc = new TextEncoder();
@@ -27,17 +28,33 @@ export class PhoneSession {
27
28
  this.closeCode = null;
28
29
  this.closeReason = "";
29
30
  this.closed = new Promise((resolve) => (this._resolveClosed = resolve));
30
- /** open = 会话可用;down = 电脑闪断、等它回来;handshake = 正在(重新)握手。 */
31
+
31
32
  this.state = "handshake";
32
- /** 在原连接上重新握手成功的次数。 */
33
+
33
34
  this.resumes = 0;
34
35
  this._waiters = [];
36
+
37
+ this.signals = [];
38
+ this.onSignal = null;
39
+ this._signalId = 0;
40
+ }
41
+
42
+ signal(msg) {
43
+ if (!this.mux) throw new Error("not open");
44
+ this.mux.sendSignal(encodeSignal({ ...msg, t: "sig", id: msg.id ?? this._signalId++ }));
45
+ if (msg.k === "bye") this.close(1000, "signal done");
46
+ }
47
+ _onSignal(bytes) {
48
+ const msg = decodeSignal(bytes);
49
+ this.signals.push(msg);
50
+ this.onSignal?.(msg);
51
+ if (msg.k === "bye") this.close(1000, "signal done");
35
52
  }
36
53
  request(req) {
37
54
  if (!this.mux) return Promise.reject(new Error(this.state === "open" ? "session closed" : "computer is reconnecting"));
38
55
  return this.mux.request(req);
39
56
  }
40
- /** 等会话(重新)可用。连接已关闭、或 `timeoutMs` 内没等到,则拒绝。 */
57
+
41
58
  whenOpen(timeoutMs = 10_000) {
42
59
  if (this.closeCode !== null) return Promise.reject(new Error(`closed (${this.closeCode})`));
43
60
  if (this.state === "open") return Promise.resolve(this);
@@ -62,7 +79,7 @@ export class PhoneSession {
62
79
  try {
63
80
  this.ws.close(code, reason);
64
81
  } catch {
65
- /* 已断开 */
82
+
66
83
  }
67
84
  }
68
85
  _shutdown(code, reason) {
@@ -80,21 +97,26 @@ export class PhoneSession {
80
97
  }
81
98
  }
82
99
 
83
- /**
84
- * @param {{ relayUrl:string, room:string, pcPub:Uint8Array, device:{priv:Uint8Array,pub:Uint8Array},
85
- * name?:string, otp?:string, WebSocketImpl?:Function, timeoutMs?:number, resume?:boolean, lan?:boolean }} o
86
- */
87
- export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000, resume = false, lan = false }) {
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000, resume = false, lan = false, signal = false, mode }) {
88
109
  return new Promise((resolve, reject) => {
89
110
  const phone = new PhoneSession();
90
- // lan:电脑 LAN 桥上的局域网加密通道(T-25),路径不带房间号(房间号只在 Noise 的序言里)
111
+
91
112
  const base = relayUrl.replace(/\/+$/, "");
92
- const ws = new WebSocketImpl(lan ? `${base}/v1/lan` : `${base}/v1/guest/${room}${resume ? "?v=2" : ""}`);
113
+ const query = [resume || signal || mode === "standby" ? "v=2" : "", signal ? "mode=signal" : ""].filter(Boolean).join("&");
114
+ const ws = new WebSocketImpl(lan ? `${base}/v1/lan` : `${base}/v1/guest/${room}${query ? `?${query}` : ""}`);
93
115
  ws.binaryType = "arraybuffer";
94
116
  phone.ws = ws;
95
117
  let noise = null;
96
- let stage = "relay"; // relay → handshake → open(resume 时还有:→ down → handshake → open …)
97
- let opened = false; // 第一次握手完成过了吗(connectPhone 的 Promise 只在那时兑现)
118
+ let stage = "relay";
119
+ let opened = false;
98
120
  let cipherOut = null;
99
121
  let cipherIn = null;
100
122
  const fail = (err) => {
@@ -103,25 +125,25 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
103
125
  try {
104
126
  ws.close();
105
127
  } catch {
106
- /* 已断开 */
128
+
107
129
  }
108
130
  reject(err instanceof Error ? err : new Error(String(err)));
109
131
  };
110
132
  const timer = setTimeout(() => fail(new Error(`connect timeout in stage ${stage}`)), timeoutMs);
111
133
 
112
- /** 握手总是全新的一次:新的临时密钥、新的握手哈希。重握时不带配对码(它是一次性的,已经用掉)。 */
134
+
113
135
  const startHandshake = () => {
114
136
  noise = new NoiseInitiator({ s: device, rs: pcPub, prologue: enc.encode(`DSH-RELAY/1|${room}`) });
115
137
  stage = "handshake";
116
138
  phone._setState("handshake");
117
- ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(otp && !opened ? { otp } : {}) }))));
139
+ ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(signal ? { mode: "signal" } : mode === "standby" ? { mode } : {}), ...(otp && !opened && !signal && mode !== "standby" ? { otp } : {}) }))));
118
140
  if (opened) {
119
141
  clearTimeout(phone._rehandshakeTimer);
120
142
  phone._rehandshakeTimer = setTimeout(() => phone.close(4408, "re-handshake timeout"), timeoutMs);
121
143
  phone._rehandshakeTimer.unref?.();
122
144
  }
123
145
  };
124
- /** 这条 Noise 会话作废:在途请求立刻失败,之后不再往这条会话里发任何东西。 */
146
+
125
147
  const suspend = () => {
126
148
  stage = "down";
127
149
  cipherOut = null;
@@ -142,8 +164,8 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
142
164
  }
143
165
  if (msg.t === "host-up") {
144
166
  if (stage === "relay") return startHandshake();
145
- // 电脑重新上线(重启 / 换连接):我们的 Noise 会话已经无处可去
146
- if (!resume) return phone._shutdown(4503, "host restarted"); // 旧版:上层重新连接
167
+
168
+ if (!resume) return phone._shutdown(4503, "host restarted");
147
169
  suspend();
148
170
  return startHandshake();
149
171
  }
@@ -156,24 +178,24 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
156
178
  cipherIn = done.recv;
157
179
  phone.info = JSON.parse(dec.decode(done.payload));
158
180
  const out = cipherOut;
159
- phone.mux = new MuxSession({ role: "client", send: (frame) => ws.send(out.encrypt(frame)) });
181
+ phone.mux = new MuxSession({ role: "client", send: (frame) => ws.send(out.encrypt(frame)), ...(signal ? { onSignal: (b) => phone._onSignal(b) } : {}) });
160
182
  stage = "open";
161
183
  if (opened) {
162
184
  clearTimeout(phone._rehandshakeTimer);
163
185
  phone.resumes++;
164
- // 电脑要求握手后限时内收到一条能解密的数据(防重放);不能指望上层恰好马上发请求
186
+
165
187
  phone.mux.ping().catch(() => {});
166
188
  return phone._setState("open");
167
189
  }
168
190
  opened = true;
169
- phone.pinger = setInterval(() => { try { ws.send(JSON.stringify({ t: "ping" })); } catch { /* 连接正在断开 */ } }, 20_000);
191
+ phone.pinger = setInterval(() => { try { ws.send(JSON.stringify({ t: "ping" })); } catch { } }, 20_000);
170
192
  phone.pinger.unref?.();
171
193
  clearTimeout(timer);
172
194
  phone._setState("open");
173
195
  return resolve(phone);
174
196
  }
175
197
  if (stage === "open") phone.mux.receive(cipherIn.decrypt(bytes));
176
- // stage === "down":作废会话的迟到帧,丢弃
198
+
177
199
  } catch (err) {
178
200
  if (!opened) return fail(err);
179
201
  phone.close(4000, "protocol error");
@@ -1,16 +1,16 @@
1
- /**
2
- * 把隧道里来的请求「回放」给插件自己的 HTTP 服务(回环),再把响应流式送回去。
3
- *
4
- * 这是整个中继方案里最敏感的一步:回放的请求从 127.0.0.1 发出,和「电脑桌面 GUI」的请求长得一样。
5
- * 如果不加防护,一台已配对的手机就能拿到只给桌面看的端点(比如 /qr-config 会返回局域网口令)。三层防护:
6
- *
7
- * ① 路径白名单:只放行 `${basePath}/api/…`,并明确拒绝 qr-config / qr.png / relay 管理 / dev 端点;
8
- * 任何会被 URL 规范化改变的路径(`..`、`//`、`%2f`、反斜杠)直接拒绝,防止绕过白名单;
9
- * ② 清洗请求头:丢掉手机自带的口令 / cookie / 代理头 / 浏览器来源头;然后写入我们自己的头——
10
- * 有效来源 IP = `relay:<设备>`(不是回环,桌面闸门因此判为非本机)、`via`(桌面闸门看到代理头即拒)、
11
- * 以及只存在于本进程内存的随机令牌(证明「这个请求确实是连接器发的」,插件据此免口令放行);
12
- * ③ 插件自己的闸门(localDesktopGate)仍然独立生效,前两层任何一层出错它都兜底。
13
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
14
  import http from "node:http";
15
15
  import { Readable } from "node:stream";
16
16
 
@@ -24,27 +24,27 @@ const DROP_REQUEST = new Set([
24
24
  const DROP_RESPONSE = new Set(["connection", "keep-alive", "transfer-encoding", "set-cookie", "proxy-authenticate", "upgrade"]);
25
25
  const DENIED = [/^\/api\/qr-config(\/|$)/, /^\/api\/qr\.png(\/|$)/, /^\/api\/relay(\/|$)/, /^\/api\/dev(\/|$)/];
26
26
 
27
- /** 返回 null 表示放行;否则返回拒绝原因。导出以便直接测试。 */
27
+
28
28
  export function checkPath(rawPath, basePath) {
29
29
  if (typeof rawPath !== "string" || rawPath === "" || rawPath.length > 4096) return "bad-path";
30
30
  if (/[\\\u0000-\u001f\u007f]/.test(rawPath)) return "bad-path";
31
31
  const q = rawPath.indexOf("?");
32
32
  const pathname = q < 0 ? rawPath : rawPath.slice(0, q);
33
- if (/%(2f|5c|2e|00)/i.test(pathname)) return "bad-path"; // 编码的 / \ . NUL 不会出现在合法路由里
33
+ if (/%(2f|5c|2e|00)/i.test(pathname)) return "bad-path";
34
34
  let normalized;
35
35
  try {
36
36
  normalized = new URL(rawPath, "http://relay.invalid").pathname;
37
37
  } catch {
38
38
  return "bad-path";
39
39
  }
40
- if (normalized !== pathname) return "bad-path"; // 规范化改变了路径(.. 或 //)= 试图绕过
40
+ if (normalized !== pathname) return "bad-path";
41
41
  if (!pathname.startsWith(`${basePath}/api/`)) return "path-not-allowed";
42
42
  const rest = pathname.slice(basePath.length);
43
43
  if (DENIED.some((re) => re.test(rest))) return "path-not-allowed";
44
44
  return null;
45
45
  }
46
46
 
47
- /** `check` 仅供测试:换成「全部放行」来验证第二、三层防护在白名单失守时仍然成立。生产不传。 */
47
+
48
48
  export function createHttpReplayer({ port, basePath, relayToken, ipToken, peerHeader, ipHeader, maxBodyBytes = 64 * 1024 * 1024, check = checkPath }) {
49
49
  return async function serve(stream, device) {
50
50
  let responded = false;
@@ -65,7 +65,7 @@ export function createHttpReplayer({ port, basePath, relayToken, ipToken, peerHe
65
65
  headers[peerHeader] = `${relayToken}|${device.id}`;
66
66
  headers[ipHeader] = `${ipToken}|relay:${device.id}`;
67
67
  headers.via = "1.1 dsh-relay";
68
- headers["accept-encoding"] = "identity"; // 隧道里不需要再压缩;SSE 更不能被压缩缓冲
68
+ headers["accept-encoding"] = "identity";
69
69
 
70
70
  const upstream = http.request({ host: "127.0.0.1", port: port(), method: stream.method, path: stream.path, headers, agent: false });
71
71
  stream.signal.addEventListener("abort", () => upstream.destroy(), { once: true });
@@ -90,11 +90,11 @@ export function createHttpReplayer({ port, basePath, relayToken, ipToken, peerHe
90
90
  const out = {};
91
91
  for (const [k, v] of Object.entries(up.headers)) if (!DROP_RESPONSE.has(k) && v !== undefined) out[k] = Array.isArray(v) ? v.join(", ") : v;
92
92
  stream.respond(up.statusCode ?? 502, out);
93
- for await (const chunk of up) await stream.write(chunk); // 受流控:手机读得慢,这里就慢
93
+ for await (const chunk of up) await stream.write(chunk);
94
94
  stream.end();
95
95
  } catch {
96
- up.destroy(); // 手机取消了(SSE 关闭)或隧道断了:别再拉上游
97
- stream.reset(5); // 上游也可能截断响应;必须让手机读流失败,不能一直等 END
96
+ up.destroy();
97
+ stream.reset(5);
98
98
  }
99
99
  });
100
100
  upstream.on("error", () => {
@@ -0,0 +1,69 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+ import { MuxError } from "./mux.js";
22
+
23
+ export const SIGNAL_KINDS = Object.freeze(["offer", "answer", "ice", "bye"]);
24
+ export const SIGNAL_BUDGET = Object.freeze({ frames: 48, frameBytes: 4 * 1024, lifetimeMs: 90_000, perHour: 8 });
25
+
26
+ export const SIGNAL_OVERHEAD = 16 + 5;
27
+
28
+ export const MAX_SIGNAL_JSON = SIGNAL_BUDGET.frameBytes - SIGNAL_OVERHEAD;
29
+
30
+ export const CLOSE_SIGNAL_BUDGET = 4431;
31
+
32
+ const enc = new TextEncoder();
33
+ const dec = new TextDecoder();
34
+
35
+
36
+ export function normalizeSignal(msg) {
37
+ if (!msg || typeof msg !== "object" || msg.t !== "sig") throw new MuxError("bad signal message");
38
+ if (!SIGNAL_KINDS.includes(msg.k)) throw new MuxError("bad signal kind");
39
+ if (!Number.isInteger(msg.id) || msg.id < 0 || msg.id > 0x7fffffff) throw new MuxError("bad signal id");
40
+ const out = { t: "sig", k: msg.k, id: msg.id };
41
+ if (msg.k === "offer" || msg.k === "answer") {
42
+ if (typeof msg.sdp !== "string" || msg.sdp.length === 0) throw new MuxError("signal without sdp");
43
+ out.sdp = msg.sdp;
44
+ }
45
+ if (msg.k === "ice") {
46
+ if (msg.cand !== null && (typeof msg.cand !== "object" || Array.isArray(msg.cand))) throw new MuxError("bad ice candidate");
47
+ out.cand = msg.cand ?? null;
48
+ }
49
+ return out;
50
+ }
51
+
52
+
53
+ export function encodeSignal(msg) {
54
+ const bytes = enc.encode(JSON.stringify(normalizeSignal(msg)));
55
+ if (bytes.length > MAX_SIGNAL_JSON) throw new MuxError("signal message too large");
56
+ return bytes;
57
+ }
58
+
59
+
60
+ export function decodeSignal(bytes) {
61
+ if (bytes.length > MAX_SIGNAL_JSON) throw new MuxError("signal message too large");
62
+ let msg;
63
+ try {
64
+ msg = JSON.parse(dec.decode(bytes));
65
+ } catch {
66
+ throw new MuxError("bad signal json");
67
+ }
68
+ return normalizeSignal(msg);
69
+ }
@@ -1,44 +1,44 @@
1
- /**
2
- * 最小的 WebSocket 服务端(RFC 6455),只给局域网加密通道用(T-25)。
3
- *
4
- * 为什么自己写:插件除了 `qrcode` 不带任何运行时依赖,Node 只内置了 WebSocket **客户端**。这里需要的
5
- * 只是「HTTP Upgrade 之后收发整条消息」,加密与认证都在上面一层的 Noise 里,所以只实现协议本身:
6
- * · 握手:校验 Upgrade / Connection / Sec-WebSocket-Version: 13 / Sec-WebSocket-Key,回 101;
7
- * · 收:客户端帧必须带掩码;支持分片(续帧);ping 自动回 pong;close 回 close 后断开;
8
- * RSV 位、未知操作码、控制帧过长或分片 → 1002;消息超过 maxPayload → 1009;文本不是合法 UTF-8 → 1007;
9
- * · 发:不分片、不带掩码;send(string) 发文本帧,send(Uint8Array) 发二进制帧。
10
- * 不支持任何扩展(permessage-deflate 等)与子协议:握手时一概不回应,客户端就不会用。
11
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
12
  import { createHash } from "node:crypto";
13
13
 
14
14
  const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
15
15
  const OP = Object.freeze({ CONT: 0, TEXT: 1, BIN: 2, CLOSE: 8, PING: 9, PONG: 10 });
16
16
  const utf8 = new TextDecoder("utf-8", { fatal: true });
17
17
 
18
- /** 握手请求像不像一个 WebSocket 升级(不读请求体,只看头)。 */
18
+
19
19
  export function isWebSocketUpgrade(req) {
20
20
  const upgrade = String(req.headers.upgrade ?? "").toLowerCase();
21
21
  const connection = String(req.headers.connection ?? "").toLowerCase();
22
22
  return upgrade === "websocket" && connection.split(",").some((t) => t.trim() === "upgrade");
23
23
  }
24
24
 
25
- /** 拒绝一个升级请求:写一个最小的 HTTP 响应后断开。 */
25
+
26
26
  export function rejectUpgrade(socket, status, text) {
27
27
  try {
28
28
  socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
29
29
  } catch {
30
- /* 已断开 */
30
+
31
31
  }
32
32
  socket.destroy();
33
33
  }
34
34
 
35
- /**
36
- * 完成握手,返回一条连接;握手不合规则回 400 并返回 null。
37
- * @param {import("node:http").IncomingMessage} req
38
- * @param {import("node:net").Socket} socket
39
- * @param {Buffer} head 升级请求之后已经读到的字节(一般为空)
40
- * @param {{ maxPayload?: number }} [o]
41
- */
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
42
  export function acceptWebSocket(req, socket, head, { maxPayload = 1 << 20 } = {}) {
43
43
  const key = String(req.headers["sec-websocket-key"] ?? "");
44
44
  if (req.method !== "GET" || !isWebSocketUpgrade(req) || req.headers["sec-websocket-version"] !== "13" || !/^[A-Za-z0-9+/]{22}==$/.test(key)) {
@@ -55,18 +55,18 @@ export class ServerWebSocket {
55
55
  constructor(socket, head, maxPayload) {
56
56
  this.socket = socket;
57
57
  this.maxPayload = maxPayload;
58
- this.readyState = 1; // 0 connecting · 1 open · 2 closing · 3 closed
58
+ this.readyState = 1;
59
59
  this.closeCode = null;
60
60
  this.listeners = { message: [], close: [] };
61
61
  this.buf = head?.length ? Buffer.from(head) : Buffer.alloc(0);
62
- this.frag = null; // 正在拼的分片消息:{ op, parts, size }
62
+ this.frag = null;
63
63
  socket.on("data", (chunk) => this.#onData(chunk));
64
64
  socket.on("close", () => this.#finish(this.closeCode ?? 1006));
65
65
  socket.on("error", () => this.#finish(1006));
66
66
  if (this.buf.length) queueMicrotask(() => this.#parse());
67
67
  }
68
68
 
69
- /** `message` → (data: string | Uint8Array);`close` → (code: number)。 */
69
+
70
70
  on(type, fn) {
71
71
  this.listeners[type]?.push(fn);
72
72
  return this;
@@ -76,7 +76,7 @@ export class ServerWebSocket {
76
76
  try {
77
77
  fn(arg);
78
78
  } catch {
79
- /* 监听者的错误不影响连接 */
79
+
80
80
  }
81
81
  }
82
82
  }
@@ -88,7 +88,7 @@ export class ServerWebSocket {
88
88
  return this.#write(text ? OP.TEXT : OP.BIN, payload);
89
89
  }
90
90
 
91
- /** 发 close 帧并在对端回应(或 2 秒)后断开。 */
91
+
92
92
  close(code = 1000, reason = "") {
93
93
  if (this.readyState >= 2) return;
94
94
  this.readyState = 2;
@@ -102,7 +102,7 @@ export class ServerWebSocket {
102
102
  t.unref?.();
103
103
  }
104
104
 
105
- /** 立刻断开,不走关闭握手(对端在乱发东西时用)。 */
105
+
106
106
  terminate(code = 1006) {
107
107
  this.closeCode ??= code;
108
108
  this.socket.destroy();
@@ -153,7 +153,7 @@ export class ServerWebSocket {
153
153
  const masked = (b[1] & 0x80) !== 0;
154
154
  let len = b[1] & 0x7f;
155
155
  let off = 2;
156
- if (rsv !== 0 || !masked) return this.#fail(1002); // 没有协商任何扩展;客户端帧必须带掩码
156
+ if (rsv !== 0 || !masked) return this.#fail(1002);
157
157
  if (len === 126) {
158
158
  if (b.length < 4) return;
159
159
  len = b.readUInt16BE(2);
@@ -177,7 +177,7 @@ export class ServerWebSocket {
177
177
  }
178
178
  }
179
179
 
180
- /** 处理一帧;返回 false 表示连接已经结束,停止解析。 */
180
+
181
181
  #frame(fin, op, payload) {
182
182
  switch (op) {
183
183
  case OP.PING:
@@ -188,7 +188,7 @@ export class ServerWebSocket {
188
188
  case OP.CLOSE: {
189
189
  const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1005;
190
190
  if (this.readyState === 1) {
191
- // 对端先关:回一个 close 帧(带同样的码),然后断开
191
+
192
192
  this.readyState = 2;
193
193
  this.closeCode = code;
194
194
  const echo = payload.length >= 2 ? payload.subarray(0, 2) : Buffer.alloc(0);
@@ -200,7 +200,7 @@ export class ServerWebSocket {
200
200
  }
201
201
  case OP.TEXT:
202
202
  case OP.BIN:
203
- if (this.frag) return this.#fail(1002) ?? false; // 上一条分片消息还没结束
203
+ if (this.frag) return this.#fail(1002) ?? false;
204
204
  if (fin) return this.#deliver(op, payload);
205
205
  this.frag = { op, parts: [payload], size: payload.length };
206
206
  return true;
@@ -220,7 +220,7 @@ export class ServerWebSocket {
220
220
  }
221
221
 
222
222
  #deliver(op, payload) {
223
- if (this.readyState !== 1) return true; // 关闭中:后面的数据不再交出去
223
+ if (this.readyState !== 1) return true;
224
224
  if (op === OP.TEXT) {
225
225
  let text;
226
226
  try {
package/lib/reminders.js CHANGED
@@ -1,13 +1,13 @@
1
- /**
2
- * Reminders the user sets (T-32): the "promises and reminders coming due" material of the
3
- * proactive scheduler (plan §5.7). A small JSON file on this PC, `<state dir>/reminders.json`.
4
- *
5
- * Routes (under /m/api):
6
- * GET /reminders list, soonest first (done ones last)
7
- * POST /reminders add { text, dueAt (ms), sessionId? }
8
- * PATCH /reminders/:id { done: true | false }
9
- * DELETE /reminders/:id delete (for real: the file is rewritten without it)
10
- */
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
11
  import { randomUUID } from "node:crypto";
12
12
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
13
13
  import { join } from "node:path";
@@ -17,9 +17,9 @@ export const MAX_REMINDER_TEXT = 500;
17
17
  export const MAX_REMINDERS = 500;
18
18
  const YEAR_MS = 366 * 24 * 60 * 60_000;
19
19
 
20
- /**
21
- * @param {{dir: string, now?: () => number}} e
22
- */
20
+
21
+
22
+
23
23
  export function createReminderStore({ dir, now = () => Date.now() }) {
24
24
  const file = join(dir, "reminders.json");
25
25
  let cache = null;
@@ -50,7 +50,7 @@ export function createReminderStore({ dir, now = () => Date.now() }) {
50
50
  file,
51
51
  list: () => sorted(load()).map((r) => ({ ...r })),
52
52
  get: (id) => load().find((r) => r.id === id) ?? null,
53
- /** Throws with `code: "bad-reminder"` on invalid input. */
53
+
54
54
  add({ text, dueAt, sessionId }) {
55
55
  const clean = typeof text === "string" ? text.replace(/\s+/g, " ").trim() : "";
56
56
  const bad = (detail) => Object.assign(new Error(detail), { code: "bad-reminder" });
@@ -83,7 +83,7 @@ export function createReminderStore({ dir, now = () => Date.now() }) {
83
83
  };
84
84
  }
85
85
 
86
- /** HTTP routes for a reminder store. Returns true when it answered the request. */
86
+
87
87
  export function createReminderRoutes({ store }) {
88
88
  return async function handleReminders(req, res, rest, method) {
89
89
  if (rest === "/reminders") {