dsh-plugin-mesh 0.5.6 → 0.5.8

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/upgrade.js ADDED
@@ -0,0 +1,635 @@
1
+ /**
2
+ * 一键升级:下载 → sha512 校验 → 解包 → 真实 import 可加载检查 → 原子替换。
3
+ *
4
+ * 为什么是这一套顺序:升级最大的风险不是"下载失败",而是**半态** ——
5
+ * 磁盘换了一半、或换了却加载不了,用户一重启 DSH 就崩(0.3.28 真踩过:
6
+ * 文件级 cmp 全绿、node --check 全绿,重启当场崩)。所以这里每一道闸都
7
+ * 放在"覆盖旧版"之前,任何一步不通过都保留旧版、清掉 staging。
8
+ *
9
+ * 为什么从 npm tarball 装、而不是 GitHub Release 资产:
10
+ * · npm 的 metadata 带 `dist.integrity`(sha512),能校验;GitHub 资产的
11
+ * digest 要问 api.github.com,而国内这个域名经常不通;
12
+ * · npm 官方源 + npmmirror 两条路,都不依赖 ghfast 这类代理;
13
+ * · npm 包里 `files` 与 GitHub 资产同源(都来自 package.json),内容等价,
14
+ * 只是多一层 `package/` 前缀,解包时 strip 掉即可。
15
+ *
16
+ * 本文件不碰 HTTP 路由,也不决定"要不要重启";那些在 index.js / client 里。
17
+ */
18
+ import { createHash, timingSafeEqual } from "node:crypto";
19
+ import {
20
+ chmodSync,
21
+ existsSync,
22
+ mkdirSync,
23
+ readFileSync,
24
+ readdirSync,
25
+ renameSync,
26
+ rmSync,
27
+ statSync,
28
+ writeFileSync,
29
+ } from "node:fs";
30
+ import { dirname, join, relative, resolve, sep } from "node:path";
31
+ import { pathToFileURL } from "node:url";
32
+ import { gunzipSync } from "node:zlib";
33
+ import { compareVersions, parseVersion } from "./update.js";
34
+
35
+ export const PACKAGE_NAME = "dsh-plugin-mesh";
36
+ /** 版本元数据源:官方优先,国内镜像兜底(镜像可能滞后,滞后会明确报错)。 */
37
+ export const REGISTRY_BASES = [
38
+ "https://registry.npmjs.org",
39
+ "https://registry.npmmirror.com",
40
+ ];
41
+ /** 安装目录同级的临时目录前缀:放同一个文件系统里,rename 才是原子的。 */
42
+ const STAGING_PREFIX = ".mesh-upgrade-staging-";
43
+ const BACKUP_PREFIX = ".mesh-upgrade-backup-";
44
+ /** 下载上限:当前包约 450KB,32MB 足够挡住错误的响应体。 */
45
+ const MAX_TARBALL_BYTES = 32 * 1024 * 1024;
46
+
47
+ // ─────────────────────── 小工具 ───────────────────────
48
+
49
+ function timeoutSignal(ms) {
50
+ if (typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function") {
51
+ return AbortSignal.timeout(ms);
52
+ }
53
+ return undefined;
54
+ }
55
+
56
+ function hostOf(url) {
57
+ try {
58
+ return new URL(url).host;
59
+ } catch {
60
+ return String(url || "版本源");
61
+ }
62
+ }
63
+
64
+ function errText(err, timeoutMs) {
65
+ const timedOut = err?.name === "TimeoutError" || err?.name === "AbortError";
66
+ return timedOut ? `超时(${timeoutMs}ms)` : String(err?.message ?? err);
67
+ }
68
+
69
+ function sha256File(file) {
70
+ return createHash("sha256").update(readFileSync(file)).digest("hex");
71
+ }
72
+
73
+ // ─────────────────────── 校验 ───────────────────────
74
+
75
+ /** 解析 npm 的 `dist.integrity`(`sha512-<base64>`);不认识就返回 null。 */
76
+ export function parseIntegrity(raw) {
77
+ const m = /^(sha512|sha384|sha256|sha1)-([A-Za-z0-9+/=]+)$/.exec(String(raw ?? "").trim());
78
+ if (!m) return null;
79
+ return { algorithm: m[1], digest: Buffer.from(m[2], "base64") };
80
+ }
81
+
82
+ /** 用 registry 记录的完整性校验下载内容。算法/长度不对一律 false。 */
83
+ export function verifyBuffer(buffer, integrity) {
84
+ const parsed = parseIntegrity(integrity);
85
+ if (!parsed || !Buffer.isBuffer(buffer)) return false;
86
+ const actual = createHash(parsed.algorithm).update(buffer).digest();
87
+ return actual.length === parsed.digest.length && timingSafeEqual(actual, parsed.digest);
88
+ }
89
+
90
+ // ─────────────────────── tar.gz ───────────────────────
91
+
92
+ /** 读 tar 头里的 C 字符串字段(NUL 或字段末尾为止)。 */
93
+ function cstr(tar, start, end) {
94
+ let i = start;
95
+ while (i < end && tar[i] !== 0) i += 1;
96
+ return tar.subarray(start, i).toString("utf8");
97
+ }
98
+
99
+ /** 八进制字段;空字段按 0。 */
100
+ function octal(tar, start, end) {
101
+ const raw = cstr(tar, start, end).trim();
102
+ if (raw === "") return 0;
103
+ const n = Number.parseInt(raw, 8);
104
+ return Number.isFinite(n) ? n : 0;
105
+ }
106
+
107
+ /**
108
+ * 解 gzip 后的 tar,返回内存里的条目(不写盘,便于单测)。
109
+ *
110
+ * 只接受普通文件和目录;符号链接/设备直接跳过 —— 插件包里没有这些,
111
+ * 而"解出符号链接"正是 tar 路径穿越最常见的利用方式。
112
+ * `stripComponents` 用来去掉 npm 包的 `package/` 前缀。
113
+ */
114
+ export function extractTarball(buffer, { stripComponents = 0 } = {}) {
115
+ if (!Buffer.isBuffer(buffer) || buffer.length === 0) throw new Error("空的压缩包");
116
+ let tar;
117
+ try {
118
+ tar = gunzipSync(buffer);
119
+ } catch (err) {
120
+ throw new Error(`不是有效的 .tar.gz:${err?.message ?? err}`);
121
+ }
122
+ const entries = [];
123
+ let offset = 0;
124
+ while (offset + 512 <= tar.length) {
125
+ const header = tar.subarray(offset, offset + 512);
126
+ if (header.every((b) => b === 0)) break;
127
+ const rawName = cstr(header, 0, 100);
128
+ const prefix = cstr(header, 345, 500);
129
+ const name = prefix ? `${prefix}/${rawName}` : rawName;
130
+ const mode = octal(header, 100, 108);
131
+ const size = octal(header, 124, 136);
132
+ const type = header[156] === 0 ? "0" : String.fromCharCode(header[156]);
133
+ const dataStart = offset + 512;
134
+ const dataEnd = dataStart + size;
135
+ if (dataEnd > tar.length) throw new Error(`压缩包被截断(${name})`);
136
+ const data = tar.subarray(dataStart, dataEnd);
137
+ offset = dataStart + Math.ceil(size / 512) * 512;
138
+ if (type !== "0" && type !== "5") continue; // 链接/设备/扩展头:不落地
139
+ const parts = name.split("/").filter((p) => p !== "" && p !== ".");
140
+ if (name.startsWith("/") || parts.includes("..")) throw new Error(`压缩包里有不安全路径:${name}`);
141
+ const stripped = parts.slice(stripComponents);
142
+ if (stripped.length === 0) continue;
143
+ entries.push({
144
+ path: stripped.join("/"),
145
+ dir: type === "5",
146
+ mode: (mode || 0o644) & 0o777,
147
+ data: type === "5" ? Buffer.alloc(0) : Buffer.from(data),
148
+ });
149
+ }
150
+ if (entries.length === 0) throw new Error("压缩包里没有文件");
151
+ return entries;
152
+ }
153
+
154
+ /** 把条目写进 staging 目录;再次拒绝越界路径(防御性,不依赖解包时的检查)。 */
155
+ export function writeEntries(dir, entries) {
156
+ const root = resolve(dir);
157
+ for (const entry of entries) {
158
+ const target = resolve(root, entry.path);
159
+ if (target !== root && !target.startsWith(root + sep)) {
160
+ throw new Error(`拒绝写到目录之外:${entry.path}`);
161
+ }
162
+ if (entry.dir) {
163
+ mkdirSync(target, { recursive: true });
164
+ continue;
165
+ }
166
+ mkdirSync(dirname(target), { recursive: true });
167
+ writeFileSync(target, entry.data);
168
+ try {
169
+ chmodSync(target, entry.mode & 0o777 || 0o644);
170
+ } catch {
171
+ /* Windows 上 chmod 基本无效,忽略 */
172
+ }
173
+ }
174
+ }
175
+
176
+ // ─────────────────────── 差异分类 ───────────────────────
177
+
178
+ function walkFiles(dir, base = dir, out = []) {
179
+ for (const name of readdirSync(dir)) {
180
+ if (name === "node_modules" || name === ".DS_Store") continue;
181
+ const full = join(dir, name);
182
+ const st = statSync(full);
183
+ if (st.isDirectory()) walkFiles(full, base, out);
184
+ else if (st.isFile()) out.push(relative(base, full).split(sep).join("/"));
185
+ }
186
+ return out;
187
+ }
188
+
189
+ /**
190
+ * 比对旧目录与新目录(按文件内容哈希),并回答两个问题:
191
+ * · 要不要重启宿主?只由 `lib/` 变化决定 —— 每版的 package.json 版本号都会变,
192
+ * 但那只是元数据,不需要为它重启;
193
+ * · 要不要重载界面?只有当 **client 变了而 lib 没变** 时,才够用。
194
+ * 其余变化(package.json 的版本号、scripts/、sidecar/ 源码、文档)不需要重启,
195
+ * 也不影响正在跑的代码。
196
+ */
197
+ export function collectChanges(oldDir, newDir) {
198
+ const before = new Map(walkFiles(oldDir).map((f) => [f, sha256File(join(oldDir, f))]));
199
+ const after = new Map(walkFiles(newDir).map((f) => [f, sha256File(join(newDir, f))]));
200
+ const changed = [];
201
+ for (const [file, hash] of after) {
202
+ if (before.get(file) !== hash) changed.push(file);
203
+ }
204
+ for (const file of before.keys()) {
205
+ if (!after.has(file)) changed.push(file);
206
+ }
207
+ changed.sort();
208
+ const isClient = (f) => f === "client" || f.startsWith("client/");
209
+ const isHost = (f) => f === "lib" || f.startsWith("lib/");
210
+ const clientChanged = changed.some(isClient);
211
+ const hostChanged = changed.some(isHost);
212
+ const pkgChanged = changed.includes("package.json");
213
+ const otherChanged = changed.some((f) => !isClient(f) && !isHost(f) && f !== "package.json");
214
+ return {
215
+ changed,
216
+ client: clientChanged,
217
+ host: hostChanged,
218
+ packageJson: pkgChanged,
219
+ other: otherChanged,
220
+ // 只改了版本号(既没动 lib 也没动 client)时也建议重启:进程里的 VERSION
221
+ // 是启动常量,不重启的话界面会一直显示旧版本号("装了却没生效"的观感)。
222
+ restartRequired: hostChanged || (!hostChanged && !clientChanged && pkgChanged),
223
+ reloadRequired: !hostChanged && clientChanged,
224
+ };
225
+ }
226
+
227
+ // ─────────────────────── 下载 ───────────────────────
228
+
229
+ /** 取某个版本的 metadata(tarball + integrity),官方源优先、镜像兜底。 */
230
+ export async function fetchVersionMeta({
231
+ version,
232
+ fetchImpl = globalThis.fetch,
233
+ timeoutMs = 8000,
234
+ bases = REGISTRY_BASES,
235
+ } = {}) {
236
+ const failures = [];
237
+ if (typeof fetchImpl !== "function") return { ok: false, error: "当前环境没有 fetch,无法下载", failures };
238
+ const wanted = String(version ?? "").trim();
239
+ if (!parseVersion(wanted)) return { ok: false, error: `版本号不合法:${wanted}`, failures };
240
+ for (const base of bases) {
241
+ const url = `${base}/${PACKAGE_NAME}/${wanted}`;
242
+ try {
243
+ const res = await fetchImpl(url, {
244
+ headers: { accept: "application/json" },
245
+ signal: timeoutSignal(timeoutMs),
246
+ });
247
+ if (!res || res.ok !== true) {
248
+ failures.push(`${hostOf(url)} HTTP ${res ? res.status : "无响应"}`);
249
+ continue;
250
+ }
251
+ const meta = await res.json();
252
+ const gotVersion = String(meta?.version ?? "").trim();
253
+ const tarball = String(meta?.dist?.tarball ?? "").trim();
254
+ const integrity = String(meta?.dist?.integrity ?? "").trim();
255
+ if (gotVersion !== wanted) {
256
+ failures.push(`${hostOf(url)} 返回 ${gotVersion || "空版本"},不是 ${wanted}`);
257
+ continue;
258
+ }
259
+ if (!tarball) {
260
+ failures.push(`${hostOf(url)} 没有 dist.tarball`);
261
+ continue;
262
+ }
263
+ if (!parseIntegrity(integrity)) {
264
+ failures.push(`${hostOf(url)} 没有可用的 dist.integrity`);
265
+ continue;
266
+ }
267
+ return { ok: true, version: wanted, tarball, integrity, source: base };
268
+ } catch (err) {
269
+ failures.push(`${hostOf(url)} ${errText(err, timeoutMs)}`);
270
+ }
271
+ }
272
+ return {
273
+ ok: false,
274
+ failures,
275
+ error: failures.length ? `取版本信息失败:${failures.join(";")}` : "没有可用的版本源",
276
+ };
277
+ }
278
+
279
+ /** 下载并校验;校验不过一律丢弃,绝不返回"可疑但能用"的包。 */
280
+ export async function downloadTarball({
281
+ tarball,
282
+ integrity,
283
+ fetchImpl = globalThis.fetch,
284
+ timeoutMs = 60000,
285
+ maxBytes = MAX_TARBALL_BYTES,
286
+ } = {}) {
287
+ if (typeof fetchImpl !== "function") return { ok: false, error: "当前环境没有 fetch,无法下载" };
288
+ let res;
289
+ try {
290
+ res = await fetchImpl(tarball, {
291
+ headers: { accept: "application/octet-stream" },
292
+ signal: timeoutSignal(timeoutMs),
293
+ });
294
+ } catch (err) {
295
+ return { ok: false, error: `下载失败:${errText(err, timeoutMs)}` };
296
+ }
297
+ if (!res || res.ok !== true) return { ok: false, error: `下载失败:HTTP ${res ? res.status : "无响应"}` };
298
+ const declared = Number(res.headers?.get?.("content-length") ?? 0);
299
+ if (declared > maxBytes) return { ok: false, error: `包太大(${declared} 字节),拒绝下载` };
300
+ const buffer = Buffer.from(await res.arrayBuffer());
301
+ if (buffer.length > maxBytes) return { ok: false, error: `包太大(${buffer.length} 字节),拒绝安装` };
302
+ if (!verifyBuffer(buffer, integrity)) {
303
+ return { ok: false, error: "sha512 校验失败:下载内容与 registry 记录不一致,已丢弃" };
304
+ }
305
+ return { ok: true, buffer };
306
+ }
307
+
308
+ // ─────────────────────── 安装 ───────────────────────
309
+
310
+ /** 默认的可加载检查:真的 import 一次入口。失败信息原样带出。 */
311
+ export async function defaultCheckLoadable(entryFile) {
312
+ const url = `${pathToFileURL(entryFile).href}?mesh-upgrade=${Date.now()}`;
313
+ const mod = await import(url);
314
+ if (typeof mod?.apply !== "function") return { ok: false, error: "入口没有导出 apply(),不是可用的插件包" };
315
+ return { ok: true, exports: Object.keys(mod).sort() };
316
+ }
317
+
318
+ /** 只保留最近 N 份本工具创建的备份,避免 node_modules 里越堆越多。 */
319
+ export function pruneBackups(parentDir, keep = 3) {
320
+ let names;
321
+ try {
322
+ names = readdirSync(parentDir).filter((n) => n.startsWith(BACKUP_PREFIX)).sort();
323
+ } catch {
324
+ return;
325
+ }
326
+ for (const name of names.slice(0, Math.max(0, names.length - keep))) {
327
+ rmSync(join(parentDir, name), { recursive: true, force: true });
328
+ }
329
+ }
330
+
331
+ export function readUpgradeMarker(path) {
332
+ try {
333
+ const data = JSON.parse(readFileSync(path, "utf8"));
334
+ return data && typeof data === "object" ? data : null;
335
+ } catch {
336
+ return null;
337
+ }
338
+ }
339
+
340
+ export function writeUpgradeMarker(path, data) {
341
+ try {
342
+ mkdirSync(dirname(path), { recursive: true });
343
+ writeFileSync(path, `${JSON.stringify(data, null, 2)}\n`);
344
+ return true;
345
+ } catch {
346
+ return false;
347
+ }
348
+ }
349
+
350
+ export function clearUpgradeMarker(path) {
351
+ try {
352
+ rmSync(path, { force: true });
353
+ } catch {
354
+ /* 清不掉不影响功能,下一次判断会重新覆盖 */
355
+ }
356
+ }
357
+
358
+ /**
359
+ * 真正的升级流程。所有输入显式传入(测试可以给假 fetch、临时目录、假可加载检查)。
360
+ *
361
+ * 返回 `{ok:false, error, stage}` 时**旧版一定还在原地**;只有 `ok:true && installed`
362
+ * 才代表磁盘已经换成新版本(此时进程仍在跑旧代码,是否重启由调用方决定)。
363
+ */
364
+ export async function installUpdate({
365
+ version,
366
+ current = "",
367
+ pluginDir,
368
+ fetchImpl = globalThis.fetch,
369
+ now = Date.now(),
370
+ checkLoadable = defaultCheckLoadable,
371
+ markerPath = "",
372
+ log = () => {},
373
+ } = {}) {
374
+ const target = String(version ?? "").trim();
375
+ const dir = String(pluginDir ?? "").trim();
376
+ if (!dir) return { ok: false, error: "不知道插件的安装目录", stage: "input" };
377
+ if (!parseVersion(target)) return { ok: false, error: `目标版本号不合法:${target}`, stage: "input" };
378
+ if (current) {
379
+ const cmp = compareVersions(target, current);
380
+ if (cmp !== 1) {
381
+ return {
382
+ ok: false,
383
+ error: `目标版本 v${target} 不比当前 v${current} 新,拒绝覆盖`,
384
+ stage: "input",
385
+ };
386
+ }
387
+ }
388
+ if (!existsSync(join(dir, "package.json"))) {
389
+ return { ok: false, error: `安装目录里没有 package.json:${dir}`, stage: "input" };
390
+ }
391
+
392
+ const started = Date.now();
393
+ const meta = await fetchVersionMeta({ version: target, fetchImpl });
394
+ if (!meta.ok) return { ok: false, error: meta.error, failures: meta.failures, stage: "meta" };
395
+ const dl = await downloadTarball({ tarball: meta.tarball, integrity: meta.integrity, fetchImpl });
396
+ if (!dl.ok) return { ok: false, error: dl.error, stage: "download" };
397
+
398
+ let entries;
399
+ try {
400
+ entries = extractTarball(dl.buffer, { stripComponents: 1 });
401
+ } catch (err) {
402
+ return { ok: false, error: err?.message ?? String(err), stage: "extract" };
403
+ }
404
+
405
+ const parent = dirname(dir);
406
+ const staging = join(parent, `${STAGING_PREFIX}${target}-${now}`);
407
+ const cleanupStaging = () => rmSync(staging, { recursive: true, force: true });
408
+ try {
409
+ rmSync(staging, { recursive: true, force: true });
410
+ mkdirSync(staging, { recursive: true });
411
+ writeEntries(staging, entries);
412
+ } catch (err) {
413
+ cleanupStaging();
414
+ return { ok: false, error: `解包失败:${err?.message ?? err}`, stage: "extract" };
415
+ }
416
+
417
+ let pkg = null;
418
+ try {
419
+ pkg = JSON.parse(readFileSync(join(staging, "package.json"), "utf8"));
420
+ } catch {
421
+ /* 下面统一报错 */
422
+ }
423
+ if (pkg?.name !== PACKAGE_NAME || String(pkg?.version ?? "") !== target) {
424
+ cleanupStaging();
425
+ return {
426
+ ok: false,
427
+ error: `新包身份不符:${String(pkg?.name ?? "缺 package.json")}@${String(pkg?.version ?? "?")}`,
428
+ stage: "validate",
429
+ };
430
+ }
431
+
432
+ const changed = collectChanges(dir, staging);
433
+ if (changed.changed.length === 0) {
434
+ cleanupStaging();
435
+ return {
436
+ ok: true,
437
+ installed: false,
438
+ upToDate: true,
439
+ version: target,
440
+ source: meta.source,
441
+ changed,
442
+ restartRequired: false,
443
+ reloadRequired: false,
444
+ durationMs: Date.now() - started,
445
+ };
446
+ }
447
+
448
+ let load;
449
+ try {
450
+ load = await checkLoadable(join(staging, "lib", "index.js"));
451
+ } catch (err) {
452
+ load = { ok: false, error: String(err?.message ?? err) };
453
+ }
454
+ if (!load?.ok) {
455
+ cleanupStaging();
456
+ return {
457
+ ok: false,
458
+ error: `新版本不可加载,已保留旧版:${load?.error ?? "未知原因"}`,
459
+ stage: "loadable",
460
+ changed,
461
+ };
462
+ }
463
+
464
+ const backup = join(parent, `${BACKUP_PREFIX}${String(current || "old")}-${now}`);
465
+ try {
466
+ renameSync(dir, backup);
467
+ } catch (err) {
468
+ cleanupStaging();
469
+ return { ok: false, error: `无法备份旧版:${err?.message ?? err}`, stage: "swap" };
470
+ }
471
+ try {
472
+ renameSync(staging, dir);
473
+ } catch (err) {
474
+ try {
475
+ renameSync(backup, dir);
476
+ } catch {
477
+ /* 回滚也失败:保留 backup 路径,让人能手工救 */
478
+ }
479
+ cleanupStaging();
480
+ return {
481
+ ok: false,
482
+ error: `替换失败,已尝试回滚:${err?.message ?? err}`,
483
+ stage: "swap",
484
+ rolledBack: true,
485
+ backupDir: backup,
486
+ };
487
+ }
488
+ pruneBackups(parent, 3);
489
+ log(`升级完成:v${current || "?"} → v${target}(备份 ${backup})`);
490
+ const result = {
491
+ ok: true,
492
+ installed: true,
493
+ version: target,
494
+ previous: current,
495
+ source: meta.source,
496
+ registry: meta.source,
497
+ integrity: meta.integrity,
498
+ backupDir: backup,
499
+ changed,
500
+ restartRequired: changed.restartRequired,
501
+ reloadRequired: changed.reloadRequired,
502
+ durationMs: Date.now() - started,
503
+ };
504
+ if (markerPath) {
505
+ writeUpgradeMarker(markerPath, {
506
+ version: target,
507
+ previous: current,
508
+ at: new Date(now).toISOString(),
509
+ restartRequired: changed.restartRequired,
510
+ reloadRequired: changed.reloadRequired,
511
+ changed: changed.changed,
512
+ });
513
+ }
514
+ return result;
515
+ }
516
+
517
+ // ─────────────────────── 控制请求守卫 / 重启 ───────────────────────
518
+
519
+ /**
520
+ * 进程控制类接口只接受「同源回环」请求。和 dshmarket 的守卫同一套判断:
521
+ * 回环 peer + 没有转发头 + Origin 与 Host 一致 —— 防止局域网页面或代理
522
+ * 借用户的浏览器点一下就把宿主重启了。
523
+ */
524
+ export function trustedControlRequest(req) {
525
+ const address = req?.socket?.remoteAddress;
526
+ if (address !== "127.0.0.1" && address !== "::1" && address !== "::ffff:127.0.0.1") return false;
527
+ const headers = req?.headers;
528
+ if (!headers) return false;
529
+ if (headers.forwarded !== undefined || headers["x-forwarded-for"] !== undefined || headers["x-real-ip"] !== undefined) {
530
+ return false;
531
+ }
532
+ const origin = headers.origin;
533
+ const host = headers.host;
534
+ if (!origin || !host) return false;
535
+ try {
536
+ const parsed = new URL(origin);
537
+ return (parsed.protocol === "http:" || parsed.protocol === "https:") && parsed.host === host;
538
+ } catch {
539
+ return false;
540
+ }
541
+ }
542
+
543
+ /**
544
+ * 用宿主自己的重启入口,而不是 shell 脚本。
545
+ *
546
+ * DSH Desktop 提供 `desktopSettingsController.restart()`:原生确认框 + 有序
547
+ * relaunch(和切换 profile 同一条路),不需要 osascript/launchctl,也就没有
548
+ * "重启循环"那一类风险。返回值里的 `afterResponse` 约定由路由层在响应结束后
549
+ * 调用,插件直接调用时要自己触发。
550
+ */
551
+ /**
552
+ * 重载渲染器(只改了 client 时用)。
553
+ *
554
+ * DSH Desktop 提供 `desktopSettingsController.reloadRenderer()`:和「设置 → 开发者
555
+ * 选项 → 重新加载界面」同一个动作,由 Electron 替换当前文档(同时绕开缓存),
556
+ * 比页面自己 `location.reload()` 更可靠。没有这个入口的宿主(dsh web/headless)
557
+ * 返回 mode:"self",由调用方退到页面自身重载 —— 客户端半的更新不需要重启宿主。
558
+ */
559
+ export function requestHostReload(ctx) {
560
+ let controller = null;
561
+ try {
562
+ controller = ctx?.get?.("desktopSettingsController") ?? null;
563
+ } catch {
564
+ controller = null;
565
+ }
566
+ if (controller && typeof controller.reloadRenderer === "function") {
567
+ try {
568
+ const result = controller.reloadRenderer();
569
+ if (result && typeof result.afterResponse === "function") result.afterResponse();
570
+ return { ok: true, mode: "desktop" };
571
+ } catch (err) {
572
+ return { ok: false, mode: "desktop", error: `内置重载入口调用失败:${err?.message ?? err}` };
573
+ }
574
+ }
575
+ return { ok: false, mode: "self", error: "当前宿主没有内置重载入口,改用页面自身重载" };
576
+ }
577
+
578
+ export async function requestHostRestart(ctx, { fetchImpl = globalThis.fetch, timeoutMs = 5000 } = {}) {
579
+ let controller = null;
580
+ try {
581
+ controller = ctx?.get?.("desktopSettingsController") ?? null;
582
+ } catch {
583
+ controller = null;
584
+ }
585
+ if (controller && typeof controller.restart === "function") {
586
+ try {
587
+ const result = controller.restart();
588
+ if (result && typeof result.afterResponse === "function") result.afterResponse();
589
+ return { ok: true, mode: "desktop" };
590
+ } catch (err) {
591
+ return { ok: false, mode: "desktop", error: `宿主重启入口调用失败:${err?.message ?? err}` };
592
+ }
593
+ }
594
+
595
+ // 没有桌面控制器(dsh web / headless / CLI)时,退到 dshmarket 的自重启:
596
+ // 它用相同启动参数 detach 重开,并自己做 supervisor 检测与端口等待。
597
+ // 我们自己不去 spawn:那是最容易写出"重启循环"的地方。
598
+ const port = Number(ctx?.webServer?.port) || 0;
599
+ if (port > 0 && typeof fetchImpl === "function") {
600
+ const origin = `http://127.0.0.1:${port}`;
601
+ try {
602
+ const res = await fetchImpl(`${origin}/dsh-market/api/v1/restart`, {
603
+ method: "POST",
604
+ // 市场的守卫按「同源回环」判:Host 与 Origin 必须一致,且不能带转发头。
605
+ headers: { origin, host: `127.0.0.1:${port}`, "content-type": "application/json", accept: "application/json" },
606
+ body: "{}",
607
+ signal: typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(timeoutMs) : undefined,
608
+ });
609
+ if (res && res.ok === true) return { ok: true, mode: "market" };
610
+ let detail = "";
611
+ try {
612
+ detail = String(await res.text()).slice(0, 300);
613
+ } catch {
614
+ /* 读不出原因就只报状态码 */
615
+ }
616
+ return {
617
+ ok: false,
618
+ mode: "manual",
619
+ error: `没有桌面重启入口,市场自重启也不可用(HTTP ${res ? res.status : "无响应"}${detail ? `:${detail}` : ""})。请手动重启 DSH。`,
620
+ };
621
+ } catch (err) {
622
+ return {
623
+ ok: false,
624
+ mode: "manual",
625
+ error: `没有桌面重启入口,市场自重启也没成功(${err?.message ?? err})。请手动重启 DSH。`,
626
+ };
627
+ }
628
+ }
629
+
630
+ return {
631
+ ok: false,
632
+ mode: "manual",
633
+ error: "当前宿主没有内置重启入口(不是 DSH Desktop,也没装市场)。请手动重启 DSH 使新版本生效。",
634
+ };
635
+ }
package/llms.txt CHANGED
@@ -30,6 +30,10 @@ Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON c
30
30
  - Auto-creates an agent session on the receiving machine when a task arrives, then routes that task to a new or reused session.
