@dsh-mobile/mobile-remote 3.3.0 → 3.3.1

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.
@@ -10,6 +10,11 @@
10
10
  * · 用户刚在桌面上要了一个配对码(5 分钟内有效)。
11
11
  * 两个条件都不成立就断开:全新安装不产生任何中继连接;撤销最后一台设备、配对码过期没人用,也会断开。
12
12
  *
13
+ * T-71 (C-04): only phones and codes **for remote access** count. A phone paired with the desktop's
14
+ * default QR (encrypted LAN only, no relay in the link) never uses the relay, so it must not keep
15
+ * this PC on our relay around the clock (cost, and the PC's IP and uptime seen by us for a user
16
+ * who never asked for remote access). See `relay` in ./devices.js.
17
+ *
13
18
  * 这个模块只做「该不该连」的判断,连接本身仍由 RelayConnector 负责(重连、心跳、会话)。
14
19
  */
15
20
 
@@ -24,8 +29,8 @@ export function createRelayDemand({ connector, devices, log = () => {}, now = Da
24
29
  let active = false; // 连接器是否被我们启动了
25
30
  let timer = null;
26
31
 
27
- const paired = () => devices.list().length > 0;
28
- const wanted = () => paired() || devices.pendingPairings() > 0;
32
+ const paired = () => (typeof devices.relayPaired === "function" ? devices.relayPaired() : devices.list().length) > 0;
33
+ const wanted = () => paired() || devices.pendingPairings({ relay: true }) > 0;
29
34
  const disarm = () => {
30
35
  if (timer) clearTimer(timer);
31
36
  timer = null;
@@ -47,7 +52,7 @@ export function createRelayDemand({ connector, devices, log = () => {}, now = Da
47
52
  }
48
53
  // 只靠配对码撑着的连接:最后一个码过期后再对一次表(码被用掉 → 有设备了 → 继续连着)
49
54
  if (active && !paired()) {
50
- timer = setTimer(sync, Math.max(1_000, devices.pairingExpiry() - now() + 1_000));
55
+ timer = setTimer(sync, Math.max(1_000, devices.pairingExpiry({ relay: true }) - now() + 1_000));
51
56
  timer.unref?.();
52
57
  }
53
58
  return active;
@@ -6,6 +6,18 @@
6
6
  *
7
7
  * 手机只需要这些:去哪个中继、哪个房间、认哪把公钥、拿什么码证明「我是被邀请的」。
8
8
  * 解析是严格的:中继必须是 wss://(回环地址的 ws:// 仅供本机测试),其它一律拒绝。
9
+ *
10
+ * lan=(T-25)是电脑 LAN 桥上的局域网加密通道:`ws://<局域网 IPv4>:<端口>`。不用 TLS,因为
11
+ * 通道本身就是 Noise 加密、认电脑的公钥;但只接受局域网地址(10/8、172.16/12、192.168/16、
12
+ * 100.64/10、回环),一个被篡改的二维码不能把手机引去连公网上的任意主机。不合规的 lan 地址丢弃,不报错。
13
+ *
14
+ * T-71 (D-01, C-15): an invite may carry no relay at all, only `lan=`. That is the desktop's
15
+ * default QR: an encrypted pairing on the local network that needs no relay room, no account and
16
+ * no subscription (D5: the LAN is free). It needs 1-4 relays **or** at least one valid LAN
17
+ * address. Such a link is `v=2`: apps before T-71 accept only `v=1`, and they answer an unknown
18
+ * version with "this QR code comes from a newer DSH, please update the app" (their own text), which
19
+ * is the right advice. Links with a relay stay `v=1`, readable by every app. The desktop panel keeps
20
+ * the old token QR for apps that cannot be updated yet, labelled as unencrypted.
9
21
  */
10
22
  import { b64u } from "./crypto.js";
11
23
 
@@ -25,18 +37,42 @@ export function isAllowedRelayUrl(s) {
25
37
  }
26
38
  }
27
39
 
40
+ /** 局域网 IPv4(含组网常用的 100.64/10 与回环)。 */
41
+ function isLanIPv4(host) {
42
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
43
+ if (!m) return false;
44
+ const [a, b] = [Number(m[1]), Number(m[2])];
45
+ if ([m[1], m[2], m[3], m[4]].some((x) => Number(x) > 255)) return false;
46
+ return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
47
+ }
48
+
49
+ /** 局域网加密通道的地址是否可接受:`ws://<局域网 IPv4>:<端口>`,不带账号、路径、查询串、片段。 */
50
+ export function isAllowedLanUrl(s) {
51
+ try {
52
+ const u = new URL(s);
53
+ if (u.protocol !== "ws:" || u.username || u.password || u.search || u.hash) return false;
54
+ if (u.pathname !== "/" && u.pathname !== "") return false;
55
+ if (!/^ws:\/\/[^/]+\/?$/.test(s)) return false; // URL 会把空路径补成 "/",原文里不能有路径
56
+ return isLanIPv4(u.hostname) && u.port !== "";
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
28
62
  export function buildPairingUri({ relays, roomId, pcPub, otp, name, lan = [] }) {
29
63
  if (!ROOM_RE.test(roomId)) throw new Error("bad room id");
30
64
  if (pcPub.length !== 32) throw new Error("bad public key");
31
- if (!Array.isArray(relays) || relays.length === 0 || relays.length > MAX_URIS) throw new Error("need 1-4 relay urls");
65
+ if (!Array.isArray(relays) || relays.length > MAX_URIS) throw new Error("need 0-4 relay urls");
32
66
  for (const r of relays) if (!isAllowedRelayUrl(r)) throw new Error(`relay url must be wss:// : ${r}`);
67
+ const lanOk = (Array.isArray(lan) ? lan : []).filter(isAllowedLanUrl).slice(0, MAX_URIS);
68
+ if (relays.length === 0 && lanOk.length === 0) throw new Error("need a relay url or a LAN address");
33
69
  const q = new URLSearchParams();
34
- q.set("v", "1");
70
+ q.set("v", relays.length === 0 ? "2" : "1");
35
71
  q.set("room", roomId);
36
72
  q.set("pk", b64u.enc(pcPub));
37
73
  q.set("otp", otp);
38
74
  for (const r of relays) q.append("r", r.replace(/\/+$/, ""));
39
- for (const l of lan.slice(0, MAX_URIS)) q.append("lan", l);
75
+ for (const l of lanOk) q.append("lan", l.replace(/\/+$/, ""));
40
76
  if (name) q.set("n", String(name).slice(0, 40));
41
77
  return `dsh://pair?${q.toString()}`;
42
78
  }
@@ -50,7 +86,8 @@ export function parsePairingUri(uri) {
50
86
  }
51
87
  if (u.protocol !== "dsh:" || u.hostname !== "pair") throw new Error("not a DSH pairing link");
52
88
  const p = u.searchParams;
53
- if (p.get("v") !== "1") throw new Error("unsupported version");
89
+ const v = p.get("v");
90
+ if (v !== "1" && v !== "2") throw new Error("unsupported version");
54
91
  const room = p.get("room") ?? "";
55
92
  if (!ROOM_RE.test(room)) throw new Error("bad room id");
56
93
  const pk = b64u.dec(p.get("pk") ?? "");
@@ -58,7 +95,9 @@ export function parsePairingUri(uri) {
58
95
  const otp = p.get("otp") ?? "";
59
96
  if (otp.length < 16 || otp.length > 64 || !/^[A-Za-z0-9_-]+$/.test(otp)) throw new Error("bad pairing code");
60
97
  const relays = p.getAll("r").map((r) => r.replace(/\/+$/, ""));
61
- if (relays.length === 0 || relays.length > MAX_URIS) throw new Error("need 1-4 relay urls");
98
+ if (relays.length > MAX_URIS || (v === "1" && relays.length === 0)) throw new Error(v === "1" ? "need 1-4 relay urls" : "need 0-4 relay urls");
62
99
  for (const r of relays) if (!isAllowedRelayUrl(r)) throw new Error("relay url must be wss://");
63
- return { room, pk, otp, relays, lan: p.getAll("lan").slice(0, MAX_URIS), name: p.get("n") ?? "" };
100
+ const lan = p.getAll("lan").filter(isAllowedLanUrl).map((l) => l.replace(/\/+$/, "")).slice(0, MAX_URIS);
101
+ if (relays.length === 0 && lan.length === 0) throw new Error("need a relay url or a LAN address");
102
+ return { room, pk, otp, relays, lan, name: p.get("n") ?? "" };
64
103
  }
@@ -82,12 +82,14 @@ export class PhoneSession {
82
82
 
83
83
  /**
84
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
85
+ * name?:string, otp?:string, WebSocketImpl?:Function, timeoutMs?:number, resume?:boolean, lan?:boolean }} o
86
86
  */
87
- export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000, resume = false }) {
87
+ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000, resume = false, lan = false }) {
88
88
  return new Promise((resolve, reject) => {
89
89
  const phone = new PhoneSession();
90
- const ws = new WebSocketImpl(`${relayUrl.replace(/\/+$/, "")}/v1/guest/${room}${resume ? "?v=2" : ""}`);
90
+ // lan:电脑 LAN 桥上的局域网加密通道(T-25),路径不带房间号(房间号只在 Noise 的序言里)
91
+ const base = relayUrl.replace(/\/+$/, "");
92
+ const ws = new WebSocketImpl(lan ? `${base}/v1/lan` : `${base}/v1/guest/${room}${resume ? "?v=2" : ""}`);
91
93
  ws.binaryType = "arraybuffer";
92
94
  phone.ws = ws;
93
95
  let noise = null;
@@ -0,0 +1,245 @@
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
+ */
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
+ /** 握手请求像不像一个 WebSocket 升级(不读请求体,只看头)。 */
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
+ /** 拒绝一个升级请求:写一个最小的 HTTP 响应后断开。 */
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
+ * 完成握手,返回一条连接;握手不合规则回 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
+ */
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; // 0 connecting · 1 open · 2 closing · 3 closed
59
+ this.closeCode = null;
60
+ this.listeners = { message: [], close: [] };
61
+ this.buf = head?.length ? Buffer.from(head) : Buffer.alloc(0);
62
+ this.frag = null; // 正在拼的分片消息:{ op, parts, size }
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
+ /** `message` → (data: string | Uint8Array);`close` → (code: number)。 */
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
+ /** 发 close 帧并在对端回应(或 2 秒)后断开。 */
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
+ /** 处理一帧;返回 false 表示连接已经结束,停止解析。 */
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
+ // 对端先关:回一个 close 帧(带同样的码),然后断开
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
+ }
File without changes
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-mobile/mobile-remote",
3
- "version": "3.3.0",
3
+ "version": "3.3.1",
4
4
  "description": "DSH Mobile:把 DeepSeek Harness 变成随身控制台——手机远程发消息派活、看进度、收通知、审批决策、管理会话;配套 Flutter App(Android、iPhone / iPad)",
5
5
  "homepage": "https://dsh.claud.ing/",
6
6
  "repository": {
@@ -60,7 +60,7 @@
60
60
  "license": "MIT",
61
61
  "engines": {
62
62
  "node": ">=24.9.0",
63
- "dsh": ">=0.1.0-rc.6 <0.4.0-0"
63
+ "dsh": ">=0.2.1-rc.2 <0.4.0-0"
64
64
  },
65
65
  "dependencies": {
66
66
  "qrcode": "^1.5.4"
@@ -69,10 +69,10 @@
69
69
  "ws": "^8.18.0"
70
70
  },
71
71
  "peerDependencies": {
72
- "@deepseek-ai/dsh-credentials": ">=0.1.0-rc.6 <0.4.0",
73
- "@deepseek-ai/dsh-llm": ">=0.1.0-rc.6 <0.4.0",
74
- "@deepseek-ai/dsh-sandbox-policy": ">=0.1.0-rc.6 <0.4.0",
75
- "@deepseek-ai/dsh-scope": ">=0.1.0-rc.6 <0.4.0",
72
+ "@deepseek-ai/dsh-credentials": ">=0.2.1-rc.2 <0.4.0",
73
+ "@deepseek-ai/dsh-llm": ">=0.2.1-rc.2 <0.4.0",
74
+ "@deepseek-ai/dsh-sandbox-policy": ">=0.2.1-rc.2 <0.4.0",
75
+ "@deepseek-ai/dsh-scope": ">=0.2.1-rc.2 <0.4.0",
76
76
  "@deepseek-ai/schemastery": ">=3.18.1",
77
77
  "dsh-codex-connect": ">=0.1.0-alpha.4.5"
78
78
  },