@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,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,19 +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 }} o
86
- */
87
- export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000, resume = 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
- const ws = new WebSocketImpl(`${relayUrl.replace(/\/+$/, "")}/v1/guest/${room}${resume ? "?v=2" : ""}`);
111
+
112
+ const base = relayUrl.replace(/\/+$/, "");
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}` : ""}`);
91
115
  ws.binaryType = "arraybuffer";
92
116
  phone.ws = ws;
93
117
  let noise = null;
94
- let stage = "relay"; // relay → handshake → open(resume 时还有:→ down → handshake → open …)
95
- let opened = false; // 第一次握手完成过了吗(connectPhone 的 Promise 只在那时兑现)
118
+ let stage = "relay";
119
+ let opened = false;
96
120
  let cipherOut = null;
97
121
  let cipherIn = null;
98
122
  const fail = (err) => {
@@ -101,25 +125,25 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
101
125
  try {
102
126
  ws.close();
103
127
  } catch {
104
- /* 已断开 */
128
+
105
129
  }
106
130
  reject(err instanceof Error ? err : new Error(String(err)));
107
131
  };
108
132
  const timer = setTimeout(() => fail(new Error(`connect timeout in stage ${stage}`)), timeoutMs);
109
133
 
110
- /** 握手总是全新的一次:新的临时密钥、新的握手哈希。重握时不带配对码(它是一次性的,已经用掉)。 */
134
+
111
135
  const startHandshake = () => {
112
136
  noise = new NoiseInitiator({ s: device, rs: pcPub, prologue: enc.encode(`DSH-RELAY/1|${room}`) });
113
137
  stage = "handshake";
114
138
  phone._setState("handshake");
115
- 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 } : {}) }))));
116
140
  if (opened) {
117
141
  clearTimeout(phone._rehandshakeTimer);
118
142
  phone._rehandshakeTimer = setTimeout(() => phone.close(4408, "re-handshake timeout"), timeoutMs);
119
143
  phone._rehandshakeTimer.unref?.();
120
144
  }
121
145
  };
122
- /** 这条 Noise 会话作废:在途请求立刻失败,之后不再往这条会话里发任何东西。 */
146
+
123
147
  const suspend = () => {
124
148
  stage = "down";
125
149
  cipherOut = null;
@@ -140,8 +164,8 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
140
164
  }
141
165
  if (msg.t === "host-up") {
142
166
  if (stage === "relay") return startHandshake();
143
- // 电脑重新上线(重启 / 换连接):我们的 Noise 会话已经无处可去
144
- if (!resume) return phone._shutdown(4503, "host restarted"); // 旧版:上层重新连接
167
+
168
+ if (!resume) return phone._shutdown(4503, "host restarted");
145
169
  suspend();
146
170
  return startHandshake();
147
171
  }
@@ -154,24 +178,24 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
154
178
  cipherIn = done.recv;
155
179
  phone.info = JSON.parse(dec.decode(done.payload));
156
180
  const out = cipherOut;
157
- 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) } : {}) });
158
182
  stage = "open";
159
183
  if (opened) {
160
184
  clearTimeout(phone._rehandshakeTimer);
161
185
  phone.resumes++;
162
- // 电脑要求握手后限时内收到一条能解密的数据(防重放);不能指望上层恰好马上发请求
186
+
163
187
  phone.mux.ping().catch(() => {});
164
188
  return phone._setState("open");
165
189
  }
166
190
  opened = true;
167
- 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);
168
192
  phone.pinger.unref?.();
169
193
  clearTimeout(timer);
170
194
  phone._setState("open");
171
195
  return resolve(phone);
172
196
  }
173
197
  if (stage === "open") phone.mux.receive(cipherIn.decrypt(bytes));
