@dsh-mobile/mobile-remote 3.4.1-beta.2 → 3.5.0-beta.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.
package/lib/toolbox.js ADDED
@@ -0,0 +1,355 @@
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+ import { randomUUID } from "node:crypto";
19
+ import { lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync } from "node:fs";
20
+ import { hostname } from "node:os";
21
+ import { isAbsolute, join, relative, resolve } from "node:path";
22
+ import { mobileRemoteStateDir } from "./auto-config.js";
23
+ import { createCapableTracker, GRACE_MS } from "./phone-announce.js";
24
+ import { isProtectedPath } from "./protected-paths.js";
25
+ import { readBody, sendError, sendJson } from "./http-util.js";
26
+
27
+ export const TOOLBOX_FEATURE = "toolbox-install";
28
+
29
+ export const TOOLBOX_HEADER = "x-dsh-toolbox";
30
+ export const MANIFEST_SCHEMA = "dsh-mobile.tool/1";
31
+ export const MAX_TOOL_BYTES = 5 * 1024 * 1024;
32
+ export const MAX_FILES = 200;
33
+ export const MAX_PATH_LENGTH = 160;
34
+ export const TOOL_ID_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
35
+
36
+ export const ALLOWED_EXTENSIONS = Object.freeze([
37
+ "html", "htm", "css", "js", "mjs", "json", "txt", "md", "csv",
38
+ "svg", "png", "jpg", "jpeg", "gif", "webp", "ico", "avif",
39
+ "woff", "woff2", "ttf", "otf", "mp3", "wav", "ogg", "m4a", "mp4", "webm",
40
+ ]);
41
+ export const OFFER_ASK_MS = 60_000;
42
+ export const OFFER_PENDING_MS = 75_000;
43
+ const OFFER_FETCH_MS = 5 * 60_000;
44
+ const MAX_PENDING_OFFERS = 4;
45
+ export const OFFER_STATUSES = Object.freeze(["installed", "declined", "timeout", "failed"]);
46
+ const TEXT_MAX = { name: 40, version: 20, description: 200 };
47
+
48
+
49
+ const clean = (v, max) => (typeof v === "string" ? v.replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max) : "");
50
+ const extOf = (p) => { const m = /\.([a-z0-9]+)$/i.exec(p); return m ? m[1].toLowerCase() : ""; };
51
+
52
+
53
+ export const toolboxDir = (stateDir = mobileRemoteStateDir()) => join(stateDir, "toolbox");
54
+
55
+
56
+
57
+
58
+
59
+ export function validateManifest(raw) {
60
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, error: "tool.json must be a JSON object" };
61
+ if (raw.schema !== undefined && raw.schema !== MANIFEST_SCHEMA) return { ok: false, error: `tool.json "schema" must be "${MANIFEST_SCHEMA}" when present` };
62
+ if (typeof raw.id !== "string" || !TOOL_ID_RE.test(raw.id)) return { ok: false, error: "tool.json \"id\" must be 1-40 characters: lowercase letters, digits and '-', starting with a letter or digit" };
63
+ if (raw.id.startsWith("builtin-")) return { ok: false, error: "tool.json \"id\" must not start with \"builtin-\" (reserved for the app's own tools)" };
64
+ const name = clean(raw.name, TEXT_MAX.name + 1);
65
+ if (name === "" || name.length > TEXT_MAX.name) return { ok: false, error: `tool.json "name" must be 1-${TEXT_MAX.name} characters` };
66
+ const version = raw.version === undefined ? "1.0.0" : clean(raw.version, TEXT_MAX.version + 1);
67
+ if (version === "" || version.length > TEXT_MAX.version) return { ok: false, error: `tool.json "version" must be 1-${TEXT_MAX.version} characters` };
68
+ if (raw.description !== undefined && typeof raw.description !== "string") return { ok: false, error: "tool.json \"description\" must be a string" };
69
+ return { ok: true, value: { schema: MANIFEST_SCHEMA, id: raw.id, name, version, description: clean(raw.description, TEXT_MAX.description) } };
70
+ }
71
+
72
+
73
+ export function validToolPath(p) {
74
+ if (typeof p !== "string" || p === "" || p.length > MAX_PATH_LENGTH) return false;
75
+ if (!/^[A-Za-z0-9._\-/]+$/.test(p) || p.startsWith("/") || p.endsWith("/")) return false;
76
+ const parts = p.split("/");
77
+ if (parts.some((s) => s === "" || s === "." || s === ".." || s.startsWith("."))) return false;
78
+ return ALLOWED_EXTENSIONS.includes(extOf(p));
79
+ }
80
+
81
+
82
+
83
+
84
+
85
+
86
+ export function packageToolFolder(dir, { maxBytes = MAX_TOOL_BYTES, maxFiles = MAX_FILES } = {}) {
87
+ let st;
88
+ try { st = lstatSync(dir); } catch { return { ok: false, error: `no such folder: ${dir}` }; }
89
+ if (!st.isDirectory()) return { ok: false, error: `not a folder: ${dir}` };
90
+ let manifestRaw;
91
+ try { manifestRaw = JSON.parse(readFileSync(join(dir, "tool.json"), "utf8")); } catch (err) {
92
+ return { ok: false, error: err?.code === "ENOENT" ? "the folder has no tool.json" : `tool.json is not valid JSON (${err?.message ?? err})` };
93
+ }
94
+ const m = validateManifest(manifestRaw);
95
+ if (!m.ok) return m;
96
+ const files = [];
97
+ let size = 0;
98
+ const walk = (abs, rel) => {
99
+ for (const ent of readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
100
+ if (ent.name.startsWith(".")) continue;
101
+ const relPath = rel === "" ? ent.name : `${rel}/${ent.name}`;
102
+ const absPath = join(abs, ent.name);
103
+ const est = lstatSync(absPath);
104
+ if (est.isSymbolicLink()) throw new Error(`symlinks are not allowed in a tool: ${relPath}`);
105
+ if (est.isDirectory()) { walk(absPath, relPath); continue; }
106
+ if (!est.isFile()) throw new Error(`not a regular file: ${relPath}`);
107
+ if (relPath === "tool.json") continue;
108
+ if (!validToolPath(relPath)) throw new Error(`file not allowed in a tool (use letters, digits, '.', '-', '_' and one of: ${ALLOWED_EXTENSIONS.join(", ")}): ${relPath}`);
109
+ size += est.size;
110
+ if (size > maxBytes) throw new Error(`the tool is larger than ${Math.round(maxBytes / 1024 / 1024)} MB`);
111
+ if (files.length >= maxFiles) throw new Error(`the tool has more than ${maxFiles} files`);
112
+ files.push({ path: relPath, bytes: readFileSync(absPath) });
113
+ }
114
+ };
115
+ try { walk(dir, ""); } catch (err) { return { ok: false, error: String(err?.message ?? err) }; }
116
+ if (!files.some((f) => f.path === "index.html")) return { ok: false, error: "the folder has no index.html" };
117
+
118
+ size = files.reduce((n, f) => n + f.bytes.length, 0);
119
+ if (size > maxBytes) return { ok: false, error: `the tool is larger than ${Math.round(maxBytes / 1024 / 1024)} MB` };
120
+ return { ok: true, manifest: m.value, files, size };
121
+ }
122
+
123
+
124
+ export const bundleBody = (pkg) => ({
125
+ ok: true,
126
+ tool: pkg.manifest,
127
+ size: pkg.size,
128
+ files: pkg.files.map((f) => ({ path: f.path, data: f.bytes.toString("base64") })),
129
+ });
130
+
131
+ export const summaryOf = (pkg) => ({ ...pkg.manifest, size: pkg.size, fileCount: pkg.files.length });
132
+
133
+
134
+ const validFolderName = (name) => typeof name === "string" && /^[A-Za-z0-9][A-Za-z0-9._ -]{0,79}$/.test(name) && !name.includes("..");
135
+
136
+
137
+ export function listLocalTools(dir) {
138
+ try { mkdirSync(dir, { recursive: true, mode: 0o700 }); } catch { }
139
+ let entries = [];
140
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return []; }
141
+ const out = [];
142
+ for (const ent of entries.sort((a, b) => a.name.localeCompare(b.name))) {
143
+ if (!ent.isDirectory() || !validFolderName(ent.name)) continue;
144
+ const pkg = packageToolFolder(join(dir, ent.name));
145
+ out.push(pkg.ok ? { folder: ent.name, ok: true, ...summaryOf(pkg) } : { folder: ent.name, ok: false, error: pkg.error });
146
+ if (out.length >= 50) break;
147
+ }
148
+ return out;
149
+ }
150
+
151
+
152
+
153
+
154
+
155
+ export function resolveToolPath(path, { dir, isProtected = isProtectedPath } = {}) {
156
+ if (typeof path !== "string" || path.trim() === "") return { ok: false, error: "path is required" };
157
+ const target = isAbsolute(path) ? resolve(path) : resolve(dir, path);
158
+ let real;
159
+ try { real = realpathSync(target); } catch { return { ok: false, error: `no such folder: ${target}` }; }
160
+ let realDir = null;
161
+ try { realDir = realpathSync(dir); } catch { }
162
+ const inToolbox = realDir !== null && (real === realDir || (relative(realDir, real) !== "" && !relative(realDir, real).startsWith("..") && !isAbsolute(relative(realDir, real))));
163
+ if (inToolbox && real === realDir) return { ok: false, error: "give one tool's folder, not the toolbox folder itself" };
164
+ if (!inToolbox && isProtected(real)) return { ok: false, error: "that folder is inside the DSH home and can't be sent to the phone" };
165
+ return { ok: true, path: real };
166
+ }
167
+
168
+ const OFFER_TOOL = {
169
+ name: "toolbox_offer_tool",
170
+ description:
171
+ "Offer a small offline tool to the user's DSH Mobile phone app (its Toolbox tab). The phone asks the user, naming this computer, and installs it only if they accept. " +
172
+ "A tool is a folder with tool.json {\"id\": \"lowercase-id\", \"name\": \"Shown name\", \"version\": \"1.0.0\", \"description\": \"one line\"} and index.html, plus optional assets (css, js, images, fonts), at most 5 MB and 200 files. " +
173
+ "It runs in a locked sandbox on the phone: no network at all (fetch, XHR, WebSocket and external URLs are blocked), no native APIs, no access to other tools or app data. " +
174
+ "Local <script src>, <link rel=stylesheet href>, <img src> and CSS url() references are inlined by the phone; fetch() of the tool's own files does not work, so embed data in JS. " +
175
+ "Save data with localStorage or IndexedDB (kept per tool, erased on uninstall). Inline scripts are allowed; eval and new Function are not. " +
176
+ "`path` is the folder: absolute, or a folder name inside this plugin's toolbox folder.",
177
+ parameters: {
178
+ type: "object",
179
+ properties: { path: { type: "string", description: "The tool's folder (absolute path, or a folder name in the toolbox folder)." } },
180
+ required: ["path"],
181
+ additionalProperties: false,
182
+ },
183
+ };
184
+ const OFFER_OUTPUT = {
185
+ type: "object",
186
+ properties: { status: { type: "string", enum: [...OFFER_STATUSES] }, detail: { type: "string" } },
187
+ required: ["status"],
188
+ additionalProperties: false,
189
+ };
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+ export function createToolbox({ ctx, broadcast, pcName, dir = toolboxDir(), now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, graceMs = GRACE_MS, isProtected = isProtectedPath } = {}) {
199
+ const name = pcName || hostname();
200
+ const offers = new Map();
201
+ let disposer = null;
202
+
203
+ const settle = (id, result) => {
204
+ const o = offers.get(id);
205
+ if (!o) return false;
206
+ offers.delete(id);
207
+ clearTimer(o.timer);
208
+ o.offAbort?.();
209
+ broadcast({ type: "toolbox-offer-resolved", id, status: result.status });
210
+ ctx?.logger?.debug?.(`mobile-remote: toolbox offer ${id} (${o.pkg.manifest.id}) → ${result.status}`);
211
+ o.resolve(result);
212
+ return true;
213
+ };
214
+ const arm = (id, ms, status, detail) => {
215
+ const o = offers.get(id);
216
+ if (!o) return;
217
+ clearTimer(o.timer);
218
+ o.timer = setTimer(() => settle(id, { status, detail }), ms);
219
+ o.timer.unref?.();
220
+ };
221
+
222
+ let registered = false;
223
+ let native = false;
224
+ const addTool = () => {
225
+ const tools = hostTools();
226
+ if (!tools) return;
227
+ try {
228
+ disposer = tools.register(toolDef(), native ? { when: () => capable.active() } : undefined) ?? (() => {});
229
+ } catch (err) {
230
+ disposer = null;
231
+ ctx?.logger?.warn?.(`mobile-remote: toolbox tool not registered (${err?.message ?? err})`);
232
+ }
233
+ };
234
+ const removeTool = () => { try { disposer?.(); } catch { } disposer = null; };
235
+
236
+
237
+ const capable = createCapableTracker({
238
+ header: TOOLBOX_HEADER, graceMs, setTimer, clearTimer,
239
+ onActive: () => { if (registered && !native && disposer === null) addTool(); },
240
+ onIdle: () => { if (!native) removeTool(); },
241
+ });
242
+
243
+
244
+ const offer = (path, exec) => {
245
+ if (!capable.active()) throw new Error("phone not connected: no DSH Mobile app that can install tools is connected to this computer right now. Tell the user to open the app, then try again.");
246
+ if (offers.size >= MAX_PENDING_OFFERS) throw new Error("too many tool offers are waiting for the user");
247
+ const where = resolveToolPath(path, { dir, isProtected });
248
+ if (!where.ok) throw new Error(where.error);
249
+ const pkg = packageToolFolder(where.path);
250
+ if (!pkg.ok) throw new Error(`not a valid tool: ${pkg.error}`);
251
+ const id = randomUUID();
252
+ return new Promise((resolveOffer) => {
253
+ const o = { pkg, resolve: resolveOffer, timer: null, phase: "asking", offAbort: null };
254
+ offers.set(id, o);
255
+ arm(id, OFFER_PENDING_MS, "timeout", "the phone did not answer in time");
256
+ const signal = exec?.signal;
257
+ if (signal) {
258
+ const onAbort = () => settle(id, { status: "declined", detail: "the agent stopped this call" });
259
+ if (signal.aborted) queueMicrotask(onAbort);
260
+ else { signal.addEventListener("abort", onAbort, { once: true }); o.offAbort = () => signal.removeEventListener("abort", onAbort); }
261
+ }
262
+ broadcast({ type: "toolbox-offer", id, pcName: name, tool: summaryOf(pkg), expiresAt: now() + OFFER_ASK_MS });
263
+ });
264
+ };
265
+
266
+ const hostTools = () => {
267
+ let tools;
268
+ try { tools = ctx?.get?.("tools"); } catch { tools = undefined; }
269
+ if (typeof tools?.register !== "function") { try { tools = ctx?.tools; } catch { tools = undefined; } }
270
+ return typeof tools?.register === "function" ? tools : undefined;
271
+ };
272
+
273
+ const toolDef = () => ({
274
+ ...OFFER_TOOL,
275
+ output: { schema: OFFER_OUTPUT, render: (_a, v) => [{ type: "text", text: `toolbox_offer_tool: ${v.status}${v.detail ? ` (${v.detail})` : ""}` }] },
276
+ async execute(args, exec) {
277
+ const r = await offer(args?.path, exec);
278
+ return r.detail ? { status: r.status, detail: r.detail } : { status: r.status };
279
+ },
280
+ });
281
+
282
+
283
+ const register = () => {
284
+ if (registered) return true;
285
+ const tools = hostTools();
286
+ if (!tools) return false;
287
+ native = typeof tools.resolve === "function";
288
+ if (native || capable.active()) {
289
+ addTool();
290
+ if (disposer === null && native) return false;
291
+ }
292
+ registered = true;
293
+ ctx?.effect?.(() => () => {
294
+ removeTool();
295
+ registered = false;
296
+ capable.dispose();
297
+ for (const id of [...offers.keys()]) settle(id, { status: "declined", detail: "plugin stopped" });
298
+ });
299
+ return true;
300
+ };
301
+
302
+
303
+ const handle = async (req, res, rest, method, url) => {
304
+ if (rest === "/toolbox/local") {
305
+ if (method !== "GET") return sendError(res, 405, "method-not-allowed"), true;
306
+ sendJson(res, 200, { ok: true, pcName: name, folder: dir, tools: listLocalTools(dir) });
307
+ return true;
308
+ }
309
+ if (rest === "/toolbox/package") {
310
+ if (method !== "GET") return sendError(res, 405, "method-not-allowed"), true;
311
+ const folder = url?.searchParams?.get("folder") ?? "";
312
+ if (!validFolderName(folder)) return sendError(res, 400, "bad-request", "folder is required"), true;
313
+ const pkg = packageToolFolder(join(dir, folder));
314
+ if (!pkg.ok) return sendError(res, 422, "invalid-tool", pkg.error), true;
315
+ sendJson(res, 200, bundleBody(pkg));
316
+ return true;
317
+ }
318
+ const m = /^\/toolbox\/offers\/([0-9a-f-]{36})$/.exec(rest);
319
+ if (m) {
320
+ if (method !== "GET") return sendError(res, 405, "method-not-allowed"), true;
321
+ const o = offers.get(m[1]);
322
+ if (!o) return sendError(res, 404, "unknown-or-expired"), true;
323
+
324
+ if (o.phase === "asking") { o.phase = "fetching"; arm(m[1], OFFER_FETCH_MS, "timeout", "the phone did not finish installing"); }
325
+ sendJson(res, 200, bundleBody(o.pkg));
326
+ return true;
327
+ }
328
+ if (rest === "/toolbox/offer-result") {
329
+ if (method !== "POST") return sendError(res, 405, "method-not-allowed"), true;
330
+ let body;
331
+ try { body = JSON.parse(await readBody(req, 8 * 1024)) ?? {}; } catch (err) {
332
+ return sendError(res, err?.status === 413 ? 413 : 400, err?.status === 413 ? "payload-too-large" : "bad-request"), true;
333
+ }
334
+ const id = typeof body.id === "string" ? body.id : "";
335
+ if (id === "" || id.length > 80 || !OFFER_STATUSES.includes(body.status)) return sendError(res, 400, "bad-request", "id and a known status are required"), true;
336
+ const detail = clean(body.detail, 200);
337
+ if (!settle(id, detail ? { status: body.status, detail } : { status: body.status })) return sendError(res, 404, "unknown-or-expired"), true;
338
+ sendJson(res, 200, { ok: true });
339
+ return true;
340
+ }
341
+ return false;
342
+ };
343
+
344
+ return {
345
+ register,
346
+ handle,
347
+ offer,
348
+
349
+ attach: (res, req) => capable.attach(res, req),
350
+ toolOffered: () => capable.active(),
351
+ pendingCount: () => offers.size,
352
+ dir,
353
+ };
354
+ }
355
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-mobile/mobile-remote",
3
- "version": "3.4.1-beta.2",
3
+ "version": "3.5.0-beta.1",
4
4
  "description": "DSH Mobile:把 DeepSeek Harness 变成随身控制台——手机远程发消息派活、看进度、收通知、审批决策、管理会话;配套 Flutter App(Android、iPhone / iPad)",
5
5
  "homepage": "https://dsh.claud.ing/",
6
6
  "repository": {