dsh-plugin-mesh 0.5.2 → 0.5.4

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/index.js CHANGED
@@ -19,7 +19,7 @@ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
19
19
  import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
20
20
  import { join, basename, isAbsolute, resolve } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
- import { homedir, hostname, userInfo, platform } from "node:os";
22
+ import { homedir, hostname, userInfo, platform, arch } from "node:os";
23
23
  import z from "@deepseek-ai/schemastery";
24
24
  import { defineTool } from "@deepseek-ai/dsh-tools";
25
25
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
@@ -45,6 +45,7 @@ import {
45
45
  CAPABILITY_STALE_MS,
46
46
  } from "./capabilities.js";
47
47
  import { conversationKey, replyTarget } from "./conversation.js";
48
+ import { buildDiagnostics, entryInfo, readPackageVersion } from "./diagnostics.js";
48
49
  import { buildPrompt } from "./prompt.js";
49
50
  import { resolvePairing } from "./pairing.js";
50
51
  import {
@@ -53,13 +54,20 @@ import {
53
54
  loadPeerSnapshot,
54
55
  savePeerSnapshot,
55
56
  } from "./persist.js";
56
- import { TsnetNode } from "./tsnet/manager.js";
57
+ import { TsnetNode, channelKey, channelSignature } from "./tsnet/manager.js";
58
+ import { resolveTailnetChannels } from "./tsnet/channels.js";
57
59
  import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
58
60
 
59
61
  export const name = "dsh-plugin-mesh";
60
62
  export const inject = ["tools", "webServer"];
61
63
 
62
- const VERSION = "0.5.2";
64
+ const VERSION = "0.5.4";
65
+ // 诊断用:进程启动时间、入口真实路径、**磁盘上** package.json 的版本。
66
+ // 这三样放一起才能回答"现在跑的到底是哪份代码" —— 只看 state.json 或重启日志
67
+ // 都答不了(真踩过:磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
68
+ const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
69
+ const ENTRY_INFO = entryInfo(import.meta.url);
70
+ const DISK_VERSION = readPackageVersion(import.meta.url);
63
71
  const RULE_ID = "mesh-inbound";
64
72
  const RULE_KIND = "mesh";
65
73
  const MAX_BODY = 256 * 1024;
@@ -68,11 +76,13 @@ const MAX_HISTORY = 200;
68
76
  export const MESH_DEFAULT_PORT = 45917;
69
77
 
70
78
  /**
71
- * 互联网自组网(tailnet)节点句柄。
72
- * 宿主机路由不到 100.x.y.z,所有指向 tailnet 对端的请求都要经它中转,
73
- * 所以这里用模块级引用,让 peerFetch / scanTailnet 能拿到当前实例。
79
+ * 互联网自组网(tailnet)通道:通道 id → 节点句柄。
80
+ *
81
+ * 宿主机路由不到 100.x.y.z,所有指向 tailnet 对端的请求都要经对应 sidecar
82
+ * 中转,所以这里用模块级引用,让 peerFetch / scanTailnet 能拿到当前实例。
83
+ * 一台机器可以同时有多条通道(多个 tailnet),每个通道一个 sidecar。
74
84
  */
75
- let tailnetNode = null;
85
+ const tailnetNodes = new Map();
76
86
 
77
87
  /**
78
88
  * 当前实例的发现注册表。
@@ -172,14 +182,40 @@ export const Config = z.object({
172
182
  // 开启后插件会自动下载一个用户态 Tailscale 节点(sidecar)并加入 tailnet,
173
183
  // 让发现与派发跨互联网可用,与局域网路径同等级。
174
184
  // 终端用户不需要装 Go,也不需要装 Tailscale 客户端:二进制随插件自动下载。
175
- /** 是否启用互联网自组网 */
185
+ // 一台机器可以同时加入**多个 tailnet**:每个通道一个 sidecar、一个 tailnet
186
+ // 地址。设备身份仍然只有一个(instanceId 不变),通道只是多条可达路径。
187
+ // 下面三个 tsnetAuthKey / tsnetControlUrl / tsnetHostname 是**旧版单通道**
188
+ // 字段,保留以兼容已部署的配置与界面;有多通道需求时用 tsnetChannels。
189
+ /** 是否启用互联网自组网(旧版单通道开关;仅在 tsnetChannels 为空时生效) */
176
190
  tsnetEnabled: z.boolean().default(false),
177
- /** Tailscale 授权码(tskey-auth-...);也可以只在界面上填,界面会存到 state.json */
191
+ /** Tailscale 授权码(tskey-auth-...);旧版单通道字段,也可以只在界面上填 */
178
192
  tsnetAuthKey: z.string().default(""),
179
- /** 控制服务器地址;留空用官方 Tailscale,Headscale 用户填自己的 */
193
+ /** 控制服务器地址;旧版单通道字段。留空用官方 Tailscale,Headscale 用户填自己的 */
180
194
  tsnetControlUrl: z.string().default(""),
181
- /** tailnet 节点名(合法 DNS label);留空用机器名 */
195
+ /** tailnet 节点名(合法 DNS label);旧版单通道字段。留空用机器名 */
182
196
  tsnetHostname: z.string().default(""),
197
+ /**
198
+ * 多 tailnet 通道。每项:
199
+ * { id, label, authKey, controlUrl, hostname, enabled }
200
+ *
201
+ * `id` 是稳定标识(进 sidecar 状态目录,决定 tailnet 里的设备身份),
202
+ * 配置文件里手写时**务必显式给**;留空会按 label + controlUrl 推导,
203
+ * 改显示名就会变成新设备。界面添加的通道由宿主生成 `ch-xxxxxxxx`。
204
+ *
205
+ * 这里配了通道后优先于 state.json(配置钉死),也优先于上面三个旧字段。
206
+ */
207
+ tsnetChannels: z
208
+ .array(
209
+ z.object({
210
+ id: z.string().default(""),
211
+ label: z.string().default(""),
212
+ authKey: z.string().default(""),
213
+ controlUrl: z.string().default(""),
214
+ hostname: z.string().default(""),
215
+ enabled: z.boolean().default(true),
216
+ }),
217
+ )
218
+ .default([]),
183
219
  /** 自定义下载源前缀,可含 {url} 占位符;留空用内置镜像列表 */
184
220
  tsnetDownloadSources: z.array(String).default([]),
185
221
  /**
@@ -418,25 +454,127 @@ function pairingPinned(config) {
418
454
  }
419
455
 
420
456
  /**
421
- * 解析 tailnet 的有效配置。
457
+ * 解析 tailnet 的**有效通道列表**(多 tailnet)。
458
+ *
459
+ * 一台机器可以同时加入多个 tailnet:个人账号、公司 tailnet、自建 Headscale
460
+ * 各一个,每个通道一个 sidecar、一个 tailnet 地址。设备身份只有一个,通道只是
461
+ * 这个节点的多条可达路径(见 MESH-DEFINITION.md)。
422
462
  *
423
- * 授权码/控制服务器既可以写在 profile 配置里(高级用户),也可以只在界面上填。
424
- * 界面填的会存进 state.json(0600),所以**只需要输入一次**,重启不用再填。
425
- * 配置里的值优先,方便用配置把界面上的值钉死。
463
+ * 解析规则(配置 > state.json > 旧版单通道字段)在 lib/tsnet/channels.js 里,
464
+ * 那里是纯函数、有独立自测 —— 这段只负责把磁盘上的 state 读出来。
426
465
  */
427
- function effectiveTsnetConfig(config) {
428
- const st = loadState();
429
- const pick = (fromConfig, fromState) => String(fromConfig ?? "").trim() || String(fromState ?? "").trim();
466
+ function effectiveTailnetChannels(config) {
467
+ return resolveTailnetChannels({ config, state: loadState() });
468
+ }
469
+
470
+ /** 通道的对外视图:**绝不回传授权码内容**,只回报是否已配置。 */
471
+ function tailnetChannelView(channel, node) {
472
+ const status = node ? node.status() : null;
430
473
  return {
431
- ...config,
432
- // 配置里写 true 表示"钉死开启";否则由界面的开关(存在 state.json)决定。
433
- tsnetEnabled: config.tsnetEnabled === true ? true : st.tsnetEnabled === true,
434
- tsnetAuthKey: pick(config.tsnetAuthKey, st.tsnetAuthKey),
435
- tsnetControlUrl: pick(config.tsnetControlUrl, st.tsnetControlUrl),
436
- tsnetHostname: pick(config.tsnetHostname, st.tsnetHostname),
474
+ id: channel.id,
475
+ label: channel.label,
476
+ controlUrl: channel.controlUrl,
477
+ hostname: channel.hostname || status?.hostname || "",
478
+ enabled: channel.enabled === true,
479
+ authKeySaved: Boolean(channel.authKey),
480
+ source: channel.source,
481
+ node: status,
482
+ recentEvents: node ? node.recentEvents().slice(-12) : [],
437
483
  };
438
484
  }
439
485
 
486
+ /** 当前运行的通道节点里,每条的 tailnet 地址(写进对外名片,供对端提前记下)。 */
487
+ function tailnetMetaAddresses() {
488
+ const out = [];
489
+ for (const node of tailnetNodes.values()) {
490
+ if (node.phase !== "running") continue;
491
+ const ip = node.selfIpv4;
492
+ if (ip) out.push(ip);
493
+ }
494
+ return out;
495
+ }
496
+
497
+ /** 把本机的 tailnet 地址同步进名片(任何一条通道起落都要调)。 */
498
+ function syncTailnetMeta(discovery) {
499
+ if (!discovery) return;
500
+ discovery.setMeta({ tailnetIps: tailnetMetaAddresses() });
501
+ }
502
+
503
+ /** 当前在跑的通道节点。 */
504
+ function runningTailnetNodes() {
505
+ return [...tailnetNodes.values()].filter((n) => n.phase === "running");
506
+ }
507
+
508
+ /**
509
+ * 启动(或重建)一条 tailnet 通道。
510
+ *
511
+ * 授权码/控制服务器/主机名任何一项变了都要重建 sidecar:一个 tsnet 节点只
512
+ * 认一个 tailnet,沿用旧进程会继续待在旧网络里。
513
+ *
514
+ * **失败只影响这条通道**:异常原样抛给调用方,局域网与其它通道不受影响。
515
+ */
516
+ async function startTailnetChannel(channel, { config, discovery, log, warn, machineName }) {
517
+ const existing = tailnetNodes.get(channel.id);
518
+ // 配置没变、节点还活着(含等待授权)→ 复用。重试不该把登录流程推倒重来;
519
+ // 配置变了才重建,否则会一直在旧 tailnet 里。
520
+ const signature = channelSignature(channel);
521
+ const live = existing && ["running", "needs-login", "starting", "downloading"].includes(existing.phase);
522
+ if (live && existing.signature === signature) {
523
+ if (existing.phase === "running" && discovery?.port) {
524
+ await existing.registerForward(discovery.port).catch(() => {});
525
+ }
526
+ return { node: existing, reused: true };
527
+ }
528
+ if (existing) {
529
+ tailnetNodes.delete(channel.id);
530
+ await existing.stop().catch(() => {});
531
+ }
532
+
533
+ const tag = `tailnet:${channel.label}`;
534
+ const tsnode = new TsnetNode({
535
+ config,
536
+ channel,
537
+ log: (m) => log(`[${tag}] ${m}`),
538
+ warn,
539
+ machineName,
540
+ });
541
+ tailnetNodes.set(channel.id, tsnode);
542
+ tsnode.on("status", (s) => {
543
+ if (s.phase === "error" && s.error) warn(`通道 ${channel.label}:${s.error}`);
544
+ // 侧车起落会改变本机的 tailnet 地址,名片要跟着更新
545
+ syncTailnetMeta(discovery);
546
+ });
547
+
548
+ try {
549
+ const { reused } = await tsnode.start();
550
+ // 让本机 mesh 服务在**这条** tailnet 上可达(tailnet :port → 127.0.0.1:port)。
551
+ // 多条通道可以注册同一个端口:每个 sidecar 的监听在各自的用户态网络栈里。
552
+ if (discovery?.port) await tsnode.registerForward(discovery.port);
553
+ syncTailnetMeta(discovery);
554
+ return { node: tsnode, reused };
555
+ } catch (err) {
556
+ // 节点留在表里:界面要能看到这条通道的错误与诊断,而不是"它凭空消失了"
557
+ syncTailnetMeta(discovery);
558
+ throw err;
559
+ }
560
+ }
561
+
562
+ /** 停掉一条通道(不传 id 停全部)。返回实际停掉的通道数。 */
563
+ async function stopTailnetChannel(id, discovery) {
564
+ const ids = id ? [String(id)] : [...tailnetNodes.keys()];
565
+ let stopped = 0;
566
+ for (const key of ids) {
567
+ const node = tailnetNodes.get(key);
568
+ if (!node) continue;
569
+ tailnetNodes.delete(key);
570
+ await node.stop().catch(() => {});
571
+ stopped += 1;
572
+ }
573
+ if (stopped > 0) syncTailnetMeta(discovery);
574
+ return stopped;
575
+ }
576
+
577
+
440
578
  /** 首次运行生成配对码;用户只需把它复制到另一台机器。 */
441
579
  function ensureSecret() {
442
580
  const st = loadState();
@@ -669,8 +807,24 @@ function applyUnsafe(ctx, config) {
669
807
  // 入站唤醒的"能力位":服务齐备后由 setupInbound 置位
670
808
  const waker = { ready: false, ctx: undefined };
671
809
 
810
+ /** 诊断块:进程自述版本 / 磁盘版本 / 入口 mtime / 安全字段的配置 / 能力摘要。 */
811
+ const diagnosticsPayload = () =>
812
+ buildDiagnostics({
813
+ version: VERSION,
814
+ packageVersion: DISK_VERSION,
815
+ entry: ENTRY_INFO.path,
816
+ entryMtimeMs: ENTRY_INFO.mtimeMs,
817
+ startedAt: PROCESS_STARTED_AT,
818
+ machine: identity.name,
819
+ hostname: hostname(),
820
+ platform: platform(),
821
+ arch: arch(),
822
+ config,
823
+ capabilities: currentCapabilities(),
824
+ });
825
+
672
826
  // 1) 先起对端 HTTP(拿到真实端口),再开始发现
673
- startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange: scheduleHistorySave })
827
+ startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange: scheduleHistorySave, diagnostics: diagnosticsPayload })
674
828
  .then(async (port) => {
675
829
  discovery.setPort(port);
676
830
 
@@ -696,43 +850,43 @@ function applyUnsafe(ctx, config) {
696
850
  });
697
851
 
698
852
  // 互联网自组网:与局域网并行的第二条发现路径,功能同等级。
699
- // 任何一步失败都只影响 tailnet —— 局域网发现照常工作,这是硬要求。
700
- const tsnetConfig = effectiveTsnetConfig(config);
701
- if (tsnetConfig.tsnetEnabled === true) {
702
- const node = new TsnetNode({ config: tsnetConfig, log, warn, machineName: identity.name });
703
- tailnetNode = node;
704
- node.on("status", (s) => {
705
- if (s.phase === "error" && s.error) warn(`互联网组网:${s.error}`);
706
- });
853
+ // 任何一步失败都只影响对应通道 —— 局域网发现照常工作,这是硬要求。
854
+ //
855
+ // 多 tailnet:每条启用的通道各起一个 sidecar(串行启动,避免并发争用
856
+ // 二进制下载);一条失败不影响其它条,也不影响局域网。
857
+ const tailnetChannels = effectiveTailnetChannels(config).filter((c) => c.enabled);
858
+ if (tailnetChannels.length > 0) {
707
859
  ctx.effect(() => () => {
708
- if (tailnetNode === node) tailnetNode = null;
709
- node.stop().catch(() => {});
860
+ for (const node of tailnetNodes.values()) node.stop().catch(() => {});
861
+ tailnetNodes.clear();
710
862
  });
711
863
 
712
- node
713
- .start()
714
- .then(async ({ reused }) => {
715
- // 让本机 mesh 服务在 tailnet 上可达(tailnet :port → 127.0.0.1:port)
716
- await node.registerForward(port);
717
- const st = node.status();
718
- // 把本机的 tailnet 地址写进对外名片。
719
- //
720
- // 这一步是决定 #2 成立的关键:对端**只靠局域网**就能知道我们的备选
721
- // 地址,于是它平时完全不用做 tailnet 探测,局域网一断却能立刻切过来。
722
- // setMeta 会立刻重新广播一次,不用等下一个心跳周期。
723
- if (st.selfIpv4) discovery.setMeta({ tailnetIp: st.selfIpv4 });
724
- log(
725
- `互联网组网已启动:节点=${node.hostname} tailnet=${st.selfIpv4 || "待登录"}` +
726
- `${reused ? "(复用已有 sidecar)" : ""}${st.authUrl ? ` 授权链接=${st.authUrl}` : ""}`,
727
- );
864
+ (async () => {
865
+ for (const channel of tailnetChannels) {
728
866
  if (stop.aborted) return;
729
- await runScan({ discovery, config, log, warn, signal: stop, reason: "tailnet 启动扫描" });
730
- })
731
- .catch((err) => {
732
- warn(`互联网组网启动失败(局域网功能不受影响):${err?.message ?? err}`);
733
- });
867
+ try {
868
+ const { node, reused } = await startTailnetChannel(channel, {
869
+ config,
870
+ discovery,
871
+ log,
872
+ warn,
873
+ machineName: identity.name,
874
+ });
875
+ const st = node.status();
876
+ log(
877
+ `通道「${channel.label}」已启动:节点=${node.hostname} tailnet=${st.selfIpv4 || "待登录"}` +
878
+ `${reused ? "(复用已有 sidecar)" : ""}${st.authUrl ? ` 授权链接=${st.authUrl}` : ""}`,
879
+ );
880
+ } catch (err) {
881
+ warn(`通道「${channel.label}」启动失败(局域网与其它通道不受影响):${err?.message ?? err}`);
882
+ }
883
+ }
884
+ if (stop.aborted) return;
885
+ // 所有通道都起来之后再扫一轮,让 tailnet 设备尽快进列表
886
+ await runScan({ discovery, config, log, warn, signal: stop, reason: "tailnet 启动扫描" });
887
+ })().catch((err) => warn(`tailnet 启动扫描失败(不影响发现):${err?.message ?? err}`));
734
888
  } else {
735
- log("互联网自组网未启用(tsnetEnabled=false)");
889
+ log("互联网自组网未启用(没有启用的 tailnet 通道)");
736
890
  }
737
891
 
738
892
  if (config.scanOnStart) {
@@ -778,7 +932,7 @@ function applyUnsafe(ctx, config) {
778
932
  registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange: scheduleHistorySave });
779
933
 
780
934
  // 4) UI 接口
781
- registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave });
935
+ registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave, diagnostics: diagnosticsPayload });
782
936
 
