@dsh-mobile/mobile-remote 3.5.0-beta.2 → 3.5.0-beta.3

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/lib/config.js CHANGED
@@ -27,6 +27,8 @@ export const DEFAULT_ENUMERATION_BUDGET_MS = 12_000;
27
27
 
28
28
  export const DEFAULT_WARM_UP_TITLE_BUDGET_MS = 10_000;
29
29
 
30
+ export const DEFAULT_RELAY_URLS = Object.freeze(["wss://dsh.claud.ing", "wss://hk-relay.dsh.claud.ing"]);
31
+
30
32
 
31
33
  export const Config = z.object({
32
34
 
@@ -174,7 +176,11 @@ export const Config = z.object({
174
176
  .object({
175
177
  enabled: z.boolean().default(true),
176
178
 
177
- urls: z.array(z.string()).default(["wss://dsh.claud.ing"]),
179
+
180
+
181
+
182
+
183
+ urls: z.array(z.string()).default([...DEFAULT_RELAY_URLS]),
178
184
 
179
185
  name: z.string().default(""),
180
186
  })
@@ -0,0 +1,49 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ import { createHash } from "node:crypto";
10
+ import { createReadStream } from "node:fs";
11
+
12
+ export const HASH_MAX_BYTES = 512 * 1024 * 1024;
13
+ export const DIGEST_HEADER = "x-dsh-sha256";
14
+ const CACHE_MAX = 64;
15
+ const cache = new Map();
16
+
17
+
18
+ export async function fileSha256(fd, { path, size, mtimeMs }) {
19
+ if (!Number.isFinite(size) || size < 0 || size > HASH_MAX_BYTES) return null;
20
+ const key = `${path}\0${size}\0${mtimeMs}`;
21
+ const hit = cache.get(key);
22
+ if (hit) {
23
+ cache.delete(key);
24
+ cache.set(key, hit);
25
+ return hit;
26
+ }
27
+ const hash = createHash("sha256");
28
+ try {
29
+ if (size > 0) {
30
+ await new Promise((resolve, reject) => {
31
+ const s = createReadStream(null, { fd, start: 0, end: size - 1, autoClose: false });
32
+ s.on("data", (chunk) => hash.update(chunk));
33
+ s.on("end", resolve);
34
+ s.on("error", reject);
35
+ });
36
+ }
37
+ } catch {
38
+ return null;
39
+ }
40
+ const hex = hash.digest("hex");
41
+ cache.set(key, hex);
42
+ while (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value);
43
+ return hex;
44
+ }
45
+
46
+
47
+ export function clearDigestCache() {
48
+ cache.clear();
49
+ }
@@ -0,0 +1,149 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+ import { sendError, sendJson } from "./http-util.js";
21
+
22
+
23
+ export const SESSION_SEARCH_FEATURE = "session-search";
24
+
25
+ export const MAX_QUERY = 200;
26
+ export const MAX_LIMIT = 30;
27
+ export const SNIPPET_MAX = 160;
28
+ export const SCAN_SESSIONS = 80;
29
+ export const SCAN_CONCURRENCY = 4;
30
+ export const SCAN_BUDGET_MS = 4000;
31
+ const INDEX_TIMEOUT_MS = 5000;
32
+
33
+ const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim();
34
+
35
+
36
+
37
+
38
+
39
+
40
+ export function snippetAround(text, query, max = SNIPPET_MAX) {
41
+ const t = oneLine(text);
42
+ if (!t) return "";
43
+ if (t.length <= max) return t;
44
+ const lower = t.toLowerCase();
45
+ const q = oneLine(query).toLowerCase();
46
+ let at = q ? lower.indexOf(q) : -1;
47
+ if (at < 0 && q) {
48
+ const first = q.split(" ").find(Boolean);
49
+ if (first) at = lower.indexOf(first);
50
+ }
51
+ if (at < 0) return `${t.slice(0, max - 1)}…`;
52
+ const lead = Math.floor((max - Math.min(q.length, max)) / 3);
53
+ let start = Math.max(0, at - lead);
54
+ let end = Math.min(t.length, start + max);
55
+ start = Math.max(0, end - max);
56
+ return `${start > 0 ? "…" : ""}${t.slice(start, end)}${end < t.length ? "…" : ""}`;
57
+ }
58
+
59
+ const isDisabled = (err) => err?.code === "SESSION_QUERY_SEARCH_DISABLED" || /SEARCH_DISABLED/.test(String(err?.message ?? ""));
60
+
61
+ export function createSessionSearchRoutes({ service, logger, now = () => Date.now() }) {
62
+ const get = (fn) => {
63
+ try { return fn(); } catch { return undefined; }
64
+ };
65
+
66
+ async function viaIndex(svc, query, limit) {
67
+ const page = await svc.searchSessions({ query, limit }, { signal: AbortSignal.timeout(INDEX_TIMEOUT_MS) });
68
+ const hits = [];
69
+ for (const hit of Array.isArray(page?.items) ? page.items : []) {
70
+ const id = hit?.header?.id;
71
+ if (typeof id !== "string" || !id) continue;
72
+ hits.push({
73
+ id,
74
+ snippet: snippetAround(hit.bestMatch?.snippet ?? "", query),
75
+ at: Number.isFinite(hit.bestMatch?.time) ? hit.bestMatch.time : null,
76
+ });
77
+ }
78
+ return { mode: "index", partial: Boolean(page?.nextCursor), hits };
79
+ }
80
+
81
+ async function viaScan(svc, query, limit) {
82
+ const started = now();
83
+ const records = await svc.listSessions(AbortSignal.timeout(SCAN_BUDGET_MS));
84
+ const ids = (Array.isArray(records) ? records : [])
85
+ .map((r) => r?.header?.id)
86
+ .filter((id) => typeof id === "string" && id);
87
+ const queue = ids.slice(0, SCAN_SESSIONS);
88
+ let partial = ids.length > queue.length;
89
+ const found = new Map();
90
+ const worker = async () => {
91
+ while (queue.length > 0 && found.size < limit) {
92
+ if (now() - started > SCAN_BUDGET_MS) { partial = true; return; }
93
+ const id = queue.shift();
94
+ try {
95
+ const docs = await svc.filterEvents(id, [{ kind: "text", text: query }]);
96
+ if (Array.isArray(docs) && docs.length > 0) {
97
+ const last = docs[docs.length - 1];
98
+ found.set(id, { id, snippet: snippetAround(last?.text ?? "", query), at: Number.isFinite(last?.time) ? last.time : null });
99
+ }
100
+ } catch (err) {
101
+ logger?.debug?.(`mobile-remote: session search scan ${id}: ${err?.message ?? err}`);
102
+ }
103
+ }
104
+ if (queue.length > 0) partial = true;
105
+ };
106
+ await Promise.all(Array.from({ length: SCAN_CONCURRENCY }, worker));
107
+ const hits = ids.filter((id) => found.has(id)).map((id) => found.get(id)).slice(0, limit);
108
+ return { mode: "scan", partial, hits };
109
+ }
110
+
111
+ return async function handleSessionSearch(req, res, rest, method, url) {
112
+ if (rest !== "/session-search") return false;
113
+ if (method !== "GET" && method !== "HEAD") { sendError(res, 405, "method-not-allowed"); return true; }
114
+ const query = oneLine(url?.searchParams?.get("q") ?? "");
115
+ if (!query || query.length > MAX_QUERY) { sendError(res, 400, "bad-request", `q must be 1..${MAX_QUERY} characters`); return true; }
116
+ const limitRaw = Number.parseInt(url?.searchParams?.get("limit") ?? "", 10);
117
+ const limit = Number.isFinite(limitRaw) ? Math.min(MAX_LIMIT, Math.max(1, limitRaw)) : 20;
118
+ const svc = get(service);
119
+ const canIndex = typeof svc?.searchSessions === "function";
120
+ const canScan = typeof svc?.listSessions === "function" && typeof svc?.filterEvents === "function";
121
+ if (!canIndex && !canScan) {
122
+ sendError(res, 503, "session-search-unavailable", "this computer's DSH does not offer session search");
123
+ return true;
124
+ }
125
+ let result = null;
126
+ if (canIndex) {
127
+ try {
128
+ result = await viaIndex(svc, query, limit);
129
+ } catch (err) {
130
+ if (!isDisabled(err)) logger?.debug?.(`mobile-remote: session search index: ${err?.message ?? err}`);
131
+ }
132
+ }
133
+ if (!result && canScan) {
134
+ try {
135
+ result = await viaScan(svc, query, limit);
136
+ } catch (err) {
137
+ logger?.warn?.(`mobile-remote: session search failed: ${err?.message ?? err}`);
138
+ sendError(res, 503, "session-search-unavailable", "session search failed on this computer");
139
+ return true;
140
+ }
141
+ }
142
+ if (!result) {
143
+ sendError(res, 503, "session-search-unavailable", "full-text search is switched off in this computer's DSH");
144
+ return true;
145
+ }
146
+ sendJson(res, 200, { ok: true, query, ...result });
147
+ return true;
148
+ };
149
+ }
package/lib/protocol.js CHANGED
@@ -38,6 +38,11 @@ export const FEATURES = Object.freeze([
38
38
  "standby",
39
39
 
40
40
 
41
+
42
+
43
+ "bulk",
44
+
45
+
41
46
  "schedules",
42
47
 
43
48
 
@@ -48,6 +53,10 @@ export const FEATURES = Object.freeze([
48
53
 
49
54
 
50
55
 
56
+ "session-search",
57
+
58
+
59
+
51
60
  "toolbox-install",
52
61
 
53
62
 
@@ -28,6 +28,12 @@
28
28
 
29
29
 
30
30
 
31
+
32
+
33
+
34
+
35
+
36
+
31
37
 
32
38
 
33
39
 
@@ -118,7 +124,10 @@ export class RelayConnector {
118
124
  return [...this.links, ...this.direct];
119
125
  }
120
126
  status() {
121
- return this.links.map((l) => ({ url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: [...l.sessions.values()].filter((s) => !s.standby).length, standby: [...l.sessions.values()].filter((s) => s.standby).length }));
127
+ return this.links.map((l) => {
128
+ const all = [...l.sessions.values()];
129
+ return { url: l.url, state: l.state, since: l.since, lastError: l.lastError, phones: all.filter((s) => !s.standby && !s.bulk).length, standby: all.filter((s) => s.standby).length, bulk: all.filter((s) => s.bulk).length };
130
+ });
122
131
  }
123
132
 
124
133
 
@@ -412,6 +421,8 @@ class GuestSession {
412
421
 
413
422
  this.standby = false;
414
423
 
424
+ this.bulk = false;
425
+
415
426
  this.framesOut = 0;
416
427
  this.timer = link.after(link.o.timing.firstFrameMs, () => {
417
428
  if (this.state !== "open") this.kick("handshake timeout");
@@ -459,8 +470,9 @@ class GuestSession {
459
470
  }
460
471
  this.signal = this.relaySignal || info.mode === "signal";
461
472
  this.standby = !this.signal && info.mode === "standby";
473
+ this.bulk = !this.signal && info.mode === "bulk";
462
474
 
463
- const result = devices.authorize(rs, this.signal || this.standby ? { ...info, otp: undefined } : info);
475
+ const result = devices.authorize(rs, this.signal || this.standby || this.bulk ? { ...info, otp: undefined } : info);
464
476
  if (!result) return this.kick("unauthorized device");
465
477
 
466
478
  if (result.refused === "full") return this.kick("设备已满:已配对的手机到了上限,配对码未作废", "full");
@@ -483,7 +495,7 @@ class GuestSession {
483
495
  this.framesOut++;
484
496
  this.link.control({ t: "verified", c: this.connId });
485
497
  this.state = "await-first";
486
- this.link.o.log(`relay: 设备「${this.device.name}」${this.signal ? "打开信令连接" : this.standby ? "打开待命连接" : result.newlyPaired ? "完成配对" : "已连接"}`);
498
+ this.link.o.log(`relay: 设备「${this.device.name}」${this.signal ? "打开信令连接" : this.standby ? "打开待命连接" : this.bulk ? "打开大文件连接" : result.newlyPaired ? "完成配对" : "已连接"}`);
487
499
  }
488
500
  #sendPlain(frame) {
489
501
  if (this.state === "closed") return;
@@ -535,11 +547,12 @@ class GuestSession {
535
547
  const id = this.device?.id;
536
548
  if (!id) return;
537
549
 
550
+
538
551
  const standby = this.standby;
539
552
  for (const link of this.link.o.allLinks()) {
540
553
  for (const other of [...link.sessions.values()]) {
541
554
 
542
- if (other !== this && other.device?.id === id && other.signal === this.signal && other.standby === standby) other.kick("replaced by a newer connection from the same device", "replaced");
555
+ if (other !== this && other.device?.id === id && other.signal === this.signal && other.standby === standby && other.bulk === this.bulk) other.kick("replaced by a newer connection from the same device", "replaced");
543
556
  }
544
557
  }
545
558
  }
package/lib/relay/p2p.js CHANGED
@@ -17,6 +17,7 @@
17
17
 
18
18
 
19
19
 
20
+
20
21
 
21
22
 
22
23
  import { registerFeature } from "../protocol.js";
@@ -30,6 +31,22 @@ export const P2P_TIMING = Object.freeze({ openMs: 15_000, maxPeers: 4, stunGathe
30
31
  const loadWerift = () => import("werift");
31
32
 
32
33
 
34
+
35
+
36
+
37
+
38
+
39
+ export function turnTlsServername(iceServers) {
40
+ for (const s of iceServers) {
41
+ for (const u of typeof s?.urls === "string" ? [s.urls] : (s?.urls ?? [])) {
42
+ const m = /^turns:([^:?/\[\]]+)/i.exec(u);
43
+ if (m && !/^[\d.]+$/.test(m[1])) return m[1].toLowerCase();
44
+ }
45
+ }
46
+ return undefined;
47
+ }
48
+
49
+
33
50
  export class ChannelSocket {
34
51
  constructor(channel, { onClose } = {}) {
35
52
  this.channel = channel;
@@ -106,9 +123,11 @@ class Attempt {
106
123
 
107
124
  }
108
125
  }
109
- async offer(sdp, werift) {
126
+ async offer(sdp, werift, extraIce = []) {
110
127
  const { RTCPeerConnection } = werift;
111
- const pc = (this.pc = new RTCPeerConnection({ iceServers: this.host.iceServers, stunGatherTimeout: this.host.timing.stunGatherSec, iceUseDefaultStunServer: false }));
128
+ const iceServers = [...this.host.iceServers, ...extraIce];
129
+ const servername = turnTlsServername(iceServers);
130
+ const pc = (this.pc = new RTCPeerConnection({ iceServers, stunGatherTimeout: this.host.timing.stunGatherSec, iceUseDefaultStunServer: false, ...(servername ? { turnTlsOptions: { servername } } : {}) }));
112
131
  pc.onIceCandidate.subscribe((c) => this.#local(c));
113
132
  pc.connectionStateChange.subscribe((s) => {
114
133
  if (s === "failed" || s === "closed") this.dispose(`connection ${s}`);
@@ -219,13 +238,13 @@ export class P2pHost {
219
238
  }
220
239
  if (e.type !== "message") return;
221
240
  const { msg, peer, deviceId } = e;
222
- if (msg.k === "offer") return void this.#offer(deviceId, peer, msg.sdp);
241
+ if (msg.k === "offer") return void this.#offer(deviceId, peer, msg.sdp, msg.ice);
223
242
  const a = this.attempts.get(deviceId);
224
243
  if (!a) return;
225
244
  if (msg.k === "ice") a.run(() => a.remoteCandidate(msg.cand));
226
245
  else if (msg.k === "bye" && !a.opened) a.dispose("bye");
227
246
  }
228
- async #offer(deviceId, peer, sdp) {
247
+ async #offer(deviceId, peer, sdp, ice = []) {
229
248
  this.attempts.get(deviceId)?.dispose("replaced by a new offer");
230
249
  if (this.attempts.size >= this.timing.maxPeers) return void peer.send({ k: "bye" });
231
250
  const a = new Attempt(this, { ...peer, deviceId });
@@ -234,6 +253,6 @@ export class P2pHost {
234
253
  a.bye();
235
254
  return a.dispose("werift unavailable");
236
255
  }
237
- a.run(() => a.offer(sdp, this.werift));
256
+ a.run(() => a.offer(sdp, this.werift, ice));
238
257
  }
239
258
  }
@@ -110,7 +110,7 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
110
110
  const phone = new PhoneSession();
111
111
 
112
112
  const base = relayUrl.replace(/\/+$/, "");
113
- const query = [resume || signal || mode === "standby" ? "v=2" : "", signal ? "mode=signal" : ""].filter(Boolean).join("&");
113
+ const query = [resume || signal || mode === "standby" || mode === "bulk" ? "v=2" : "", signal ? "mode=signal" : ""].filter(Boolean).join("&");
114
114
  const ws = new WebSocketImpl(lan ? `${base}/v1/lan` : `${base}/v1/guest/${room}${query ? `?${query}` : ""}`);
115
115
  ws.binaryType = "arraybuffer";
116
116
  phone.ws = ws;
@@ -136,7 +136,7 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
136
136
  noise = new NoiseInitiator({ s: device, rs: pcPub, prologue: enc.encode(`DSH-RELAY/1|${room}`) });
137
137
  stage = "handshake";
138
138
  phone._setState("handshake");
139
- ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(signal ? { mode: "signal" } : mode === "standby" ? { mode } : {}), ...(otp && !opened && !signal && mode !== "standby" ? { otp } : {}) }))));
139
+ ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(signal ? { mode: "signal" } : mode === "standby" || mode === "bulk" ? { mode } : {}), ...(otp && !opened && !signal && !mode ? { otp } : {}) }))));
140
140
  if (opened) {
141
141
  clearTimeout(phone._rehandshakeTimer);
142
142
  phone._rehandshakeTimer = setTimeout(() => phone.close(4408, "re-handshake timeout"), timeoutMs);
@@ -14,6 +14,10 @@
14
14
 
15
15
 
16
16
 
17
+
18
+
19
+
20
+
17
21
 
18
22
 
19
23
 
@@ -32,6 +36,26 @@ export const CLOSE_SIGNAL_BUDGET = 4431;
32
36
  const enc = new TextEncoder();
33
37
  const dec = new TextDecoder();
34
38
 
39
+ const ICE_URL_RE = /^(stun|turn|turns):[^\s]{1,250}$/;
40
+ const ICE_TEXT_MAX = 256;
41
+
42
+
43
+ export function normalizeIceServers(list) {
44
+ if (!Array.isArray(list) || list.length > 4) throw new MuxError("bad ice servers");
45
+ return list.map((s) => {
46
+ if (!s || typeof s !== "object" || Array.isArray(s)) throw new MuxError("bad ice server");
47
+ const urls = typeof s.urls === "string" ? [s.urls] : s.urls;
48
+ if (!Array.isArray(urls) || urls.length === 0 || urls.length > 6 || !urls.every((u) => typeof u === "string" && ICE_URL_RE.test(u))) throw new MuxError("bad ice server urls");
49
+ const out = { urls: [...urls] };
50
+ for (const k of ["username", "credential"]) {
51
+ if (s[k] === undefined) continue;
52
+ if (typeof s[k] !== "string" || s[k].length > ICE_TEXT_MAX) throw new MuxError("bad ice server credential");
53
+ out[k] = s[k];
54
+ }
55
+ return out;
56
+ });
57
+ }
58
+
35
59
 
36
60
  export function normalizeSignal(msg) {
37
61
  if (!msg || typeof msg !== "object" || msg.t !== "sig") throw new MuxError("bad signal message");
@@ -42,6 +66,7 @@ export function normalizeSignal(msg) {
42
66
  if (typeof msg.sdp !== "string" || msg.sdp.length === 0) throw new MuxError("signal without sdp");
43
67
  out.sdp = msg.sdp;
44
68
  }
69
+ if (msg.k === "offer" && msg.ice !== undefined) out.ice = normalizeIceServers(msg.ice);
45
70
  if (msg.k === "ice") {
46
71
  if (msg.cand !== null && (typeof msg.cand !== "object" || Array.isArray(msg.cand))) throw new MuxError("bad ice candidate");
47
72
  out.cand = msg.cand ?? null;
@@ -12,6 +12,7 @@ import { fileMimeOf, ifNoneMatch, normalizeServerPath, parseByteRange, requestHe
12
12
  import { guardRes, requireGet, sendJson } from "../http-util.js";
13
13
  import { isProtectedFile, isProtectedPath, isStillAt, realPathOf, removeCreatedEntry } from "../protected-paths.js";
14
14
  import { NOT_HANDLED } from "./route-groups.js";
15
+ import { DIGEST_HEADER, fileSha256 } from "../file-digest.js";
15
16
 
16
17
  export async function handleFilesRoutes(deps, req, res, url, rest, method, miss) {
17
18
  const {
@@ -196,6 +197,8 @@ export async function handleFilesRoutes(deps, req, res, url, rest, method, miss)
196
197
  const start = range ? range.start : 0;
197
198
  const end = range ? range.end : st.size - 1;
198
199
  const length = st.size === 0 ? 0 : end - start + 1;
200
+
201
+ const digest = method === "HEAD" ? null : await fileSha256(fd, { path: target, size: st.size, mtimeMs: st.mtimeMs });
199
202
  const headers = {
200
203
  "content-type": fileMimeOf(name),
201
204
  "content-length": String(length),
@@ -207,6 +210,7 @@ export async function handleFilesRoutes(deps, req, res, url, rest, method, miss)
207
210
 
208
211
  connection: "close",
209
212
  ...(range ? { "content-range": `bytes ${start}-${end}/${st.size}` } : {}),
213
+ ...(digest ? { [DIGEST_HEADER]: digest } : {}),
210
214
  };
211
215
  res.writeHead(range ? 206 : 200, headers);
212
216
  if (method === "HEAD" || st.size === 0) {
@@ -7,8 +7,10 @@
7
7
 
8
8
 
9
9
 
10
+
10
11
  import { createHostPluginRoutes } from "../host-plugins.js";
11
12
  import { createScheduleRoutes } from "../host-schedule.js";
13
+ import { createSessionSearchRoutes } from "../host-session-search.js";
12
14
  import { createTeamRoutes } from "../host-team.js";
13
15
  import { NOT_HANDLED } from "./route-groups.js";
14
16
 
@@ -22,6 +24,7 @@ function handlersFor(deps) {
22
24
  const logger = ctx?.logger;
23
25
  h = {
24
26
  schedules: createScheduleRoutes({ service: () => ctx.get("schedule"), logger }),
27
+ search: createSessionSearchRoutes({ service: () => ctx.get("sessionQuery"), logger }),
25
28
  team: createTeamRoutes({ service: () => ctx.get("agentTeams"), agents: () => ctx.get("agents"), logger }),
26
29
  plugins: createHostPluginRoutes({
27
30
  manager: () => ctx.get("pluginManager"),
@@ -42,6 +45,7 @@ export async function handleHostServicesRoutes(deps, req, res, url, rest, method
42
45
  if (owns(rest, "/schedules")) pick = "schedules";
43
46
  else if (rest === "/team/tasks") pick = "team";
44
47
  else if (owns(rest, "/host-plugins")) pick = "plugins";
48
+ else if (rest === "/session-search") pick = "search";
45
49
  if (!pick) {
46
50
  miss.now = true;
47
51
  return NOT_HANDLED;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-mobile/mobile-remote",
3
- "version": "3.5.0-beta.2",
3
+ "version": "3.5.0-beta.3",
4
4
  "description": "DSH Mobile:把 DeepSeek Harness 变成随身控制台——手机远程发消息派活、看进度、收通知、审批决策、管理会话;配套 Flutter App(Android、iPhone / iPad)",
5
5
  "homepage": "https://dsh.claud.ing/",
6
6
  "repository": {