dsh-plugin-mesh 0.5.4 → 0.5.5

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
@@ -48,6 +48,13 @@ import { conversationKey, replyTarget } from "./conversation.js";
48
48
  import { buildDiagnostics, entryInfo, readPackageVersion } from "./diagnostics.js";
49
49
  import { buildPrompt } from "./prompt.js";
50
50
  import { resolvePairing } from "./pairing.js";
51
+ import {
52
+ applyMeshSwitch,
53
+ describeMeshSwitch,
54
+ normalizeSwitchScope,
55
+ resolveMeshSwitch,
56
+ MESH_SWITCH_LABEL,
57
+ } from "./switch.js";
51
58
  import {
52
59
  loadTaskHistory,
53
60
  saveTaskHistory,
@@ -61,7 +68,7 @@ import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
61
68
  export const name = "dsh-plugin-mesh";
62
69
  export const inject = ["tools", "webServer"];
63
70
 
64
- const VERSION = "0.5.4";
71
+ const VERSION = "0.5.5";
65
72
  // 诊断用:进程启动时间、入口真实路径、**磁盘上** package.json 的版本。
66
73
  // 这三样放一起才能回答"现在跑的到底是哪份代码" —— 只看 state.json 或重启日志
67
74
  // 都答不了(真踩过:磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -92,6 +99,19 @@ const tailnetNodes = new Map();
92
99
  */
93
100
  let activeDiscovery = null;
94
101
 
102
+ /**
103
+ * 传输开关(一键关闭):`true` = 这条路径可用。
104
+ *
105
+ * 由 applyUnsafe 按 state.json 里的 `shutdown` 维护,发送路径(peerFetch)、
106
+ * 扫描(runScan / scanTailnet)、保活(pingKnownPeers)都读它 —— 关掉一条
107
+ * 路径之后,不能再"从别的地方偷偷用它":那正是这类开关最典型的 bug
108
+ * (界面显示已关闭,实际还在发包)。
109
+ *
110
+ * 放模块级的原因和 activeDiscovery 一样:peerFetch / runScan / pingKnownPeers
111
+ * 都是模块级函数,而开关状态属于本次挂载的实例。
112
+ */
113
+ export const transportGate = { lan: true, internet: true };
114
+
95
115
  /**
96
116
  * 会话键 → 正在为它建会话期间堆积的消息。
97
117
  *
@@ -823,118 +843,381 @@ function applyUnsafe(ctx, config) {
823
843
  capabilities: currentCapabilities(),
824
844
  });
825
845
 
826
- // 1) 先起对端 HTTP(拿到真实端口),再开始发现
827
- startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange: scheduleHistorySave, diagnostics: diagnosticsPayload })
828
- .then(async (port) => {
829
- discovery.setPort(port);
846
+ // ── 一键关闭(kill switch)的运行时 ──
847
+ //
848
+ // 三条原则:
849
+ // 1. **不卸载插件、不注销 UI 路由**。关掉之后面板还得能打开 —— 否则
850
+ // 「一键关闭」就成了「一键把自己锁在外面」。
851
+ // 2. 关掉一条路径之后,任何出站/入站都不能再偷偷用它(发送、扫描、ping、
852
+ // 对端 HTTP 都读 transportGate)。这类开关最典型的 bug 就是界面显示
853
+ // 已关闭、实际还在发包。
854
+ // 3. 期望状态和真实状态**分开回报**。重绑回环失败时界面必须看得见,
855
+ // 不能拿"用户点了关闭"当"已经关好了"。
856
+ //
857
+ // 局域网关 = 组播停发、不再扫本网段 / ping,对端端口从 0.0.0.0 收回 127.0.0.1
858
+ // (tailnet 的 sidecar 是反代到本机回环的,所以互联网那半还能用)。
859
+ // 互联网关 = 停掉全部 tailnet sidecar;通道配置保留,打开即恢复。
860
+ // 期望状态写进 state.json 的 shutdown,重启后照旧。
861
+ let switchDesired = resolveMeshSwitch(loadState());
862
+ transportGate.lan = !switchDesired.lan;
863
+ transportGate.internet = !switchDesired.internet;
864
+
865
+ /** 当前监听中的对端服务句柄:{ port, host, server }。关闭时为 null。 */
866
+ let peerServer = null;
867
+ /** 上一次成功监听的端口:重开时优先沿用它,别让对端记着的地址失效。 */
868
+ let lastPort = 0;
869
+ /** 互联网是否已经尝试启动过(避免每次点开关都重走一遍 sidecar 启动)。 */
870
+ let internetUp = false;
871
+ /** 本次运行时起的定时器(扫描 / ping),重排时统一清掉。 */
872
+ let runtimeTimers = [];
873
+ /** 每次重排 +1:旧的异步扫描循环靠它自杀,不会在关闭后继续发包。 */
874
+ let lanGeneration = 0;
875
+ /** discovery 当前是否带组播启动(null = 没启动)。 */
876
+ let discoveryMulticast = null;
877
+ /** 运行时偏差说明:非空 = 没能完全按开关执行,界面要显示。 */
878
+ const switchNote = { lan: "", internet: "" };
879
+ /** 开关操作串行化:界面和 agent 可能同时点,不能让两个 reconcile 交错。 */
880
+ let switching = Promise.resolve();
881
+
882
+ const serialize = (fn) => {
883
+ const run = switching.then(fn, fn);
884
+ switching = run.then(() => undefined, () => undefined);
885
+ return run;
886
+ };
830
887
 
831
- // 始终 start:sweep(离线判定)在里面,与组播无关。
832
- // 关掉组播只影响被动发现,主动扫描 / ping 仍会用同一个注册表。
833
- discovery.start({ multicast: config.useMulticast !== false });
834
- if (config.useMulticast !== false) {
835
- discovery.announceNow();
836
- } else {
837
- log("已关闭组播,仅使用主动扫描 + ping");
838
- }
888
+ const shutRuntimeTimers = () => {
889
+ for (const t of runtimeTimers) clearInterval(t);
890
+ runtimeTimers = [];
891
+ };
839
892
 
840
- log(
841
- `已启动 machine=${identity.name}(来源 ${identity.source})` +
842
- ` 地址=${preferredAddress()}:${port} 实例=${instanceId} ` +
843
- `配对要求=${config.requirePairing ? "开" : "关"}`,
844
- );
893
+ /**
894
+ * 关掉对端服务并等它真正释放端口。
895
+ *
896
+ * 必须等 close 回调:紧接着就要在同一端口用另一个地址重新 listen,
897
+ * 不等的话会撞 EADDRINUSE,重绑静默失败 —— 那正是"显示关了、其实还开着"。
898
+ * 1.5s 兜底:极端情况下不让开关卡死。
899
+ */
900
+ const closePeerServer = () =>
901
+ new Promise((resolveClose) => {
902
+ const handle = peerServer;
903
+ peerServer = null;
904
+ if (!handle) {
905
+ resolveClose();
906
+ return;
907
+ }
908
+ let settled = false;
909
+ const done = () => {
910
+ if (settled) return;
911
+ settled = true;
912
+ resolveClose();
913
+ };
914
+ try {
915
+ handle.server.closeAllConnections?.();
916
+ } catch {
917
+ /* 老版本 Node 没有这个方法 */
918
+ }
919
+ try {
920
+ handle.server.close(done);
921
+ } catch {
922
+ done();
923
+ }
924
+ const t = setTimeout(done, 1500);
925
+ t.unref?.();
926
+ });
845
927
 
846
- // 主动发现 + 保活
847
- const stop = { aborted: false };
848
- ctx.effect(() => () => {
849
- stop.aborted = true;
850
- });
928
+ /**
929
+ * 起 / 重绑对端服务。`bindHost` 决定局域网是否可达:
930
+ * 0.0.0.0 → 局域网可连(局域网打开时)
931
+ * 127.0.0.1 → 只有本机(和 sidecar 反代)能连
932
+ *
933
+ * 重绑沿用**上一次的真实端口**,否则对端记着的地址、tailnet 的 forward 全部失效。
934
+ */
935
+ const ensurePeerServer = async (bindHost) => {
936
+ if (peerServer && peerServer.host === bindHost) return peerServer;
937
+ const keepPort = peerServer ? peerServer.port : lastPort || undefined;
938
+ await closePeerServer();
939
+ const handle = await startPeerServer(ctx, {
940
+ config,
941
+ discovery,
942
+ inbound,
943
+ outbound,
944
+ log,
945
+ warn,
946
+ waker,
947
+ threadState,
948
+ capFor,
949
+ capOverrides,
950
+ throttled,
951
+ onHistoryChange: scheduleHistorySave,
952
+ diagnostics: diagnosticsPayload,
953
+ port: keepPort,
954
+ bindHost,
955
+ });
956
+ peerServer = handle;
957
+ lastPort = handle.port;
958
+ discovery.setPort(handle.port);
959
+ return handle;
960
+ };
851
961
 
852
- // 互联网自组网:与局域网并行的第二条发现路径,功能同等级。
853
- // 任何一步失败都只影响对应通道 —— 局域网发现照常工作,这是硬要求。
854
- //
855
- // 多 tailnet:每条启用的通道各起一个 sidecar(串行启动,避免并发争用
856
- // 二进制下载);一条失败不影响其它条,也不影响局域网。
857
- const tailnetChannels = effectiveTailnetChannels(config).filter((c) => c.enabled);
858
- if (tailnetChannels.length > 0) {
859
- ctx.effect(() => () => {
860
- for (const node of tailnetNodes.values()) node.stop().catch(() => {});
861
- tailnetNodes.clear();
962
+ /**
963
+ * 起互联网(tailnet)通道。
964
+ *
965
+ * 串行启动:每条 sidecar 首次都要下载 30MB 二进制,并发会互相抢。
966
+ * 一条失败不影响其它条,也不影响局域网 —— 这是硬要求。
967
+ */
968
+ const ensureInternet = async (reason = "") => {
969
+ if (!transportGate.internet) return;
970
+ const channels = effectiveTailnetChannels(config).filter((c) => c.enabled);
971
+ if (channels.length === 0) {
972
+ log("互联网自组网未启用(没有启用的 tailnet 通道)");
973
+ return;
974
+ }
975
+ internetUp = true;
976
+ switchNote.internet = "";
977
+ for (const channel of channels) {
978
+ if (!transportGate.internet) {
979
+ // 启动途中被关掉:立刻收手,并把可能已经拉起来的 sidecar 收干净
980
+ await stopTailnetChannel(channel.id, discovery).catch(() => 0);
981
+ return;
982
+ }
983
+ try {
984
+ const { node, reused } = await startTailnetChannel(channel, {
985
+ config,
986
+ discovery,
987
+ log,
988
+ warn,
989
+ machineName: identity.name,
862
990
  });
991
+ const st = node.status();
992
+ log(
993
+ `通道「${channel.label}」已启动:节点=${node.hostname} tailnet=${st.selfIpv4 || "待登录"}` +
994
+ `${reused ? "(复用已有 sidecar)" : ""}${st.authUrl ? ` 授权链接=${st.authUrl}` : ""}`,
995
+ );
996
+ } catch (err) {
997
+ warn(`通道「${channel.label}」启动失败(局域网与其它通道不受影响):${err?.message ?? err}`);
998
+ switchNote.internet = `通道「${channel.label}」启动失败:${err?.message ?? err}`;
999
+ }
1000
+ }
1001
+ if (!transportGate.internet) return;
1002
+ // 所有通道都起来之后再扫一轮,让 tailnet 设备尽快进列表
1003
+ await scanTailnet({
1004
+ discovery,
1005
+ config,
1006
+ log,
1007
+ reason: reason || "tailnet 启动扫描",
1008
+ ports: scanPortList(discovery, config),
1009
+ }).catch(() => {});
1010
+ };
863
1011
 
864
- (async () => {
865
- for (const channel of tailnetChannels) {
866
- if (stop.aborted) return;
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}`));
1012
+ /**
1013
+ * 局域网发现:启动扫描(含退避重试)与周期扫描。
1014
+ * ping 保活由 syncRuntime 统一管(互联网开着也要 ping)。
1015
+ */
1016
+ const startLanDiscovery = () => {
1017
+ const gen = lanGeneration;
1018
+ if (config.scanOnStart) {
1019
+ // 启动扫描常常抢在对方起来之前跑完,所以没找到就退避重试几次。
1020
+ // 这直接决定"刚装好能不能自动发现",值得多试几下。
1021
+ const delays = [0, 8000, 20000, 45000];
1022
+ (async () => {
1023
+ for (let i = 0; i < delays.length; i += 1) {
1024
+ if (gen !== lanGeneration || !transportGate.lan) return;
1025
+ if (delays[i] > 0) await sleep(delays[i]);
1026
+ if (gen !== lanGeneration || !transportGate.lan) return;
1027
+ await runScan({ discovery, config, log, warn, reason: `启动扫描#${i + 1}` });
1028
+ if (discovery.peers().length > 0) return; // 找到了就不再重试
1029
+ }
1030
+ log("启动扫描未发现对端;之后靠组播与周期扫描继续尝试");
1031
+ })().catch(() => {});
1032
+ }
1033
+ if (config.scanIntervalMs > 0) {
1034
+ const t = setInterval(
1035
+ () => runScan({ discovery, config, log, warn, reason: "周期扫描" }).catch(() => {}),
1036
+ config.scanIntervalMs,
1037
+ );
1038
+ t.unref?.();
1039
+ runtimeTimers.push(t);
1040
+ }
1041
+ };
1042
+
1043
+ /**
1044
+ * 把运行时对齐到期望的开关状态。幂等:启动时调一次,之后每次开关都调。
1045
+ */
1046
+ const syncRuntime = async ({ reason = "" } = {}) => {
1047
+ lanGeneration += 1;
1048
+ shutRuntimeTimers();
1049
+ const wantLan = !switchDesired.lan;
1050
+ const wantNet = !switchDesired.internet;
1051
+ transportGate.lan = wantLan;
1052
+ transportGate.internet = wantNet;
1053
+
1054
+ // ── 互联网 ──
1055
+ if (!wantNet) {
1056
+ const stopped = await stopTailnetChannel("", discovery).catch(() => 0);
1057
+ internetUp = false;
1058
+ switchNote.internet = "";
1059
+ if (stopped > 0) log(`互联网 mesh 已关闭:停止 ${stopped} 条 tailnet 通道(通道配置保留)`);
1060
+ }
1061
+
1062
+ // ── 局域网 ──
1063
+ if (!wantLan && !wantNet) {
1064
+ await closePeerServer();
1065
+ if (discoveryMulticast !== null) {
1066
+ discovery.stop();
1067
+ discoveryMulticast = null;
1068
+ }
1069
+ switchNote.lan = "";
1070
+ } else {
1071
+ // 互联网开着就必须留着对端服务(tailnet 入站靠 sidecar 反代到本机回环)
1072
+ const bindHost = wantLan ? "0.0.0.0" : "127.0.0.1";
1073
+ try {
1074
+ await ensurePeerServer(bindHost);
1075
+ switchNote.lan = "";
1076
+ } catch (err) {
1077
+ switchNote.lan = `对端服务未能监听 ${bindHost}:${discovery.port || "?"} —— ${err?.message ?? err}`;
1078
+ warn(switchNote.lan);
1079
+ }
1080
+ // 组播只在局域网打开时启用:关掉之后连收包都不做。
1081
+ const multicast = wantLan && config.useMulticast !== false;
1082
+ if (discoveryMulticast !== multicast) {
1083
+ if (discoveryMulticast !== null) discovery.stop();
1084
+ discovery.start({ multicast });
1085
+ discoveryMulticast = multicast;
1086
+ }
1087
+ if (multicast) {
1088
+ discovery.announceNow();
1089
+ } else if (wantNet) {
1090
+ log("局域网 mesh 已关闭:不广播、不扫本网段,对端端口只绑回环");
888
1091
  } else {
889
- log("互联网自组网未启用(没有启用的 tailnet 通道)");
1092
+ log("已关闭组播,仅使用主动扫描 + ping");
890
1093
  }
1094
+ if (wantLan) startLanDiscovery();
1095
+ }
891
1096
 
892
- if (config.scanOnStart) {
893
- // 启动扫描常常抢在对方起来之前跑完,所以没找到就退避重试几次。
894
- // 这直接决定"刚装好能不能自动发现",值得多试几下。
895
- const delays = [0, 8000, 20000, 45000];
896
- (async () => {
897
- for (let i = 0; i < delays.length; i += 1) {
898
- if (stop.aborted) return;
899
- if (delays[i] > 0) await sleep(delays[i]);
900
- if (stop.aborted) return;
901
- await runScan({ discovery, config, log, warn, signal: stop, reason: `启动扫描#${i + 1}` });
902
- if (discovery.peers().length > 0) return; // 找到了就不再重试
903
- }
904
- log("启动扫描未发现对端;之后靠组播与周期扫描继续尝试");
905
- })().catch(() => {});
906
- }
1097
+ // ── 互联网启动(后台跑:首次要下载 sidecar,不能让界面/接口干等)──
1098
+ if (wantNet && !internetUp) {
1099
+ void ensureInternet(reason).catch((err) => warn(`互联网通道启动异常:${err?.message ?? err}`));
1100
+ }
907
1101
 
908
- if (config.scanIntervalMs > 0) {
909
- const t = setInterval(
910
- () => runScan({ discovery, config, log, warn, signal: stop, reason: "周期扫描" }).catch(() => {}),
911
- config.scanIntervalMs,
912
- );
913
- t.unref?.();
914
- ctx.effect(() => () => clearInterval(t));
915
- }
1102
+ // ── ping 保活:只要还有一条通道活着就要跑;pingKnownPeers 自己按开关过滤 ──
1103
+ if ((wantLan || wantNet) && config.pingIntervalMs > 0) {
1104
+ const t = setInterval(
1105
+ () => pingKnownPeers({ discovery, config, warn }).catch(() => {}),
1106
+ config.pingIntervalMs,
1107
+ );
1108
+ t.unref?.();
1109
+ runtimeTimers.push(t);
1110
+ }
1111
+ };
916
1112
 
917
- if (config.pingIntervalMs > 0) {
918
- const t = setInterval(
919
- () => pingKnownPeers({ discovery, config, warn }).catch(() => {}),
920
- config.pingIntervalMs,
921
- );
922
- t.unref?.();
923
- ctx.effect(() => () => clearInterval(t));
1113
+ /**
1114
+ * 对外回报的开关状态:期望值 + 真实运行情况 + 偏差说明。
1115
+ * 界面和 agent 都读这一份,避免两处各编一套说法。
1116
+ */
1117
+ const switchStatus = () => {
1118
+ const lanOff = switchDesired.lan;
1119
+ const netOff = switchDesired.internet;
1120
+ const bind = peerServer?.host ?? "";
1121
+ let lanNote = switchNote.lan;
1122
+ // 说得到就要做得到:关闭状态下如果还听着 0.0.0.0,必须明说。
1123
+ if (lanOff && bind && bind !== "127.0.0.1" && bind !== "::1" && bind !== "::ffff:127.0.0.1") {
1124
+ lanNote = lanNote || "端口仍对局域网开放(未能收回回环,检查端口占用)";
1125
+ }
1126
+ const running = runningTailnetNodes().length;
1127
+ // 互联网侧的真实麻烦(连不上控制面 / 授权码失效)必须出现在这里:
1128
+ // 「开启但没连上」如果只说成"未连接",用户会以为是正常在等。
1129
+ const stalled = [...tailnetNodes.values()]
1130
+ .map((n) => n.status())
1131
+ .filter((s) => s && s.stalled);
1132
+ const internetNote =
1133
+ switchNote.internet ||
1134
+ (stalled.length > 0
1135
+ ? `有 ${stalled.length} 条通道启动受阻:${stalled[0].stalledReason || "控制面没有回应"}` +
1136
+ (stalled[0].stalledHint ? `(${stalled[0].stalledHint})` : "")
1137
+ : "");
1138
+ return {
1139
+ lan: {
1140
+ off: lanOff,
1141
+ // active 表示"真的在监听",不是"用户说它开着" —— 绑定失败时要能看出来
1142
+ active: !lanOff && Boolean(peerServer),
1143
+ bind,
1144
+ port: peerServer?.port ?? 0,
1145
+ multicast: discoveryMulticast === true,
1146
+ note: lanNote,
1147
+ },
1148
+ internet: {
1149
+ off: netOff,
1150
+ active: !netOff && running > 0,
1151
+ running,
1152
+ configured: effectiveTailnetChannels(config).filter((c) => c.enabled).length,
1153
+ /** 启动受阻的通道数(卡在控制面/登录,界面要说话,不能一直转圈) */
1154
+ stalled: stalled.length,
1155
+ note: internetNote,
1156
+ },
1157
+ all: lanOff && netOff,
1158
+ at: switchDesired.at,
1159
+ by: switchDesired.by,
1160
+ summary: describeMeshSwitch(switchDesired),
1161
+ };
1162
+ };
1163
+
1164
+ /**
1165
+ * 执行一次开关操作(界面按钮与 mesh_switch 工具共用)。
1166
+ *
1167
+ * 先落盘再动运行时:写盘失败时**不**去停服务,避免"这一秒关了、重启又开着"
1168
+ * 这种更糟的半态。
1169
+ */
1170
+ const setSwitch = (opts = {}) =>
1171
+ serialize(async () => {
1172
+ const scope = normalizeSwitchScope(opts.scope);
1173
+ if (!scope) throw new Error(`未知的开关范围:${String(opts.scope)}(应为 all / lan / internet)`);
1174
+ const next = applyMeshSwitch(switchDesired, { scope, off: opts.off, by: opts.by ?? "ui" });
1175
+ const before = { lan: switchDesired.lan, internet: switchDesired.internet };
1176
+ saveState({ shutdown: next });
1177
+ switchDesired = resolveMeshSwitch({ shutdown: next });
1178
+ const changed = before.lan !== switchDesired.lan || before.internet !== switchDesired.internet;
1179
+ if (changed) {
1180
+ const label = MESH_SWITCH_LABEL[scope] ?? scope;
1181
+ log(`一键关闭「${label}」→ ${describeMeshSwitch(switchDesired)}(来源 ${next.by},立即生效,重启后保持)`);
1182
+ await syncRuntime({ reason: `一键关闭:${label}` });
924
1183
  }
925
- })
926
- .catch((err) => warn(`对端服务启动失败,发现功能未启用: ${err?.message ?? err}`));
1184
+ return { changed, scope, status: switchStatus() };
1185
+ });
1186
+
1187
+ // 1) 按开关状态起对端服务与发现;局域网/互联网各自独立
1188
+ (async () => {
1189
+ await syncRuntime({ reason: "启动" });
1190
+ log(
1191
+ `已启动 machine=${identity.name}(来源 ${identity.source})` +
1192
+ ` 地址=${preferredAddress()}:${discovery.port || "?"} 实例=${instanceId} ` +
1193
+ `配对要求=${config.requirePairing ? "开" : "关"} ` +
1194
+ `开关=${describeMeshSwitch(switchDesired)}`,
1195
+ );
1196
+ if (switchDesired.all) {
1197
+ log("上次退出前处于「全部关闭」状态:保持关闭,Mesh 面板里可以重新打开");
1198
+ }
1199
+ })().catch((err) => warn(`对端服务启动失败,发现功能未启用: ${err?.message ?? err}`));
927
1200
 
