dsh-plugin-mesh 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +5 -4
- package/README.md +61 -1
- package/client/client.js +324 -122
- package/lib/_selftest-tsnet.mjs +173 -1
- package/lib/_selftest-workbench.mjs +53 -0
- package/lib/discovery.js +89 -18
- package/lib/index.js +543 -178
- package/lib/tsnet/channels.js +72 -0
- package/lib/tsnet/manager.js +187 -48
- package/llms.txt +17 -10
- package/package.json +2 -2
package/lib/index.js
CHANGED
|
@@ -54,13 +54,14 @@ import {
|
|
|
54
54
|
loadPeerSnapshot,
|
|
55
55
|
savePeerSnapshot,
|
|
56
56
|
} from "./persist.js";
|
|
57
|
-
import { TsnetNode } from "./tsnet/manager.js";
|
|
57
|
+
import { TsnetNode, channelKey, channelSignature } from "./tsnet/manager.js";
|
|
58
|
+
import { resolveTailnetChannels } from "./tsnet/channels.js";
|
|
58
59
|
import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
|
|
59
60
|
|
|
60
61
|
export const name = "dsh-plugin-mesh";
|
|
61
62
|
export const inject = ["tools", "webServer"];
|
|
62
63
|
|
|
63
|
-
const VERSION = "0.5.
|
|
64
|
+
const VERSION = "0.5.4";
|
|
64
65
|
// 诊断用:进程启动时间、入口真实路径、**磁盘上** package.json 的版本。
|
|
65
66
|
// 这三样放一起才能回答"现在跑的到底是哪份代码" —— 只看 state.json 或重启日志
|
|
66
67
|
// 都答不了(真踩过:磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
|
|
@@ -75,11 +76,13 @@ const MAX_HISTORY = 200;
|
|
|
75
76
|
export const MESH_DEFAULT_PORT = 45917;
|
|
76
77
|
|
|
77
78
|
/**
|
|
78
|
-
* 互联网自组网(tailnet
|
|
79
|
-
*
|
|
80
|
-
*
|
|
79
|
+
* 互联网自组网(tailnet)通道:通道 id → 节点句柄。
|
|
80
|
+
*
|
|
81
|
+
* 宿主机路由不到 100.x.y.z,所有指向 tailnet 对端的请求都要经对应 sidecar
|
|
82
|
+
* 中转,所以这里用模块级引用,让 peerFetch / scanTailnet 能拿到当前实例。
|
|
83
|
+
* 一台机器可以同时有多条通道(多个 tailnet),每个通道一个 sidecar。
|
|
81
84
|
*/
|
|
82
|
-
|
|
85
|
+
const tailnetNodes = new Map();
|
|
83
86
|
|
|
84
87
|
/**
|
|
85
88
|
* 当前实例的发现注册表。
|
|
@@ -179,14 +182,40 @@ export const Config = z.object({
|
|
|
179
182
|
// 开启后插件会自动下载一个用户态 Tailscale 节点(sidecar)并加入 tailnet,
|
|
180
183
|
// 让发现与派发跨互联网可用,与局域网路径同等级。
|
|
181
184
|
// 终端用户不需要装 Go,也不需要装 Tailscale 客户端:二进制随插件自动下载。
|
|
182
|
-
|
|
185
|
+
// 一台机器可以同时加入**多个 tailnet**:每个通道一个 sidecar、一个 tailnet
|
|
186
|
+
// 地址。设备身份仍然只有一个(instanceId 不变),通道只是多条可达路径。
|
|
187
|
+
// 下面三个 tsnetAuthKey / tsnetControlUrl / tsnetHostname 是**旧版单通道**
|
|
188
|
+
// 字段,保留以兼容已部署的配置与界面;有多通道需求时用 tsnetChannels。
|
|
189
|
+
/** 是否启用互联网自组网(旧版单通道开关;仅在 tsnetChannels 为空时生效) */
|
|
183
190
|
tsnetEnabled: z.boolean().default(false),
|
|
184
|
-
/** Tailscale 授权码(tskey-auth
|
|
191
|
+
/** Tailscale 授权码(tskey-auth-...);旧版单通道字段,也可以只在界面上填 */
|
|
185
192
|
tsnetAuthKey: z.string().default(""),
|
|
186
|
-
/**
|
|
193
|
+
/** 控制服务器地址;旧版单通道字段。留空用官方 Tailscale,Headscale 用户填自己的 */
|
|
187
194
|
tsnetControlUrl: z.string().default(""),
|
|
188
|
-
/** tailnet 节点名(合法 DNS label
|
|
195
|
+
/** tailnet 节点名(合法 DNS label);旧版单通道字段。留空用机器名 */
|
|
189
196
|
tsnetHostname: z.string().default(""),
|
|
197
|
+
/**
|
|
198
|
+
* 多 tailnet 通道。每项:
|
|
199
|
+
* { id, label, authKey, controlUrl, hostname, enabled }
|
|
200
|
+
*
|
|
201
|
+
* `id` 是稳定标识(进 sidecar 状态目录,决定 tailnet 里的设备身份),
|
|
202
|
+
* 配置文件里手写时**务必显式给**;留空会按 label + controlUrl 推导,
|
|
203
|
+
* 改显示名就会变成新设备。界面添加的通道由宿主生成 `ch-xxxxxxxx`。
|
|
204
|
+
*
|
|
205
|
+
* 这里配了通道后优先于 state.json(配置钉死),也优先于上面三个旧字段。
|
|
206
|
+
*/
|
|
207
|
+
tsnetChannels: z
|
|
208
|
+
.array(
|
|
209
|
+
z.object({
|
|
210
|
+
id: z.string().default(""),
|
|
211
|
+
label: z.string().default(""),
|
|
212
|
+
authKey: z.string().default(""),
|
|
213
|
+
controlUrl: z.string().default(""),
|
|
214
|
+
hostname: z.string().default(""),
|
|
215
|
+
enabled: z.boolean().default(true),
|
|
216
|
+
}),
|
|
217
|
+
)
|
|
218
|
+
.default([]),
|
|
190
219
|
/** 自定义下载源前缀,可含 {url} 占位符;留空用内置镜像列表 */
|
|
191
220
|
tsnetDownloadSources: z.array(String).default([]),
|
|
192
221
|
/**
|
|
@@ -425,25 +454,127 @@ function pairingPinned(config) {
|
|
|
425
454
|
}
|
|
426
455
|
|
|
427
456
|
/**
|
|
428
|
-
* 解析 tailnet
|
|
457
|
+
* 解析 tailnet 的**有效通道列表**(多 tailnet)。
|
|
458
|
+
*
|
|
459
|
+
* 一台机器可以同时加入多个 tailnet:个人账号、公司 tailnet、自建 Headscale
|
|
460
|
+
* 各一个,每个通道一个 sidecar、一个 tailnet 地址。设备身份只有一个,通道只是
|
|
461
|
+
* 这个节点的多条可达路径(见 MESH-DEFINITION.md)。
|
|
429
462
|
*
|
|
430
|
-
*
|
|
431
|
-
*
|
|
432
|
-
* 配置里的值优先,方便用配置把界面上的值钉死。
|
|
463
|
+
* 解析规则(配置 > state.json > 旧版单通道字段)在 lib/tsnet/channels.js 里,
|
|
464
|
+
* 那里是纯函数、有独立自测 —— 这段只负责把磁盘上的 state 读出来。
|
|
433
465
|
*/
|
|
434
|
-
function
|
|
435
|
-
|
|
436
|
-
|
|
466
|
+
function effectiveTailnetChannels(config) {
|
|
467
|
+
return resolveTailnetChannels({ config, state: loadState() });
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** 通道的对外视图:**绝不回传授权码内容**,只回报是否已配置。 */
|
|
471
|
+
function tailnetChannelView(channel, node) {
|
|
472
|
+
const status = node ? node.status() : null;
|
|
437
473
|
return {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
474
|
+
id: channel.id,
|
|
475
|
+
label: channel.label,
|
|
476
|
+
controlUrl: channel.controlUrl,
|
|
477
|
+
hostname: channel.hostname || status?.hostname || "",
|
|
478
|
+
enabled: channel.enabled === true,
|
|
479
|
+
authKeySaved: Boolean(channel.authKey),
|
|
480
|
+
source: channel.source,
|
|
481
|
+
node: status,
|
|
482
|
+
recentEvents: node ? node.recentEvents().slice(-12) : [],
|
|
444
483
|
};
|
|
445
484
|
}
|
|
446
485
|
|
|
486
|
+
/** 当前运行的通道节点里,每条的 tailnet 地址(写进对外名片,供对端提前记下)。 */
|
|
487
|
+
function tailnetMetaAddresses() {
|
|
488
|
+
const out = [];
|
|
489
|
+
for (const node of tailnetNodes.values()) {
|
|
490
|
+
if (node.phase !== "running") continue;
|
|
491
|
+
const ip = node.selfIpv4;
|
|
492
|
+
if (ip) out.push(ip);
|
|
493
|
+
}
|
|
494
|
+
return out;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** 把本机的 tailnet 地址同步进名片(任何一条通道起落都要调)。 */
|
|
498
|
+
function syncTailnetMeta(discovery) {
|
|
499
|
+
if (!discovery) return;
|
|
500
|
+
discovery.setMeta({ tailnetIps: tailnetMetaAddresses() });
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** 当前在跑的通道节点。 */
|
|
504
|
+
function runningTailnetNodes() {
|
|
505
|
+
return [...tailnetNodes.values()].filter((n) => n.phase === "running");
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* 启动(或重建)一条 tailnet 通道。
|
|
510
|
+
*
|
|
511
|
+
* 授权码/控制服务器/主机名任何一项变了都要重建 sidecar:一个 tsnet 节点只
|
|
512
|
+
* 认一个 tailnet,沿用旧进程会继续待在旧网络里。
|
|
513
|
+
*
|
|
514
|
+
* **失败只影响这条通道**:异常原样抛给调用方,局域网与其它通道不受影响。
|
|
515
|
+
*/
|
|
516
|
+
async function startTailnetChannel(channel, { config, discovery, log, warn, machineName }) {
|
|
517
|
+
const existing = tailnetNodes.get(channel.id);
|
|
518
|
+
// 配置没变、节点还活着(含等待授权)→ 复用。重试不该把登录流程推倒重来;
|
|
519
|
+
// 配置变了才重建,否则会一直在旧 tailnet 里。
|
|
520
|
+
const signature = channelSignature(channel);
|
|
521
|
+
const live = existing && ["running", "needs-login", "starting", "downloading"].includes(existing.phase);
|
|
522
|
+
if (live && existing.signature === signature) {
|
|
523
|
+
if (existing.phase === "running" && discovery?.port) {
|
|
524
|
+
await existing.registerForward(discovery.port).catch(() => {});
|
|
525
|
+
}
|
|
526
|
+
return { node: existing, reused: true };
|
|
527
|
+
}
|
|
528
|
+
if (existing) {
|
|
529
|
+
tailnetNodes.delete(channel.id);
|
|
530
|
+
await existing.stop().catch(() => {});
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const tag = `tailnet:${channel.label}`;
|
|
534
|
+
const tsnode = new TsnetNode({
|
|
535
|
+
config,
|
|
536
|
+
channel,
|
|
537
|
+
log: (m) => log(`[${tag}] ${m}`),
|
|
538
|
+
warn,
|
|
539
|
+
machineName,
|
|
540
|
+
});
|
|
541
|
+
tailnetNodes.set(channel.id, tsnode);
|
|
542
|
+
tsnode.on("status", (s) => {
|
|
543
|
+
if (s.phase === "error" && s.error) warn(`通道 ${channel.label}:${s.error}`);
|
|
544
|
+
// 侧车起落会改变本机的 tailnet 地址,名片要跟着更新
|
|
545
|
+
syncTailnetMeta(discovery);
|
|
546
|
+
});
|
|
547
|
+
|
|
548
|
+
try {
|
|
549
|
+
const { reused } = await tsnode.start();
|
|
550
|
+
// 让本机 mesh 服务在**这条** tailnet 上可达(tailnet :port → 127.0.0.1:port)。
|
|
551
|
+
// 多条通道可以注册同一个端口:每个 sidecar 的监听在各自的用户态网络栈里。
|
|
552
|
+
if (discovery?.port) await tsnode.registerForward(discovery.port);
|
|
553
|
+
syncTailnetMeta(discovery);
|
|
554
|
+
return { node: tsnode, reused };
|
|
555
|
+
} catch (err) {
|
|
556
|
+
// 节点留在表里:界面要能看到这条通道的错误与诊断,而不是"它凭空消失了"
|
|
557
|
+
syncTailnetMeta(discovery);
|
|
558
|
+
throw err;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** 停掉一条通道(不传 id 停全部)。返回实际停掉的通道数。 */
|
|
563
|
+
async function stopTailnetChannel(id, discovery) {
|
|
564
|
+
const ids = id ? [String(id)] : [...tailnetNodes.keys()];
|
|
565
|
+
let stopped = 0;
|
|
566
|
+
for (const key of ids) {
|
|
567
|
+
const node = tailnetNodes.get(key);
|
|
568
|
+
if (!node) continue;
|
|
569
|
+
tailnetNodes.delete(key);
|
|
570
|
+
await node.stop().catch(() => {});
|
|
571
|
+
stopped += 1;
|
|
572
|
+
}
|
|
573
|
+
if (stopped > 0) syncTailnetMeta(discovery);
|
|
574
|
+
return stopped;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
|
|
447
578
|
/** 首次运行生成配对码;用户只需把它复制到另一台机器。 */
|
|
448
579
|
function ensureSecret() {
|
|
449
580
|
const st = loadState();
|
|
@@ -719,43 +850,43 @@ function applyUnsafe(ctx, config) {
|
|
|
719
850
|
});
|
|
720
851
|
|
|
721
852
|
// 互联网自组网:与局域网并行的第二条发现路径,功能同等级。
|
|
722
|
-
//
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
if (s.phase === "error" && s.error) warn(`互联网组网:${s.error}`);
|
|
729
|
-
});
|
|
853
|
+
// 任何一步失败都只影响对应通道 —— 局域网发现照常工作,这是硬要求。
|
|
854
|
+
//
|
|
855
|
+
// 多 tailnet:每条启用的通道各起一个 sidecar(串行启动,避免并发争用
|
|
856
|
+
// 二进制下载);一条失败不影响其它条,也不影响局域网。
|
|
857
|
+
const tailnetChannels = effectiveTailnetChannels(config).filter((c) => c.enabled);
|
|
858
|
+
if (tailnetChannels.length > 0) {
|
|
730
859
|
ctx.effect(() => () => {
|
|
731
|
-
|
|
732
|
-
|
|
860
|
+
for (const node of tailnetNodes.values()) node.stop().catch(() => {});
|
|
861
|
+
tailnetNodes.clear();
|
|
733
862
|
});
|
|
734
863
|
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
.then(async ({ reused }) => {
|
|
738
|
-
// 让本机 mesh 服务在 tailnet 上可达(tailnet :port → 127.0.0.1:port)
|
|
739
|
-
await node.registerForward(port);
|
|
740
|
-
const st = node.status();
|
|
741
|
-
// 把本机的 tailnet 地址写进对外名片。
|
|
742
|
-
//
|
|
743
|
-
// 这一步是决定 #2 成立的关键:对端**只靠局域网**就能知道我们的备选
|
|
744
|
-
// 地址,于是它平时完全不用做 tailnet 探测,局域网一断却能立刻切过来。
|
|
745
|
-
// setMeta 会立刻重新广播一次,不用等下一个心跳周期。
|
|
746
|
-
if (st.selfIpv4) discovery.setMeta({ tailnetIp: st.selfIpv4 });
|
|
747
|
-
log(
|
|
748
|
-
`互联网组网已启动:节点=${node.hostname} tailnet=${st.selfIpv4 || "待登录"}` +
|
|
749
|
-
`${reused ? "(复用已有 sidecar)" : ""}${st.authUrl ? ` 授权链接=${st.authUrl}` : ""}`,
|
|
750
|
-
);
|
|
864
|
+
(async () => {
|
|
865
|
+
for (const channel of tailnetChannels) {
|
|
751
866
|
if (stop.aborted) return;
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
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}`));
|
|
757
888
|
} else {
|
|
758
|
-
log("
|
|
889
|
+
log("互联网自组网未启用(没有启用的 tailnet 通道)");
|
|
759
890
|
}
|
|
760
891
|
|
|
761
892
|
if (config.scanOnStart) {
|
|
@@ -1494,18 +1625,17 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1494
1625
|
|
|
1495
1626
|
// ───────────────────────── 主动发现与保活 ─────────────────────────
|
|
1496
1627
|
|
|
1497
|
-
/**
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
* 把差异收在这一个函数里,上面所有调用点都不必关心对端是怎么找到的。
|
|
1503
|
-
*/
|
|
1628
|
+
/** 端点的稳定 key:`lan` / `tsnet:<通道 id>`(兼容旧端点的 `tsnet`)。 */
|
|
1629
|
+
function endpointKeyOf(ep) {
|
|
1630
|
+
return String(ep?.channel ?? ep?.transport ?? "lan");
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1504
1633
|
/**
|
|
1505
1634
|
* 按端点健康**逐个失败切换**地发一个请求。
|
|
1506
1635
|
*
|
|
1507
|
-
* 这是"
|
|
1508
|
-
*
|
|
1636
|
+
* 这是"多条通道绑一台设备"的实际收益:局域网不通就走某条 tailnet,一条
|
|
1637
|
+
* tailnet 不通还可以走另一条。以前只看 `peer.transport`(最后探测到的那个),
|
|
1638
|
+
* 一条通道坏掉整个对端就不可达。
|
|
1509
1639
|
*
|
|
1510
1640
|
* 只有**网络层失败**才切换通道:HTTP 4xx/5xx 说明端点本身是通的,换一条也
|
|
1511
1641
|
* 一样,不该白试一遍、更不该把好端点的健康记录打坏。
|
|
@@ -1527,7 +1657,7 @@ async function peerFetch(peer, path, opts = {}) {
|
|
|
1527
1657
|
// `http://:0/mesh/v1/hello` —— 端点明明选对了,URL 却是坏的。
|
|
1528
1658
|
// 实测就是这个报错:`Get "http://:0/mesh/v1/hello": lookup : no such host`。
|
|
1529
1659
|
if (!ep.host || !ep.port) {
|
|
1530
|
-
failures.push(`${ep
|
|
1660
|
+
failures.push(`${endpointKeyOf(ep)} 端点地址不完整(${ep.host}:${ep.port})`);
|
|
1531
1661
|
continue;
|
|
1532
1662
|
}
|
|
1533
1663
|
const url = `http://${ep.host}:${ep.port}${path}`;
|
|
@@ -1537,11 +1667,11 @@ async function peerFetch(peer, path, opts = {}) {
|
|
|
1537
1667
|
ep.transport === "tsnet"
|
|
1538
1668
|
? await fetchViaTailnet(ep, url, { ...rest, timeoutMs })
|
|
1539
1669
|
: await fetchViaLan(ep, url, { ...rest, timeoutMs });
|
|
1540
|
-
activeDiscovery?.markEndpoint(peer.id, ep
|
|
1670
|
+
activeDiscovery?.markEndpoint(peer.id, endpointKeyOf(ep), { ok: true, rttMs: Date.now() - started });
|
|
1541
1671
|
return res;
|
|
1542
1672
|
} catch (err) {
|
|
1543
|
-
failures.push(`${ep
|
|
1544
|
-
activeDiscovery?.markEndpoint(peer.id, ep
|
|
1673
|
+
failures.push(`${endpointKeyOf(ep)}(${ep.host}:${ep.port}) ${err?.message ?? err}`);
|
|
1674
|
+
activeDiscovery?.markEndpoint(peer.id, endpointKeyOf(ep), { ok: false });
|
|
1545
1675
|
}
|
|
1546
1676
|
}
|
|
1547
1677
|
throw new Error(`所有通道都失败 —— ${failures.join(";")}`);
|
|
@@ -1556,76 +1686,120 @@ async function fetchViaLan(ep, url, opts = {}) {
|
|
|
1556
1686
|
/**
|
|
1557
1687
|
* 经 sidecar 的用户态隧道出去。
|
|
1558
1688
|
* 宿主机没有 TUN 设备,`fetch("http://100.x.y.z:...")` 会直接 ENETUNREACH。
|
|
1689
|
+
*
|
|
1690
|
+
* 出口选择:
|
|
1691
|
+
* · 端点带通道(`tsnet:<id>`)→ 优先走那条通道的 sidecar;它不可用时再依次
|
|
1692
|
+
* 试其它通道(IP 本来就属于哪条 tailnet 是连通性说的,不必猜)。
|
|
1693
|
+
* · 端点没有通道(对端名片里报来的候选地址)→ 依次试所有通道。
|
|
1694
|
+
*
|
|
1695
|
+
* 多条 tailnet 可能有重叠的 100.x 网段,所以"试"是唯一可靠的做法;失败的
|
|
1696
|
+
* 通道不会留下状态(真实健康记录由调用方 markEndpoint 写)。
|
|
1559
1697
|
*/
|
|
1560
1698
|
async function fetchViaTailnet(ep, url, opts = {}) {
|
|
1561
|
-
|
|
1562
|
-
|
|
1699
|
+
const key = endpointKeyOf(ep);
|
|
1700
|
+
const wantId = key.startsWith("tsnet:") ? key.slice("tsnet:".length) : "";
|
|
1701
|
+
const wanted = wantId ? tailnetNodes.get(wantId) : null;
|
|
1702
|
+
const candidates = [];
|
|
1703
|
+
if (wanted && wanted.phase === "running") candidates.push(wanted);
|
|
1704
|
+
for (const node of runningTailnetNodes()) {
|
|
1705
|
+
if (!candidates.includes(node)) candidates.push(node);
|
|
1706
|
+
}
|
|
1707
|
+
if (candidates.length === 0) throw new Error("tailnet 节点尚未启动");
|
|
1708
|
+
let lastErr = null;
|
|
1709
|
+
for (const node of candidates) {
|
|
1710
|
+
try {
|
|
1711
|
+
return await tailnetFetch(node, url, opts);
|
|
1712
|
+
} catch (err) {
|
|
1713
|
+
lastErr = err;
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
throw lastErr ?? new Error("没有可用的 tailnet 通道");
|
|
1563
1717
|
}
|
|
1564
1718
|
|
|
1565
1719
|
/**
|
|
1566
|
-
*
|
|
1720
|
+
* 借每条 tailnet 通道的 sidecar 节点表做第二轮探测。
|
|
1567
1721
|
*
|
|
1568
1722
|
* 与局域网扫描刻意保持同构:拿候选地址 → 探 /mesh/v1/health → 自述记录进
|
|
1569
|
-
*
|
|
1570
|
-
*
|
|
1723
|
+
* 同一个注册表。区别是:候选地址来自 tailnet,请求必须走对应的 sidecar 隧道,
|
|
1724
|
+
* 且**每条通道各扫一遍** —— 一台设备可能在多个 tailnet 里,每个 tailnet 给的
|
|
1725
|
+
* 地址不同,端点要按通道分别记录。
|
|
1726
|
+
*
|
|
1727
|
+
* @param channelId 只扫某一条通道;省略 = 所有在跑的通道
|
|
1571
1728
|
*/
|
|
1572
|
-
async function scanTailnet({ discovery, config, log, reason, ports }) {
|
|
1573
|
-
|
|
1574
|
-
if (
|
|
1575
|
-
return { scanned: 0, found: 0 };
|
|
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 };
|
|
1729
|
+
async function scanTailnet({ discovery, config, log, reason, ports, channelId = "" }) {
|
|
1730
|
+
const nodes = runningTailnetNodes().filter((n) => !channelId || n.channelKey === channelId);
|
|
1731
|
+
if (nodes.length === 0) return { scanned: 0, found: 0, channels: [] };
|
|
1589
1732
|
|
|
1590
1733
|
// tailnet 上没有"端口先验",但同机单实例 + 默认端口是常态,命中率很高。
|
|
1591
1734
|
const targetPorts = [...new Set([...ports, MESH_DEFAULT_PORT])].filter((p) => Number(p) > 0);
|
|
1592
|
-
|
|
1593
|
-
|
|
1735
|
+
const probeIntervalMs = Math.max(config.pingIntervalMs, config.tsnetProbeIntervalMs ?? 60000);
|
|
1736
|
+
const perChannel = [];
|
|
1594
1737
|
|
|
1595
1738
|
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
|
-
|
|
1739
|
+
nodes.map(async (node) => {
|
|
1740
|
+
const channel = `tsnet:${node.channelKey}`;
|
|
1741
|
+
const summary = { id: node.channelKey, label: node.label, scanned: 0, found: 0, error: "" };
|
|
1742
|
+
perChannel.push(summary);
|
|
1743
|
+
|
|
1744
|
+
let peers;
|
|
1745
|
+
try {
|
|
1746
|
+
peers = await node.peersRemote();
|
|
1747
|
+
} catch (err) {
|
|
1748
|
+
summary.error = String(err?.message ?? err);
|
|
1749
|
+
log(`${reason}(${node.label}): 取节点表失败 —— ${summary.error}`);
|
|
1750
|
+
return;
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
// 只看在线且有 IPv4 的;自己不在 Peer 列表里,不用排除。
|
|
1754
|
+
const candidates = peers.filter((p) => p.online && p.ipv4);
|
|
1755
|
+
summary.scanned = candidates.length * targetPorts.length;
|
|
1756
|
+
if (candidates.length === 0) return;
|
|
1757
|
+
|
|
1758
|
+
let found = 0;
|
|
1759
|
+
let added = 0;
|
|
1760
|
+
await Promise.all(
|
|
1761
|
+
candidates.flatMap((p) =>
|
|
1762
|
+
targetPorts.map(async (tp) => {
|
|
1763
|
+
try {
|
|
1764
|
+
const started = Date.now();
|
|
1765
|
+
const res = await tailnetFetch(node, `http://${p.ipv4}:${tp}/mesh/v1/health`, {
|
|
1766
|
+
timeoutMs: Math.min(4000, config.requestTimeoutMs),
|
|
1767
|
+
});
|
|
1768
|
+
if (!res.ok) return;
|
|
1769
|
+
const body = await res.json();
|
|
1770
|
+
if (body?.app !== "dsh-mesh" || !body.id) return;
|
|
1771
|
+
found += 1;
|
|
1772
|
+
// 强制记 tailnet IP:对端自述的 host 是它的局域网地址,跨互联网不可达。
|
|
1773
|
+
// 通道 key 必须带上:同一台设备可能同时出现在多条 tailnet 里,
|
|
1774
|
+
// 不区分就会互相覆盖,一条通道断了另一条也跟着消失。
|
|
1775
|
+
// 同时带上探测间隔与 RTT —— 漏了 interval 会让这条通道按默认 TTL(20s)
|
|
1776
|
+
// 判活,而它 60s 才探一次,于是探完 20 秒就"死了"、整台设备假离线。
|
|
1777
|
+
// 实测踩过:ok=4 fail=0 rtt=473ms 却显示 online=False。
|
|
1778
|
+
if (
|
|
1779
|
+
discovery.note(body, p.ipv4, {
|
|
1780
|
+
transport: "tsnet",
|
|
1781
|
+
channel,
|
|
1782
|
+
port: tp,
|
|
1783
|
+
rttMs: Date.now() - started,
|
|
1784
|
+
probeIntervalMs,
|
|
1785
|
+
})
|
|
1786
|
+
)
|
|
1787
|
+
added += 1;
|
|
1788
|
+
} catch {
|
|
1789
|
+
/* 该地址上没有 DSH 节点,或端口没开 —— 正常情况,不打扰用户 */
|
|
1790
|
+
}
|
|
1791
|
+
}),
|
|
1792
|
+
),
|
|
1793
|
+
);
|
|
1794
|
+
|
|
1795
|
+
summary.found = found;
|
|
1796
|
+
if (found > 0) log(`${reason}(${node.label}): 命中 ${found} 台(新登记 ${added})`);
|
|
1797
|
+
}),
|
|
1625
1798
|
);
|
|
1626
1799
|
|
|
1627
|
-
|
|
1628
|
-
|
|
1800
|
+
const found = perChannel.reduce((n, c) => n + c.found, 0);
|
|
1801
|
+
const scanned = perChannel.reduce((n, c) => n + c.scanned, 0);
|
|
1802
|
+
return { scanned, found, channels: perChannel };
|
|
1629
1803
|
}
|
|
1630
1804
|
|
|
1631
1805
|
/**
|
|
@@ -1732,14 +1906,19 @@ async function pingKnownPeers({ discovery, config, warn }) {
|
|
|
1732
1906
|
});
|
|
1733
1907
|
if (!res.ok) {
|
|
1734
1908
|
// 端点通但返回错误:不打坏健康记录,也不换通道重试(换了也一样)
|
|
1735
|
-
discovery.markEndpoint(p.id, ep
|
|
1909
|
+
discovery.markEndpoint(p.id, endpointKeyOf(ep), { ok: true, rttMs: Date.now() - started });
|
|
1736
1910
|
return;
|
|
1737
1911
|
}
|
|
1738
1912
|
const body = await res.json();
|
|
1739
1913
|
if (body?.app === "dsh-mesh" && body.id) {
|
|
1740
|
-
// 对方可能重启过、换了端口 —— 以 ping
|
|
1914
|
+
// 对方可能重启过、换了端口 —— 以 ping 到的为准,并刷新这条端点。
|
|
1915
|
+
// channel 用**这条端点自己的 key**:多 tailnet 时若统一写成 tsnet,
|
|
1916
|
+
// 不同通道会互相覆盖,一条断了另一条也跟着假死。
|
|
1917
|
+
// 候选端点(tsnet:cand:…)探通后就此转正,保持同一个 key,
|
|
1918
|
+
// 发送时按"依次试所有通道"解析。
|
|
1741
1919
|
discovery.note(body, ep.host, {
|
|
1742
1920
|
transport: ep.transport,
|
|
1921
|
+
channel: endpointKeyOf(ep),
|
|
1743
1922
|
port: ep.port,
|
|
1744
1923
|
// 把探测结果一起带上:note() 是成功路径的入口,RTT 与探测间隔
|
|
1745
1924
|
// 在这里接住,通道的存活窗口才会跟着自己的节奏走
|
|
@@ -1749,7 +1928,7 @@ async function pingKnownPeers({ discovery, config, warn }) {
|
|
|
1749
1928
|
}
|
|
1750
1929
|
} catch {
|
|
1751
1930
|
// 这条通道不通:记一次失败,累计到阈值就进冷却,排序会把它排到最后
|
|
1752
|
-
discovery.markEndpoint(p.id, ep
|
|
1931
|
+
discovery.markEndpoint(p.id, endpointKeyOf(ep), {
|
|
1753
1932
|
ok: false,
|
|
1754
1933
|
probeIntervalMs: ep.transport === "tsnet" ? tsnetInterval : config.pingIntervalMs,
|
|
1755
1934
|
});
|
|
@@ -2183,9 +2362,12 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2183
2362
|
};
|
|
2184
2363
|
|
|
2185
2364
|
const state = () => {
|
|
2186
|
-
// state.json
|
|
2187
|
-
//
|
|
2188
|
-
const
|
|
2365
|
+
// state.json 只读一次:这个接口会被页面轮询,而通道解析内部每次都读文件,
|
|
2366
|
+
// 逐字段调用会把一次轮询变成多次磁盘读。
|
|
2367
|
+
const tailnetChannels = effectiveTailnetChannels(config);
|
|
2368
|
+
const channelViews = tailnetChannels.map((c) => tailnetChannelView(c, tailnetNodes.get(c.id) ?? null));
|
|
2369
|
+
// 兼容旧界面:node / hostname / authKeySaved 取"第一条启用的通道"
|
|
2370
|
+
const primary = channelViews.find((c) => c.enabled) ?? channelViews[0] ?? null;
|
|
2189
2371
|
return {
|
|
2190
2372
|
ok: true,
|
|
2191
2373
|
self: {
|
|
@@ -2235,15 +2417,19 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2235
2417
|
},
|
|
2236
2418
|
// 互联网自组网状态。注意:**绝不回传授权码本身**,只回报"是否已配置"。
|
|
2237
2419
|
tsnet: {
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2420
|
+
// 多 tailnet 通道列表:UI 的主视图
|
|
2421
|
+
channels: channelViews,
|
|
2422
|
+
/** 有任意一条启用的通道即为 true(旧界面兼容) */
|
|
2423
|
+
enabled: channelViews.some((c) => c.enabled),
|
|
2424
|
+
/** 旧单通道字段:取第一条启用通道 */
|
|
2425
|
+
authKeySaved: Boolean(primary?.authKeySaved),
|
|
2426
|
+
controlUrl: primary?.controlUrl ?? "",
|
|
2427
|
+
hostname: primary?.hostname ?? "",
|
|
2242
2428
|
permissionPreset: config.tsnetPermissionPreset || "",
|
|
2243
2429
|
/** 留空时实际生效的权限,与局域网一致 */
|
|
2244
2430
|
permissionPresetEffective: config.tsnetPermissionPreset || config.permissionPreset,
|
|
2245
|
-
node:
|
|
2246
|
-
recentEvents:
|
|
2431
|
+
node: primary?.node ?? null,
|
|
2432
|
+
recentEvents: primary?.recentEvents ?? [],
|
|
2247
2433
|
},
|
|
2248
2434
|
peers: discovery.peers(),
|
|
2249
2435
|
duplicateNames: duplicateNames(),
|
|
@@ -2402,18 +2588,145 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2402
2588
|
|
|
2403
2589
|
// 无论节点是启动时创建还是后来从界面启动的,插件卸载时都收干净。
|
|
2404
2590
|
ctx.effect(() => () => {
|
|
2405
|
-
const node
|
|
2406
|
-
|
|
2407
|
-
node?.stop().catch(() => {});
|
|
2591
|
+
for (const node of tailnetNodes.values()) node.stop().catch(() => {});
|
|
2592
|
+
tailnetNodes.clear();
|
|
2408
2593
|
});
|
|
2409
2594
|
|
|
2595
|
+
/** 通道列表是否被插件配置钉死(此时界面只能看,不能改)。 */
|
|
2596
|
+
const tailnetChannelsPinned = () => Array.isArray(config.tsnetChannels) && config.tsnetChannels.length > 0;
|
|
2597
|
+
|
|
2598
|
+
/** 把当前生效的通道列表转成对外视图(不回传授权码)。 */
|
|
2599
|
+
const tailnetViews = () =>
|
|
2600
|
+
effectiveTailnetChannels(config).map((c) => tailnetChannelView(c, tailnetNodes.get(c.id) ?? null));
|
|
2601
|
+
|
|
2410
2602
|
/**
|
|
2411
|
-
* 保存 tailnet
|
|
2603
|
+
* 保存 tailnet 配置(多通道)。
|
|
2604
|
+
*
|
|
2605
|
+
* 两种形态:
|
|
2606
|
+
* · `{ channels: [...] }` —— 整体替换通道列表(界面走这条)
|
|
2607
|
+
* · 旧的单通道字段 `{ authKey, controlUrl, hostname, enabled }` —— 兼容老页面
|
|
2608
|
+
*
|
|
2412
2609
|
* 授权码存进 state.json(0600),所以**只需要输入一次**,重启不用再填。
|
|
2413
|
-
*
|
|
2610
|
+
* 某项的 `authKey` 传空串表示"不改动已保存的值";要清掉就传
|
|
2611
|
+
* `clearAuthKey: true`,避免界面回显后又被空值覆盖。
|
|
2414
2612
|
*/
|
|
2415
2613
|
post("/mesh/api/tsnet/config", async (req, res) => {
|
|
2416
2614
|
const body = await readJson(req);
|
|
2615
|
+
|
|
2616
|
+
if (Array.isArray(body?.channels)) {
|
|
2617
|
+
if (tailnetChannelsPinned()) {
|
|
2618
|
+
return send(res, 409, {
|
|
2619
|
+
ok: false,
|
|
2620
|
+
error: "通道列表已由插件配置 tsnetChannels 固定,界面不能修改",
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
const existing = effectiveTailnetChannels(config);
|
|
2624
|
+
const byId = new Map(existing.map((c) => [c.id, c]));
|
|
2625
|
+
const used = new Set();
|
|
2626
|
+
const next = [];
|
|
2627
|
+
for (const item of body.channels) {
|
|
2628
|
+
if (!item || typeof item !== "object") continue;
|
|
2629
|
+
const rawLabel = String(item.label ?? "").trim().slice(0, 60);
|
|
2630
|
+
const rawControl = String(item.controlUrl ?? "").trim();
|
|
2631
|
+
let id = channelKey(item.id, "");
|
|
2632
|
+
if (!id) {
|
|
2633
|
+
// 新通道:宿主生成稳定 id。之后改显示名不会改变设备身份。
|
|
2634
|
+
do {
|
|
2635
|
+
id = `ch-${randomBytes(4).toString("hex")}`;
|
|
2636
|
+
} while (used.has(id) || byId.has(id) && !item.id);
|
|
2637
|
+
}
|
|
2638
|
+
if (used.has(id)) {
|
|
2639
|
+
return send(res, 400, { ok: false, error: `通道 id 重复:${id}` });
|
|
2640
|
+
}
|
|
2641
|
+
used.add(id);
|
|
2642
|
+
const prev = byId.get(id);
|
|
2643
|
+
const incomingKey = typeof item.authKey === "string" ? item.authKey.trim() : "";
|
|
2644
|
+
const authKey = item.clearAuthKey === true ? "" : incomingKey || prev?.authKey || "";
|
|
2645
|
+
next.push({
|
|
2646
|
+
id,
|
|
2647
|
+
label: rawLabel || prev?.label || `Tailnet ${next.length + 1}`,
|
|
2648
|
+
authKey,
|
|
2649
|
+
controlUrl: rawControl || prev?.controlUrl || "",
|
|
2650
|
+
hostname: String(item.hostname ?? "").trim() || prev?.hostname || "",
|
|
2651
|
+
enabled: item.enabled !== false,
|
|
2652
|
+
});
|
|
2653
|
+
}
|
|
2654
|
+
// 允许清空:这是"彻底关掉跨网络组网"的唯一可靠路径。必须同时清掉旧版
|
|
2655
|
+
// 单通道字段 —— 否则空列表会退回旧字段,把刚删掉的通道又变出来。
|
|
2656
|
+
if (next.length === 0) {
|
|
2657
|
+
await stopTailnetChannel("", discovery);
|
|
2658
|
+
saveState({
|
|
2659
|
+
tsnetChannels: [],
|
|
2660
|
+
tsnetEnabled: false,
|
|
2661
|
+
tsnetAuthKey: "",
|
|
2662
|
+
tsnetControlUrl: "",
|
|
2663
|
+
tsnetHostname: "",
|
|
2664
|
+
});
|
|
2665
|
+
log("tailnet 通道已全部删除,跨网络组网关闭");
|
|
2666
|
+
return send(res, 200, { ok: true, channels: [], enabled: false, authKeySaved: false, controlUrl: "", hostname: "" });
|
|
2667
|
+
}
|
|
2668
|
+
saveState({
|
|
2669
|
+
tsnetChannels: next,
|
|
2670
|
+
// 旧字段跟着走,避免老版本页面/回退时看到"未启用"
|
|
2671
|
+
tsnetEnabled: next.some((c) => c.enabled),
|
|
2672
|
+
});
|
|
2673
|
+
// 停掉被删掉、已禁用、或连接参数已变的通道;新配置由 /tsnet/start 拉起。
|
|
2674
|
+
// 参数变了却继续跑旧 sidecar,会留下"配置显示 A、实际连的是 B"的假象。
|
|
2675
|
+
for (const [id, node] of [...tailnetNodes.entries()]) {
|
|
2676
|
+
const spec = next.find((c) => c.id === id);
|
|
2677
|
+
const keep = spec && spec.enabled && node.signature === channelSignature(spec);
|
|
2678
|
+
if (!keep) {
|
|
2679
|
+
tailnetNodes.delete(id);
|
|
2680
|
+
await node.stop().catch(() => {});
|
|
2681
|
+
}
|
|
2682
|
+
}
|
|
2683
|
+
syncTailnetMeta(discovery);
|
|
2684
|
+
const views = tailnetViews();
|
|
2685
|
+
log(`tailnet 通道已保存:${next.map((c) => `${c.label}(${c.id})`).join("、")}`);
|
|
2686
|
+
return send(res, 200, {
|
|
2687
|
+
ok: true,
|
|
2688
|
+
channels: views,
|
|
2689
|
+
// 旧界面字段(取第一条启用通道)
|
|
2690
|
+
enabled: next.some((c) => c.enabled),
|
|
2691
|
+
authKeySaved: views.some((v) => v.authKeySaved),
|
|
2692
|
+
controlUrl: views[0]?.controlUrl ?? "",
|
|
2693
|
+
hostname: views[0]?.hostname ?? "",
|
|
2694
|
+
});
|
|
2695
|
+
}
|
|
2696
|
+
|
|
2697
|
+
// ── 旧版单通道字段(兼容已部署页面 / 脚本)──
|
|
2698
|
+
//
|
|
2699
|
+
// 如果已经有多通道列表,就作用到第一条(优先 default)通道上。
|
|
2700
|
+
// 直接忽略会变成"界面说保存成功、实际什么都没变"—— 这个项目最怕的静默失败。
|
|
2701
|
+
const currentChannels = effectiveTailnetChannels(config);
|
|
2702
|
+
if (currentChannels.length > 0 && !tailnetChannelsPinned()) {
|
|
2703
|
+
const next = currentChannels.map((c) => ({
|
|
2704
|
+
id: c.id,
|
|
2705
|
+
label: c.label,
|
|
2706
|
+
authKey: c.authKey,
|
|
2707
|
+
controlUrl: c.controlUrl,
|
|
2708
|
+
hostname: c.hostname,
|
|
2709
|
+
enabled: c.enabled,
|
|
2710
|
+
}));
|
|
2711
|
+
const target = next.find((c) => c.id === "default") ?? next[0];
|
|
2712
|
+
if (typeof body?.authKey === "string" && body.authKey.trim()) target.authKey = body.authKey.trim();
|
|
2713
|
+
if (body?.clearAuthKey === true) target.authKey = "";
|
|
2714
|
+
if (typeof body?.controlUrl === "string") target.controlUrl = body.controlUrl.trim();
|
|
2715
|
+
if (typeof body?.hostname === "string") target.hostname = body.hostname.trim();
|
|
2716
|
+
if (typeof body?.enabled === "boolean") target.enabled = body.enabled;
|
|
2717
|
+
saveState({ tsnetChannels: next, tsnetEnabled: next.some((c) => c.enabled) });
|
|
2718
|
+
log(`tailnet 配置已更新(作用于通道 ${target.id}):启用=${target.enabled} 授权码=${target.authKey ? "已保存" : "未设置"}`);
|
|
2719
|
+
const views = tailnetViews();
|
|
2720
|
+
return send(res, 200, {
|
|
2721
|
+
ok: true,
|
|
2722
|
+
channels: views,
|
|
2723
|
+
authKeySaved: views.some((v) => v.authKeySaved),
|
|
2724
|
+
controlUrl: target.controlUrl ?? "",
|
|
2725
|
+
hostname: target.hostname ?? "",
|
|
2726
|
+
enabled: views.some((v) => v.enabled),
|
|
2727
|
+
});
|
|
2728
|
+
}
|
|
2729
|
+
|
|
2417
2730
|
const patch = {};
|
|
2418
2731
|
if (typeof body?.authKey === "string" && body.authKey.trim()) patch.tsnetAuthKey = body.authKey.trim();
|
|
2419
2732
|
if (body?.clearAuthKey === true) patch.tsnetAuthKey = "";
|
|
@@ -2422,12 +2735,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2422
2735
|
if (typeof body?.enabled === "boolean") patch.tsnetEnabled = body.enabled;
|
|
2423
2736
|
const saved = saveState(patch);
|
|
2424
2737
|
log(
|
|
2425
|
-
`tailnet
|
|
2738
|
+
`tailnet 旧版单通道配置已更新:启用=${saved.tsnetEnabled === true} ` +
|
|
2426
2739
|
`授权码=${patch.tsnetAuthKey ? "已保存" : saved.tsnetAuthKey ? "保留原值" : "未设置"} ` +
|
|
2427
2740
|
`控制服务器=${saved.tsnetControlUrl || "官方"}`,
|
|
2428
2741
|
);
|
|
2429
2742
|
return send(res, 200, {
|
|
2430
2743
|
ok: true,
|
|
2744
|
+
channels: tailnetViews(),
|
|
2431
2745
|
// 绝不回传授权码内容,只回报是否已配置
|
|
2432
2746
|
authKeySaved: Boolean(saved.tsnetAuthKey),
|
|
2433
2747
|
controlUrl: saved.tsnetControlUrl ?? "",
|
|
@@ -2436,65 +2750,115 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2436
2750
|
});
|
|
2437
2751
|
});
|
|
2438
2752
|
|
|
2439
|
-
/**
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2753
|
+
/**
|
|
2754
|
+
* 启动(或按最新配置重启)tailnet 通道。
|
|
2755
|
+
*
|
|
2756
|
+
* body.id 省略 = 启动所有启用的通道(兼容旧页面点「只启动」)。
|
|
2757
|
+
*/
|
|
2758
|
+
post("/mesh/api/tsnet/start", async (req, res) => {
|
|
2759
|
+
const body = await readJson(req);
|
|
2760
|
+
const wantId = String(body?.id ?? "").trim();
|
|
2761
|
+
const all = effectiveTailnetChannels(config);
|
|
2762
|
+
const targets = wantId ? all.filter((c) => c.id === channelKey(wantId)) : all.filter((c) => c.enabled);
|
|
2763
|
+
if (targets.length === 0) {
|
|
2764
|
+
return send(res, 404, { ok: false, error: wantId ? `没有 id 为 ${wantId} 的通道` : "没有启用的 tailnet 通道" });
|
|
2445
2765
|
}
|
|
2446
|
-
const
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2766
|
+
const started = [];
|
|
2767
|
+
for (const channel of targets) {
|
|
2768
|
+
try {
|
|
2769
|
+
const { reused } = await startTailnetChannel(channel, {
|
|
2770
|
+
config,
|
|
2771
|
+
discovery,
|
|
2772
|
+
log,
|
|
2773
|
+
warn,
|
|
2774
|
+
machineName: identity.name,
|
|
2775
|
+
});
|
|
2776
|
+
started.push({ id: channel.id, ok: true, reused });
|
|
2777
|
+
} catch (err) {
|
|
2778
|
+
started.push({ id: channel.id, ok: false, error: String(err?.message ?? err) });
|
|
2779
|
+
}
|
|
2455
2780
|
}
|
|
2781
|
+
await runScan({ discovery, config, log, warn, reason: "tailnet 手动扫描" }).catch(() => {});
|
|
2782
|
+
const ok = started.some((r) => r.ok);
|
|
2783
|
+
const first = targets[0];
|
|
2784
|
+
return send(res, 200, {
|
|
2785
|
+
ok,
|
|
2786
|
+
results: started,
|
|
2787
|
+
error: ok ? undefined : started.map((r) => `${r.id}: ${r.error}`).join(";"),
|
|
2788
|
+
node: tailnetNodes.get(first.id)?.status() ?? null,
|
|
2789
|
+
channels: tailnetViews(),
|
|
2790
|
+
});
|
|
2456
2791
|
});
|
|
2457
2792
|
|
|
2458
2793
|
/**
|
|
2459
|
-
* 停止 tailnet
|
|
2794
|
+
* 停止 tailnet 通道(body.id 省略 = 全部)。
|
|
2460
2795
|
*
|
|
2461
2796
|
* 这里**不能**传 keepRemote:stop() 在 "非 owner 或 keepRemote" 时走保留分支,
|
|
2462
2797
|
* 而无条件传 true 会让本实例自己拉起的 sidecar 也停不掉(实测点「停止」后
|
|
2463
2798
|
* 进程仍在跑、rendezvous 也没清)。不传参数即按归属判断:自己拉起的关掉,
|
|
2464
2799
|
* 复用别人的只注销自己的 forward。
|
|
2465
2800
|
*/
|
|
2466
|
-
post("/mesh/api/tsnet/stop", async (
|
|
2467
|
-
const
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2801
|
+
post("/mesh/api/tsnet/stop", async (req, res) => {
|
|
2802
|
+
const body = await readJson(req);
|
|
2803
|
+
const wantId = String(body?.id ?? "").trim();
|
|
2804
|
+
const stopped = await stopTailnetChannel(wantId ? channelKey(wantId) : "", discovery);
|
|
2805
|
+
log(`tailnet ${wantId ? `通道 ${wantId} ` : "全部通道"}已停止(${stopped} 个)`);
|
|
2806
|
+
return send(res, 200, { ok: true, stopped, channels: tailnetViews() });
|
|
2471
2807
|
});
|
|
2472
2808
|
|
|
2473
|
-
/** 清掉节点身份重新登录(授权码失效 / 换账号时用)。 */
|
|
2474
|
-
post("/mesh/api/tsnet/relogin", async (
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2809
|
+
/** 清掉节点身份重新登录(授权码失效 / 换账号时用)。body.id 省略 = 所有在跑的通道。 */
|
|
2810
|
+
post("/mesh/api/tsnet/relogin", async (req, res) => {
|
|
2811
|
+
const body = await readJson(req);
|
|
2812
|
+
const wantId = String(body?.id ?? "").trim();
|
|
2813
|
+
const ids = wantId ? [channelKey(wantId)] : [...tailnetNodes.keys()];
|
|
2814
|
+
const nodes = ids.map((id) => tailnetNodes.get(id)).filter(Boolean);
|
|
2815
|
+
if (nodes.length === 0) return send(res, 409, { ok: false, error: "互联网组网未启动" });
|
|
2816
|
+
const done = [];
|
|
2817
|
+
for (const node of nodes) {
|
|
2818
|
+
try {
|
|
2819
|
+
await node.relogin();
|
|
2820
|
+
if (discovery.port) await node.registerForward(discovery.port);
|
|
2821
|
+
done.push({ id: node.channelKey, ok: true, node: node.status() });
|
|
2822
|
+
} catch (err) {
|
|
2823
|
+
done.push({ id: node.channelKey, ok: false, error: String(err?.message ?? err), node: node.status() });
|
|
2824
|
+
}
|
|
2482
2825
|
}
|
|
2826
|
+
syncTailnetMeta(discovery);
|
|
2827
|
+
const ok = done.some((r) => r.ok);
|
|
2828
|
+
return send(res, 200, {
|
|
2829
|
+
ok,
|
|
2830
|
+
results: done,
|
|
2831
|
+
node: nodes[0].status(),
|
|
2832
|
+
channels: tailnetViews(),
|
|
2833
|
+
});
|
|
2483
2834
|
});
|
|
2484
2835
|
|
|
2485
|
-
/**
|
|
2486
|
-
|
|
2487
|
-
|
|
2836
|
+
/**
|
|
2837
|
+
* 重新下载 sidecar 二进制(下载损坏或换平台时用)。
|
|
2838
|
+
*
|
|
2839
|
+
* 二进制是**整机共享**的:先停掉所有通道再换文件,否则 Windows 上文件锁着
|
|
2840
|
+
* 换不掉;换完不自动重启,按旧行为留给用户点「连接」。
|
|
2841
|
+
*/
|
|
2842
|
+
post("/mesh/api/tsnet/reinstall", async (req, res) => {
|
|
2843
|
+
const body = await readJson(req);
|
|
2844
|
+
const wantId = String(body?.id ?? "").trim();
|
|
2845
|
+
const channels = effectiveTailnetChannels(config);
|
|
2846
|
+
const target = (wantId ? channels.find((c) => c.id === channelKey(wantId)) : null) ?? channels[0] ?? null;
|
|
2847
|
+
if (!target) return send(res, 409, { ok: false, error: "还没有配置 tailnet 通道" });
|
|
2848
|
+
await stopTailnetChannel("", discovery);
|
|
2849
|
+
const node = new TsnetNode({ config, channel: target, log, warn, machineName: identity.name });
|
|
2488
2850
|
try {
|
|
2489
|
-
const r = await
|
|
2851
|
+
const r = await node.reinstallBinary();
|
|
2490
2852
|
return send(res, 200, { ok: true, path: r.path, source: r.source });
|
|
2491
2853
|
} catch (err) {
|
|
2492
2854
|
return send(res, 200, { ok: false, error: String(err?.message ?? err) });
|
|
2493
2855
|
}
|
|
2494
2856
|
});
|
|
2495
2857
|
|
|
2496
|
-
/** 只扫 tailnet,不扫局域网。 */
|
|
2497
|
-
post("/mesh/api/tsnet/scan", async (
|
|
2858
|
+
/** 只扫 tailnet,不扫局域网。body.id 省略 = 所有在跑的通道。 */
|
|
2859
|
+
post("/mesh/api/tsnet/scan", async (req, res) => {
|
|
2860
|
+
const body = await readJson(req);
|
|
2861
|
+
const wantId = String(body?.id ?? "").trim();
|
|
2498
2862
|
const before = new Set(discovery.peers().map((p) => p.id));
|
|
2499
2863
|
const result = await scanTailnet({
|
|
2500
2864
|
discovery,
|
|
@@ -2502,12 +2866,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2502
2866
|
log,
|
|
2503
2867
|
reason: "tailnet 手动扫描",
|
|
2504
2868
|
ports: scanPortList(discovery, config),
|
|
2869
|
+
channelId: wantId ? channelKey(wantId) : "",
|
|
2505
2870
|
});
|
|
2506
2871
|
const added = discovery.peers().filter((p) => !before.has(p.id));
|
|
2507
2872
|
return send(res, 200, {
|
|
2508
2873
|
ok: true,
|
|
2509
2874
|
...result,
|
|
2510
|
-
added: added.map((p) => ({ machine: p.machine, host: p.host, port: p.port })),
|
|
2875
|
+
added: added.map((p) => ({ machine: p.machine, host: p.host, port: p.port, channel: p.channel })),
|
|
2511
2876
|
});
|
|
2512
2877
|
});
|
|
2513
2878
|
|