174
- // stage === "down":作废会话的迟到帧,丢弃
198
+
175
199
  } catch (err) {
176
200
  if (!opened) return fail(err);
177
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
+ }
@@ -0,0 +1,245 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+ import { createHash } from "node:crypto";
13
+
14
+ const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
15
+ const OP = Object.freeze({ CONT: 0, TEXT: 1, BIN: 2, CLOSE: 8, PING: 9, PONG: 10 });
16
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
17
+
18
+
19
+ export function isWebSocketUpgrade(req) {
20
+ const upgrade = String(req.headers.upgrade ?? "").toLowerCase();
21
+ const connection = String(req.headers.connection ?? "").toLowerCase();
22
+ return upgrade === "websocket" && connection.split(",").some((t) => t.trim() === "upgrade");
23
+ }
24
+
25
+
26
+ export function rejectUpgrade(socket, status, text) {
27
+ try {
28
+ socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
29
+ } catch {
30
+
31
+ }
32
+ socket.destroy();
33
+ }
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+ export function acceptWebSocket(req, socket, head, { maxPayload = 1 << 20 } = {}) {
43
+ const key = String(req.headers["sec-websocket-key"] ?? "");
44
+ if (req.method !== "GET" || !isWebSocketUpgrade(req) || req.headers["sec-websocket-version"] !== "13" || !/^[A-Za-z0-9+/]{22}==$/.test(key)) {
45
+ rejectUpgrade(socket, 400, "Bad Request");
46
+ return null;
47
+ }
48
+ const accept = createHash("sha1").update(key + GUID).digest("base64");
49
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
50
+ socket.setNoDelay?.(true);
51
+ return new ServerWebSocket(socket, head, maxPayload);
52
+ }
53
+
54
+ export class ServerWebSocket {
55
+ constructor(socket, head, maxPayload) {
56
+ this.socket = socket;
57
+ this.maxPayload = maxPayload;
58
+ this.readyState = 1;
59
+ this.closeCode = null;
60
+ this.listeners = { message: [], close: [] };
61
+ this.buf = head?.length ? Buffer.from(head) : Buffer.alloc(0);
62
+ this.frag = null;
63
+ socket.on("data", (chunk) => this.#onData(chunk));
64
+ socket.on("close", () => this.#finish(this.closeCode ?? 1006));
65
+ socket.on("error", () => this.#finish(1006));
66
+ if (this.buf.length) queueMicrotask(() => this.#parse());
67
+ }
68
+
69
+
70
+ on(type, fn) {
71
+ this.listeners[type]?.push(fn);
72
+ return this;
73
+ }
74
+ #emit(type, arg) {
75
+ for (const fn of this.listeners[type] ?? []) {
76
+ try {
77
+ fn(arg);
78
+ } catch {
79
+
80
+ }
81
+ }
82
+ }
83
+
84
+ send(data) {
85
+ if (this.readyState !== 1) return false;
86
+ const text = typeof data === "string";
87
+ const payload = text ? Buffer.from(data, "utf8") : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
88
+ return this.#write(text ? OP.TEXT : OP.BIN, payload);
89
+ }
90
+
91
+
92
+ close(code = 1000, reason = "") {
93
+ if (this.readyState >= 2) return;
94
+ this.readyState = 2;
95
+ this.closeCode = code;
96
+ const r = Buffer.from(String(reason).slice(0, 100), "utf8").subarray(0, 123);
97
+ const payload = Buffer.alloc(2 + r.length);
98
+ payload.writeUInt16BE(code, 0);
99
+ r.copy(payload, 2);
100
+ this.#write(OP.CLOSE, payload);
101
+ const t = setTimeout(() => this.socket.destroy(), 2000);
102
+ t.unref?.();
103
+ }
104
+
105
+
106
+ terminate(code = 1006) {
107
+ this.closeCode ??= code;
108
+ this.socket.destroy();
109
+ }
110
+
111
+ #write(op, payload) {
112
+ const n = payload.length;
113
+ let header;
114
+ if (n < 126) {
115
+ header = Buffer.from([0x80 | op, n]);
116
+ } else if (n < 65_536) {
117
+ header = Buffer.alloc(4);
118
+ header[0] = 0x80 | op;
119
+ header[1] = 126;
120
+ header.writeUInt16BE(n, 2);
121
+ } else {
122
+ header = Buffer.alloc(10);
123
+ header[0] = 0x80 | op;
124
+ header[1] = 127;
125
+ header.writeBigUInt64BE(BigInt(n), 2);
126
+ }
127
+ try {
128
+ this.socket.write(Buffer.concat([header, payload]));
129
+ return true;
130
+ } catch {
131
+ return false;
132
+ }
133
+ }
134
+
135
+ #onData(chunk) {
136
+ this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;
137
+ this.#parse();
138
+ }
139
+
140
+ #fail(code) {
141
+ if (this.readyState >= 2) return void this.socket.destroy();
142
+ this.close(code);
143
+ this.socket.destroy();
144
+ }
145
+
146
+ #parse() {
147
+ while (this.readyState === 1 || this.readyState === 2) {
148
+ const b = this.buf;
149
+ if (b.length < 2) return;
150
+ const fin = (b[0] & 0x80) !== 0;
151
+ const rsv = b[0] & 0x70;
152
+ const op = b[0] & 0x0f;
153
+ const masked = (b[1] & 0x80) !== 0;
154
+ let len = b[1] & 0x7f;
155
+ let off = 2;
156
+ if (rsv !== 0 || !masked) return this.#fail(1002);
157
+ if (len === 126) {
158
+ if (b.length < 4) return;
159
+ len = b.readUInt16BE(2);
160
+ off = 4;
161
+ } else if (len === 127) {
162
+ if (b.length < 10) return;
163
+ const big = b.readBigUInt64BE(2);
164
+ if (big > BigInt(this.maxPayload)) return this.#fail(1009);
165
+ len = Number(big);
166
+ off = 10;
167
+ }
168
+ const control = op >= 8;
169
+ if (control && (len > 125 || !fin)) return this.#fail(1002);
170
+ if (!control && len > this.maxPayload) return this.#fail(1009);
171
+ if (b.length < off + 4 + len) return;
172
+ const mask = b.subarray(off, off + 4);
173
+ const payload = Buffer.from(b.subarray(off + 4, off + 4 + len));
174
+ for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
175
+ this.buf = b.subarray(off + 4 + len);
176
+ if (!this.#frame(fin, op, payload)) return;
177
+ }
178
+ }
179
+
180
+
181
+ #frame(fin, op, payload) {
182
+ switch (op) {
183
+ case OP.PING:
184
+ this.#write(OP.PONG, payload);
185
+ return true;
186
+ case OP.PONG:
187
+ return true;
188
+ case OP.CLOSE: {
189
+ const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1005;
190
+ if (this.readyState === 1) {
191
+
192
+ this.readyState = 2;
193
+ this.closeCode = code;
194
+ const echo = payload.length >= 2 ? payload.subarray(0, 2) : Buffer.alloc(0);
195
+ this.#write(OP.CLOSE, echo);
196
+ }
197
+ this.closeCode ??= code;
198
+ this.socket.end();
199
+ return false;
200
+ }
201
+ case OP.TEXT:
202
+ case OP.BIN:
203
+ if (this.frag) return this.#fail(1002) ?? false;
204
+ if (fin) return this.#deliver(op, payload);
205
+ this.frag = { op, parts: [payload], size: payload.length };
206
+ return true;
207
+ case OP.CONT: {
208
+ const f = this.frag;
209
+ if (!f) return this.#fail(1002) ?? false;
210
+ f.size += payload.length;
211
+ if (f.size > this.maxPayload) return this.#fail(1009) ?? false;
212
+ f.parts.push(payload);
213
+ if (!fin) return true;
214
+ this.frag = null;
215
+ return this.#deliver(f.op, Buffer.concat(f.parts));
216
+ }
217
+ default:
218
+ return this.#fail(1002) ?? false;
219
+ }
220
+ }
221
+
222
+ #deliver(op, payload) {
223
+ if (this.readyState !== 1) return true;
224
+ if (op === OP.TEXT) {
225
+ let text;
226
+ try {
227
+ text = utf8.decode(payload);
228
+ } catch {
229
+ this.#fail(1007);
230
+ return false;
231
+ }
232
+ this.#emit("message", text);
233
+ } else {
234
+ this.#emit("message", new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength));
235
+ }
236
+ return true;
237
+ }
238
+
239
+ #finish(code) {
240
+ if (this.readyState === 3) return;
241
+ this.readyState = 3;
242
+ this.closeCode ??= code;
243
+ this.#emit("close", this.closeCode);
244
+ }
245
+ }
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") {