928
1201
  // 2) 入站唤醒:注册一次 webhook 规则,之后每个任务只 dispatch
929
1202
  setupInbound(ctx, config, log, warn, waker);
930
1203
 
1204
+ /** 一键关闭的对外门面:UI 路由与 agent 工具共用同一份实现。 */
1205
+ const meshSwitch = { status: switchStatus, set: setSwitch };
1206
+
931
1207
  // 3) agent 工具
932
- registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange: scheduleHistorySave });
1208
+ registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange: scheduleHistorySave, meshSwitch });
933
1209
 
934
1210
  // 4) UI 接口
935
- registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave, diagnostics: diagnosticsPayload });
1211
+ registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave, diagnostics: diagnosticsPayload, meshSwitch });
936
1212
 
937
1213
  ctx.effect(() => () => {
1214
+ // 卸载时一并收干净:定时器、对端端口、tailnet sidecar。
1215
+ // 一键关闭只是"暂停",卸载才是"拆走"。
1216
+ lanGeneration += 1;
1217
+ shutRuntimeTimers();
1218
+ void closePeerServer();
1219
+ for (const node of tailnetNodes.values()) node.stop().catch(() => {});
1220
+ tailnetNodes.clear();
938
1221
  discovery.stop();
939
1222
  log("已停止");
940
1223
  });
