@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.
- package/FAQ.md +2 -2
- package/LICENSE +0 -0
- package/README.md +13 -8
- package/docs/PRIVACY-POLICY.en.md +26 -18
- package/docs/PRIVACY-POLICY.md +26 -18
- package/docs/SUPPORT.md +1 -1
- package/docs/TERMS-OF-SERVICE.en.md +5 -3
- package/docs/TERMS-OF-SERVICE.md +5 -3
- package/docs/USER-GUIDE.zh-CN.md +7 -6
- package/lib/account-usage-query.js +60 -60
- package/lib/account-usage.js +10 -10
- package/lib/api-helpers.js +114 -110
- package/lib/assistant-prefs.js +119 -76
- package/lib/auto-config.js +65 -65
- package/lib/backup.js +159 -123
- package/lib/break-reminder.js +45 -45
- package/lib/client.js +336 -138
- package/lib/config.js +234 -218
- package/lib/git-read-bundled-provider.js +27 -7
- package/lib/git-read-service.js +5 -5
- package/lib/host-compat.js +84 -84
- package/lib/http-util.js +17 -17
- package/lib/index.js +1670 -1511
- package/lib/memory/context.js +45 -40
- package/lib/memory/decay.js +93 -93
- package/lib/memory/extract.js +77 -77
- package/lib/memory/routes.js +33 -33
- package/lib/memory/store.js +239 -192
- package/lib/notify-copy.js +93 -93
- package/lib/permission-guide.js +86 -86
- package/lib/persona-cards.js +73 -61
- package/lib/phone-action-args.js +175 -0
- package/lib/phone-actions.js +227 -0
- package/lib/phone-announce.js +58 -0
- package/lib/proactive-material.js +42 -42
- package/lib/proactive.js +122 -119
- package/lib/protected-paths.js +205 -45
- package/lib/protocol.js +62 -23
- package/lib/push.js +29 -29
- package/lib/rate-limit.js +16 -16
- package/lib/relay/connector.js +334 -81
- package/lib/relay/crypto.js +15 -15
- package/lib/relay/devices.js +64 -32
- package/lib/relay/fingerprint.js +34 -34
- package/lib/relay/identity.js +26 -26
- package/lib/relay/mux.js +60 -46
- package/lib/relay/noise.js +40 -40
- package/lib/relay/on-demand.js +36 -31
- package/lib/relay/p2p.js +239 -0
- package/lib/relay/pairing.js +54 -15
- package/lib/relay/phone.js +63 -39
- package/lib/relay/serve.js +21 -21
- package/lib/relay/signal.js +69 -0
- package/lib/relay/ws-server.js +245 -0
- package/lib/reminders.js +15 -15
- package/lib/rpc-adapter.js +43 -43
- package/lib/session-list.js +31 -31
- package/lib/session-rotation.js +95 -95
- package/lib/session-title-cache.js +35 -35
- package/lib/session-title-refresh.js +51 -51
- package/lib/timeline.js +140 -140
- package/lib/turn-outline.js +104 -104
- package/package.json +11 -18
package/lib/relay/phone.js
CHANGED
|
@@ -1,21 +1,22 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
-
|
|
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";
|
|
95
|
-
let opened = false;
|
|
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
|
-
|
|
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
|
-
|
|
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 {
|
|
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
|
-
|
|
198
|
+
|
|
175
199
|
} catch (err) {
|
|
176
200
|
if (!opened) return fail(err);
|
|
177
201
|
phone.close(4000, "protocol error");
|
package/lib/relay/serve.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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
|
-
|
|
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";
|
|
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
|
-
|
|
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";
|
|
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();
|
|
97
|
-
stream.reset(5);
|
|
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
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
86
|
+
|
|
87
87
|
export function createReminderRoutes({ store }) {
|
|
88
88
|
return async function handleReminders(req, res, rest, method) {
|
|
89
89
|
if (rest === "/reminders") {
|