783
937
  ctx.effect(() => () => {
784
938
  discovery.stop();
@@ -790,6 +944,31 @@ function machineOf(discovery) {
790
944
  return discovery.selfRecord().machine;
791
945
  }
792
946
 
947
+ /**
948
+ * 对端的系统身份,单行文本(mesh_peers 工具用)。
949
+ * 新对端有结构化 osInfo;老对端只有 os 字符串,原样回退。
950
+ */
951
+ function osLine(peer) {
952
+ const info = peer?.osInfo;
953
+ if (!info) return peer?.os || "?";
954
+ const label = [info.name, info.version].filter(Boolean).join(" ") || peer?.os || "?";
955
+ const extra = [info.arch, info.distro, info.desktop].filter(Boolean).join(" / ");
956
+ return extra ? `${label} (${extra})` : label;
957
+ }
958
+
959
+ /** 一台机器的全部系统(宿主机 + WSL 等),单行文本。 */
960
+ function systemsLine(peer) {
961
+ const list = Array.isArray(peer?.systems) && peer.systems.length ? peer.systems : null;
962
+ if (!list) return osLine(peer);
963
+ return list
964
+ .map((s) => {
965
+ const label = [s.name, s.version].filter(Boolean).join(" ") || s.platform || "?";
966
+ const extra = [s.kind === "wsl" ? "WSL" : "", s.distro, s.desktop, s.arch].filter(Boolean).join("/");
967
+ return extra ? `${label} (${extra})` : label;
968
+ })
969
+ .join(" + ");
970
+ }
971
+
793
972
  /**
794
973
  * 把对端的能力名片渲染成几行文本(mesh_peers 工具用)。
795
974
  * 渲染逻辑在 capabilities.js 里(可单测),这里只做转发。
@@ -1446,18 +1625,17 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1446
1625
 
1447
1626
  // ───────────────────────── 主动发现与保活 ─────────────────────────
1448
1627
 
1449
- /**
1450
- * 按对端的 transport 选择出口。
1451
- *
1452
- * 局域网直连即可;tailnet 对端必须借 sidecar 的用户态隧道 —— 宿主机没有
1453
- * TUN 设备,`fetch("http://100.x.y.z:...")` 会直接 ENETUNREACH。
1454
- * 把差异收在这一个函数里,上面所有调用点都不必关心对端是怎么找到的。
1455
- */
1628
+ /** 端点的稳定 key:`lan` / `tsnet:<通道 id>`(兼容旧端点的 `tsnet`)。 */
1629
+ function endpointKeyOf(ep) {
1630
+ return String(ep?.channel ?? ep?.transport ?? "lan");
1631
+ }
1632
+
1456
1633
  /**
1457
1634
  * 按端点健康**逐个失败切换**地发一个请求。
1458
1635
  *
1459
- * 这是"两条通道绑一台设备"的实际收益:局域网不通就走 tailnet,反之亦然。
1460
- * 以前只看 `peer.transport`(最后探测到的那个),一条通道坏掉整个对端就不可达。
1636
+ * 这是"多条通道绑一台设备"的实际收益:局域网不通就走某条 tailnet,一条
1637
+ * tailnet 不通还可以走另一条。以前只看 `peer.transport`(最后探测到的那个),
1638
+ * 一条通道坏掉整个对端就不可达。
1461
1639
  *
1462
1640
  * 只有**网络层失败**才切换通道:HTTP 4xx/5xx 说明端点本身是通的,换一条也
1463
1641
  * 一样,不该白试一遍、更不该把好端点的健康记录打坏。
@@ -1479,7 +1657,7 @@ async function peerFetch(peer, path, opts = {}) {
1479
1657
  // `http://:0/mesh/v1/hello` —— 端点明明选对了,URL 却是坏的。
1480
1658
  // 实测就是这个报错:`Get "http://:0/mesh/v1/hello": lookup : no such host`。
1481
1659
  if (!ep.host || !ep.port) {
1482
- failures.push(`${ep.transport} 端点地址不完整(${ep.host}:${ep.port})`);
1660
+ failures.push(`${endpointKeyOf(ep)} 端点地址不完整(${ep.host}:${ep.port})`);
1483
1661
  continue;
1484
1662
  }
1485
1663
  const url = `http://${ep.host}:${ep.port}${path}`;
@@ -1489,11 +1667,11 @@ async function peerFetch(peer, path, opts = {}) {
1489
1667
  ep.transport === "tsnet"
1490
1668
  ? await fetchViaTailnet(ep, url, { ...rest, timeoutMs })
1491
1669
  : await fetchViaLan(ep, url, { ...rest, timeoutMs });
1492
- activeDiscovery?.markEndpoint(peer.id, ep.transport, { ok: true, rttMs: Date.now() - started });
1670
+ activeDiscovery?.markEndpoint(peer.id, endpointKeyOf(ep), { ok: true, rttMs: Date.now() - started });
1493
1671
  return res;
1494
1672
  } catch (err) {
1495
- failures.push(`${ep.transport}(${ep.host}:${ep.port}) ${err?.message ?? err}`);
1496
- activeDiscovery?.markEndpoint(peer.id, ep.transport, { ok: false });
1673
+ failures.push(`${endpointKeyOf(ep)}(${ep.host}:${ep.port}) ${err?.message ?? err}`);
1674
+ activeDiscovery?.markEndpoint(peer.id, endpointKeyOf(ep), { ok: false });
1497
1675
  }
1498
1676
  }
1499
1677
  throw new Error(`所有通道都失败 —— ${failures.join(";")}`);
@@ -1508,76 +1686,120 @@ async function fetchViaLan(ep, url, opts = {}) {
1508
1686
  /**
1509
1687
  * 经 sidecar 的用户态隧道出去。
1510
1688
  * 宿主机没有 TUN 设备,`fetch("http://100.x.y.z:...")` 会直接 ENETUNREACH。
1689
+ *
1690
+ * 出口选择:
1691
+ * · 端点带通道(`tsnet:<id>`)→ 优先走那条通道的 sidecar;它不可用时再依次
1692
+ * 试其它通道(IP 本来就属于哪条 tailnet 是连通性说的,不必猜)。
1693
+ * · 端点没有通道(对端名片里报来的候选地址)→ 依次试所有通道。
1694
+ *
1695
+ * 多条 tailnet 可能有重叠的 100.x 网段,所以"试"是唯一可靠的做法;失败的
1696
+ * 通道不会留下状态(真实健康记录由调用方 markEndpoint 写)。
1511
1697
  */
1512
1698
  async function fetchViaTailnet(ep, url, opts = {}) {
1513
- if (!tailnetNode) throw new Error("tailnet 节点尚未启动");
1514
- return tailnetFetch(tailnetNode, url, opts);
1699
+ const key = endpointKeyOf(ep);
1700
+ const wantId = key.startsWith("tsnet:") ? key.slice("tsnet:".length) : "";
1701
+ const wanted = wantId ? tailnetNodes.get(wantId) : null;
1702
+ const candidates = [];
1703
+ if (wanted && wanted.phase === "running") candidates.push(wanted);
1704
+ for (const node of runningTailnetNodes()) {
1705
+ if (!candidates.includes(node)) candidates.push(node);
1706
+ }
1707
+ if (candidates.length === 0) throw new Error("tailnet 节点尚未启动");
1708
+ let lastErr = null;
1709
+ for (const node of candidates) {
1710
+ try {
1711
+ return await tailnetFetch(node, url, opts);
1712
+ } catch (err) {
1713
+ lastErr = err;
1714
+ }
1715
+ }
1716
+ throw lastErr ?? new Error("没有可用的 tailnet 通道");
1515
1717
  }
1516
1718
 
1517
1719
  /**
1518
- * 借 sidecar 的 tailnet 节点表做第二轮探测。
1720
+ * 借每条 tailnet 通道的 sidecar 节点表做第二轮探测。
1519
1721
  *
1520
1722
  * 与局域网扫描刻意保持同构:拿候选地址 → 探 /mesh/v1/health → 自述记录进
1521
- * 同一个注册表。区别只有两点:候选地址来自 tailnet 而不是本网段,
1522
- * 且请求必须走 sidecar 隧道。
1723
+ * 同一个注册表。区别是:候选地址来自 tailnet,请求必须走对应的 sidecar 隧道,
1724
+ * 且**每条通道各扫一遍** —— 一台设备可能在多个 tailnet 里,每个 tailnet 给的
1725
+ * 地址不同,端点要按通道分别记录。
1726
+ *
1727
+ * @param channelId 只扫某一条通道;省略 = 所有在跑的通道
1523
1728
  */
1524
- async function scanTailnet({ discovery, config, log, reason, ports }) {
1525
- // 只需判断节点是否在跑:节点存在本身就说明用户启用了它。
1526
- if (!tailnetNode || tailnetNode.phase !== "running") {
1527
- return { scanned: 0, found: 0 };
1528
- }
1529
-
1530
- let peers;
1531
- try {
1532
- peers = await tailnetNode.peersRemote();
1533
- } catch (err) {
1534
- log(`${reason}(tailnet): 取节点表失败 —— ${err.message}`);
1535
- return { scanned: 0, found: 0 };
1536
- }
1537
-
1538
- // 只看在线且有 IPv4 的;自己不在 Peer 列表里,不用排除。
1539
- const candidates = peers.filter((p) => p.online && p.ipv4);
1540
- if (candidates.length === 0) return { scanned: 0, found: 0 };
1729
+ async function scanTailnet({ discovery, config, log, reason, ports, channelId = "" }) {
1730
+ const nodes = runningTailnetNodes().filter((n) => !channelId || n.channelKey === channelId);
1731
+ if (nodes.length === 0) return { scanned: 0, found: 0, channels: [] };
1541
1732
 
1542
1733
  // tailnet 上没有"端口先验",但同机单实例 + 默认端口是常态,命中率很高。
1543
1734
  const targetPorts = [...new Set([...ports, MESH_DEFAULT_PORT])].filter((p) => Number(p) > 0);
1544
- let found = 0;
1545
- let added = 0;
1735
+ const probeIntervalMs = Math.max(config.pingIntervalMs, config.tsnetProbeIntervalMs ?? 60000);
1736
+ const perChannel = [];
1546
1737
 
1547
1738
  await Promise.all(
1548
- candidates.flatMap((p) =>
1549
- targetPorts.map(async (tp) => {
1550
- try {
1551
- const started = Date.now();
1552
- const res = await tailnetFetch(tailnetNode, `http://${p.ipv4}:${tp}/mesh/v1/health`, {
1553
- timeoutMs: Math.min(4000, config.requestTimeoutMs),
1554
- });
1555
- if (!res.ok) return;
1556
- const body = await res.json();
1557
- if (body?.app !== "dsh-mesh" || !body.id) return;
1558
- found += 1;
1559
- // 强制记 tailnet IP:对端自述的 host 是它的局域网地址,跨互联网不可达。
1560
- // 同时带上探测间隔与 RTT —— 漏了 interval 会让这条通道按默认 TTL(20s)
1561
- // 判活,而它 60s 才探一次,于是探完 20 秒就"死了"、整台设备假离线。
1562
- // 实测踩过:ok=4 fail=0 rtt=473ms 却显示 online=False。
1563
- if (
1564
- discovery.note(body, p.ipv4, {
1565
- transport: "tsnet",
1566
- port: tp,
1567
- rttMs: Date.now() - started,
1568
- probeIntervalMs: Math.max(config.pingIntervalMs, config.tsnetProbeIntervalMs ?? 60000),
1569
- })
1570
- )
1571
- added += 1;
1572
- } catch {
1573
- /* 该地址上没有 DSH 节点,或端口没开 —— 正常情况,不打扰用户 */
1574
- }
1575
- }),
1576
- ),
1739
+ nodes.map(async (node) => {
1740
+ const channel = `tsnet:${node.channelKey}`;
1741
+ const summary = { id: node.channelKey, label: node.label, scanned: 0, found: 0, error: "" };
1742
+ perChannel.push(summary);
1743
+
1744
+ let peers;
1745
+ try {
1746
+ peers = await node.peersRemote();
1747
+ } catch (err) {
1748
+ summary.error = String(err?.message ?? err);
1749
+ log(`${reason}(${node.label}): 取节点表失败 —— ${summary.error}`);
1750
+ return;
1751
+ }
1752
+
1753
+ // 只看在线且有 IPv4 的;自己不在 Peer 列表里,不用排除。
1754
+ const candidates = peers.filter((p) => p.online && p.ipv4);
1755
+ summary.scanned = candidates.length * targetPorts.length;
1756
+ if (candidates.length === 0) return;
1757
+
1758
+ let found = 0;
1759
+ let added = 0;
1760
+ await Promise.all(
1761
+ candidates.flatMap((p) =>
1762
+ targetPorts.map(async (tp) => {
1763
+ try {
1764
+ const started = Date.now();
1765
+ const res = await tailnetFetch(node, `http://${p.ipv4}:${tp}/mesh/v1/health`, {
1766
+ timeoutMs: Math.min(4000, config.requestTimeoutMs),
1767
+ });
1768
+ if (!res.ok) return;
1769
+ const body = await res.json();
1770
+ if (body?.app !== "dsh-mesh" || !body.id) return;
1771
+ found += 1;
1772
+ // 强制记 tailnet IP:对端自述的 host 是它的局域网地址,跨互联网不可达。
1773
+ // 通道 key 必须带上:同一台设备可能同时出现在多条 tailnet 里,
1774
+ // 不区分就会互相覆盖,一条通道断了另一条也跟着消失。
1775
+ // 同时带上探测间隔与 RTT —— 漏了 interval 会让这条通道按默认 TTL(20s)
1776
+ // 判活,而它 60s 才探一次,于是探完 20 秒就"死了"、整台设备假离线。
1777
+ // 实测踩过:ok=4 fail=0 rtt=473ms 却显示 online=False。
1778
+ if (
1779
+ discovery.note(body, p.ipv4, {
1780
+ transport: "tsnet",
1781
+ channel,
1782
+ port: tp,
1783
+ rttMs: Date.now() - started,
1784
+ probeIntervalMs,
1785
+ })
1786
+ )
1787
+ added += 1;
1788
+ } catch {
1789
+ /* 该地址上没有 DSH 节点,或端口没开 —— 正常情况,不打扰用户 */
1790
+ }
1791
+ }),
1792
+ ),
1793
+ );
1794
+
1795
+ summary.found = found;
1796
+ if (found > 0) log(`${reason}(${node.label}): 命中 ${found} 台(新登记 ${added})`);
1797
+ }),
1577
1798
  );
1578
1799
 
1579
- if (found > 0) log(`${reason}(tailnet): 命中 ${found} 台(新登记 ${added})`);
1580
- return { scanned: candidates.length * targetPorts.length, found };
1800
+ const found = perChannel.reduce((n, c) => n + c.found, 0);
1801
+ const scanned = perChannel.reduce((n, c) => n + c.scanned, 0);
1802
+ return { scanned, found, channels: perChannel };
1581
1803
  }
1582
1804
 
1583
1805
  /**
@@ -1684,14 +1906,19 @@ async function pingKnownPeers({ discovery, config, warn }) {
1684
1906
  });
1685
1907
  if (!res.ok) {
1686
1908
  // 端点通但返回错误:不打坏健康记录,也不换通道重试(换了也一样)
1687
- discovery.markEndpoint(p.id, ep.transport, { ok: true, rttMs: Date.now() - started });
1909
+ discovery.markEndpoint(p.id, endpointKeyOf(ep), { ok: true, rttMs: Date.now() - started });
1688
1910
  return;
1689
1911
  }
1690
1912
  const body = await res.json();
1691
1913
  if (body?.app === "dsh-mesh" && body.id) {
1692
- // 对方可能重启过、换了端口 —— 以 ping 到的为准,并刷新这条端点
1914
+ // 对方可能重启过、换了端口 —— 以 ping 到的为准,并刷新这条端点。
1915
+ // channel 用**这条端点自己的 key**:多 tailnet 时若统一写成 tsnet,
1916
+ // 不同通道会互相覆盖,一条断了另一条也跟着假死。
1917
+ // 候选端点(tsnet:cand:…)探通后就此转正,保持同一个 key,
1918
+ // 发送时按"依次试所有通道"解析。
1693
1919
  discovery.note(body, ep.host, {
1694
1920
  transport: ep.transport,
1921
+ channel: endpointKeyOf(ep),
1695
1922
  port: ep.port,
1696
1923
  // 把探测结果一起带上:note() 是成功路径的入口,RTT 与探测间隔
1697
1924
  // 在这里接住,通道的存活窗口才会跟着自己的节奏走
@@ -1701,7 +1928,7 @@ async function pingKnownPeers({ discovery, config, warn }) {
1701
1928
  }
1702
1929
  } catch {
1703
1930
  // 这条通道不通:记一次失败,累计到阈值就进冷却,排序会把它排到最后
1704
- discovery.markEndpoint(p.id, ep.transport, {
1931
+ discovery.markEndpoint(p.id, endpointKeyOf(ep), {
1705
1932
  ok: false,
1706
1933
  probeIntervalMs: ep.transport === "tsnet" ? tsnetInterval : config.pingIntervalMs,
1707
1934
  });
@@ -1721,7 +1948,7 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
1721
1948
 
1722
1949
  // ───────────────────────── 对端 HTTP 服务 ─────────────────────────
1723
1950
 
1724
- function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange }) {
1951
+ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange, diagnostics }) {
1725
1952
  const send = (res, code, payload) => {
1726
1953
  const body = Buffer.from(JSON.stringify(payload), "utf8");
1727
1954
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -1754,6 +1981,9 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
1754
1981
 
1755
1982
  if (!authed(req)) return send(res, 403, { ok: false, error: "未配对:两台机器的配对码不一致(本机开启了 requirePairing)" });
1756
1983
 
1984
+ // 诊断:进程版本 vs 磁盘版本。**必须在对端鉴权之后** —— 里面有本机路径。
1985
+ if (path === "/mesh/v1/diagnostics") return send(res, 200, diagnostics());
1986
+
1757
1987
  if (path === "/mesh/v1/peers") return send(res, 200, { ok: true, peers: discovery.peers() });
1758
1988
 
1759
1989
  if (path === "/mesh/v1/tasks" && req.method === "GET") {
@@ -1879,7 +2109,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
1879
2109
  const lines = list.map((p) => {
1880
2110
  const caps = capabilityLine(p);
1881
2111
  return (
1882
- `${p.online ? "● 在线" : "○ 离线"} ${p.machine} ${p.host}:${p.port} ${p.os} user=${p.user}` +
2112
+ `${p.online ? "● 在线" : "○ 离线"} ${p.machine} ${p.host}:${p.port} ${systemsLine(p)} user=${p.user}` +
1883
2113
  (p.hostname ? `\n hostname=${p.hostname}` : "") +
1884
2114
  (p.mac ? ` mac=${p.mac}` : "") +
1885
2115
  (caps ? `\n${caps}` : "")
@@ -2048,7 +2278,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
2048
2278
 
2049
2279
  // ───────────────────────── UI 接口(本地回环) ─────────────────────────
2050
2280
 
2051
- function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange }) {
2281
+ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange, diagnostics }) {
2052
2282
  const send = (res, code, payload) => {
2053
2283
  const body = Buffer.from(JSON.stringify(payload), "utf8");
2054
2284
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -2132,9 +2362,12 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2132
2362
  };
2133
2363
 
2134
2364
  const state = () => {
2135
- // state.json 只读一次:这个接口会被页面轮询,而 effectiveTsnetConfig 内部
2136
- // 每次都读文件,逐字段调用会把一次轮询变成三次磁盘读。
2137
- const tsnetEff = effectiveTsnetConfig(config);
2365
+ // state.json 只读一次:这个接口会被页面轮询,而通道解析内部每次都读文件,
2366
+ // 逐字段调用会把一次轮询变成多次磁盘读。
2367
+ const tailnetChannels = effectiveTailnetChannels(config);
2368
+ const channelViews = tailnetChannels.map((c) => tailnetChannelView(c, tailnetNodes.get(c.id) ?? null));
2369
+ // 兼容旧界面:node / hostname / authKeySaved 取"第一条启用的通道"
2370
+ const primary = channelViews.find((c) => c.enabled) ?? channelViews[0] ?? null;
2138
2371
  return {
2139
2372
  ok: true,
2140
2373
  self: {
@@ -2149,6 +2382,10 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2149
2382
  addresses: lanIPv4Addresses(),
2150
2383
  platform: platform(),
2151
2384
  version: VERSION,
2385
+ // 磁盘上的版本 vs 本进程加载的版本。两者不一致 = 升级了但没重启,
2386
+ // 界面要明说"重启后生效",否则用户会拿旧行为当新版本的 bug 报上来。
2387
+ diskVersion: DISK_VERSION,
2388
+ versionDrift: !!DISK_VERSION && DISK_VERSION !== VERSION,
2152
2389
  secret: currentSecret(),
2153
2390
  // 本机的能力名片(对端看到的也是这一份)。**本机直接读采集缓存**,
2154
2391
  // 不走网络 —— 和 mac 一样,"自己的信息"没必要绕一圈。
@@ -2180,15 +2417,19 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2180
2417
  },
2181
2418
  // 互联网自组网状态。注意:**绝不回传授权码本身**,只回报"是否已配置"。
2182
2419
  tsnet: {
2183
- enabled: tsnetEff.tsnetEnabled === true,
2184
- authKeySaved: Boolean(tsnetEff.tsnetAuthKey),
2185
- controlUrl: tsnetEff.tsnetControlUrl,
2186
- hostname: tailnetNode?.hostname ?? "",
2420
+ // 多 tailnet 通道列表:UI 的主视图
2421
+ channels: channelViews,
2422
+ /** 有任意一条启用的通道即为 true(旧界面兼容) */
2423
+ enabled: channelViews.some((c) => c.enabled),
2424
+ /** 旧单通道字段:取第一条启用通道 */
2425
+ authKeySaved: Boolean(primary?.authKeySaved),
2426
+ controlUrl: primary?.controlUrl ?? "",
2427
+ hostname: primary?.hostname ?? "",
2187
2428
  permissionPreset: config.tsnetPermissionPreset || "",
2188
2429
  /** 留空时实际生效的权限,与局域网一致 */
2189
2430
  permissionPresetEffective: config.tsnetPermissionPreset || config.permissionPreset,
2190
- node: tailnetNode ? tailnetNode.status() : null,
2191
- recentEvents: tailnetNode ? tailnetNode.recentEvents().slice(-12) : [],
2431
+ node: primary?.node ?? null,
2432
+ recentEvents: primary?.recentEvents ?? [],
2192
2433
  },
2193
2434
  peers: discovery.peers(),
2194
2435
  duplicateNames: duplicateNames(),
@@ -2210,6 +2451,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2210
2451
  };
2211
2452
 
2212
2453
  route("/mesh/api/state", (_req, res) => send(res, 200, state()));
2454
+ // 只读诊断:UI 的「诊断」卡片用它;与 /mesh/v1/diagnostics 同一份数据。
2455
+ route("/mesh/api/diagnostics", (_req, res) => send(res, 200, diagnostics()));
2213
2456
 
2214
2457
  /**
2215
2458
  * 用户决定提高某个 thread 的限速上限。
@@ -2345,18 +2588,145 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2345
2588
 
2346
2589
  // 无论节点是启动时创建还是后来从界面启动的,插件卸载时都收干净。
2347
2590
  ctx.effect(() => () => {
2348
- const node = tailnetNode;
2349
- tailnetNode = null;
2350
- node?.stop().catch(() => {});
2591
+ for (const node of tailnetNodes.values()) node.stop().catch(() => {});
2592
+ tailnetNodes.clear();
2351
2593
  });
2352
2594
 
2595
+ /** 通道列表是否被插件配置钉死(此时界面只能看,不能改)。 */
2596
+ const tailnetChannelsPinned = () => Array.isArray(config.tsnetChannels) && config.tsnetChannels.length > 0;
2597
+
2598
+ /** 把当前生效的通道列表转成对外视图(不回传授权码)。 */
2599
+ const tailnetViews = () =>
2600
+ effectiveTailnetChannels(config).map((c) => tailnetChannelView(c, tailnetNodes.get(c.id) ?? null));
2601
+
2353
2602
  /**
2354
- * 保存 tailnet 配置。
2603
+ * 保存 tailnet 配置(多通道)。
2604
+ *
2605
+ * 两种形态:
2606
+ * · `{ channels: [...] }` —— 整体替换通道列表(界面走这条)
2607
+ * · 旧的单通道字段 `{ authKey, controlUrl, hostname, enabled }` —— 兼容老页面
2608
+ *
2355
2609
  * 授权码存进 state.json(0600),所以**只需要输入一次**,重启不用再填。
2356
- * 授权码传空串表示"不改动已保存的值",避免界面回显后又被空值覆盖。
2610
+ * 某项的 `authKey` 传空串表示"不改动已保存的值";要清掉就传
2611
+ * `clearAuthKey: true`,避免界面回显后又被空值覆盖。
2357
2612
  */
2358
2613
  post("/mesh/api/tsnet/config", async (req, res) => {
2359
2614
  const body = await readJson(req);
2615
+
2616
+ if (Array.isArray(body?.channels)) {
2617
+ if (tailnetChannelsPinned()) {
2618
+ return send(res, 409, {
2619
+ ok: false,
2620
+ error: "通道列表已由插件配置 tsnetChannels 固定,界面不能修改",
2621
+ });
2622
+ }
2623
+ const existing = effectiveTailnetChannels(config);
2624
+ const byId = new Map(existing.map((c) => [c.id, c]));
2625
+ const used = new Set();
2626
+ const next = [];
2627
+ for (const item of body.channels) {
2628
+ if (!item || typeof item !== "object") continue;
2629
+ const rawLabel = String(item.label ?? "").trim().slice(0, 60);
2630
+ const rawControl = String(item.controlUrl ?? "").trim();
2631
+ let id = channelKey(item.id, "");
2632
+ if (!id) {
2633
+ // 新通道:宿主生成稳定 id。之后改显示名不会改变设备身份。
2634
+ do {
2635
+ id = `ch-${randomBytes(4).toString("hex")}`;
2636
+ } while (used.has(id) || byId.has(id) && !item.id);
2637
+ }
2638
+ if (used.has(id)) {
2639
+ return send(res, 400, { ok: false, error: `通道 id 重复:${id}` });
2640
+ }
2641
+ used.add(id);
2642
+ const prev = byId.get(id);
2643
+ const incomingKey = typeof item.authKey === "string" ? item.authKey.trim() : "";
2644
+ const authKey = item.clearAuthKey === true ? "" : incomingKey || prev?.authKey || "";
2645
+ next.push({
2646
+ id,
2647
+ label: rawLabel || prev?.label || `Tailnet ${next.length + 1}`,
2648
+ authKey,
2649
+ controlUrl: rawControl || prev?.controlUrl || "",
2650
+ hostname: String(item.hostname ?? "").trim() || prev?.hostname || "",
2651
+ enabled: item.enabled !== false,
2652
+ });
2653
+ }
2654
+ // 允许清空:这是"彻底关掉跨网络组网"的唯一可靠路径。必须同时清掉旧版
2655
+ // 单通道字段 —— 否则空列表会退回旧字段,把刚删掉的通道又变出来。
2656
+ if (next.length === 0) {
2657
+ await stopTailnetChannel("", discovery);
2658
+ saveState({
2659
+ tsnetChannels: [],
2660
+ tsnetEnabled: false,
2661
+ tsnetAuthKey: "",
2662
+ tsnetControlUrl: "",
2663
+ tsnetHostname: "",
2664
+ });
2665
+ log("tailnet 通道已全部删除,跨网络组网关闭");
2666
+ return send(res, 200, { ok: true, channels: [], enabled: false, authKeySaved: false, controlUrl: "", hostname: "" });
2667
+ }
2668
+ saveState({
2669
+ tsnetChannels: next,
2670
+ // 旧字段跟着走,避免老版本页面/回退时看到"未启用"
2671
+ tsnetEnabled: next.some((c) => c.enabled),
2672
+ });
2673
+ // 停掉被删掉、已禁用、或连接参数已变的通道;新配置由 /tsnet/start 拉起。
2674
+ // 参数变了却继续跑旧 sidecar,会留下"配置显示 A、实际连的是 B"的假象。
2675
+ for (const [id, node] of [...tailnetNodes.entries()]) {
2676
+ const spec = next.find((c) => c.id === id);
2677
+ const keep = spec && spec.enabled && node.signature === channelSignature(spec);
2678
+ if (!keep) {
2679
+ tailnetNodes.delete(id);
2680
+ await node.stop().catch(() => {});
2681
+ }
2682
+ }
2683
+ syncTailnetMeta(discovery);
2684
+ const views = tailnetViews();
2685
+ log(`tailnet 通道已保存:${next.map((c) => `${c.label}(${c.id})`).join("、")}`);
2686
+ return send(res, 200, {
2687
+ ok: true,
2688
+ channels: views,
2689
+ // 旧界面字段(取第一条启用通道)
2690
+ enabled: next.some((c) => c.enabled),
2691
+ authKeySaved: views.some((v) => v.authKeySaved),
2692
+ controlUrl: views[0]?.controlUrl ?? "",
2693
+ hostname: views[0]?.hostname ?? "",
2694
+ });
2695
+ }
2696
+
2697
+ // ── 旧版单通道字段(兼容已部署页面 / 脚本)──
2698
+ //
2699
+ // 如果已经有多通道列表,就作用到第一条(优先 default)通道上。
2700
+ // 直接忽略会变成"界面说保存成功、实际什么都没变"—— 这个项目最怕的静默失败。
2701
+ const currentChannels = effectiveTailnetChannels(config);
2702
+ if (currentChannels.length > 0 && !tailnetChannelsPinned()) {
2703
+ const next = currentChannels.map((c) => ({
2704
+ id: c.id,
2705
+ label: c.label,
2706
+ authKey: c.authKey,
2707
+ controlUrl: c.controlUrl,
2708
+ hostname: c.hostname,
2709
+ enabled: c.enabled,
2710
+ }));
2711
+ const target = next.find((c) => c.id === "default") ?? next[0];
2712
+ if (typeof body?.authKey === "string" && body.authKey.trim()) target.authKey = body.authKey.trim();
2713
+ if (body?.clearAuthKey === true) target.authKey = "";
2714
+ if (typeof body?.controlUrl === "string") target.controlUrl = body.controlUrl.trim();
2715
+ if (typeof body?.hostname === "string") target.hostname = body.hostname.trim();
2716
+ if (typeof body?.enabled === "boolean") target.enabled = body.enabled;
2717
+ saveState({ tsnetChannels: next, tsnetEnabled: next.some((c) => c.enabled) });
2718
+ log(`tailnet 配置已更新(作用于通道 ${target.id}):启用=${target.enabled} 授权码=${target.authKey ? "已保存" : "未设置"}`);
2719
+ const views = tailnetViews();
2720
+ return send(res, 200, {
2721
+ ok: true,
2722
+ channels: views,
2723
+ authKeySaved: views.some((v) => v.authKeySaved),
2724
+ controlUrl: target.controlUrl ?? "",
2725
+ hostname: target.hostname ?? "",
2726
+ enabled: views.some((v) => v.enabled),
2727
+ });
2728
+ }
2729
+
2360
2730
  const patch = {};
2361
2731
  if (typeof body?.authKey === "string" && body.authKey.trim()) patch.tsnetAuthKey = body.authKey.trim();
2362
2732
  if (body?.clearAuthKey === true) patch.tsnetAuthKey = "";
@@ -2365,12 +2735,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2365
2735
  if (typeof body?.enabled === "boolean") patch.tsnetEnabled = body.enabled;
2366
2736
  const saved = saveState(patch);
2367
2737
  log(
2368
- `tailnet 配置已更新:启用=${saved.tsnetEnabled === true} ` +
2738
+ `tailnet 旧版单通道配置已更新:启用=${saved.tsnetEnabled === true} ` +
2369
2739
  `授权码=${patch.tsnetAuthKey ? "已保存" : saved.tsnetAuthKey ? "保留原值" : "未设置"} ` +
2370
2740
  `控制服务器=${saved.tsnetControlUrl || "官方"}`,
2371
2741
  );
2372
2742
  return send(res, 200, {
2373
2743
  ok: true,
2744
+ channels: tailnetViews(),
2374
2745
  // 绝不回传授权码内容,只回报是否已配置
2375
2746
  authKeySaved: Boolean(saved.tsnetAuthKey),
2376
2747
  controlUrl: saved.tsnetControlUrl ?? "",
@@ -2379,65 +2750,115 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2379
2750
  });
2380
2751
  });
2381
2752
 
2382
- /** 启动(或按最新配置重启)tailnet 节点。 */
2383
- post("/mesh/api/tsnet/start", async (_req, res) => {
2384
- if (tailnetNode) {
2385
- const old = tailnetNode;
2386
- tailnetNode = null;
2387
- await old.stop().catch(() => {});
2753
+ /**
2754
+ * 启动(或按最新配置重启)tailnet 通道。
2755
+ *
2756
+ * body.id 省略 = 启动所有启用的通道(兼容旧页面点「只启动」)。
2757
+ */
2758
+ post("/mesh/api/tsnet/start", async (req, res) => {
2759
+ const body = await readJson(req);
2760
+ const wantId = String(body?.id ?? "").trim();
2761
+ const all = effectiveTailnetChannels(config);
2762
+ const targets = wantId ? all.filter((c) => c.id === channelKey(wantId)) : all.filter((c) => c.enabled);
2763
+ if (targets.length === 0) {
2764
+ return send(res, 404, { ok: false, error: wantId ? `没有 id 为 ${wantId} 的通道` : "没有启用的 tailnet 通道" });
2388
2765
  }
2389
- const node = new TsnetNode({ config: effectiveTsnetConfig(config), log, warn, machineName: identity.name });
2390
- tailnetNode = node;
2391
- try {
2392
- const { reused } = await node.start();
2393
- if (discovery.port) await node.registerForward(discovery.port);
2394
- await runScan({ discovery, config, log, warn, reason: "tailnet 手动扫描" });
2395
- return send(res, 200, { ok: true, reused, node: node.status() });
2396
- } catch (err) {
2397
- return send(res, 200, { ok: false, error: String(err?.message ?? err), node: node.status() });
2766
+ const started = [];
2767
+ for (const channel of targets) {
2768
+ try {
2769
+ const { reused } = await startTailnetChannel(channel, {
2770
+ config,
2771
+ discovery,
2772
+ log,
2773
+ warn,
2774
+ machineName: identity.name,
2775
+ });
2776
+ started.push({ id: channel.id, ok: true, reused });
2777
+ } catch (err) {
2778
+ started.push({ id: channel.id, ok: false, error: String(err?.message ?? err) });
2779
+ }
2398
2780
  }
2781
+ await runScan({ discovery, config, log, warn, reason: "tailnet 手动扫描" }).catch(() => {});
2782
+ const ok = started.some((r) => r.ok);
2783
+ const first = targets[0];
2784
+ return send(res, 200, {
2785
+ ok,
2786
+ results: started,
2787
+ error: ok ? undefined : started.map((r) => `${r.id}: ${r.error}`).join(";"),
2788
+ node: tailnetNodes.get(first.id)?.status() ?? null,
2789
+ channels: tailnetViews(),
2790
+ });
2399
2791
  });
2400
2792
 
2401
2793
  /**
2402
- * 停止 tailnet 节点。
2794
+ * 停止 tailnet 通道(body.id 省略 = 全部)。
2403
2795
  *
2404
2796
  * 这里**不能**传 keepRemote:stop() 在 "非 owner 或 keepRemote" 时走保留分支,
2405
2797
  * 而无条件传 true 会让本实例自己拉起的 sidecar 也停不掉(实测点「停止」后
2406
2798
  * 进程仍在跑、rendezvous 也没清)。不传参数即按归属判断:自己拉起的关掉,
2407
2799
  * 复用别人的只注销自己的 forward。
2408
2800
  */
2409
- post("/mesh/api/tsnet/stop", async (_req, res) => {
2410
- const node = tailnetNode;
2411
- tailnetNode = null;
2412
- if (node) await node.stop().catch(() => {});
2413
- return send(res, 200, { ok: true });
2801
+ post("/mesh/api/tsnet/stop", async (req, res) => {
2802
+ const body = await readJson(req);
2803
+ const wantId = String(body?.id ?? "").trim();
2804
+ const stopped = await stopTailnetChannel(wantId ? channelKey(wantId) : "", discovery);
2805
+ log(`tailnet ${wantId ? `通道 ${wantId} ` : "全部通道"}已停止(${stopped} 个)`);
2806
+ return send(res, 200, { ok: true, stopped, channels: tailnetViews() });
2414
2807
  });
2415
2808
 
2416
- /** 清掉节点身份重新登录(授权码失效 / 换账号时用)。 */
2417
- post("/mesh/api/tsnet/relogin", async (_req, res) => {
2418
- if (!tailnetNode) return send(res, 409, { ok: false, error: "互联网组网未启动" });
2419
- try {
2420
- await tailnetNode.relogin();
2421
- if (discovery.port) await tailnetNode.registerForward(discovery.port);
2422
- return send(res, 200, { ok: true, node: tailnetNode.status() });
2423
- } catch (err) {
2424
- return send(res, 200, { ok: false, error: String(err?.message ?? err), node: tailnetNode.status() });
2809
+ /** 清掉节点身份重新登录(授权码失效 / 换账号时用)。body.id 省略 = 所有在跑的通道。 */
2810
+ post("/mesh/api/tsnet/relogin", async (req, res) => {
2811
+ const body = await readJson(req);
2812
+ const wantId = String(body?.id ?? "").trim();
2813
+ const ids = wantId ? [channelKey(wantId)] : [...tailnetNodes.keys()];
2814
+ const nodes = ids.map((id) => tailnetNodes.get(id)).filter(Boolean);
2815
+ if (nodes.length === 0) return send(res, 409, { ok: false, error: "互联网组网未启动" });
2816
+ const done = [];
2817
+ for (const node of nodes) {
2818
+ try {
2819
+ await node.relogin();
2820
+ if (discovery.port) await node.registerForward(discovery.port);
2821
+ done.push({ id: node.channelKey, ok: true, node: node.status() });
2822
+ } catch (err) {
2823
+ done.push({ id: node.channelKey, ok: false, error: String(err?.message ?? err), node: node.status() });
2824
+ }
2425
2825
  }
2826
+ syncTailnetMeta(discovery);
2827
+ const ok = done.some((r) => r.ok);
2828
+ return send(res, 200, {
2829
+ ok,
2830
+ results: done,
2831
+ node: nodes[0].status(),
2832
+ channels: tailnetViews(),
2833
+ });
2426
2834
  });
2427
2835
 
2428
- /** 重新下载 sidecar 二进制(下载损坏或换平台时用)。 */
2429
- post("/mesh/api/tsnet/reinstall", async (_req, res) => {
2430
- if (!tailnetNode) return send(res, 409, { ok: false, error: "互联网组网未启动" });
2836
+ /**
2837
+ * 重新下载 sidecar 二进制(下载损坏或换平台时用)。
2838
+ *
2839
+ * 二进制是**整机共享**的:先停掉所有通道再换文件,否则 Windows 上文件锁着
2840
+ * 换不掉;换完不自动重启,按旧行为留给用户点「连接」。
2841
+ */
2842
+ post("/mesh/api/tsnet/reinstall", async (req, res) => {
2843
+ const body = await readJson(req);
2844
+ const wantId = String(body?.id ?? "").trim();
2845
+ const channels = effectiveTailnetChannels(config);
2846
+ const target = (wantId ? channels.find((c) => c.id === channelKey(wantId)) : null) ?? channels[0] ?? null;
2847
+ if (!target) return send(res, 409, { ok: false, error: "还没有配置 tailnet 通道" });
2848
+ await stopTailnetChannel("", discovery);
2849
+ const node = new TsnetNode({ config, channel: target, log, warn, machineName: identity.name });
2431
2850
  try {
2432
- const r = await tailnetNode.reinstallBinary();
2851
+ const r = await node.reinstallBinary();
2433
2852
  return send(res, 200, { ok: true, path: r.path, source: r.source });
2434
2853
  } catch (err) {
2435
2854
  return send(res, 200, { ok: false, error: String(err?.message ?? err) });
2436
2855
  }
2437
2856
  });
2438
2857
 
2439
- /** 只扫 tailnet,不扫局域网。 */
2440
- post("/mesh/api/tsnet/scan", async (_req, res) => {
2858
+ /** 只扫 tailnet,不扫局域网。body.id 省略 = 所有在跑的通道。 */
2859
+ post("/mesh/api/tsnet/scan", async (req, res) => {
2860
+ const body = await readJson(req);
2861
+ const wantId = String(body?.id ?? "").trim();
2441
2862
  const before = new Set(discovery.peers().map((p) => p.id));
2442
2863
  const result = await scanTailnet({
2443
2864
  discovery,
@@ -2445,12 +2866,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2445
2866
  log,
2446
2867
  reason: "tailnet 手动扫描",
2447
2868
  ports: scanPortList(discovery, config),
2869
+ channelId: wantId ? channelKey(wantId) : "",
2448
2870
  });
2449
2871
  const added = discovery.peers().filter((p) => !before.has(p.id));
2450
2872
  return send(res, 200, {
2451
2873
  ok: true,
2452
2874
  ...result,
2453
- added: added.map((p) => ({ machine: p.machine, host: p.host, port: p.port })),
2875
+ added: added.map((p) => ({ machine: p.machine, host: p.host, port: p.port, channel: p.channel })),
2454
2876
  });
2455
2877
  });
2456
2878