@@ -1645,8 +1928,24 @@ function endpointKeyOf(ep) {
1645
1928
  */
1646
1929
  async function peerFetch(peer, path, opts = {}) {
1647
1930
  const { timeoutMs = 20000, ...rest } = opts;
1648
- const eps = orderedEndpoints(peer);
1649
- if (eps.length === 0) throw new Error(`对端 ${peer?.machine ?? "?"} 没有任何已知通道`);
1931
+ const all = orderedEndpoints(peer);
1932
+ if (all.length === 0) throw new Error(`对端 ${peer?.machine ?? "?"} 没有任何已知通道`);
1933
+
1934
+ // 一键关闭掉的路径不许用于出站。
1935
+ // 宁可明确说"这条通道关了",也不要让它退化成"所有通道都失败" —— 后者会让
1936
+ // 用户以为对端掉线了,实际是本机自己关的(这类误判在这个项目里踩过)。
1937
+ const eps = all.filter((ep) => (ep.transport === "tsnet" ? transportGate.internet : transportGate.lan));
1938
+ if (eps.length === 0) {
1939
+ const closed = new Set();
1940
+ for (const ep of all) {
1941
+ const transport = ep.transport === "tsnet" ? "internet" : "lan";
1942
+ if (!transportGate[transport]) closed.add(transport === "internet" ? "互联网 mesh" : "局域网 mesh");
1943
+ }
1944
+ throw new Error(
1945
+ `本机已关闭${[...closed].join("、")},对端 ${peer?.machine ?? "?"} 没有可用通道。` +
1946
+ "可在 Mesh 面板「连接 → 一键关闭」里打开后重试。",
1947
+ );
1948
+ }
1650
1949
 
1651
1950
  const failures = [];
1652
1951
  for (const ep of eps) {
@@ -1727,6 +2026,9 @@ async function fetchViaTailnet(ep, url, opts = {}) {
1727
2026
  * @param channelId 只扫某一条通道;省略 = 所有在跑的通道
1728
2027
  */
1729
2028
  async function scanTailnet({ discovery, config, log, reason, ports, channelId = "" }) {
2029
+ // 互联网 mesh 被一键关闭时一律不扫:sidecar 已经停了,扫也只会报一堆
2030
+ // "节点未启动",反而像故障。
2031
+ if (!transportGate.internet) return { scanned: 0, found: 0, channels: [], closed: true };
1730
2032
  const nodes = runningTailnetNodes().filter((n) => !channelId || n.channelKey === channelId);
1731
2033
  if (nodes.length === 0) return { scanned: 0, found: 0, channels: [] };
1732
2034
 
@@ -1827,6 +2129,14 @@ async function runScan({ discovery, config, log, warn, signal, reason = "扫描"
1827
2129
  const ports = scanPortList(discovery, config);
1828
2130
  let lanFound = 0;
1829
2131
 
2132
+ // 局域网 mesh 一键关闭后不再发任何探测包(这是一条真实的出网行为,
2133
+ // 不能因为"只是扫描"就留着)。tailnet 那半段仍按各自的开关决定。
2134
+ if (!transportGate.lan) {
2135
+ log(`${reason}: 局域网 mesh 已关闭,只扫互联网通道`);
2136
+ const tailOnly = await scanTailnet({ discovery, config, log, reason, ports });
2137
+ return { scanned: tailOnly.scanned, found: tailOnly.found, lan: false, tailnet: tailOnly };
2138
+ }
2139
+
1830
2140
  if (addresses.length === 0) {
1831
2141
  warn(`${reason}: 没有可扫描的地址(检查 scanRanges 是否合法 / 网卡是否存在)`);
1832
2142
  }
@@ -1881,7 +2191,7 @@ async function pingKnownPeers({ discovery, config, warn }) {
1881
2191
  // tailnet 按 tsnetProbeIntervalMs(默认 60s)低频验证;另外**还没探通过的
1882
2192
  // 通道立刻探一次**,让它尽快有个真实状态而不是停在"未探测"。
1883
2193
  const tsnetInterval = Math.max(config.pingIntervalMs, config.tsnetProbeIntervalMs ?? 60000);
1884
- const targets = endpoints.filter((ep) => {
2194
+ const targets = endpoints.filter((ep) => (ep.transport === "tsnet" ? transportGate.internet : transportGate.lan)).filter((ep) => {
1885
2195
  const interval = ep.transport === "tsnet" ? tsnetInterval : config.pingIntervalMs;
1886
2196
  if (ep.verified === false) {
1887
2197
  // 首次立刻探一次;失败后按通道节奏重试,并尊重 markEndpoint 记下
@@ -1948,7 +2258,18 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
1948
2258
 
1949
2259
  // ───────────────────────── 对端 HTTP 服务 ─────────────────────────
1950
2260
 
1951
- function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange, diagnostics }) {
2261
+ /**
2262
+ * 起一个对端 HTTP 服务。
2263
+ *
2264
+ * 返回值从"端口号"改成了句柄 `{ port, host, server }`:一键关闭需要把监听
2265
+ * 从 0.0.0.0 收回到 127.0.0.1(局域网不可达,tailnet 的 sidecar 反代仍在
2266
+ * 本机回环上),恢复时再重新绑回去。没有句柄就没法做这件事。
2267
+ *
2268
+ * @param options.port 指定端口;省略用 config.port。重绑时传上一次的真实端口,
2269
+ * 否则对端记着的端口会变(tailnet 的 forward 也会失效)。
2270
+ * @param options.bindHost 监听地址。局域网关着时传 "127.0.0.1"。
2271
+ */
2272
+ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange, diagnostics, port: fixedPort, bindHost = "0.0.0.0" }) {
1952
2273
  const send = (res, code, payload) => {
1953
2274
  const body = Buffer.from(JSON.stringify(payload), "utf8");
1954
2275
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -1961,11 +2282,29 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
1961
2282
  const authed = (req) =>
1962
2283
  !pairingRequired(config) || safeEqual(req.headers["x-dsh-mesh-token"], currentSecret());
1963
2284
 
2285
+ /**
2286
+ * 一键关闭的入站闸门。
2287
+ *
2288
+ * 只绑回环已经能挡住局域网(连接直接被拒),但这一层仍必须有:重绑失败
2289
+ * (端口被占、系统限制)时不能变成"界面显示关了、实际还收任务"。tailnet
2290
+ * 的入站由 sidecar 反代到回环,带 X-Forwarded-For,按 transport 区分。
2291
+ */
2292
+ const inboundClosedReason = (req) => {
2293
+ const origin = tailnetOrigin(req);
2294
+ if (origin.transport === "tsnet") return transportGate.internet ? "" : "互联网 mesh 已关闭";
2295
+ return transportGate.lan ? "" : "局域网 mesh 已关闭";
2296
+ };
2297
+
1964
2298
  const server = createServer(async (req, res) => {
1965
2299
  const url = new URL(req.url, "http://localhost");
1966
2300
  const path = url.pathname;
1967
2301
  const self = { ...discovery.selfRecord(), instanceId: discovery.instanceId };
1968
2302
 
2303
+ // 关闭期间连 health 都不答(否则对端会认为我们还活着)。503 带上原因,
2304
+ // 排障时能一眼看出是本机自己关的,而不是网络不通。
2305
+ const closed = inboundClosedReason(req);
2306
+ if (closed) return send(res, 503, { ok: false, closed: true, error: `本机已关闭${closed}(Mesh 面板可重新打开)` });
2307
+
1969
2308
  // 免鉴权:只暴露身份,用于连通性探测、主动扫描与配对握手
1970
2309
  if (path === "/mesh/v1/health") return send(res, 200, { ok: true, ...self, requirePairing: pairingRequired(config) });
1971
2310
  if (path === "/mesh/v1/hello") {
@@ -2034,7 +2373,7 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2034
2373
  });
2035
2374
 
2036
2375
  return new Promise((resolvePromise, rejectPromise) => {
2037
- const wanted = config.port ?? MESH_DEFAULT_PORT;
2376
+ const wanted = fixedPort ?? config.port ?? MESH_DEFAULT_PORT;
2038
2377
  const start = (port, isFallback) => {
2039
2378
  server.once("error", (err) => {
2040
2379
  if (!isFallback && err?.code === "EADDRINUSE") {
@@ -2044,11 +2383,10 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2044
2383
  }
2045
2384
  rejectPromise(err);
2046
2385
  });
2047
- server.listen(port, "0.0.0.0", () => {
2386
+ server.listen(port, bindHost, () => {
2048
2387
  const addr = server.address();
2049
- log(`对端服务监听 0.0.0.0:${addr.port}${isFallback ? "(随机)" : "(固定)"}`);
2050
- ctx.effect(() => () => server.close());
2051
- resolvePromise(addr.port);
2388
+ log(`对端服务监听 ${addr.address}:${addr.port}${isFallback ? "(随机)" : "(固定)"}`);
2389
+ resolvePromise({ port: addr.port, host: addr.address, server });
2052
2390
  });
2053
2391
  };
2054
2392
  start(wanted, false);
@@ -2081,8 +2419,17 @@ function readJson(req) {
2081
2419
 
2082
2420
  // ───────────────────────── agent 工具 ─────────────────────────
2083
2421
 
2084
- function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange }) {
2422
+ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange, meshSwitch }) {
2085
2423
  const text = (v) => [{ type: "text", text: v }];
2424
+ /**
2425
+ * 当前开关的一行摘要。所有工具的输出都带上它 —— agent 看到"没有对端"
2426
+ * 时,第一件要能分清的事是"真没有"还是"本机自己关了"(这个项目里
2427
+ * 把"没答"当成"没有"已经出过一次事故)。
2428
+ */
2429
+ const switchLine = () => (meshSwitch ? meshSwitch.status().summary : "局域网 开启 · 互联网 开启");
2430
+ const lanOff = () => !!(meshSwitch && meshSwitch.status().lan.off);
2431
+ const netOff = () => !!(meshSwitch && meshSwitch.status().internet.off);
2432
+ const allOff = () => !!(meshSwitch && meshSwitch.status().all);
2086
2433
 
2087
2434
  ctx.tools.register(
2088
2435
  defineTool({
@@ -2098,12 +2445,24 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
2098
2445
  const peers = discovery.peers();
2099
2446
  const list = args?.includeOffline === false ? peers.filter((p) => p.online) : peers;
2100
2447
  if (list.length === 0) {
2448
+ if (allOff()) {
2449
+ return (
2450
+ `本机 mesh 已全部关闭(${switchLine()}),所以看不到任何对端 —— 这不代表网络里没有机器。\n` +
2451
+ "需要时用 mesh_switch(scope=all, action=on)打开,或让用户在 Mesh 面板「连接 → 一键关闭」里打开。"
2452
+ );
2453
+ }
2454
+ if (lanOff()) {
2455
+ return (
2456
+ `本机局域网 mesh 已关闭(${switchLine()}),本网段的机器目前不可见。\n` +
2457
+ "互联网通道若已配置,可继续用 mesh_peers 看到 tailnet 上的机器。"
2458
+ );
2459
+ }
2101
2460
  return (
2102
2461
  "没有发现其他 DSH 机器。\n" +
2103
2462
  "用 mesh_scan 主动扫一次本网段(组播常被路由器/防火墙挡住)。\n" +
2104
2463
  "仍找不到就排查:1) 两台机器是否同一网段 2) 对端是否装了 dsh-plugin-mesh 并已重启 DSH " +
2105
2464
  "3) 对端防火墙是否放行这个 TCP 端口\n" +
2106
- `本机: ${machineOf(discovery)} (${preferredAddress()})`
2465
+ `本机: ${machineOf(discovery)} (${preferredAddress()}) · 开关: ${switchLine()}`
2107
2466
  );
2108
2467
  }
2109
2468
  const lines = list.map((p) => {
@@ -2115,7 +2474,10 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
2115
2474
  (caps ? `\n${caps}` : "")
2116
2475
  );
2117
2476
  });
2118
- return `发现 ${list.length} 台机器:\n${lines.join("\n")}\n\n本机: ${machineOf(discovery)} (${preferredAddress()})`;
2477
+ return (
2478
+ `发现 ${list.length} 台机器:\n${lines.join("\n")}\n\n` +
2479
+ `本机: ${machineOf(discovery)} (${preferredAddress()}) · 开关: ${switchLine()}`
2480
+ );
2119
2481
  },
2120
2482
  }),
2121
2483
  );
@@ -2129,6 +2491,17 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
2129
2491
  parameters: {},
2130
2492
  output: { schema: { type: "string" }, render: (_a, v) => text(v) },
2131
2493
  async execute() {
2494
+ if (allOff()) {
2495
+ return "未扫描:本机 mesh 已全部关闭。用 mesh_switch(scope=all, action=on)打开后再扫。";
2496
+ }
2497
+ if (lanOff()) {
2498
+ return (
2499
+ "未扫描:本机局域网 mesh 已关闭(不会向本网段发包)。\n" +
2500
+ (netOff()
2501
+ ? "互联网 mesh 也关着,所以两条路径都不可用。"
2502
+ : "互联网通道仍可用:需要找 tailnet 上的机器请用 mesh_switch 之外的方式,或先打开局域网。")
2503
+ );
2504
+ }
2132
2505
  const before = discovery.peers().length;
2133
2506
  const r = await runScan({ discovery, config, log, warn, reason: "agent 触发扫描" });
2134
2507
  const after = discovery.peers();
@@ -2173,6 +2546,12 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
2173
2546
  const peerName = String(args?.peer ?? "").trim();
2174
2547
  const task = String(args?.task ?? "").trim();
2175
2548
  if (!peerName || !task) return "peer 和 task 都必填。";
2549
+ if (allOff()) {
2550
+ return (
2551
+ "任务未派发:本机 mesh 已全部关闭(局域网 + 互联网)。\n" +
2552
+ "用 mesh_switch(scope=all, action=on)打开,或请用户在 Mesh 面板「连接 → 一键关闭」里打开。"
2553
+ );
2554
+ }
2176
2555
 
2177
2556
  const matches = findPeersByName(discovery, peerName);
2178
2557
  if (matches.length === 0) {
@@ -2273,12 +2652,78 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
2273
2652
  }),
2274
2653
  );
2275
2654
 
2276
- log("已注册工具 mesh_peers / mesh_run / mesh_tasks");
2655
+ /**
2656
+ * 一键关闭 / 打开。
2657
+ *
2658
+ * 为什么做成工具而不只是界面按钮:用户经常是在对话里说"把 mesh 关了",
2659
+ * 而且关掉之后往往正是要 agent 继续干活(离线跑长任务)。做成工具,agent
2660
+ * 能自己执行并立刻回报"现在还有哪条通道是活的"。
2661
+ *
2662
+ * 默认动作是**关闭**:这是主动作,也是用户说"关掉"时的意思;打开必须显式传。
2663
+ */
2664
+ ctx.tools.register(
2665
+ defineTool({
2666
+ name: "mesh_switch",
2667
+ description:
2668
+ "一键关闭 / 打开本机 mesh。三种范围:all(全部)、lan(局域网)、internet(互联网 tailnet)。" +
2669
+ "关闭立即生效:局域网关闭后不再组播广播、不再扫本网段,对端端口只绑回环;" +
2670
+ "互联网关闭后停掉全部 tailnet sidecar(通道配置保留)。" +
2671
+ "状态写入 state.json,重启 DSH 后仍保持,直到显式打开。" +
2672
+ "界面上同一组开关在 Mesh 面板「连接 → 一键关闭」。",
2673
+ parameters: {
2674
+ scope: {
2675
+ type: "string",
2676
+ required: true,
2677
+ description: "关闭/打开的范围:all(全部 mesh)、lan(局域网 mesh)、internet(互联网 mesh)",
2678
+ },
2679
+ action: {
2680
+ type: "string",
2681
+ description: "off = 关闭(默认),on = 打开",
2682
+ },
2683
+ },
2684
+ output: { schema: { type: "string" }, render: (_a, v) => text(v) },
2685
+ async execute(args) {
2686
+ if (!meshSwitch) return "本机没有可用的 mesh 开关实现(插件版本过旧)。";
2687
+ const scope = normalizeSwitchScope(args?.scope);
2688
+ if (!scope) {
2689
+ return `scope 不合法:${String(args?.scope ?? "")}。用 all / lan / internet 之一。`;
2690
+ }
2691
+ const rawAction = String(args?.action ?? "off").trim().toLowerCase();
2692
+ if (!["off", "on", "close", "open", "disable", "enable"].includes(rawAction)) {
2693
+ return `action 不合法:${rawAction}。用 off(关闭)或 on(打开)。`;
2694
+ }
2695
+ const wantOff = ["off", "close", "disable"].includes(rawAction);
2696
+ const result = await meshSwitch.set({ scope, off: wantOff, by: "tool" });
2697
+ const st = result.status;
2698
+ const label = MESH_SWITCH_LABEL[scope] ?? scope;
2699
+ const lines = [
2700
+ `${label}已${wantOff ? "关闭" : "打开"}${result.changed ? "" : "(状态本来就是这样,没有变化)"}。`,
2701
+ `当前:${st.summary}`,
2702
+ `局域网:${st.lan.off ? "已关闭" : "开启"}` +
2703
+ (st.lan.off
2704
+ ? ` · 对端端口${st.lan.bind ? `只绑 ${st.lan.bind}` : "已停"}`
2705
+ : ` · 监听 ${st.lan.bind || "—"}:${st.lan.port || "—"} · 组播 ${st.lan.multicast ? "开" : "关"}`) +
2706
+ (st.lan.note ? ` · 注意:${st.lan.note}` : ""),
2707
+ `互联网:${st.internet.off ? "已关闭" : "开启"}` +
2708
+ (st.internet.off
2709
+ ? ` · 运行中 sidecar ${st.internet.running} 条(配置里启用 ${st.internet.configured} 条,配置保留)`
2710
+ : ` · 运行中 ${st.internet.running}/${st.internet.configured} 条`) +
2711
+ (st.internet.note ? ` · 注意:${st.internet.note}` : ""),
2712
+ ];
2713
+ if (!wantOff && scope !== "lan" && st.internet.configured === 0) {
2714
+ lines.push("提示:互联网 mesh 没有启用的 tailnet 通道,需要在 Mesh 面板里添加授权码。");
2715
+ }
2716
+ return lines.join("\n");
2717
+ },
2718
+ }),
2719
+ );
2720
+
2721
+ log("已注册工具 mesh_peers / mesh_run / mesh_tasks / mesh_switch");
2277
2722
  }
2278
2723
 
2279
2724
  // ───────────────────────── UI 接口(本地回环) ─────────────────────────
2280
2725
 
2281
- function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange, diagnostics }) {
2726
+ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange, diagnostics, meshSwitch }) {
2282
2727
  const send = (res, code, payload) => {
2283
2728
  const body = Buffer.from(JSON.stringify(payload), "utf8");
2284
2729
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -2431,6 +2876,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2431
2876
  node: primary?.node ?? null,
2432
2877
  recentEvents: primary?.recentEvents ?? [],
2433
2878
  },
2879
+ // 一键关闭:期望值 + 真实运行情况 + 偏差说明(界面按它渲染三个开关)
2880
+ switch: meshSwitch ? meshSwitch.status() : null,
2434
2881
  peers: discovery.peers(),
2435
2882
  duplicateNames: duplicateNames(),
2436
2883
  inbound: inbound.slice(-30).reverse(),
@@ -2533,11 +2980,22 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2533
2980
  });
2534
2981
 
2535
2982
  post("/mesh/api/refresh", (_req, res) => {
2536
- discovery.announceNow();
2537
- send(res, 200, { ok: true });
2983
+ const st = meshSwitch ? meshSwitch.status() : null;
2984
+ // 关着局域网时 announceNow 是空操作。如实回报,别让界面以为"广播过了"。
2985
+ const announced = Boolean(st && !st.lan.off && st.lan.multicast);
2986
+ if (announced) discovery.announceNow();
2987
+ send(res, 200, { ok: true, announced });
2538
2988
  });
2539
2989
 
2540
2990
  post("/mesh/api/scan", async (_req, res) => {
2991
+ // 局域网关着就别发包(按钮叫「局域网探测」,不能偷偷改成只扫 tailnet)
2992
+ if (meshSwitch && meshSwitch.status().lan.off) {
2993
+ return send(res, 409, {
2994
+ ok: false,
2995
+ closed: true,
2996
+ error: "局域网 mesh 已关闭 —— 在「连接 → 一键关闭」里打开后再探测",
2997
+ });
2998
+ }
2541
2999
  try {
2542
3000
  const result = await runScan({ discovery, config, log, warn, reason: "手动扫描" });
2543
3001
  send(res, 200, { ok: true, ...result, peers: discovery.peers() });
@@ -2574,6 +3032,37 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2574
3032
  return send(res, 200, { ok: true, requirePairing: want });
2575
3033
  });
2576
3034
 
3035
+ /**
3036
+ * 界面上的「一键关闭」。
3037
+ *
3038
+ * body: `{ scope: "all"|"lan"|"internet", off: boolean }`
3039
+ *
3040
+ * 和配对码开关一样写 state.json(不改用户的 cordis.patch.yml),
3041
+ * 但**会跨重启保持**:一键关闭的语义是"我现在不想让这台机器被找到、被派活",
3042
+ * 重启后自己悄悄恢复是最坏的结果。
3043
+ *
3044
+ * `off` 必须是布尔值:`body?.off === true` 这种写法在 GET/空 body 上会变成
3045
+ * false,那是"悄悄打开"—— 和 pairing 那次 fail-open 同一类错误,这里直接
3046
+ * 400 拒掉。
3047
+ */
3048
+ post("/mesh/api/switch", async (req, res) => {
3049
+ const body = await readJson(req);
3050
+ const scope = normalizeSwitchScope(body?.scope);
3051
+ if (!scope) {
3052
+ return send(res, 400, { ok: false, error: "scope 必须是 all / lan / internet 之一" });
3053
+ }
3054
+ if (typeof body?.off !== "boolean") {
3055
+ return send(res, 400, { ok: false, error: "off 必须是布尔值(true = 关闭,false = 打开)" });
3056
+ }
3057
+ if (!meshSwitch) return send(res, 503, { ok: false, error: "开关实现不可用(插件版本过旧)" });
3058
+ try {
3059
+ const result = await meshSwitch.set({ scope, off: body.off, by: "ui" });
3060
+ return send(res, 200, { ok: true, changed: result.changed, scope, switch: result.status });
3061
+ } catch (err) {
3062
+ return send(res, 500, { ok: false, error: String(err?.message ?? err) });
3063
+ }
3064
+ });
3065
+
2577
3066
  post("/mesh/api/secret", async (req, res) => {
2578
3067
  const body = await readJson(req);
2579
3068
  const secret = String(body?.secret ?? "").trim();
@@ -2756,6 +3245,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2756
3245
  * body.id 省略 = 启动所有启用的通道(兼容旧页面点「只启动」)。
2757
3246
  */
2758
3247
  post("/mesh/api/tsnet/start", async (req, res) => {
3248
+ if (meshSwitch && meshSwitch.status().internet.off) {
3249
+ return send(res, 409, {
3250
+ ok: false,
3251
+ closed: true,
3252
+ error: "互联网 mesh 已关闭 —— 在「连接 → 一键关闭」里打开后再启动通道",
3253
+ });
3254
+ }
2759
3255
  const body = await readJson(req);
2760
3256
  const wantId = String(body?.id ?? "").trim();
2761
3257
  const all = effectiveTailnetChannels(config);
@@ -2857,6 +3353,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2857
3353
 
2858
3354
  /** 只扫 tailnet,不扫局域网。body.id 省略 = 所有在跑的通道。 */
2859
3355
  post("/mesh/api/tsnet/scan", async (req, res) => {
3356
+ if (meshSwitch && meshSwitch.status().internet.off) {
3357
+ return send(res, 409, {
3358
+ ok: false,
3359
+ closed: true,
3360
+ error: "互联网 mesh 已关闭 —— 在「连接 → 一键关闭」里打开后再扫描",
3361
+ });
3362
+ }
2860
3363
  const body = await readJson(req);
2861
3364
  const wantId = String(body?.id ?? "").trim();
2862
3365
  const before = new Set(discovery.peers().map((p) => p.id));
@@ -2881,6 +3384,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2881
3384
  const peerName = String(body?.peer ?? "").trim();
2882
3385
  const task = String(body?.task ?? "").trim();
2883
3386
  if (!peerName || !task) return send(res, 400, { ok: false, error: "peer 和 task 必填" });
3387
+ if (meshSwitch && meshSwitch.status().all) {
3388
+ return send(res, 409, {
3389
+ ok: false,
3390
+ closed: true,
3391
+ error: "本机 mesh 已全部关闭 —— 在「连接 → 一键关闭」里打开后再派发",
3392
+ });
3393
+ }
2884
3394
  const found = findPeer(peerName);
2885
3395
  if (found.error) return send(res, found.error.startsWith("名字") ? 409 : 404, { ok: false, error: found.error });
2886
3396
  const target = found.peer;