dsh-plugin-mesh 0.5.3 → 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/AGENTS.md +7 -4
- package/README.md +98 -2
- package/client/client.js +685 -122
- package/lib/_selftest-reply-route.mjs +80 -2
- package/lib/_selftest-switch.mjs +142 -0
- package/lib/_selftest-tsnet.mjs +258 -1
- package/lib/_selftest-workbench.mjs +289 -0
- package/lib/discovery.js +89 -18
- package/lib/index.js +1128 -253
- package/lib/switch.js +110 -0
- package/lib/tsnet/channels.js +72 -0
- package/lib/tsnet/manager.js +316 -51
- package/llms.txt +56 -10
- package/package.json +5 -4
- package/scripts/check-tarball.mjs +1 -0
package/lib/index.js
CHANGED
|
@@ -48,19 +48,27 @@ 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,
|
|
54
61
|
loadPeerSnapshot,
|
|
55
62
|
savePeerSnapshot,
|
|
56
63
|
} from "./persist.js";
|
|
57
|
-
import { TsnetNode } from "./tsnet/manager.js";
|
|
64
|
+
import { TsnetNode, channelKey, channelSignature } from "./tsnet/manager.js";
|
|
65
|
+
import { resolveTailnetChannels } from "./tsnet/channels.js";
|
|
58
66
|
import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
|
|
59
67
|
|
|
60
68
|
export const name = "dsh-plugin-mesh";
|
|
61
69
|
export const inject = ["tools", "webServer"];
|
|
62
70
|
|
|
63
|
-
const VERSION = "0.5.
|
|
71
|
+
const VERSION = "0.5.5";
|
|
64
72
|
// 诊断用:进程启动时间、入口真实路径、**磁盘上** package.json 的版本。
|
|
65
73
|
// 这三样放一起才能回答"现在跑的到底是哪份代码" —— 只看 state.json 或重启日志
|
|
66
74
|
// 都答不了(真踩过:磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
|
|
@@ -75,11 +83,13 @@ const MAX_HISTORY = 200;
|
|
|
75
83
|
export const MESH_DEFAULT_PORT = 45917;
|
|
76
84
|
|
|
77
85
|
/**
|
|
78
|
-
* 互联网自组网(tailnet
|
|
79
|
-
*
|
|
80
|
-
*
|
|
86
|
+
* 互联网自组网(tailnet)通道:通道 id → 节点句柄。
|
|
87
|
+
*
|
|
88
|
+
* 宿主机路由不到 100.x.y.z,所有指向 tailnet 对端的请求都要经对应 sidecar
|
|
89
|
+
* 中转,所以这里用模块级引用,让 peerFetch / scanTailnet 能拿到当前实例。
|
|
90
|
+
* 一台机器可以同时有多条通道(多个 tailnet),每个通道一个 sidecar。
|
|
81
91
|
*/
|
|
82
|
-
|
|
92
|
+
const tailnetNodes = new Map();
|
|
83
93
|
|
|
84
94
|
/**
|
|
85
95
|
* 当前实例的发现注册表。
|
|
@@ -89,6 +99,19 @@ let tailnetNode = null;
|
|
|
89
99
|
*/
|
|
90
100
|
let activeDiscovery = null;
|
|
91
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
|
+
|
|
92
115
|
/**
|
|
93
116
|
* 会话键 → 正在为它建会话期间堆积的消息。
|
|
94
117
|
*
|
|
@@ -179,14 +202,40 @@ export const Config = z.object({
|
|
|
179
202
|
// 开启后插件会自动下载一个用户态 Tailscale 节点(sidecar)并加入 tailnet,
|
|
180
203
|
// 让发现与派发跨互联网可用,与局域网路径同等级。
|
|
181
204
|
// 终端用户不需要装 Go,也不需要装 Tailscale 客户端:二进制随插件自动下载。
|
|
182
|
-
|
|
205
|
+
// 一台机器可以同时加入**多个 tailnet**:每个通道一个 sidecar、一个 tailnet
|
|
206
|
+
// 地址。设备身份仍然只有一个(instanceId 不变),通道只是多条可达路径。
|
|
207
|
+
// 下面三个 tsnetAuthKey / tsnetControlUrl / tsnetHostname 是**旧版单通道**
|
|
208
|
+
// 字段,保留以兼容已部署的配置与界面;有多通道需求时用 tsnetChannels。
|
|
209
|
+
/** 是否启用互联网自组网(旧版单通道开关;仅在 tsnetChannels 为空时生效) */
|
|
183
210
|
tsnetEnabled: z.boolean().default(false),
|
|
184
|
-
/** Tailscale 授权码(tskey-auth
|
|
211
|
+
/** Tailscale 授权码(tskey-auth-...);旧版单通道字段,也可以只在界面上填 */
|
|
185
212
|
tsnetAuthKey: z.string().default(""),
|
|
186
|
-
/**
|
|
213
|
+
/** 控制服务器地址;旧版单通道字段。留空用官方 Tailscale,Headscale 用户填自己的 */
|
|
187
214
|
tsnetControlUrl: z.string().default(""),
|
|
188
|
-
/** tailnet 节点名(合法 DNS label
|
|
215
|
+
/** tailnet 节点名(合法 DNS label);旧版单通道字段。留空用机器名 */
|
|
189
216
|
tsnetHostname: z.string().default(""),
|
|
217
|
+
/**
|
|
218
|
+
* 多 tailnet 通道。每项:
|
|
219
|
+
* { id, label, authKey, controlUrl, hostname, enabled }
|
|
220
|
+
*
|
|
221
|
+
* `id` 是稳定标识(进 sidecar 状态目录,决定 tailnet 里的设备身份),
|
|
222
|
+
* 配置文件里手写时**务必显式给**;留空会按 label + controlUrl 推导,
|
|
223
|
+
* 改显示名就会变成新设备。界面添加的通道由宿主生成 `ch-xxxxxxxx`。
|
|
224
|
+
*
|
|
225
|
+
* 这里配了通道后优先于 state.json(配置钉死),也优先于上面三个旧字段。
|
|
226
|
+
*/
|
|
227
|
+
tsnetChannels: z
|
|
228
|
+
.array(
|
|
229
|
+
z.object({
|
|
230
|
+
id: z.string().default(""),
|
|
231
|
+
label: z.string().default(""),
|
|
232
|
+
authKey: z.string().default(""),
|
|
233
|
+
controlUrl: z.string().default(""),
|
|
234
|
+
hostname: z.string().default(""),
|
|
235
|
+
enabled: z.boolean().default(true),
|
|
236
|
+
}),
|
|
237
|
+
)
|
|
238
|
+
.default([]),
|
|
190
239
|
/** 自定义下载源前缀,可含 {url} 占位符;留空用内置镜像列表 */
|
|
191
240
|
tsnetDownloadSources: z.array(String).default([]),
|
|
192
241
|
/**
|
|
@@ -425,25 +474,127 @@ function pairingPinned(config) {
|
|
|
425
474
|
}
|
|
426
475
|
|
|
427
476
|
/**
|
|
428
|
-
* 解析 tailnet
|
|
477
|
+
* 解析 tailnet 的**有效通道列表**(多 tailnet)。
|
|
478
|
+
*
|
|
479
|
+
* 一台机器可以同时加入多个 tailnet:个人账号、公司 tailnet、自建 Headscale
|
|
480
|
+
* 各一个,每个通道一个 sidecar、一个 tailnet 地址。设备身份只有一个,通道只是
|
|
481
|
+
* 这个节点的多条可达路径(见 MESH-DEFINITION.md)。
|
|
429
482
|
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
432
|
-
* 配置里的值优先,方便用配置把界面上的值钉死。
|
|
483
|
+
* 解析规则(配置 > state.json > 旧版单通道字段)在 lib/tsnet/channels.js 里,
|
|
484
|
+
* 那里是纯函数、有独立自测 —— 这段只负责把磁盘上的 state 读出来。
|
|
433
485
|
*/
|
|
434
|
-
function
|
|
435
|
-
|
|
436
|
-
|
|
486
|
+
function effectiveTailnetChannels(config) {
|
|
487
|
+
return resolveTailnetChannels({ config, state: loadState() });
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** 通道的对外视图:**绝不回传授权码内容**,只回报是否已配置。 */
|
|
491
|
+
function tailnetChannelView(channel, node) {
|
|
492
|
+
const status = node ? node.status() : null;
|
|
437
493
|
return {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
494
|
+
id: channel.id,
|
|
495
|
+
label: channel.label,
|
|
496
|
+
controlUrl: channel.controlUrl,
|
|
497
|
+
hostname: channel.hostname || status?.hostname || "",
|
|
498
|
+
enabled: channel.enabled === true,
|
|
499
|
+
authKeySaved: Boolean(channel.authKey),
|
|
500
|
+
source: channel.source,
|
|
501
|
+
node: status,
|
|
502
|
+
recentEvents: node ? node.recentEvents().slice(-12) : [],
|
|
444
503
|
};
|
|
445
504
|
}
|
|
446
505
|
|
|
506
|
+
/** 当前运行的通道节点里,每条的 tailnet 地址(写进对外名片,供对端提前记下)。 */
|
|
507
|
+
function tailnetMetaAddresses() {
|
|
508
|
+
const out = [];
|
|
509
|
+
for (const node of tailnetNodes.values()) {
|
|
510
|
+
if (node.phase !== "running") continue;
|
|
511
|
+
const ip = node.selfIpv4;
|
|
512
|
+
if (ip) out.push(ip);
|
|
513
|
+
}
|
|
514
|
+
return out;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** 把本机的 tailnet 地址同步进名片(任何一条通道起落都要调)。 */
|
|
518
|
+
function syncTailnetMeta(discovery) {
|
|
519
|
+
if (!discovery) return;
|
|
520
|
+
discovery.setMeta({ tailnetIps: tailnetMetaAddresses() });
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** 当前在跑的通道节点。 */
|
|
524
|
+
function runningTailnetNodes() {
|
|
525
|
+
return [...tailnetNodes.values()].filter((n) => n.phase === "running");
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* 启动(或重建)一条 tailnet 通道。
|
|
530
|
+
*
|
|
531
|
+
* 授权码/控制服务器/主机名任何一项变了都要重建 sidecar:一个 tsnet 节点只
|
|
532
|
+
* 认一个 tailnet,沿用旧进程会继续待在旧网络里。
|
|
533
|
+
*
|
|
534
|
+
* **失败只影响这条通道**:异常原样抛给调用方,局域网与其它通道不受影响。
|
|
535
|
+
*/
|
|
536
|
+
async function startTailnetChannel(channel, { config, discovery, log, warn, machineName }) {
|
|
537
|
+
const existing = tailnetNodes.get(channel.id);
|
|
538
|
+
// 配置没变、节点还活着(含等待授权)→ 复用。重试不该把登录流程推倒重来;
|
|
539
|
+
// 配置变了才重建,否则会一直在旧 tailnet 里。
|
|
540
|
+
const signature = channelSignature(channel);
|
|
541
|
+
const live = existing && ["running", "needs-login", "starting", "downloading"].includes(existing.phase);
|
|
542
|
+
if (live && existing.signature === signature) {
|
|
543
|
+
if (existing.phase === "running" && discovery?.port) {
|
|
544
|
+
await existing.registerForward(discovery.port).catch(() => {});
|
|
545
|
+
}
|
|
546
|
+
return { node: existing, reused: true };
|
|
547
|
+
}
|
|
548
|
+
if (existing) {
|
|
549
|
+
tailnetNodes.delete(channel.id);
|
|
550
|
+
await existing.stop().catch(() => {});
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const tag = `tailnet:${channel.label}`;
|
|
554
|
+
const tsnode = new TsnetNode({
|
|
555
|
+
config,
|
|
556
|
+
channel,
|
|
557
|
+
log: (m) => log(`[${tag}] ${m}`),
|
|
558
|
+
warn,
|
|
559
|
+
machineName,
|
|
560
|
+
});
|
|
561
|
+
tailnetNodes.set(channel.id, tsnode);
|
|
562
|
+
tsnode.on("status", (s) => {
|
|
563
|
+
if (s.phase === "error" && s.error) warn(`通道 ${channel.label}:${s.error}`);
|
|
564
|
+
// 侧车起落会改变本机的 tailnet 地址,名片要跟着更新
|
|
565
|
+
syncTailnetMeta(discovery);
|
|
566
|
+
});
|
|
567
|
+
|
|
568
|
+
try {
|
|
569
|
+
const { reused } = await tsnode.start();
|
|
570
|
+
// 让本机 mesh 服务在**这条** tailnet 上可达(tailnet :port → 127.0.0.1:port)。
|
|
571
|
+
// 多条通道可以注册同一个端口:每个 sidecar 的监听在各自的用户态网络栈里。
|
|
572
|
+
if (discovery?.port) await tsnode.registerForward(discovery.port);
|
|
573
|
+
syncTailnetMeta(discovery);
|
|
574
|
+
return { node: tsnode, reused };
|
|
575
|
+
} catch (err) {
|
|
576
|
+
// 节点留在表里:界面要能看到这条通道的错误与诊断,而不是"它凭空消失了"
|
|
577
|
+
syncTailnetMeta(discovery);
|
|
578
|
+
throw err;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** 停掉一条通道(不传 id 停全部)。返回实际停掉的通道数。 */
|
|
583
|
+
async function stopTailnetChannel(id, discovery) {
|
|
584
|
+
const ids = id ? [String(id)] : [...tailnetNodes.keys()];
|
|
585
|
+
let stopped = 0;
|
|
586
|
+
for (const key of ids) {
|
|
587
|
+
const node = tailnetNodes.get(key);
|
|
588
|
+
if (!node) continue;
|
|
589
|
+
tailnetNodes.delete(key);
|
|
590
|
+
await node.stop().catch(() => {});
|
|
591
|
+
stopped += 1;
|
|
592
|
+
}
|
|
593
|
+
if (stopped > 0) syncTailnetMeta(discovery);
|
|
594
|
+
return stopped;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
|
|
447
598
|
/** 首次运行生成配对码;用户只需把它复制到另一台机器。 */
|
|
448
599
|
function ensureSecret() {
|
|
449
600
|
const st = loadState();
|
|
@@ -692,118 +843,381 @@ function applyUnsafe(ctx, config) {
|
|
|
692
843
|
capabilities: currentCapabilities(),
|
|
693
844
|
});
|
|
694
845
|
|
|
695
|
-
//
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
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
|
+
};
|
|
699
887
|
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
discovery.announceNow();
|
|
705
|
-
} else {
|
|
706
|
-
log("已关闭组播,仅使用主动扫描 + ping");
|
|
707
|
-
}
|
|
888
|
+
const shutRuntimeTimers = () => {
|
|
889
|
+
for (const t of runtimeTimers) clearInterval(t);
|
|
890
|
+
runtimeTimers = [];
|
|
891
|
+
};
|
|
708
892
|
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
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
|
+
});
|
|
714
927
|
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
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
|
+
};
|
|
720
961
|
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
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,
|
|
733
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
|
+
};
|
|
734
1011
|
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
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 已关闭:不广播、不扫本网段,对端端口只绑回环");
|
|
757
1091
|
} else {
|
|
758
|
-
log("
|
|
1092
|
+
log("已关闭组播,仅使用主动扫描 + ping");
|
|
759
1093
|
}
|
|
1094
|
+
if (wantLan) startLanDiscovery();
|
|
1095
|
+
}
|
|
760
1096
|
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
(async () => {
|
|
766
|
-
for (let i = 0; i < delays.length; i += 1) {
|
|
767
|
-
if (stop.aborted) return;
|
|
768
|
-
if (delays[i] > 0) await sleep(delays[i]);
|
|
769
|
-
if (stop.aborted) return;
|
|
770
|
-
await runScan({ discovery, config, log, warn, signal: stop, reason: `启动扫描#${i + 1}` });
|
|
771
|
-
if (discovery.peers().length > 0) return; // 找到了就不再重试
|
|
772
|
-
}
|
|
773
|
-
log("启动扫描未发现对端;之后靠组播与周期扫描继续尝试");
|
|
774
|
-
})().catch(() => {});
|
|
775
|
-
}
|
|
1097
|
+
// ── 互联网启动(后台跑:首次要下载 sidecar,不能让界面/接口干等)──
|
|
1098
|
+
if (wantNet && !internetUp) {
|
|
1099
|
+
void ensureInternet(reason).catch((err) => warn(`互联网通道启动异常:${err?.message ?? err}`));
|
|
1100
|
+
}
|
|
776
1101
|
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
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
|
+
};
|
|
785
1112
|
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
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}` });
|
|
793
1183
|
}
|
|
794
|
-
|
|
795
|
-
|
|
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}`));
|
|
796
1200
|
|
|
797
1201
|
// 2) 入站唤醒:注册一次 webhook 规则,之后每个任务只 dispatch
|
|
798
1202
|
setupInbound(ctx, config, log, warn, waker);
|
|
799
1203
|
|
|
1204
|
+
/** 一键关闭的对外门面:UI 路由与 agent 工具共用同一份实现。 */
|
|
1205
|
+
const meshSwitch = { status: switchStatus, set: setSwitch };
|
|
1206
|
+
|
|
800
1207
|
// 3) agent 工具
|
|
801
|
-
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 });
|
|
802
1209
|
|
|
803
1210
|
// 4) UI 接口
|
|
804
|
-
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 });
|
|
805
1212
|
|
|
806
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();
|
|
807
1221
|
discovery.stop();
|
|
808
1222
|
log("已停止");
|
|
809
1223
|
});
|
|
@@ -1494,18 +1908,17 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1494
1908
|
|
|
1495
1909
|
// ───────────────────────── 主动发现与保活 ─────────────────────────
|
|
1496
1910
|
|
|
1497
|
-
/**
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
* 把差异收在这一个函数里,上面所有调用点都不必关心对端是怎么找到的。
|
|
1503
|
-
*/
|
|
1911
|
+
/** 端点的稳定 key:`lan` / `tsnet:<通道 id>`(兼容旧端点的 `tsnet`)。 */
|
|
1912
|
+
function endpointKeyOf(ep) {
|
|
1913
|
+
return String(ep?.channel ?? ep?.transport ?? "lan");
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1504
1916
|
/**
|
|
1505
1917
|
* 按端点健康**逐个失败切换**地发一个请求。
|
|
1506
1918
|
*
|
|
1507
|
-
* 这是"
|
|
1508
|
-
*
|
|
1919
|
+
* 这是"多条通道绑一台设备"的实际收益:局域网不通就走某条 tailnet,一条
|
|
1920
|
+
* tailnet 不通还可以走另一条。以前只看 `peer.transport`(最后探测到的那个),
|
|
1921
|
+
* 一条通道坏掉整个对端就不可达。
|
|
1509
1922
|
*
|
|
1510
1923
|
* 只有**网络层失败**才切换通道:HTTP 4xx/5xx 说明端点本身是通的,换一条也
|
|
1511
1924
|
* 一样,不该白试一遍、更不该把好端点的健康记录打坏。
|
|
@@ -1515,8 +1928,24 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1515
1928
|
*/
|
|
1516
1929
|
async function peerFetch(peer, path, opts = {}) {
|
|
1517
1930
|
const { timeoutMs = 20000, ...rest } = opts;
|
|
1518
|
-
const
|
|
1519
|
-
if (
|
|
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
|
+
}
|
|
1520
1949
|
|
|
1521
1950
|
const failures = [];
|
|
1522
1951
|
for (const ep of eps) {
|
|
@@ -1527,7 +1956,7 @@ async function peerFetch(peer, path, opts = {}) {
|
|
|
1527
1956
|
// `http://:0/mesh/v1/hello` —— 端点明明选对了,URL 却是坏的。
|
|
1528
1957
|
// 实测就是这个报错:`Get "http://:0/mesh/v1/hello": lookup : no such host`。
|
|
1529
1958
|
if (!ep.host || !ep.port) {
|
|
1530
|
-
failures.push(`${ep
|
|
1959
|
+
failures.push(`${endpointKeyOf(ep)} 端点地址不完整(${ep.host}:${ep.port})`);
|
|
1531
1960
|
continue;
|
|
1532
1961
|
}
|
|
1533
1962
|
const url = `http://${ep.host}:${ep.port}${path}`;
|
|
@@ -1537,11 +1966,11 @@ async function peerFetch(peer, path, opts = {}) {
|
|
|
1537
1966
|
ep.transport === "tsnet"
|
|
1538
1967
|
? await fetchViaTailnet(ep, url, { ...rest, timeoutMs })
|
|
1539
1968
|
: await fetchViaLan(ep, url, { ...rest, timeoutMs });
|
|
1540
|
-
activeDiscovery?.markEndpoint(peer.id, ep
|
|
1969
|
+
activeDiscovery?.markEndpoint(peer.id, endpointKeyOf(ep), { ok: true, rttMs: Date.now() - started });
|
|
1541
1970
|
return res;
|
|
1542
1971
|
} catch (err) {
|
|
1543
|
-
failures.push(`${ep
|
|
1544
|
-
activeDiscovery?.markEndpoint(peer.id, ep
|
|
1972
|
+
failures.push(`${endpointKeyOf(ep)}(${ep.host}:${ep.port}) ${err?.message ?? err}`);
|
|
1973
|
+
activeDiscovery?.markEndpoint(peer.id, endpointKeyOf(ep), { ok: false });
|
|
1545
1974
|
}
|
|
1546
1975
|
}
|
|
1547
1976
|
throw new Error(`所有通道都失败 —— ${failures.join(";")}`);
|
|
@@ -1556,76 +1985,123 @@ async function fetchViaLan(ep, url, opts = {}) {
|
|
|
1556
1985
|
/**
|
|
1557
1986
|
* 经 sidecar 的用户态隧道出去。
|
|
1558
1987
|
* 宿主机没有 TUN 设备,`fetch("http://100.x.y.z:...")` 会直接 ENETUNREACH。
|
|
1988
|
+
*
|
|
1989
|
+
* 出口选择:
|
|
1990
|
+
* · 端点带通道(`tsnet:<id>`)→ 优先走那条通道的 sidecar;它不可用时再依次
|
|
1991
|
+
* 试其它通道(IP 本来就属于哪条 tailnet 是连通性说的,不必猜)。
|
|
1992
|
+
* · 端点没有通道(对端名片里报来的候选地址)→ 依次试所有通道。
|
|
1993
|
+
*
|
|
1994
|
+
* 多条 tailnet 可能有重叠的 100.x 网段,所以"试"是唯一可靠的做法;失败的
|
|
1995
|
+
* 通道不会留下状态(真实健康记录由调用方 markEndpoint 写)。
|
|
1559
1996
|
*/
|
|
1560
1997
|
async function fetchViaTailnet(ep, url, opts = {}) {
|
|
1561
|
-
|
|
1562
|
-
|
|
1998
|
+
const key = endpointKeyOf(ep);
|
|
1999
|
+
const wantId = key.startsWith("tsnet:") ? key.slice("tsnet:".length) : "";
|
|
2000
|
+
const wanted = wantId ? tailnetNodes.get(wantId) : null;
|
|
2001
|
+
const candidates = [];
|
|
2002
|
+
if (wanted && wanted.phase === "running") candidates.push(wanted);
|
|
2003
|
+
for (const node of runningTailnetNodes()) {
|
|
2004
|
+
if (!candidates.includes(node)) candidates.push(node);
|
|
2005
|
+
}
|
|
2006
|
+
if (candidates.length === 0) throw new Error("tailnet 节点尚未启动");
|
|
2007
|
+
let lastErr = null;
|
|
2008
|
+
for (const node of candidates) {
|
|
2009
|
+
try {
|
|
2010
|
+
return await tailnetFetch(node, url, opts);
|
|
2011
|
+
} catch (err) {
|
|
2012
|
+
lastErr = err;
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
throw lastErr ?? new Error("没有可用的 tailnet 通道");
|
|
1563
2016
|
}
|
|
1564
2017
|
|
|
1565
2018
|
/**
|
|
1566
|
-
*
|
|
2019
|
+
* 借每条 tailnet 通道的 sidecar 节点表做第二轮探测。
|
|
1567
2020
|
*
|
|
1568
2021
|
* 与局域网扫描刻意保持同构:拿候选地址 → 探 /mesh/v1/health → 自述记录进
|
|
1569
|
-
*
|
|
1570
|
-
*
|
|
2022
|
+
* 同一个注册表。区别是:候选地址来自 tailnet,请求必须走对应的 sidecar 隧道,
|
|
2023
|
+
* 且**每条通道各扫一遍** —— 一台设备可能在多个 tailnet 里,每个 tailnet 给的
|
|
2024
|
+
* 地址不同,端点要按通道分别记录。
|
|
2025
|
+
*
|
|
2026
|
+
* @param channelId 只扫某一条通道;省略 = 所有在跑的通道
|
|
1571
2027
|
*/
|
|
1572
|
-
async function scanTailnet({ discovery, config, log, reason, ports }) {
|
|
1573
|
-
//
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
let peers;
|
|
1579
|
-
try {
|
|
1580
|
-
peers = await tailnetNode.peersRemote();
|
|
1581
|
-
} catch (err) {
|
|
1582
|
-
log(`${reason}(tailnet): 取节点表失败 —— ${err.message}`);
|
|
1583
|
-
return { scanned: 0, found: 0 };
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1586
|
-
// 只看在线且有 IPv4 的;自己不在 Peer 列表里,不用排除。
|
|
1587
|
-
const candidates = peers.filter((p) => p.online && p.ipv4);
|
|
1588
|
-
if (candidates.length === 0) return { scanned: 0, found: 0 };
|
|
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 };
|
|
2032
|
+
const nodes = runningTailnetNodes().filter((n) => !channelId || n.channelKey === channelId);
|
|
2033
|
+
if (nodes.length === 0) return { scanned: 0, found: 0, channels: [] };
|
|
1589
2034
|
|
|
1590
2035
|
// tailnet 上没有"端口先验",但同机单实例 + 默认端口是常态,命中率很高。
|
|
1591
2036
|
const targetPorts = [...new Set([...ports, MESH_DEFAULT_PORT])].filter((p) => Number(p) > 0);
|
|
1592
|
-
|
|
1593
|
-
|
|
2037
|
+
const probeIntervalMs = Math.max(config.pingIntervalMs, config.tsnetProbeIntervalMs ?? 60000);
|
|
2038
|
+
const perChannel = [];
|
|
1594
2039
|
|
|
1595
2040
|
await Promise.all(
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
2041
|
+
nodes.map(async (node) => {
|
|
2042
|
+
const channel = `tsnet:${node.channelKey}`;
|
|
2043
|
+
const summary = { id: node.channelKey, label: node.label, scanned: 0, found: 0, error: "" };
|
|
2044
|
+
perChannel.push(summary);
|
|
2045
|
+
|
|
2046
|
+
let peers;
|
|
2047
|
+
try {
|
|
2048
|
+
peers = await node.peersRemote();
|
|
2049
|
+
} catch (err) {
|
|
2050
|
+
summary.error = String(err?.message ?? err);
|
|
2051
|
+
log(`${reason}(${node.label}): 取节点表失败 —— ${summary.error}`);
|
|
2052
|
+
return;
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
// 只看在线且有 IPv4 的;自己不在 Peer 列表里,不用排除。
|
|
2056
|
+
const candidates = peers.filter((p) => p.online && p.ipv4);
|
|
2057
|
+
summary.scanned = candidates.length * targetPorts.length;
|
|
2058
|
+
if (candidates.length === 0) return;
|
|
2059
|
+
|
|
2060
|
+
let found = 0;
|
|
2061
|
+
let added = 0;
|
|
2062
|
+
await Promise.all(
|
|
2063
|
+
candidates.flatMap((p) =>
|
|
2064
|
+
targetPorts.map(async (tp) => {
|
|
2065
|
+
try {
|
|
2066
|
+
const started = Date.now();
|
|
2067
|
+
const res = await tailnetFetch(node, `http://${p.ipv4}:${tp}/mesh/v1/health`, {
|
|
2068
|
+
timeoutMs: Math.min(4000, config.requestTimeoutMs),
|
|
2069
|
+
});
|
|
2070
|
+
if (!res.ok) return;
|
|
2071
|
+
const body = await res.json();
|
|
2072
|
+
if (body?.app !== "dsh-mesh" || !body.id) return;
|
|
2073
|
+
found += 1;
|
|
2074
|
+
// 强制记 tailnet IP:对端自述的 host 是它的局域网地址,跨互联网不可达。
|
|
2075
|
+
// 通道 key 必须带上:同一台设备可能同时出现在多条 tailnet 里,
|
|
2076
|
+
// 不区分就会互相覆盖,一条通道断了另一条也跟着消失。
|
|
2077
|
+
// 同时带上探测间隔与 RTT —— 漏了 interval 会让这条通道按默认 TTL(20s)
|
|
2078
|
+
// 判活,而它 60s 才探一次,于是探完 20 秒就"死了"、整台设备假离线。
|
|
2079
|
+
// 实测踩过:ok=4 fail=0 rtt=473ms 却显示 online=False。
|
|
2080
|
+
if (
|
|
2081
|
+
discovery.note(body, p.ipv4, {
|
|
2082
|
+
transport: "tsnet",
|
|
2083
|
+
channel,
|
|
2084
|
+
port: tp,
|
|
2085
|
+
rttMs: Date.now() - started,
|
|
2086
|
+
probeIntervalMs,
|
|
2087
|
+
})
|
|
2088
|
+
)
|
|
2089
|
+
added += 1;
|
|
2090
|
+
} catch {
|
|
2091
|
+
/* 该地址上没有 DSH 节点,或端口没开 —— 正常情况,不打扰用户 */
|
|
2092
|
+
}
|
|
2093
|
+
}),
|
|
2094
|
+
),
|
|
2095
|
+
);
|
|
2096
|
+
|
|
2097
|
+
summary.found = found;
|
|
2098
|
+
if (found > 0) log(`${reason}(${node.label}): 命中 ${found} 台(新登记 ${added})`);
|
|
2099
|
+
}),
|
|
1625
2100
|
);
|
|
1626
2101
|
|
|
1627
|
-
|
|
1628
|
-
|
|
2102
|
+
const found = perChannel.reduce((n, c) => n + c.found, 0);
|
|
2103
|
+
const scanned = perChannel.reduce((n, c) => n + c.scanned, 0);
|
|
2104
|
+
return { scanned, found, channels: perChannel };
|
|
1629
2105
|
}
|
|
1630
2106
|
|
|
1631
2107
|
/**
|
|
@@ -1653,6 +2129,14 @@ async function runScan({ discovery, config, log, warn, signal, reason = "扫描"
|
|
|
1653
2129
|
const ports = scanPortList(discovery, config);
|
|
1654
2130
|
let lanFound = 0;
|
|
1655
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
|
+
|
|
1656
2140
|
if (addresses.length === 0) {
|
|
1657
2141
|
warn(`${reason}: 没有可扫描的地址(检查 scanRanges 是否合法 / 网卡是否存在)`);
|
|
1658
2142
|
}
|
|
@@ -1707,7 +2191,7 @@ async function pingKnownPeers({ discovery, config, warn }) {
|
|
|
1707
2191
|
// tailnet 按 tsnetProbeIntervalMs(默认 60s)低频验证;另外**还没探通过的
|
|
1708
2192
|
// 通道立刻探一次**,让它尽快有个真实状态而不是停在"未探测"。
|
|
1709
2193
|
const tsnetInterval = Math.max(config.pingIntervalMs, config.tsnetProbeIntervalMs ?? 60000);
|
|
1710
|
-
const targets = endpoints.filter((ep) => {
|
|
2194
|
+
const targets = endpoints.filter((ep) => (ep.transport === "tsnet" ? transportGate.internet : transportGate.lan)).filter((ep) => {
|
|
1711
2195
|
const interval = ep.transport === "tsnet" ? tsnetInterval : config.pingIntervalMs;
|
|
1712
2196
|
if (ep.verified === false) {
|
|
1713
2197
|
// 首次立刻探一次;失败后按通道节奏重试,并尊重 markEndpoint 记下
|
|
@@ -1732,14 +2216,19 @@ async function pingKnownPeers({ discovery, config, warn }) {
|
|
|
1732
2216
|
});
|
|
1733
2217
|
if (!res.ok) {
|
|
1734
2218
|
// 端点通但返回错误:不打坏健康记录,也不换通道重试(换了也一样)
|
|
1735
|
-
discovery.markEndpoint(p.id, ep
|
|
2219
|
+
discovery.markEndpoint(p.id, endpointKeyOf(ep), { ok: true, rttMs: Date.now() - started });
|
|
1736
2220
|
return;
|
|
1737
2221
|
}
|
|
1738
2222
|
const body = await res.json();
|
|
1739
2223
|
if (body?.app === "dsh-mesh" && body.id) {
|
|
1740
|
-
// 对方可能重启过、换了端口 —— 以 ping
|
|
2224
|
+
// 对方可能重启过、换了端口 —— 以 ping 到的为准,并刷新这条端点。
|
|
2225
|
+
// channel 用**这条端点自己的 key**:多 tailnet 时若统一写成 tsnet,
|
|
2226
|
+
// 不同通道会互相覆盖,一条断了另一条也跟着假死。
|
|
2227
|
+
// 候选端点(tsnet:cand:…)探通后就此转正,保持同一个 key,
|
|
2228
|
+
// 发送时按"依次试所有通道"解析。
|
|
1741
2229
|
discovery.note(body, ep.host, {
|
|
1742
2230
|
transport: ep.transport,
|
|
2231
|
+
channel: endpointKeyOf(ep),
|
|
1743
2232
|
port: ep.port,
|
|
1744
2233
|
// 把探测结果一起带上:note() 是成功路径的入口,RTT 与探测间隔
|
|
1745
2234
|
// 在这里接住,通道的存活窗口才会跟着自己的节奏走
|
|
@@ -1749,7 +2238,7 @@ async function pingKnownPeers({ discovery, config, warn }) {
|
|
|
1749
2238
|
}
|
|
1750
2239
|
} catch {
|
|
1751
2240
|
// 这条通道不通:记一次失败,累计到阈值就进冷却,排序会把它排到最后
|
|
1752
|
-
discovery.markEndpoint(p.id, ep
|
|
2241
|
+
discovery.markEndpoint(p.id, endpointKeyOf(ep), {
|
|
1753
2242
|
ok: false,
|
|
1754
2243
|
probeIntervalMs: ep.transport === "tsnet" ? tsnetInterval : config.pingIntervalMs,
|
|
1755
2244
|
});
|
|
@@ -1769,7 +2258,18 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
|
|
|
1769
2258
|
|
|
1770
2259
|
// ───────────────────────── 对端 HTTP 服务 ─────────────────────────
|
|
1771
2260
|
|
|
1772
|
-
|
|
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" }) {
|
|
1773
2273
|
const send = (res, code, payload) => {
|
|
1774
2274
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
1775
2275
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -1782,11 +2282,29 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
|
|
|
1782
2282
|
const authed = (req) =>
|
|
1783
2283
|
!pairingRequired(config) || safeEqual(req.headers["x-dsh-mesh-token"], currentSecret());
|
|
1784
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
|
+
|
|
1785
2298
|
const server = createServer(async (req, res) => {
|
|
1786
2299
|
const url = new URL(req.url, "http://localhost");
|
|
1787
2300
|
const path = url.pathname;
|
|
1788
2301
|
const self = { ...discovery.selfRecord(), instanceId: discovery.instanceId };
|
|
1789
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
|
+
|
|
1790
2308
|
// 免鉴权:只暴露身份,用于连通性探测、主动扫描与配对握手
|
|
1791
2309
|
if (path === "/mesh/v1/health") return send(res, 200, { ok: true, ...self, requirePairing: pairingRequired(config) });
|
|
1792
2310
|
if (path === "/mesh/v1/hello") {
|
|
@@ -1855,7 +2373,7 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
|
|
|
1855
2373
|
});
|
|
1856
2374
|
|
|
1857
2375
|
return new Promise((resolvePromise, rejectPromise) => {
|
|
1858
|
-
const wanted = config.port ?? MESH_DEFAULT_PORT;
|
|
2376
|
+
const wanted = fixedPort ?? config.port ?? MESH_DEFAULT_PORT;
|
|
1859
2377
|
const start = (port, isFallback) => {
|
|
1860
2378
|
server.once("error", (err) => {
|
|
1861
2379
|
if (!isFallback && err?.code === "EADDRINUSE") {
|
|
@@ -1865,11 +2383,10 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
|
|
|
1865
2383
|
}
|
|
1866
2384
|
rejectPromise(err);
|
|
1867
2385
|
});
|
|
1868
|
-
server.listen(port,
|
|
2386
|
+
server.listen(port, bindHost, () => {
|
|
1869
2387
|
const addr = server.address();
|
|
1870
|
-
log(`对端服务监听
|
|
1871
|
-
|
|
1872
|
-
resolvePromise(addr.port);
|
|
2388
|
+
log(`对端服务监听 ${addr.address}:${addr.port}${isFallback ? "(随机)" : "(固定)"}`);
|
|
2389
|
+
resolvePromise({ port: addr.port, host: addr.address, server });
|
|
1873
2390
|
});
|
|
1874
2391
|
};
|
|
1875
2392
|
start(wanted, false);
|
|
@@ -1902,8 +2419,17 @@ function readJson(req) {
|
|
|
1902
2419
|
|
|
1903
2420
|
// ───────────────────────── agent 工具 ─────────────────────────
|
|
1904
2421
|
|
|
1905
|
-
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 }) {
|
|
1906
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);
|
|
1907
2433
|
|
|
1908
2434
|
ctx.tools.register(
|
|
1909
2435
|
defineTool({
|
|
@@ -1919,12 +2445,24 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1919
2445
|
const peers = discovery.peers();
|
|
1920
2446
|
const list = args?.includeOffline === false ? peers.filter((p) => p.online) : peers;
|
|
1921
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
|
+
}
|
|
1922
2460
|
return (
|
|
1923
2461
|
"没有发现其他 DSH 机器。\n" +
|
|
1924
2462
|
"用 mesh_scan 主动扫一次本网段(组播常被路由器/防火墙挡住)。\n" +
|
|
1925
2463
|
"仍找不到就排查:1) 两台机器是否同一网段 2) 对端是否装了 dsh-plugin-mesh 并已重启 DSH " +
|
|
1926
2464
|
"3) 对端防火墙是否放行这个 TCP 端口\n" +
|
|
1927
|
-
`本机: ${machineOf(discovery)} (${preferredAddress()})`
|
|
2465
|
+
`本机: ${machineOf(discovery)} (${preferredAddress()}) · 开关: ${switchLine()}`
|
|
1928
2466
|
);
|
|
1929
2467
|
}
|
|
1930
2468
|
const lines = list.map((p) => {
|
|
@@ -1936,7 +2474,10 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1936
2474
|
(caps ? `\n${caps}` : "")
|
|
1937
2475
|
);
|
|
1938
2476
|
});
|
|
1939
|
-
return
|
|
2477
|
+
return (
|
|
2478
|
+
`发现 ${list.length} 台机器:\n${lines.join("\n")}\n\n` +
|
|
2479
|
+
`本机: ${machineOf(discovery)} (${preferredAddress()}) · 开关: ${switchLine()}`
|
|
2480
|
+
);
|
|
1940
2481
|
},
|
|
1941
2482
|
}),
|
|
1942
2483
|
);
|
|
@@ -1950,6 +2491,17 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1950
2491
|
parameters: {},
|
|
1951
2492
|
output: { schema: { type: "string" }, render: (_a, v) => text(v) },
|
|
1952
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
|
+
}
|
|
1953
2505
|
const before = discovery.peers().length;
|
|
1954
2506
|
const r = await runScan({ discovery, config, log, warn, reason: "agent 触发扫描" });
|
|
1955
2507
|
const after = discovery.peers();
|
|
@@ -1994,6 +2546,12 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1994
2546
|
const peerName = String(args?.peer ?? "").trim();
|
|
1995
2547
|
const task = String(args?.task ?? "").trim();
|
|
1996
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
|
+
}
|
|
1997
2555
|
|
|
1998
2556
|
const matches = findPeersByName(discovery, peerName);
|
|
1999
2557
|
if (matches.length === 0) {
|
|
@@ -2094,12 +2652,78 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
2094
2652
|
}),
|
|
2095
2653
|
);
|
|
2096
2654
|
|
|
2097
|
-
|
|
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");
|
|
2098
2722
|
}
|
|
2099
2723
|
|
|
2100
2724
|
// ───────────────────────── UI 接口(本地回环) ─────────────────────────
|
|
2101
2725
|
|
|
2102
|
-
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 }) {
|
|
2103
2727
|
const send = (res, code, payload) => {
|
|
2104
2728
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
2105
2729
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -2183,9 +2807,12 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2183
2807
|
};
|
|
2184
2808
|
|
|
2185
2809
|
const state = () => {
|
|
2186
|
-
// state.json
|
|
2187
|
-
//
|
|
2188
|
-
const
|
|
2810
|
+
// state.json 只读一次:这个接口会被页面轮询,而通道解析内部每次都读文件,
|
|
2811
|
+
// 逐字段调用会把一次轮询变成多次磁盘读。
|
|
2812
|
+
const tailnetChannels = effectiveTailnetChannels(config);
|
|
2813
|
+
const channelViews = tailnetChannels.map((c) => tailnetChannelView(c, tailnetNodes.get(c.id) ?? null));
|
|
2814
|
+
// 兼容旧界面:node / hostname / authKeySaved 取"第一条启用的通道"
|
|
2815
|
+
const primary = channelViews.find((c) => c.enabled) ?? channelViews[0] ?? null;
|
|
2189
2816
|
return {
|
|
2190
2817
|
ok: true,
|
|
2191
2818
|
self: {
|
|
@@ -2235,16 +2862,22 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2235
2862
|
},
|
|
2236
2863
|
// 互联网自组网状态。注意:**绝不回传授权码本身**,只回报"是否已配置"。
|
|
2237
2864
|
tsnet: {
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2865
|
+
// 多 tailnet 通道列表:UI 的主视图
|
|
2866
|
+
channels: channelViews,
|
|
2867
|
+
/** 有任意一条启用的通道即为 true(旧界面兼容) */
|
|
2868
|
+
enabled: channelViews.some((c) => c.enabled),
|
|
2869
|
+
/** 旧单通道字段:取第一条启用通道 */
|
|
2870
|
+
authKeySaved: Boolean(primary?.authKeySaved),
|
|
2871
|
+
controlUrl: primary?.controlUrl ?? "",
|
|
2872
|
+
hostname: primary?.hostname ?? "",
|
|
2242
2873
|
permissionPreset: config.tsnetPermissionPreset || "",
|
|
2243
2874
|
/** 留空时实际生效的权限,与局域网一致 */
|
|
2244
2875
|
permissionPresetEffective: config.tsnetPermissionPreset || config.permissionPreset,
|
|
2245
|
-
node:
|
|
2246
|
-
recentEvents:
|
|
2876
|
+
node: primary?.node ?? null,
|
|
2877
|
+
recentEvents: primary?.recentEvents ?? [],
|
|
2247
2878
|
},
|
|
2879
|
+
// 一键关闭:期望值 + 真实运行情况 + 偏差说明(界面按它渲染三个开关)
|
|
2880
|
+
switch: meshSwitch ? meshSwitch.status() : null,
|
|
2248
2881
|
peers: discovery.peers(),
|
|
2249
2882
|
duplicateNames: duplicateNames(),
|
|
2250
2883
|
inbound: inbound.slice(-30).reverse(),
|
|
@@ -2347,11 +2980,22 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2347
2980
|
});
|
|
2348
2981
|
|
|
2349
2982
|
post("/mesh/api/refresh", (_req, res) => {
|
|
2350
|
-
|
|
2351
|
-
|
|
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 });
|
|
2352
2988
|
});
|
|
2353
2989
|
|
|
2354
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
|
+
}
|
|
2355
2999
|
try {
|
|
2356
3000
|
const result = await runScan({ discovery, config, log, warn, reason: "手动扫描" });
|
|
2357
3001
|
send(res, 200, { ok: true, ...result, peers: discovery.peers() });
|
|
@@ -2388,6 +3032,37 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2388
3032
|
return send(res, 200, { ok: true, requirePairing: want });
|
|
2389
3033
|
});
|
|
2390
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
|
+
|
|
2391
3066
|
post("/mesh/api/secret", async (req, res) => {
|
|
2392
3067
|
const body = await readJson(req);
|
|
2393
3068
|
const secret = String(body?.secret ?? "").trim();
|
|
@@ -2402,18 +3077,145 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2402
3077
|
|
|
2403
3078
|
// 无论节点是启动时创建还是后来从界面启动的,插件卸载时都收干净。
|
|
2404
3079
|
ctx.effect(() => () => {
|
|
2405
|
-
const node
|
|
2406
|
-
|
|
2407
|
-
node?.stop().catch(() => {});
|
|
3080
|
+
for (const node of tailnetNodes.values()) node.stop().catch(() => {});
|
|
3081
|
+
tailnetNodes.clear();
|
|
2408
3082
|
});
|
|
2409
3083
|
|
|
3084
|
+
/** 通道列表是否被插件配置钉死(此时界面只能看,不能改)。 */
|
|
3085
|
+
const tailnetChannelsPinned = () => Array.isArray(config.tsnetChannels) && config.tsnetChannels.length > 0;
|
|
3086
|
+
|
|
3087
|
+
/** 把当前生效的通道列表转成对外视图(不回传授权码)。 */
|
|
3088
|
+
const tailnetViews = () =>
|
|
3089
|
+
effectiveTailnetChannels(config).map((c) => tailnetChannelView(c, tailnetNodes.get(c.id) ?? null));
|
|
3090
|
+
|
|
2410
3091
|
/**
|
|
2411
|
-
* 保存 tailnet
|
|
3092
|
+
* 保存 tailnet 配置(多通道)。
|
|
3093
|
+
*
|
|
3094
|
+
* 两种形态:
|
|
3095
|
+
* · `{ channels: [...] }` —— 整体替换通道列表(界面走这条)
|
|
3096
|
+
* · 旧的单通道字段 `{ authKey, controlUrl, hostname, enabled }` —— 兼容老页面
|
|
3097
|
+
*
|
|
2412
3098
|
* 授权码存进 state.json(0600),所以**只需要输入一次**,重启不用再填。
|
|
2413
|
-
*
|
|
3099
|
+
* 某项的 `authKey` 传空串表示"不改动已保存的值";要清掉就传
|
|
3100
|
+
* `clearAuthKey: true`,避免界面回显后又被空值覆盖。
|
|
2414
3101
|
*/
|
|
2415
3102
|
post("/mesh/api/tsnet/config", async (req, res) => {
|
|
2416
3103
|
const body = await readJson(req);
|
|
3104
|
+
|
|
3105
|
+
if (Array.isArray(body?.channels)) {
|
|
3106
|
+
if (tailnetChannelsPinned()) {
|
|
3107
|
+
return send(res, 409, {
|
|
3108
|
+
ok: false,
|
|
3109
|
+
error: "通道列表已由插件配置 tsnetChannels 固定,界面不能修改",
|
|
3110
|
+
});
|
|
3111
|
+
}
|
|
3112
|
+
const existing = effectiveTailnetChannels(config);
|
|
3113
|
+
const byId = new Map(existing.map((c) => [c.id, c]));
|
|
3114
|
+
const used = new Set();
|
|
3115
|
+
const next = [];
|
|
3116
|
+
for (const item of body.channels) {
|
|
3117
|
+
if (!item || typeof item !== "object") continue;
|
|
3118
|
+
const rawLabel = String(item.label ?? "").trim().slice(0, 60);
|
|
3119
|
+
const rawControl = String(item.controlUrl ?? "").trim();
|
|
3120
|
+
let id = channelKey(item.id, "");
|
|
3121
|
+
if (!id) {
|
|
3122
|
+
// 新通道:宿主生成稳定 id。之后改显示名不会改变设备身份。
|
|
3123
|
+
do {
|
|
3124
|
+
id = `ch-${randomBytes(4).toString("hex")}`;
|
|
3125
|
+
} while (used.has(id) || byId.has(id) && !item.id);
|
|
3126
|
+
}
|
|
3127
|
+
if (used.has(id)) {
|
|
3128
|
+
return send(res, 400, { ok: false, error: `通道 id 重复:${id}` });
|
|
3129
|
+
}
|
|
3130
|
+
used.add(id);
|
|
3131
|
+
const prev = byId.get(id);
|
|
3132
|
+
const incomingKey = typeof item.authKey === "string" ? item.authKey.trim() : "";
|
|
3133
|
+
const authKey = item.clearAuthKey === true ? "" : incomingKey || prev?.authKey || "";
|
|
3134
|
+
next.push({
|
|
3135
|
+
id,
|
|
3136
|
+
label: rawLabel || prev?.label || `Tailnet ${next.length + 1}`,
|
|
3137
|
+
authKey,
|
|
3138
|
+
controlUrl: rawControl || prev?.controlUrl || "",
|
|
3139
|
+
hostname: String(item.hostname ?? "").trim() || prev?.hostname || "",
|
|
3140
|
+
enabled: item.enabled !== false,
|
|
3141
|
+
});
|
|
3142
|
+
}
|
|
3143
|
+
// 允许清空:这是"彻底关掉跨网络组网"的唯一可靠路径。必须同时清掉旧版
|
|
3144
|
+
// 单通道字段 —— 否则空列表会退回旧字段,把刚删掉的通道又变出来。
|
|
3145
|
+
if (next.length === 0) {
|
|
3146
|
+
await stopTailnetChannel("", discovery);
|
|
3147
|
+
saveState({
|
|
3148
|
+
tsnetChannels: [],
|
|
3149
|
+
tsnetEnabled: false,
|
|
3150
|
+
tsnetAuthKey: "",
|
|
3151
|
+
tsnetControlUrl: "",
|
|
3152
|
+
tsnetHostname: "",
|
|
3153
|
+
});
|
|
3154
|
+
log("tailnet 通道已全部删除,跨网络组网关闭");
|
|
3155
|
+
return send(res, 200, { ok: true, channels: [], enabled: false, authKeySaved: false, controlUrl: "", hostname: "" });
|
|
3156
|
+
}
|
|
3157
|
+
saveState({
|
|
3158
|
+
tsnetChannels: next,
|
|
3159
|
+
// 旧字段跟着走,避免老版本页面/回退时看到"未启用"
|
|
3160
|
+
tsnetEnabled: next.some((c) => c.enabled),
|
|
3161
|
+
});
|
|
3162
|
+
// 停掉被删掉、已禁用、或连接参数已变的通道;新配置由 /tsnet/start 拉起。
|
|
3163
|
+
// 参数变了却继续跑旧 sidecar,会留下"配置显示 A、实际连的是 B"的假象。
|
|
3164
|
+
for (const [id, node] of [...tailnetNodes.entries()]) {
|
|
3165
|
+
const spec = next.find((c) => c.id === id);
|
|
3166
|
+
const keep = spec && spec.enabled && node.signature === channelSignature(spec);
|
|
3167
|
+
if (!keep) {
|
|
3168
|
+
tailnetNodes.delete(id);
|
|
3169
|
+
await node.stop().catch(() => {});
|
|
3170
|
+
}
|
|
3171
|
+
}
|
|
3172
|
+
syncTailnetMeta(discovery);
|
|
3173
|
+
const views = tailnetViews();
|
|
3174
|
+
log(`tailnet 通道已保存:${next.map((c) => `${c.label}(${c.id})`).join("、")}`);
|
|
3175
|
+
return send(res, 200, {
|
|
3176
|
+
ok: true,
|
|
3177
|
+
channels: views,
|
|
3178
|
+
// 旧界面字段(取第一条启用通道)
|
|
3179
|
+
enabled: next.some((c) => c.enabled),
|
|
3180
|
+
authKeySaved: views.some((v) => v.authKeySaved),
|
|
3181
|
+
controlUrl: views[0]?.controlUrl ?? "",
|
|
3182
|
+
hostname: views[0]?.hostname ?? "",
|
|
3183
|
+
});
|
|
3184
|
+
}
|
|
3185
|
+
|
|
3186
|
+
// ── 旧版单通道字段(兼容已部署页面 / 脚本)──
|
|
3187
|
+
//
|
|
3188
|
+
// 如果已经有多通道列表,就作用到第一条(优先 default)通道上。
|
|
3189
|
+
// 直接忽略会变成"界面说保存成功、实际什么都没变"—— 这个项目最怕的静默失败。
|
|
3190
|
+
const currentChannels = effectiveTailnetChannels(config);
|
|
3191
|
+
if (currentChannels.length > 0 && !tailnetChannelsPinned()) {
|
|
3192
|
+
const next = currentChannels.map((c) => ({
|
|
3193
|
+
id: c.id,
|
|
3194
|
+
label: c.label,
|
|
3195
|
+
authKey: c.authKey,
|
|
3196
|
+
controlUrl: c.controlUrl,
|
|
3197
|
+
hostname: c.hostname,
|
|
3198
|
+
enabled: c.enabled,
|
|
3199
|
+
}));
|
|
3200
|
+
const target = next.find((c) => c.id === "default") ?? next[0];
|
|
3201
|
+
if (typeof body?.authKey === "string" && body.authKey.trim()) target.authKey = body.authKey.trim();
|
|
3202
|
+
if (body?.clearAuthKey === true) target.authKey = "";
|
|
3203
|
+
if (typeof body?.controlUrl === "string") target.controlUrl = body.controlUrl.trim();
|
|
3204
|
+
if (typeof body?.hostname === "string") target.hostname = body.hostname.trim();
|
|
3205
|
+
if (typeof body?.enabled === "boolean") target.enabled = body.enabled;
|
|
3206
|
+
saveState({ tsnetChannels: next, tsnetEnabled: next.some((c) => c.enabled) });
|
|
3207
|
+
log(`tailnet 配置已更新(作用于通道 ${target.id}):启用=${target.enabled} 授权码=${target.authKey ? "已保存" : "未设置"}`);
|
|
3208
|
+
const views = tailnetViews();
|
|
3209
|
+
return send(res, 200, {
|
|
3210
|
+
ok: true,
|
|
3211
|
+
channels: views,
|
|
3212
|
+
authKeySaved: views.some((v) => v.authKeySaved),
|
|
3213
|
+
controlUrl: target.controlUrl ?? "",
|
|
3214
|
+
hostname: target.hostname ?? "",
|
|
3215
|
+
enabled: views.some((v) => v.enabled),
|
|
3216
|
+
});
|
|
3217
|
+
}
|
|
3218
|
+
|
|
2417
3219
|
const patch = {};
|
|
2418
3220
|
if (typeof body?.authKey === "string" && body.authKey.trim()) patch.tsnetAuthKey = body.authKey.trim();
|
|
2419
3221
|
if (body?.clearAuthKey === true) patch.tsnetAuthKey = "";
|
|
@@ -2422,12 +3224,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2422
3224
|
if (typeof body?.enabled === "boolean") patch.tsnetEnabled = body.enabled;
|
|
2423
3225
|
const saved = saveState(patch);
|
|
2424
3226
|
log(
|
|
2425
|
-
`tailnet
|
|
3227
|
+
`tailnet 旧版单通道配置已更新:启用=${saved.tsnetEnabled === true} ` +
|
|
2426
3228
|
`授权码=${patch.tsnetAuthKey ? "已保存" : saved.tsnetAuthKey ? "保留原值" : "未设置"} ` +
|
|
2427
3229
|
`控制服务器=${saved.tsnetControlUrl || "官方"}`,
|
|
2428
3230
|
);
|
|
2429
3231
|
return send(res, 200, {
|
|
2430
3232
|
ok: true,
|
|
3233
|
+
channels: tailnetViews(),
|
|
2431
3234
|
// 绝不回传授权码内容,只回报是否已配置
|
|
2432
3235
|
authKeySaved: Boolean(saved.tsnetAuthKey),
|
|
2433
3236
|
controlUrl: saved.tsnetControlUrl ?? "",
|
|
@@ -2436,65 +3239,129 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2436
3239
|
});
|
|
2437
3240
|
});
|
|
2438
3241
|
|
|
2439
|
-
/**
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
3242
|
+
/**
|
|
3243
|
+
* 启动(或按最新配置重启)tailnet 通道。
|
|
3244
|
+
*
|
|
3245
|
+
* body.id 省略 = 启动所有启用的通道(兼容旧页面点「只启动」)。
|
|
3246
|
+
*/
|
|
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
|
+
});
|
|
2445
3254
|
}
|
|
2446
|
-
const
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
3255
|
+
const body = await readJson(req);
|
|
3256
|
+
const wantId = String(body?.id ?? "").trim();
|
|
3257
|
+
const all = effectiveTailnetChannels(config);
|
|
3258
|
+
const targets = wantId ? all.filter((c) => c.id === channelKey(wantId)) : all.filter((c) => c.enabled);
|
|
3259
|
+
if (targets.length === 0) {
|
|
3260
|
+
return send(res, 404, { ok: false, error: wantId ? `没有 id 为 ${wantId} 的通道` : "没有启用的 tailnet 通道" });
|
|
3261
|
+
}
|
|
3262
|
+
const started = [];
|
|
3263
|
+
for (const channel of targets) {
|
|
3264
|
+
try {
|
|
3265
|
+
const { reused } = await startTailnetChannel(channel, {
|
|
3266
|
+
config,
|
|
3267
|
+
discovery,
|
|
3268
|
+
log,
|
|
3269
|
+
warn,
|
|
3270
|
+
machineName: identity.name,
|
|
3271
|
+
});
|
|
3272
|
+
started.push({ id: channel.id, ok: true, reused });
|
|
3273
|
+
} catch (err) {
|
|
3274
|
+
started.push({ id: channel.id, ok: false, error: String(err?.message ?? err) });
|
|
3275
|
+
}
|
|
2455
3276
|
}
|
|
3277
|
+
await runScan({ discovery, config, log, warn, reason: "tailnet 手动扫描" }).catch(() => {});
|
|
3278
|
+
const ok = started.some((r) => r.ok);
|
|
3279
|
+
const first = targets[0];
|
|
3280
|
+
return send(res, 200, {
|
|
3281
|
+
ok,
|
|
3282
|
+
results: started,
|
|
3283
|
+
error: ok ? undefined : started.map((r) => `${r.id}: ${r.error}`).join(";"),
|
|
3284
|
+
node: tailnetNodes.get(first.id)?.status() ?? null,
|
|
3285
|
+
channels: tailnetViews(),
|
|
3286
|
+
});
|
|
2456
3287
|
});
|
|
2457
3288
|
|
|
2458
3289
|
/**
|
|
2459
|
-
* 停止 tailnet
|
|
3290
|
+
* 停止 tailnet 通道(body.id 省略 = 全部)。
|
|
2460
3291
|
*
|
|
2461
3292
|
* 这里**不能**传 keepRemote:stop() 在 "非 owner 或 keepRemote" 时走保留分支,
|
|
2462
3293
|
* 而无条件传 true 会让本实例自己拉起的 sidecar 也停不掉(实测点「停止」后
|
|
2463
3294
|
* 进程仍在跑、rendezvous 也没清)。不传参数即按归属判断:自己拉起的关掉,
|
|
2464
3295
|
* 复用别人的只注销自己的 forward。
|
|
2465
3296
|
*/
|
|
2466
|
-
post("/mesh/api/tsnet/stop", async (
|
|
2467
|
-
const
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
3297
|
+
post("/mesh/api/tsnet/stop", async (req, res) => {
|
|
3298
|
+
const body = await readJson(req);
|
|
3299
|
+
const wantId = String(body?.id ?? "").trim();
|
|
3300
|
+
const stopped = await stopTailnetChannel(wantId ? channelKey(wantId) : "", discovery);
|
|
3301
|
+
log(`tailnet ${wantId ? `通道 ${wantId} ` : "全部通道"}已停止(${stopped} 个)`);
|
|
3302
|
+
return send(res, 200, { ok: true, stopped, channels: tailnetViews() });
|
|
2471
3303
|
});
|
|
2472
3304
|
|
|
2473
|
-
/** 清掉节点身份重新登录(授权码失效 / 换账号时用)。 */
|
|
2474
|
-
post("/mesh/api/tsnet/relogin", async (
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
3305
|
+
/** 清掉节点身份重新登录(授权码失效 / 换账号时用)。body.id 省略 = 所有在跑的通道。 */
|
|
3306
|
+
post("/mesh/api/tsnet/relogin", async (req, res) => {
|
|
3307
|
+
const body = await readJson(req);
|
|
3308
|
+
const wantId = String(body?.id ?? "").trim();
|
|
3309
|
+
const ids = wantId ? [channelKey(wantId)] : [...tailnetNodes.keys()];
|
|
3310
|
+
const nodes = ids.map((id) => tailnetNodes.get(id)).filter(Boolean);
|
|
3311
|
+
if (nodes.length === 0) return send(res, 409, { ok: false, error: "互联网组网未启动" });
|
|
3312
|
+
const done = [];
|
|
3313
|
+
for (const node of nodes) {
|
|
3314
|
+
try {
|
|
3315
|
+
await node.relogin();
|
|
3316
|
+
if (discovery.port) await node.registerForward(discovery.port);
|
|
3317
|
+
done.push({ id: node.channelKey, ok: true, node: node.status() });
|
|
3318
|
+
} catch (err) {
|
|
3319
|
+
done.push({ id: node.channelKey, ok: false, error: String(err?.message ?? err), node: node.status() });
|
|
3320
|
+
}
|
|
2482
3321
|
}
|
|
3322
|
+
syncTailnetMeta(discovery);
|
|
3323
|
+
const ok = done.some((r) => r.ok);
|
|
3324
|
+
return send(res, 200, {
|
|
3325
|
+
ok,
|
|
3326
|
+
results: done,
|
|
3327
|
+
node: nodes[0].status(),
|
|
3328
|
+
channels: tailnetViews(),
|
|
3329
|
+
});
|
|
2483
3330
|
});
|
|
2484
3331
|
|
|
2485
|
-
/**
|
|
2486
|
-
|
|
2487
|
-
|
|
3332
|
+
/**
|
|
3333
|
+
* 重新下载 sidecar 二进制(下载损坏或换平台时用)。
|
|
3334
|
+
*
|
|
3335
|
+
* 二进制是**整机共享**的:先停掉所有通道再换文件,否则 Windows 上文件锁着
|
|
3336
|
+
* 换不掉;换完不自动重启,按旧行为留给用户点「连接」。
|
|
3337
|
+
*/
|
|
3338
|
+
post("/mesh/api/tsnet/reinstall", async (req, res) => {
|
|
3339
|
+
const body = await readJson(req);
|
|
3340
|
+
const wantId = String(body?.id ?? "").trim();
|
|
3341
|
+
const channels = effectiveTailnetChannels(config);
|
|
3342
|
+
const target = (wantId ? channels.find((c) => c.id === channelKey(wantId)) : null) ?? channels[0] ?? null;
|
|
3343
|
+
if (!target) return send(res, 409, { ok: false, error: "还没有配置 tailnet 通道" });
|
|
3344
|
+
await stopTailnetChannel("", discovery);
|
|
3345
|
+
const node = new TsnetNode({ config, channel: target, log, warn, machineName: identity.name });
|
|
2488
3346
|
try {
|
|
2489
|
-
const r = await
|
|
3347
|
+
const r = await node.reinstallBinary();
|
|
2490
3348
|
return send(res, 200, { ok: true, path: r.path, source: r.source });
|
|
2491
3349
|
} catch (err) {
|
|
2492
3350
|
return send(res, 200, { ok: false, error: String(err?.message ?? err) });
|
|
2493
3351
|
}
|
|
2494
3352
|
});
|
|
2495
3353
|
|
|
2496
|
-
/** 只扫 tailnet,不扫局域网。 */
|
|
2497
|
-
post("/mesh/api/tsnet/scan", async (
|
|
3354
|
+
/** 只扫 tailnet,不扫局域网。body.id 省略 = 所有在跑的通道。 */
|
|
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
|
+
}
|
|
3363
|
+
const body = await readJson(req);
|
|
3364
|
+
const wantId = String(body?.id ?? "").trim();
|
|
2498
3365
|
const before = new Set(discovery.peers().map((p) => p.id));
|
|
2499
3366
|
const result = await scanTailnet({
|
|
2500
3367
|
discovery,
|
|
@@ -2502,12 +3369,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2502
3369
|
log,
|
|
2503
3370
|
reason: "tailnet 手动扫描",
|
|
2504
3371
|
ports: scanPortList(discovery, config),
|
|
3372
|
+
channelId: wantId ? channelKey(wantId) : "",
|
|
2505
3373
|
});
|
|
2506
3374
|
const added = discovery.peers().filter((p) => !before.has(p.id));
|
|
2507
3375
|
return send(res, 200, {
|
|
2508
3376
|
ok: true,
|
|
2509
3377
|
...result,
|
|
2510
|
-
added: added.map((p) => ({ machine: p.machine, host: p.host, port: p.port })),
|
|
3378
|
+
added: added.map((p) => ({ machine: p.machine, host: p.host, port: p.port, channel: p.channel })),
|
|
2511
3379
|
});
|
|
2512
3380
|
});
|
|
2513
3381
|
|
|
@@ -2516,6 +3384,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2516
3384
|
const peerName = String(body?.peer ?? "").trim();
|
|
2517
3385
|
const task = String(body?.task ?? "").trim();
|
|
2518
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
|
+
}
|
|
2519
3394
|
const found = findPeer(peerName);
|
|
2520
3395
|
if (found.error) return send(res, found.error.startsWith("名字") ? 409 : 404, { ok: false, error: found.error });
|
|
2521
3396
|
const target = found.peer;
|