31
31
  - Reports a structured `osInfo` card entry (host) and a `systems[]` array: host first, then environments such as WSL distros on Windows (`kind: "wsl"`, Linux `platform`, distro name/version). Older peers only send `os`, and the UI falls back to parsing it; purely display data, at most 4 systems.
32
32
  - On Windows, probes runtimes inside **running** WSL distros (`wsl.exe -d <name> -e sh -lc …`) and reports them as `capabilities.wsl[]`; stopped distros are never started just to probe. Host and WSL runtimes are displayed separately.
33
+ - Home-page header exposes two compact text links (no cards): **问题反馈** opens a prefilled GitHub issue, and **检查更新** calls `GET /mesh/api/update`. The update route asks the npm registry (`registry.npmjs.org`, falling back to `registry.npmmirror.com`, 5 s per source, 30 min host-side cache) and compares with the running `VERSION`. A failed check returns `{ok:false,error,failures[]}` and is shown as "检查失败" — never as "已是最新".
34
+ - One-click install: the inline "新版本 vX" link calls `POST /mesh/api/upgrade` (same-origin loopback only). It downloads the npm tarball for that version, verifies `dist.integrity` (sha512), extracts to a sibling staging dir, runs a real `import()` loadability check, backs up the old directory (`.mesh-upgrade-backup-*`, last 3 kept) and atomically swaps. Any failure keeps the old version and returns the failing stage. The result classifies the change: `restartRequired` only when `lib/` changed (plus version-only bumps), `reloadRequired` when only `client/` changed.
35
+ - A successful install writes `upgrade.json` under the mesh state dir; until the process restarts, `GET /mesh/api/update` reports `pendingUpgrade` so the UI offers **重启生效** (`POST /mesh/api/upgrade/restart`) or **重载界面** instead of installing again (`POST /mesh/api/upgrade/reload` uses DSH Desktop's built-in `desktopSettingsController.reloadRenderer()`, the same action as Settings → Developer options → Reload interface; other hosts fall back to a page reload). On DSH Desktop the restart goes through the host's own `desktopSettingsController.restart()` (native confirm + ordered relaunch); plain `dsh web`/headless falls back to dshmarket's self-restart (`POST /dsh-market/api/v1/restart`) when that plugin is installed and not under a detected systemd supervisor. When neither entry exists the response is `mode:"manual"` with an explicit reason — it never pretends a restart happened.
36
+ - The prefilled feedback issue carries the same diagnostics text as the diagnostics section; `buildDiagnostics()` deliberately excludes secrets (pairing code, tsnet auth key). The author's email (`geekstartup@163.com`) is the fallback when GitHub is unreachable.
33
37
 
34
38
  ## Tools registered (callable by the agent)
35
39
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.6",
3
+ "version": "0.5.8",
4
4
  "type": "module",
5
5
  "description": "DSH Mesh:局域网自动发现同网段的 DSH 实例、显示每台机器上报的能力,并双向派发任务;可用内置的用户态 Tailscale 节点跨互联网组网。Discovers other DSH instances on the LAN, shows the capabilities each one reports, and dispatches tasks between machines in both directions, with an optional userspace Tailscale node for links across networks.",
6
6
  "license": "MIT",
@@ -66,8 +66,10 @@
66
66
  "selftest:layout": "node lib/_selftest-layout.mjs",
67
67
  "selftest:diagnostics": "node lib/_selftest-diagnostics.mjs",
68
68
  "selftest:osinfo": "node lib/_selftest-osinfo.mjs",
69
- "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:pairing && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo",
70
- "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
69
+ "selftest:update": "node lib/_selftest-update.mjs",
70
+ "selftest:upgrade": "node lib/_selftest-upgrade.mjs",
71
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:update && npm run selftest:upgrade",
72
+ "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/at-mention.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/upgrade.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
71
73
  "build:sidecar": "bash scripts/build-sidecar.sh",
72
74
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
73
75
  "release:plan": "node scripts/release-plan.mjs",
@@ -78,7 +80,9 @@
78
80
  "prepublishOnly": "npm test && node scripts/check-tarball.mjs",
79
81
  "check:docs": "node scripts/sync-llms.mjs",
80
82
  "selftest:pairing": "node lib/_selftest-pairing.mjs",
81
- "selftest:switch": "node lib/_selftest-switch.mjs"
83
+ "selftest:switch": "node lib/_selftest-switch.mjs",
84
+ "selftest:at": "node lib/_selftest-at-mention.mjs",
85
+ "selftest:at:host": "node --experimental-vm-modules lib/_selftest-at-mention-host.mjs"
82
86
  },
83
87
  "publishConfig": {
84
88
  "registry": "https://registry.npmjs.org/",