dsh-plugin-mesh 0.5.1 → 0.5.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.
@@ -23,9 +23,13 @@
23
23
  * 失败更糟,因为它看起来像正常的空数据。
24
24
  */
25
25
  import { execFile } from "node:child_process";
26
+ import { promisify } from "node:util";
26
27
  import { existsSync } from "node:fs";
27
28
  import { homedir, release, totalmem, cpus, platform, arch } from "node:os";
28
29
  import { join, delimiter } from "node:path";
30
+ import { wslTargets } from "./osinfo.js";
31
+
32
+ const execFileAsync = promisify(execFile);
29
33
 
30
34
  /** 重新采集的间隔。设计上低频:装了新运行时最迟 10 分钟后上名片。 */
31
35
  export const CAPABILITY_REFRESH_MS = 10 * 60 * 1000;
@@ -104,7 +108,8 @@ function extraPathDirs(p = platform(), env = process.env) {
104
108
  env["ProgramFiles(x86)"] && join(env["ProgramFiles(x86)"], "nodejs"),
105
109
  env.APPDATA && join(env.APPDATA, "npm"),
106
110
  env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Programs", "Python"),
107
- env.LOCALAPPDATA && join(env.LOCALAPPDATA, "Microsoft", "WindowsApps"),
111
+ // 不要把 WindowsApps 补进探测 PATH:那里几乎全是 0 字节的 Store 别名存根,
112
+ // 前置后会遮住后面真正的 python.exe / node.exe(spawn 得 exit 9009)。
108
113
  env.ProgramFiles && join(env.ProgramFiles, "Git", "cmd"),
109
114
  env.ProgramFiles && join(env.ProgramFiles, "Docker", "Docker", "resources", "bin"),
110
115
  env.ProgramData && join(env.ProgramData, "chocolatey", "bin"),
@@ -263,7 +268,14 @@ async function probeRuntime(spec, timeoutMs = PROBE_TIMEOUT_MS) {
263
268
  * 是**不确定** —— 不能当作"没装"。
264
269
  */
265
270
  function isUncertain(error) {
266
- return error === "timeout" || error === "spawn-failed" || String(error).startsWith("throw:");
271
+ return (
272
+ error === "timeout" ||
273
+ error === "spawn-failed" ||
274
+ // Windows Store 别名存根:文件 0 字节,spawn 得到 exit 9009、无输出。
275
+ // 这是“没问出答案”,不是“确定没装”。
276
+ error === "exit-9009" ||
277
+ String(error).startsWith("throw:")
278
+ );
267
279
  }
268
280
 
269
281
  /**
@@ -324,6 +336,85 @@ export async function collectRuntimes(specs = RUNTIMES) {
324
336
  return { runtimes, errors };
325
337
  }
326
338
 
339
+ /**
340
+ * 在 WSL 里探测运行时的 shell 片段。
341
+ *
342
+ * 命令是常量(来自 RUNTIMES),不拼接用户输入。每行输出 `名字<TAB>版本输出`;
343
+ * 没装的运行时不会出现在输出里。python 的 fallback 用 if/elif,避免 python3 与
344
+ * python 各打一行。
345
+ */
346
+ function wslProbeScript() {
347
+ return RUNTIMES.map((spec) => {
348
+ const cmds = [spec, spec.fallback].filter(Boolean);
349
+ const branches = cmds
350
+ .map(
351
+ (c, i) =>
352
+ `${i === 0 ? "if" : "elif"} command -v ${c.cmd} >/dev/null 2>&1; then ` +
353
+ `v=$(${c.cmd} ${c.args.join(" ")} 2>&1 | head -n 1); printf '%s\\t%s\\n' ${spec.name} "$v";`,
354
+ )
355
+ .join(" ");
356
+ return `${branches} fi`;
357
+ }).join("\n");
358
+ }
359
+
360
+ /**
361
+ * 探测运行中的 WSL 发行版里的运行时。
362
+ *
363
+ * 只探 `running` 的发行版:`wsl -d <name>` 对停着的发行版会把它启动起来,
364
+ * 为了看一眼版本付几十秒启动代价不值得。最多两个发行版,每个 8s 超时;
365
+ * 失败只记录短错误码,绝不抛(能力采集不能拖垮启动)。
366
+ *
367
+ * @returns [{ name, runtimes, error }]
368
+ */
369
+ export async function collectWslRuntimes({ platform: p = platform(), targets, run, timeoutMs = 8000 } = {}) {
370
+ if (p !== "win32") return [];
371
+ let list = targets;
372
+ if (!list) {
373
+ try {
374
+ list = wslTargets();
375
+ } catch {
376
+ return [];
377
+ }
378
+ }
379
+ const running = (list ?? []).filter((t) => t && t.running).slice(0, 2);
380
+ if (running.length === 0) return [];
381
+
382
+ const exec = run ?? ((cmd, args, opts) => execFileAsync(cmd, args, opts));
383
+ const script = wslProbeScript();
384
+
385
+ return Promise.all(
386
+ running.map(async (target) => {
387
+ try {
388
+ const { stdout } = await exec(
389
+ "wsl.exe",
390
+ ["-d", target.name, "-e", "sh", "-lc", script],
391
+ { timeout: timeoutMs, windowsHide: true, maxBuffer: 1 << 20 },
392
+ );
393
+ const runtimes = {};
394
+ for (const line of String(stdout ?? "").split("\n")) {
395
+ const tab = line.indexOf("\t");
396
+ if (tab <= 0) continue;
397
+ const name = line.slice(0, tab).trim().toLowerCase();
398
+ const version = parseVersion(line.slice(tab + 1));
399
+ if (name && version) runtimes[name] = version;
400
+ }
401
+ return {
402
+ name: target.name,
403
+ runtimes,
404
+ error: Object.keys(runtimes).length > 0 ? "" : "empty-output",
405
+ };
406
+ } catch (err) {
407
+ return {
408
+ name: target.name,
409
+ runtimes: {},
410
+ error: String(err?.code ?? err?.message ?? err).slice(0, 80),
411
+ };
412
+ }
413
+ }),
414
+ );
415
+ }
416
+
417
+
327
418
  /**
328
419
  * 探测失败的项里有没有"不确定"的(超时 / spawn 失败)。
329
420
  *
@@ -391,8 +482,11 @@ function isEmptyButFailed({ runtimes, errors } = {}) {
391
482
  * WindowsApps 算进去,Windows 上会**恒判"可信"** → 假阴性原样复发 —— 实测
392
483
  * 文超-win 的候选表去掉 WindowsApps 后恰好为 0,带上它则为 1。
393
484
  *
394
- * 注意范围:只用于**健康判据**。探测用 PATH 里保留 WindowsApps 无害(它本来
395
- * 通常就在真实 PATH 里),且 store 存根输出为空不会被记成运行时(见 parseVersion)。
485
+ * 注意范围:这个正则本身只用于**健康判据**;探测用的 PATH 里也**不再**补
486
+ * WindowsApps(见 extraPathDirs)。原先这里写着"留着无害",是错的:把它前置到
487
+ * PATH 会挡住真正的 python.exe / node.exe,spawn 得到 exit=9009 + 空输出,
488
+ * 于是"装了"被当成"没装"。现在这种输出记为**不确定**(见 isUncertain),
489
+ * 而不是当作反向证据。
396
490
  */
397
491
  const STORE_ALIAS_DIR = /[\\/]Microsoft[\\/]WindowsApps$/i;
398
492
 
@@ -419,6 +513,9 @@ export const __pathLookupUnreliable = pathLookupUnreliable;
419
513
  export const __normPathForCompare = normPathForCompare;
420
514
  /** 只为自测导出:原始 GPU 探测输出 —— 用来区分"这台机器没有显卡"和"解析器坏了"。 */
421
515
  export const __probeGpu = probeGpu;
516
+ export const __isUncertain = isUncertain;
517
+ /** 只为自测导出:GPU 探测的候选链 —— 靠它钉住「Windows 先问 nvidia-smi」这个顺序。 */
518
+ export const __gpuProbeSpecs = gpuProbeSpecs;
422
519
  /** 只为自测导出:Store 别名目录的排除规则(Mac 上没有该目录,无法端到端复现)。 */
423
520
  export const __storeAliasDir = STORE_ALIAS_DIR;
424
521
  /** 只为自测导出:让自测能按判据反推 runtimesIncomplete 的期望值,而不是写死。 */
@@ -486,15 +583,30 @@ export function parseNvidiaGpu(text) {
486
583
  }
487
584
 
488
585
  /**
489
- * 从 powershell `Get-CimInstance Win32_VideoController` 的输出里取第一行型号。
586
+ * 虚拟显示驱动/远程桌面适配器的名字特征。
587
+ *
588
+ * 为什么需要它:`Get-CimInstance Win32_VideoController` 在多显卡机器上给出多行,
589
+ * 而 MuMu / GameViewer / Parsec / RDP / Hyper-V 这类虚拟适配器常常**排在真卡
590
+ * 前面**。原实现只取第一行,于是装了 3060 的机器会被名片报成
591
+ * "MuMuVMM Display Adapter" —— 真卡被藏起来,Placement 拿到的是假事实。
490
592
  *
491
- * 注意 `Name -join "\`n"` 在多显卡时给出多行;只取第一行是有意的 ——
492
- * 名片只报"有没有 GPU + 主卡型号",不报全部。
593
+ * 保守起见只匹配明确的虚拟/远程产品名;Intel/AMD 的核显是**真卡**,不排除。
594
+ */
595
+ const VIRTUAL_GPU =
596
+ /virtual|remote|parsec|gameviewer|mumu|vmware|virtualbox|hyper-?v|basic display|rdp|citrix|spacedesk|sunlogin|todesk|displaylink/i;
597
+
598
+ /**
599
+ * 从 powershell `Get-CimInstance Win32_VideoController` 的多行输出里挑真卡。
600
+ *
601
+ * 规则:跳过已知虚拟适配器,取第一条剩下的;全都像虚拟适配器时退回第一行
602
+ * (**不要**因此返回 null —— "只有虚拟显卡"是一台真机器的真实状态,退回第一行
603
+ * 至少让调用方看到它是什么)。
493
604
  */
494
605
  export function parseWindowsGpu(text) {
495
606
  const s = gpuText(text);
496
607
  if (s === null) return null;
497
- const name = s.split("\n").map((l) => l.trim()).filter(Boolean)[0] ?? "";
608
+ const names = s.split("\n").map((l) => l.trim()).filter(Boolean);
609
+ const name = names.find((n) => !VIRTUAL_GPU.test(n)) ?? names[0] ?? "";
498
610
  return name ? { present: true, name, vramMb: 0 } : null;
499
611
  }
500
612
 
@@ -508,26 +620,37 @@ export function parseWindowsGpu(text) {
508
620
  * ⚠️ 每个分支都必须读 `r.output`(runProbe 返回的是 `{output,error}`)。
509
621
  * 直接把 `r` 交给解析函数就是上面说的那个 bug。
510
622
  */
511
- /** 每个平台"怎么问 + 用哪个解析器"集中一张表:自测与生产共用同一条命令。 */
512
- function gpuProbeSpec(p = platform()) {
623
+ /**
624
+ * 每个平台"按什么顺序问 + 用哪个解析器"集中一张表:自测与生产共用同一张表。
625
+ *
626
+ * 返回的是**候选列表**而不是单个命令,因为 Windows 上要"先问准的、再问全的":
627
+ * · `nvidia-smi` 只报真 N 卡,还带显存,是最可信的一手;
628
+ * · `Win32_VideoController` 更全(核显/AMD 也有),但会把虚拟适配器排前面。
629
+ * 先跑前者、解析不出来再跑后者,就不会被虚拟适配器骗到。
630
+ */
631
+ function gpuProbeSpecs(p = platform()) {
632
+ const NV = {
633
+ cmd: "nvidia-smi",
634
+ args: ["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"],
635
+ parse: parseNvidiaGpu,
636
+ };
513
637
  switch (p) {
514
638
  case "darwin":
515
- return { cmd: "system_profiler", args: ["SPDisplaysDataType"], parse: parseMacGpu };
639
+ return [{ cmd: "system_profiler", args: ["SPDisplaysDataType"], parse: parseMacGpu }];
516
640
  case "linux":
517
641
  case "android":
518
- return {
519
- cmd: "nvidia-smi",
520
- args: ["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"],
521
- parse: parseNvidiaGpu,
522
- };
642
+ return [NV];
523
643
  case "win32":
524
- return {
525
- cmd: "powershell",
526
- args: ["-NoProfile", "-Command", "(Get-CimInstance Win32_VideoController).Name -join \"`n\""],
527
- parse: parseWindowsGpu,
528
- };
644
+ return [
645
+ NV,
646
+ {
647
+ cmd: "powershell",
648
+ args: ["-NoProfile", "-Command", "(Get-CimInstance Win32_VideoController).Name -join \"`n\""],
649
+ parse: parseWindowsGpu,
650
+ },
651
+ ];
529
652
  default:
530
- return null;
653
+ return [];
531
654
  }
532
655
  }
533
656
 
@@ -540,12 +663,19 @@ function gpuProbeSpec(p = platform()) {
540
663
  * 否则在有显卡的机器上永远绿、在 VM 上永远红(GitHub runner 上就是这么红的)。
541
664
  */
542
665
  async function probeGpu() {
543
- const spec = gpuProbeSpec();
544
- if (!spec) return { output: "", gpu: null };
545
- const r = await runProbe(spec.cmd, spec.args, GPU_TIMEOUT_MS);
546
- const output = r.output ?? "";
547
- if (!output) return { output: "", gpu: null };
548
- return { output, gpu: spec.parse(output) };
666
+ const specs = gpuProbeSpecs();
667
+ let output = "";
668
+ for (const spec of specs) {
669
+ const r = await runProbe(spec.cmd, spec.args, GPU_TIMEOUT_MS);
670
+ const out = r.output ?? "";
671
+ // 命令没装/超时 → 空输出,换下一条;不要因为"没装 nvidia-smi"就报"没有 GPU"。
672
+ if (!out) continue;
673
+ output = out;
674
+ const gpu = spec.parse(out);
675
+ // 解析出真卡就停;解析不出来继续问下一条更全的命令。
676
+ if (gpu) return { output, gpu };
677
+ }
678
+ return { output, gpu: null };
549
679
  }
550
680
 
551
681
  async function collectGpu() {
@@ -623,9 +753,10 @@ export function setCapabilitiesForTest(value) {
623
753
  * @param options.hints 额外的"常用目录"(插件传 config.workspaceRoot)
624
754
  */
625
755
  export async function collectCapabilities({ now = Date.now(), hints = [] } = {}) {
626
- const [rt, gpu] = await Promise.all([
756
+ const [rt, gpu, wsl] = await Promise.all([
627
757
  collectRuntimes().catch(() => ({ runtimes: {}, errors: { _: "collect-threw" } })),
628
758
  collectGpu().catch(() => null),
759
+ collectWslRuntimes().catch(() => []),
629
760
  ]);
630
761
  // 三种触发(对端 hos 逼出来的完整版):
631
762
  // ① 探测本身没给出结论(超时 / spawn 失败 / 抛异常)
@@ -655,6 +786,9 @@ export async function collectCapabilities({ now = Date.now(), hints = [] } = {})
655
786
  // 只看 `runtimes` 的投影时,"3 项没探到"和"8 项全没探到"长得一样。
656
787
  probeFailCount: probeFailCount(rt),
657
788
  gpu,
789
+ // WSL 发行版里的运行时(只探运行中的);一台 Windows 机器上"装了 Python"
790
+ // 可能指宿主机,也可能指 WSL 里 —— 分开报才不会被当成同一件事。
791
+ ...(wsl.length > 0 ? { wsl } : {}),
658
792
  workspaceHints: collectWorkspaceHints(hints),
659
793
  capabilitiesAt: now,
660
794
  };
@@ -769,6 +903,32 @@ export function sanitizeCapabilities(raw) {
769
903
  if (name) gpu = { present: raw.gpu.present !== false, name, vramMb: safeNum(raw.gpu.vramMb, 1 << 20) };
770
904
  }
771
905
 
906
+ const wsl = [];
907
+ if (Array.isArray(raw.wsl)) {
908
+ for (const item of raw.wsl.slice(0, 8)) {
909
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
910
+ const name = safeStr(item.name, 32);
911
+ if (!name) continue;
912
+ const wslRuntimes = {};
913
+ let wslCount = 0;
914
+ const rawWslRuntimes =
915
+ item.runtimes && typeof item.runtimes === "object" && !Array.isArray(item.runtimes)
916
+ ? item.runtimes
917
+ : {};
918
+ for (const [k, v] of Object.entries(rawWslRuntimes)) {
919
+ if (wslCount >= 12) break;
920
+ const rtName = safeStr(k, 24).toLowerCase();
921
+ const rtVersion = safeStr(v, 16).replace(/[^0-9.]/g, "");
922
+ if (rtName && rtVersion) {
923
+ wslRuntimes[rtName] = rtVersion;
924
+ wslCount += 1;
925
+ }
926
+ }
927
+ wsl.push({ name, runtimes: wslRuntimes, error: safeStr(item.error, 80) });
928
+ if (wsl.length >= 2) break;
929
+ }
930
+ }
931
+
772
932
  const hints = Array.isArray(raw.workspaceHints)
773
933
  ? raw.workspaceHints.slice(0, 8).map((h) => safeStr(h, 40)).filter(Boolean)
774
934
  : [];
@@ -786,6 +946,8 @@ export function sanitizeCapabilities(raw) {
786
946
  // "8 项全没探到"是两回事)。旧对端没有这个字段 → 0(当作"没失败")。
787
947
  probeFailCount: safeNum(raw.probeFailCount, 64),
788
948
  gpu,
949
+ // 对端报来的 WSL 运行时同样要清洗:名字截断、版本只留数字和点、最多两个发行版。
950
+ ...(wsl.length > 0 ? { wsl } : {}),
789
951
  workspaceHints: hints,
790
952
  // 时间戳不能用 safeNum 的"非法即 0"——0 会让 capabilityAge 变成
791
953
  // "1970 年采的",也就是永远过期。非法就置 0 并在下面按"未知"处理。
@@ -831,6 +993,12 @@ export function describePeerCapabilities(peer) {
831
993
  ` 能力${marks.length ? `(${marks.join(";")})` : ""}:${specs.join(" / ") || "规格未知"}`,
832
994
  ` 运行时:${summarizeCapabilities(caps) || "(未探到)"}`,
833
995
  ];
996
+ for (const w of caps.wsl ?? []) {
997
+ const detail = Object.entries(w.runtimes ?? {})
998
+ .map(([name, ver]) => `${name} ${ver}`)
999
+ .join("、");
1000
+ lines.push(` WSL ${w.name}:${detail || "(未探到)"}`);
1001
+ }
834
1002
  if (caps.workspaceHints?.length) lines.push(` 常用目录:${caps.workspaceHints.join(" ")}`);
835
1003
  if (caps.capabilitiesAt) {
836
1004
  lines.push(` 采集于 ${new Date(caps.capabilitiesAt).toISOString().slice(0, 16).replace("T", " ")} UTC`);
@@ -0,0 +1,109 @@
1
+ /**
2
+ * 诊断信息(纯函数 + 两个小 IO 辅助)。
3
+ *
4
+ * 移植自 PR #17,只保留「诊断」这半:任务记录详情主干已有,不再重复。
5
+ *
6
+ * 为什么需要它:这个项目反复在“进程版本 ≠ 磁盘版本”上误诊 —— 重启日志、
7
+ * state.json、磁盘 package.json 都不能证明**当前进程加载的是哪份代码**。
8
+ * 诊断块把三件事摆在一起:
9
+ * · 进程自述版本(VERSION 常量,来自已加载的代码)
10
+ * · 磁盘 package.json 的版本
11
+ * · 入口文件 mtime 与进程启动时间的先后
12
+ *
13
+ * 输出只包含排障必需的信息,**不含** secret / tsnetAuthKey。
14
+ */
15
+ import { readFileSync, statSync } from "node:fs";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ /** 读入口同级 package.json 的版本;失败返回空串。 */
19
+ export function readPackageVersion(entryUrl) {
20
+ try {
21
+ const pkg = new URL("../package.json", entryUrl);
22
+ const raw = JSON.parse(readFileSync(pkg, "utf8"));
23
+ return typeof raw?.version === "string" ? raw.version : "";
24
+ } catch {
25
+ return "";
26
+ }
27
+ }
28
+
29
+ /** 入口文件的真实路径与 mtime;失败返回空。 */
30
+ export function entryInfo(entryUrl) {
31
+ try {
32
+ const path = fileURLToPath(entryUrl);
33
+ const stat = statSync(path);
34
+ return { path, mtimeMs: stat.mtimeMs };
35
+ } catch {
36
+ return { path: "", mtimeMs: 0 };
37
+ }
38
+ }
39
+
40
+ /**
41
+ * 组装诊断块。所有输入显式传入,方便单测;不做任何探测。
42
+ *
43
+ * @param config 插件配置(只挑安全字段输出,绝不回传 secret / tsnetAuthKey)
44
+ */
45
+ export function buildDiagnostics({
46
+ version = "",
47
+ packageVersion = "",
48
+ entry = "",
49
+ entryMtimeMs = 0,
50
+ startedAt = Date.now(),
51
+ now = Date.now(),
52
+ pid = process.pid,
53
+ node = process.version,
54
+ platform = process.platform,
55
+ arch = process.arch,
56
+ hostname = "",
57
+ machine = "",
58
+ config = {},
59
+ capabilities = null,
60
+ } = {}) {
61
+ const safeConfig = {};
62
+ for (const key of [
63
+ "port",
64
+ "useMulticast",
65
+ "scanOnStart",
66
+ "scanIntervalMs",
67
+ "pingIntervalMs",
68
+ "requirePairing",
69
+ "agentPreset",
70
+ "permissionPreset",
71
+ "workspaceRoot",
72
+ "tsnetEnabled",
73
+ ]) {
74
+ if (config?.[key] !== undefined) safeConfig[key] = config[key];
75
+ }
76
+
77
+ return {
78
+ ok: true,
79
+ app: "dsh-mesh",
80
+ version: String(version ?? ""),
81
+ packageVersion: String(packageVersion ?? ""),
82
+ // 进程自述版本 vs 磁盘 package.json
83
+ versionMatches: !!version && String(version) === String(packageVersion),
84
+ // 入口文件比进程启动还新 → 磁盘换了代码但没重启
85
+ diskNewerThanProcess: entryMtimeMs > 0 && entryMtimeMs > startedAt,
86
+ startedAt: new Date(startedAt).toISOString(),
87
+ uptimeMs: Math.max(0, Number(now) - Number(startedAt)),
88
+ pid,
89
+ node,
90
+ platform,
91
+ arch,
92
+ hostname: String(hostname ?? ""),
93
+ machine: String(machine ?? ""),
94
+ entry: String(entry ?? ""),
95
+ entryMtime: entryMtimeMs > 0 ? new Date(entryMtimeMs).toISOString() : "",
96
+ config: safeConfig,
97
+ capabilities: capabilities
98
+ ? {
99
+ at: Number(capabilities.capabilitiesAt) || 0,
100
+ runtimesIncomplete: capabilities.runtimesIncomplete === true,
101
+ probeFailCount: Number(capabilities.probeFailCount) || 0,
102
+ gpu: String(capabilities.gpu?.name ?? ""),
103
+ wsl: Array.isArray(capabilities.wsl)
104
+ ? capabilities.wsl.map((w) => String(w?.name ?? "")).filter(Boolean)
105
+ : [],
106
+ }
107
+ : null,
108
+ };
109
+ }
package/lib/discovery.js CHANGED
@@ -17,6 +17,7 @@ import dgram from "node:dgram";
17
17
  import { EventEmitter } from "node:events";
18
18
  import os from "node:os";
19
19
  import { sanitizeCapabilities, isCapabilityStale, summarizeCapabilities, currentCapabilities } from "./capabilities.js";
20
+ import { osInfo, sanitizeOsInfo, systems, sanitizeSystems } from "./osinfo.js";
20
21
 
21
22
  export const MESH_GROUP = "239.255.42.99";
22
23
  export const MESH_PORT = 45892;
@@ -305,6 +306,11 @@ export class MeshDiscovery extends EventEmitter {
305
306
  host: this.#address,
306
307
  port: this.#port,
307
308
  os: `${os.platform()} ${os.release()}`,
309
+ // 结构化系统身份(平台/系统名/版本/发行版/内核/桌面/架构)。
310
+ // 老对端没有这两个字段;UI 会回退解析 os 字符串,所以是纯增量协议。
311
+ osInfo: osInfo(),
312
+ // 这台机器上可用的系统列表(宿主机 + WSL 等);宿主机排第一。
313
+ systems: systems(),
308
314
  user: this.#meta.user ?? os.userInfo().username,
309
315
  profile: this.#meta.profile ?? "",
310
316
  version: this.#meta.version ?? "",
@@ -594,6 +600,8 @@ export class MeshDiscovery extends EventEmitter {
594
600
  hostname: String(msg.hostname ?? ""),
595
601
  mac: String(msg.mac ?? ""),
596
602
  os: String(msg.os ?? ""),
603
+ osInfo: sanitizeOsInfo(msg.osInfo),
604
+ systems: sanitizeSystems(msg.systems),
597
605
  user: String(msg.user ?? ""),
598
606
  profile: String(msg.profile ?? ""),
599
607
  version: String(msg.version ?? ""),
@@ -708,7 +716,11 @@ export class MeshDiscovery extends EventEmitter {
708
716
  const address = String(rinfo.address ?? selfHost ?? "?").trim();
709
717
  // tailnet 通道**必须**用观察到的地址:对端自述的 host 是它的局域网 IP,
710
718
  // 跨互联网根本不可达。
711
- const host = transport === "tsnet" ? address : selfHost || address;
719
+ // Prefer the observed source address on every transport. The peer's
720
+ // self-reported host/port is unauthenticated; trusting it on the LAN lets a
721
+ // spoofed heartbeat redirect task dispatch (and X-Dsh-Mesh-Token) to an
722
+ // arbitrary host. note()'s contract has always said observed wins.
723
+ const host = address || selfHost;
712
724
  const port = Number(rinfo.port ?? msg.port) || 0;
713
725
  const verified = rinfo.probe === false ? false : true;
714
726
 
@@ -718,6 +730,9 @@ export class MeshDiscovery extends EventEmitter {
718
730
  hostname: "",
719
731
  mac: "",
720
732
  os: "",
733
+ // 结构化系统身份;老对端只报 os 字符串时为 null。
734
+ osInfo: null,
735
+ systems: null,
721
736
  user: "",
722
737
  profile: "",
723
738
  version: "",
@@ -734,6 +749,12 @@ export class MeshDiscovery extends EventEmitter {
734
749
  peer.hostname = String(msg.hostname ?? peer.hostname ?? "");
735
750
  peer.mac = String(msg.mac ?? peer.mac ?? "");
736
751
  peer.os = String(msg.os ?? peer.os ?? "");
752
+ // 系统身份是**网络输入**:清洗后再存。没报/报坏了就保持原值,让 UI 回退到
753
+ // 老的 os 字符串,而不是伪造一个空系统。
754
+ const incomingOs = sanitizeOsInfo(msg.osInfo);
755
+ if (incomingOs) peer.osInfo = incomingOs;
756
+ const incomingSystems = sanitizeSystems(msg.systems);
757
+ if (incomingSystems) peer.systems = incomingSystems;
737
758
  peer.user = String(msg.user ?? peer.user ?? "");
738
759
  peer.profile = String(msg.profile ?? peer.profile ?? "");
739
760
  peer.version = String(msg.version ?? peer.version ?? "");
@@ -788,12 +809,15 @@ export class MeshDiscovery extends EventEmitter {
788
809
  lastOkAt: verified ? now : (prevEp?.lastOkAt ?? 0),
789
810
  lastFailAt: prevEp?.lastFailAt ?? 0,
790
811
  okCount: verified ? (prevEp?.okCount ?? 0) + 1 : (prevEp?.okCount ?? 0),
791
- failCount: 0,
812
+ // An inbound heartbeat proves the peer can reach us, not that we can
813
+ // reach it. Keep the outbound failure state; only a successful probe or
814
+ // send (markEndpoint ok) may clear it.
815
+ failCount: prevEp?.failCount ?? 0,
792
816
  // RTT 与探测间隔由调用方按实际结果带进来(成功路径走的是 note(),
793
817
  // 不是 markEndpoint,所以要在这里一并接住,否则 RTT 永远是 0)
794
818
  rttMs: Number(rinfo.rttMs) > 0 ? Number(rinfo.rttMs) : (prevEp?.rttMs ?? 0),
795
819
  probeIntervalMs: Number(rinfo.probeIntervalMs) > 0 ? Number(rinfo.probeIntervalMs) : (prevEp?.probeIntervalMs ?? 0),
796
- downUntil: 0,
820
+ downUntil: prevEp?.downUntil ?? 0,
797
821
  verified: prevEp?.verified === true || verified,
798
822
  };
799
823