dsh-plugin-mesh 0.5.4 → 0.5.6
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 +4 -2
- package/README.md +61 -1
- package/client/client.js +1122 -17
- package/lib/_selftest-reply-route.mjs +80 -2
- package/lib/_selftest-switch.mjs +142 -0
- package/lib/_selftest-tsnet.mjs +86 -1
- package/lib/_selftest-workbench.mjs +236 -0
- package/lib/desktop-auth.js +88 -0
- package/lib/desktop-web.js +146 -0
- package/lib/index.js +1022 -109
- package/lib/ssh-host.js +380 -0
- package/lib/switch.js +110 -0
- package/lib/tsnet/manager.js +129 -3
- package/lib/web-proxy.js +333 -0
- package/lib/ws-mini.js +156 -0
- package/llms.txt +61 -1
- package/package.json +8 -4
- package/scripts/check-tarball.mjs +1 -0
package/lib/index.js
CHANGED
|
@@ -48,6 +48,13 @@ import { conversationKey, replyTarget } from "./conversation.js";
|
|
|
48
48
|
import { buildDiagnostics, entryInfo, readPackageVersion } from "./diagnostics.js";
|
|
49
49
|
import { buildPrompt } from "./prompt.js";
|
|
50
50
|
import { resolvePairing } from "./pairing.js";
|
|
51
|
+
import {
|
|
52
|
+
applyMeshSwitch,
|
|
53
|
+
describeMeshSwitch,
|
|
54
|
+
normalizeSwitchScope,
|
|
55
|
+
resolveMeshSwitch,
|
|
56
|
+
MESH_SWITCH_LABEL,
|
|
57
|
+
} from "./switch.js";
|
|
51
58
|
import {
|
|
52
59
|
loadTaskHistory,
|
|
53
60
|
saveTaskHistory,
|
|
@@ -57,23 +64,37 @@ import {
|
|
|
57
64
|
import { TsnetNode, channelKey, channelSignature } from "./tsnet/manager.js";
|
|
58
65
|
import { resolveTailnetChannels } from "./tsnet/channels.js";
|
|
59
66
|
import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
|
|
67
|
+
import { createWebProxy } from "./web-proxy.js";
|
|
68
|
+
import { createSecretReader } from "./desktop-auth.js";
|
|
69
|
+
import { createSshManager } from "./ssh-host.js";
|
|
70
|
+
import { acceptUpgrade } from "./ws-mini.js";
|
|
71
|
+
import {
|
|
72
|
+
createDesktopWebForwarder,
|
|
73
|
+
createDesktopWebUpgrade,
|
|
74
|
+
DESKTOP_WEB_PREFIX,
|
|
75
|
+
DESKTOP_WEB_STREAM_PATH,
|
|
76
|
+
} from "./desktop-web.js";
|
|
60
77
|
|
|
61
78
|
export const name = "dsh-plugin-mesh";
|
|
62
79
|
export const inject = ["tools", "webServer"];
|
|
63
80
|
|
|
64
|
-
const VERSION = "0.5.
|
|
81
|
+
const VERSION = "0.5.6";
|
|
65
82
|
// 诊断用:进程启动时间、入口真实路径、**磁盘上** package.json 的版本。
|
|
66
83
|
// 这三样放一起才能回答"现在跑的到底是哪份代码" —— 只看 state.json 或重启日志
|
|
67
84
|
// 都答不了(真踩过:磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
|
|
68
85
|
const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
|
|
69
86
|
const ENTRY_INFO = entryInfo(import.meta.url);
|
|
70
87
|
const DISK_VERSION = readPackageVersion(import.meta.url);
|
|
88
|
+
/** 一次性取文件用的 nonce:进程每次启动都换,写进日志给运维/agent 取。 */
|
|
89
|
+
const FILE_TRANSFER_NONCE = randomBytes(9).toString("base64url");
|
|
71
90
|
const RULE_ID = "mesh-inbound";
|
|
72
91
|
const RULE_KIND = "mesh";
|
|
73
92
|
const MAX_BODY = 256 * 1024;
|
|
74
93
|
const MAX_HISTORY = 200;
|
|
75
94
|
/** 默认固定端口:内网里"扫这个端口 + ping 一下"就能建立连接,无需任何配置。 */
|
|
76
95
|
export const MESH_DEFAULT_PORT = 45917;
|
|
96
|
+
/** 对端 DSH Web 的部署默认端口(回环代理拿不到对端自报地址时按它拼)。 */
|
|
97
|
+
const WEB_PANEL_DEFAULT_PORT = 3080;
|
|
77
98
|
|
|
78
99
|
/**
|
|
79
100
|
* 互联网自组网(tailnet)通道:通道 id → 节点句柄。
|
|
@@ -92,6 +113,19 @@ const tailnetNodes = new Map();
|
|
|
92
113
|
*/
|
|
93
114
|
let activeDiscovery = null;
|
|
94
115
|
|
|
116
|
+
/**
|
|
117
|
+
* 传输开关(一键关闭):`true` = 这条路径可用。
|
|
118
|
+
*
|
|
119
|
+
* 由 applyUnsafe 按 state.json 里的 `shutdown` 维护,发送路径(peerFetch)、
|
|
120
|
+
* 扫描(runScan / scanTailnet)、保活(pingKnownPeers)都读它 —— 关掉一条
|
|
121
|
+
* 路径之后,不能再"从别的地方偷偷用它":那正是这类开关最典型的 bug
|
|
122
|
+
* (界面显示已关闭,实际还在发包)。
|
|
123
|
+
*
|
|
124
|
+
* 放模块级的原因和 activeDiscovery 一样:peerFetch / runScan / pingKnownPeers
|
|
125
|
+
* 都是模块级函数,而开关状态属于本次挂载的实例。
|
|
126
|
+
*/
|
|
127
|
+
export const transportGate = { lan: true, internet: true };
|
|
128
|
+
|
|
95
129
|
/**
|
|
96
130
|
* 会话键 → 正在为它建会话期间堆积的消息。
|
|
97
131
|
*
|
|
@@ -134,6 +168,12 @@ export const Config = z.object({
|
|
|
134
168
|
* 同机跑多个实例时会被占用,此时自动退回随机端口(仍能用组播互相发现)。
|
|
135
169
|
*/
|
|
136
170
|
port: z.natural().default(MESH_DEFAULT_PORT),
|
|
171
|
+
/**
|
|
172
|
+
* 本机另一个 DSH 引擎(通常是桌面 App)的 Web 端口:0 = 关闭这条前缀代理。
|
|
173
|
+
* 开了之后 `<本机>:<port>/mesh/web/...` 会转发到 127.0.0.1:<desktopWebPort>,
|
|
174
|
+
* 并自带签名 cookie —— 供手机在应用内查看"有历史会话的那个引擎"。
|
|
175
|
+
*/
|
|
176
|
+
desktopWebPort: z.natural().max(65535).default(0),
|
|
137
177
|
announceIntervalMs: z.natural().default(5000),
|
|
138
178
|
/** 超过这么久没心跳、也没 ping 通,算离线 */
|
|
139
179
|
peerTtlMs: z.natural().default(20000),
|
|
@@ -823,118 +863,382 @@ function applyUnsafe(ctx, config) {
|
|
|
823
863
|
capabilities: currentCapabilities(),
|
|
824
864
|
});
|
|
825
865
|
|
|
826
|
-
//
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
866
|
+
// ── 一键关闭(kill switch)的运行时 ──
|
|
867
|
+
//
|
|
868
|
+
// 三条原则:
|
|
869
|
+
// 1. **不卸载插件、不注销 UI 路由**。关掉之后面板还得能打开 —— 否则
|
|
870
|
+
// 「一键关闭」就成了「一键把自己锁在外面」。
|
|
871
|
+
// 2. 关掉一条路径之后,任何出站/入站都不能再偷偷用它(发送、扫描、ping、
|
|
872
|
+
// 对端 HTTP 都读 transportGate)。这类开关最典型的 bug 就是界面显示
|
|
873
|
+
// 已关闭、实际还在发包。
|
|
874
|
+
// 3. 期望状态和真实状态**分开回报**。重绑回环失败时界面必须看得见,
|
|
875
|
+
// 不能拿"用户点了关闭"当"已经关好了"。
|
|
876
|
+
//
|
|
877
|
+
// 局域网关 = 组播停发、不再扫本网段 / ping,对端端口从 0.0.0.0 收回 127.0.0.1
|
|
878
|
+
// (tailnet 的 sidecar 是反代到本机回环的,所以互联网那半还能用)。
|
|
879
|
+
// 互联网关 = 停掉全部 tailnet sidecar;通道配置保留,打开即恢复。
|
|
880
|
+
// 期望状态写进 state.json 的 shutdown,重启后照旧。
|
|
881
|
+
let switchDesired = resolveMeshSwitch(loadState());
|
|
882
|
+
transportGate.lan = !switchDesired.lan;
|
|
883
|
+
transportGate.internet = !switchDesired.internet;
|
|
884
|
+
|
|
885
|
+
/** 当前监听中的对端服务句柄:{ port, host, server }。关闭时为 null。 */
|
|
886
|
+
let peerServer = null;
|
|
887
|
+
/** 上一次成功监听的端口:重开时优先沿用它,别让对端记着的地址失效。 */
|
|
888
|
+
let lastPort = 0;
|
|
889
|
+
/** 互联网是否已经尝试启动过(避免每次点开关都重走一遍 sidecar 启动)。 */
|
|
890
|
+
let internetUp = false;
|
|
891
|
+
/** 本次运行时起的定时器(扫描 / ping),重排时统一清掉。 */
|
|
892
|
+
let runtimeTimers = [];
|
|
893
|
+
/** 每次重排 +1:旧的异步扫描循环靠它自杀,不会在关闭后继续发包。 */
|
|
894
|
+
let lanGeneration = 0;
|
|
895
|
+
/** discovery 当前是否带组播启动(null = 没启动)。 */
|
|
896
|
+
let discoveryMulticast = null;
|
|
897
|
+
/** 运行时偏差说明:非空 = 没能完全按开关执行,界面要显示。 */
|
|
898
|
+
const switchNote = { lan: "", internet: "" };
|
|
899
|
+
/** 开关操作串行化:界面和 agent 可能同时点,不能让两个 reconcile 交错。 */
|
|
900
|
+
let switching = Promise.resolve();
|
|
901
|
+
|
|
902
|
+
const serialize = (fn) => {
|
|
903
|
+
const run = switching.then(fn, fn);
|
|
904
|
+
switching = run.then(() => undefined, () => undefined);
|
|
905
|
+
return run;
|
|
906
|
+
};
|
|
830
907
|
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
discovery.announceNow();
|
|
836
|
-
} else {
|
|
837
|
-
log("已关闭组播,仅使用主动扫描 + ping");
|
|
838
|
-
}
|
|
908
|
+
const shutRuntimeTimers = () => {
|
|
909
|
+
for (const t of runtimeTimers) clearInterval(t);
|
|
910
|
+
runtimeTimers = [];
|
|
911
|
+
};
|
|
839
912
|
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
913
|
+
/**
|
|
914
|
+
* 关掉对端服务并等它真正释放端口。
|
|
915
|
+
*
|
|
916
|
+
* 必须等 close 回调:紧接着就要在同一端口用另一个地址重新 listen,
|
|
917
|
+
* 不等的话会撞 EADDRINUSE,重绑静默失败 —— 那正是"显示关了、其实还开着"。
|
|
918
|
+
* 1.5s 兜底:极端情况下不让开关卡死。
|
|
919
|
+
*/
|
|
920
|
+
const closePeerServer = () =>
|
|
921
|
+
new Promise((resolveClose) => {
|
|
922
|
+
const handle = peerServer;
|
|
923
|
+
peerServer = null;
|
|
924
|
+
if (!handle) {
|
|
925
|
+
resolveClose();
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
let settled = false;
|
|
929
|
+
const done = () => {
|
|
930
|
+
if (settled) return;
|
|
931
|
+
settled = true;
|
|
932
|
+
resolveClose();
|
|
933
|
+
};
|
|
934
|
+
try {
|
|
935
|
+
handle.server.closeAllConnections?.();
|
|
936
|
+
} catch {
|
|
937
|
+
/* 老版本 Node 没有这个方法 */
|
|
938
|
+
}
|
|
939
|
+
try {
|
|
940
|
+
handle.server.close(done);
|
|
941
|
+
} catch {
|
|
942
|
+
done();
|
|
943
|
+
}
|
|
944
|
+
const t = setTimeout(done, 1500);
|
|
945
|
+
t.unref?.();
|
|
946
|
+
});
|
|
845
947
|
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
948
|
+
/**
|
|
949
|
+
* 起 / 重绑对端服务。`bindHost` 决定局域网是否可达:
|
|
950
|
+
* 0.0.0.0 → 局域网可连(局域网打开时)
|
|
951
|
+
* 127.0.0.1 → 只有本机(和 sidecar 反代)能连
|
|
952
|
+
*
|
|
953
|
+
* 重绑沿用**上一次的真实端口**,否则对端记着的地址、tailnet 的 forward 全部失效。
|
|
954
|
+
*/
|
|
955
|
+
const ensurePeerServer = async (bindHost) => {
|
|
956
|
+
if (peerServer && peerServer.host === bindHost) return peerServer;
|
|
957
|
+
const keepPort = peerServer ? peerServer.port : lastPort || undefined;
|
|
958
|
+
await closePeerServer();
|
|
959
|
+
const handle = await startPeerServer(ctx, {
|
|
960
|
+
config,
|
|
961
|
+
discovery,
|
|
962
|
+
inbound,
|
|
963
|
+
outbound,
|
|
964
|
+
log,
|
|
965
|
+
warn,
|
|
966
|
+
waker,
|
|
967
|
+
threadState,
|
|
968
|
+
capFor,
|
|
969
|
+
capOverrides,
|
|
970
|
+
throttled,
|
|
971
|
+
onHistoryChange: scheduleHistorySave,
|
|
972
|
+
diagnostics: diagnosticsPayload,
|
|
973
|
+
port: keepPort,
|
|
974
|
+
bindHost,
|
|
975
|
+
});
|
|
976
|
+
peerServer = handle;
|
|
977
|
+
lastPort = handle.port;
|
|
978
|
+
discovery.setPort(handle.port);
|
|
979
|
+
return handle;
|
|
980
|
+
};
|
|
851
981
|
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
982
|
+
/**
|
|
983
|
+
* 起互联网(tailnet)通道。
|
|
984
|
+
*
|
|
985
|
+
* 串行启动:每条 sidecar 首次都要下载 30MB 二进制,并发会互相抢。
|
|
986
|
+
* 一条失败不影响其它条,也不影响局域网 —— 这是硬要求。
|
|
987
|
+
*/
|
|
988
|
+
const ensureInternet = async (reason = "") => {
|
|
989
|
+
if (!transportGate.internet) return;
|
|
990
|
+
const channels = effectiveTailnetChannels(config).filter((c) => c.enabled);
|
|
991
|
+
if (channels.length === 0) {
|
|
992
|
+
log("互联网自组网未启用(没有启用的 tailnet 通道)");
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
internetUp = true;
|
|
996
|
+
switchNote.internet = "";
|
|
997
|
+
for (const channel of channels) {
|
|
998
|
+
if (!transportGate.internet) {
|
|
999
|
+
// 启动途中被关掉:立刻收手,并把可能已经拉起来的 sidecar 收干净
|
|
1000
|
+
await stopTailnetChannel(channel.id, discovery).catch(() => 0);
|
|
1001
|
+
return;
|
|
1002
|
+
}
|
|
1003
|
+
try {
|
|
1004
|
+
const { node, reused } = await startTailnetChannel(channel, {
|
|
1005
|
+
config,
|
|
1006
|
+
discovery,
|
|
1007
|
+
log,
|
|
1008
|
+
warn,
|
|
1009
|
+
machineName: identity.name,
|
|
862
1010
|
});
|
|
1011
|
+
const st = node.status();
|
|
1012
|
+
log(
|
|
1013
|
+
`通道「${channel.label}」已启动:节点=${node.hostname} tailnet=${st.selfIpv4 || "待登录"}` +
|
|
1014
|
+
`${reused ? "(复用已有 sidecar)" : ""}${st.authUrl ? ` 授权链接=${st.authUrl}` : ""}`,
|
|
1015
|
+
);
|
|
1016
|
+
} catch (err) {
|
|
1017
|
+
warn(`通道「${channel.label}」启动失败(局域网与其它通道不受影响):${err?.message ?? err}`);
|
|
1018
|
+
switchNote.internet = `通道「${channel.label}」启动失败:${err?.message ?? err}`;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (!transportGate.internet) return;
|
|
1022
|
+
// 所有通道都起来之后再扫一轮,让 tailnet 设备尽快进列表
|
|
1023
|
+
await scanTailnet({
|
|
1024
|
+
discovery,
|
|
1025
|
+
config,
|
|
1026
|
+
log,
|
|
1027
|
+
reason: reason || "tailnet 启动扫描",
|
|
1028
|
+
ports: scanPortList(discovery, config),
|
|
1029
|
+
}).catch(() => {});
|
|
1030
|
+
};
|
|
863
1031
|
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
1032
|
+
/**
|
|
1033
|
+
* 局域网发现:启动扫描(含退避重试)与周期扫描。
|
|
1034
|
+
* ping 保活由 syncRuntime 统一管(互联网开着也要 ping)。
|
|
1035
|
+
*/
|
|
1036
|
+
const startLanDiscovery = () => {
|
|
1037
|
+
const gen = lanGeneration;
|
|
1038
|
+
if (config.scanOnStart) {
|
|
1039
|
+
// 启动扫描常常抢在对方起来之前跑完,所以没找到就退避重试几次。
|
|
1040
|
+
// 这直接决定"刚装好能不能自动发现",值得多试几下。
|
|
1041
|
+
const delays = [0, 8000, 20000, 45000];
|
|
1042
|
+
(async () => {
|
|
1043
|
+
for (let i = 0; i < delays.length; i += 1) {
|
|
1044
|
+
if (gen !== lanGeneration || !transportGate.lan) return;
|
|
1045
|
+
if (delays[i] > 0) await sleep(delays[i]);
|
|
1046
|
+
if (gen !== lanGeneration || !transportGate.lan) return;
|
|
1047
|
+
await runScan({ discovery, config, log, warn, reason: `启动扫描#${i + 1}` });
|
|
1048
|
+
if (discovery.peers().length > 0) return; // 找到了就不再重试
|
|
1049
|
+
}
|
|
1050
|
+
log("启动扫描未发现对端;之后靠组播与周期扫描继续尝试");
|
|
1051
|
+
})().catch(() => {});
|
|
1052
|
+
}
|
|
1053
|
+
if (config.scanIntervalMs > 0) {
|
|
1054
|
+
const t = setInterval(
|
|
1055
|
+
() => runScan({ discovery, config, log, warn, reason: "周期扫描" }).catch(() => {}),
|
|
1056
|
+
config.scanIntervalMs,
|
|
1057
|
+
);
|
|
1058
|
+
t.unref?.();
|
|
1059
|
+
runtimeTimers.push(t);
|
|
1060
|
+
}
|
|
1061
|
+
};
|
|
1062
|
+
|
|
1063
|
+
/**
|
|
1064
|
+
* 把运行时对齐到期望的开关状态。幂等:启动时调一次,之后每次开关都调。
|
|
1065
|
+
*/
|
|
1066
|
+
const syncRuntime = async ({ reason = "" } = {}) => {
|
|
1067
|
+
lanGeneration += 1;
|
|
1068
|
+
shutRuntimeTimers();
|
|
1069
|
+
const wantLan = !switchDesired.lan;
|
|
1070
|
+
const wantNet = !switchDesired.internet;
|
|
1071
|
+
transportGate.lan = wantLan;
|
|
1072
|
+
transportGate.internet = wantNet;
|
|
1073
|
+
|
|
1074
|
+
// ── 互联网 ──
|
|
1075
|
+
if (!wantNet) {
|
|
1076
|
+
const stopped = await stopTailnetChannel("", discovery).catch(() => 0);
|
|
1077
|
+
internetUp = false;
|
|
1078
|
+
switchNote.internet = "";
|
|
1079
|
+
if (stopped > 0) log(`互联网 mesh 已关闭:停止 ${stopped} 条 tailnet 通道(通道配置保留)`);
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
// ── 局域网 ──
|
|
1083
|
+
if (!wantLan && !wantNet) {
|
|
1084
|
+
await closePeerServer();
|
|
1085
|
+
if (discoveryMulticast !== null) {
|
|
1086
|
+
discovery.stop();
|
|
1087
|
+
discoveryMulticast = null;
|
|
1088
|
+
}
|
|
1089
|
+
switchNote.lan = "";
|
|
1090
|
+
} else {
|
|
1091
|
+
// 互联网开着就必须留着对端服务(tailnet 入站靠 sidecar 反代到本机回环)
|
|
1092
|
+
const bindHost = wantLan ? "0.0.0.0" : "127.0.0.1";
|
|
1093
|
+
try {
|
|
1094
|
+
await ensurePeerServer(bindHost);
|
|
1095
|
+
switchNote.lan = "";
|
|
1096
|
+
} catch (err) {
|
|
1097
|
+
switchNote.lan = `对端服务未能监听 ${bindHost}:${discovery.port || "?"} —— ${err?.message ?? err}`;
|
|
1098
|
+
warn(switchNote.lan);
|
|
1099
|
+
}
|
|
1100
|
+
// 组播只在局域网打开时启用:关掉之后连收包都不做。
|
|
1101
|
+
const multicast = wantLan && config.useMulticast !== false;
|
|
1102
|
+
if (discoveryMulticast !== multicast) {
|
|
1103
|
+
if (discoveryMulticast !== null) discovery.stop();
|
|
1104
|
+
discovery.start({ multicast });
|
|
1105
|
+
discoveryMulticast = multicast;
|
|
1106
|
+
}
|
|
1107
|
+
if (multicast) {
|
|
1108
|
+
discovery.announceNow();
|
|
1109
|
+
} else if (wantNet) {
|
|
1110
|
+
log("局域网 mesh 已关闭:不广播、不扫本网段,对端端口只绑回环");
|
|
888
1111
|
} else {
|
|
889
|
-
log("
|
|
1112
|
+
log("已关闭组播,仅使用主动扫描 + ping");
|
|
890
1113
|
}
|
|
1114
|
+
if (wantLan) startLanDiscovery();
|
|
1115
|
+
}
|
|
891
1116
|
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
(async () => {
|
|
897
|
-
for (let i = 0; i < delays.length; i += 1) {
|
|
898
|
-
if (stop.aborted) return;
|
|
899
|
-
if (delays[i] > 0) await sleep(delays[i]);
|
|
900
|
-
if (stop.aborted) return;
|
|
901
|
-
await runScan({ discovery, config, log, warn, signal: stop, reason: `启动扫描#${i + 1}` });
|
|
902
|
-
if (discovery.peers().length > 0) return; // 找到了就不再重试
|
|
903
|
-
}
|
|
904
|
-
log("启动扫描未发现对端;之后靠组播与周期扫描继续尝试");
|
|
905
|
-
})().catch(() => {});
|
|
906
|
-
}
|
|
1117
|
+
// ── 互联网启动(后台跑:首次要下载 sidecar,不能让界面/接口干等)──
|
|
1118
|
+
if (wantNet && !internetUp) {
|
|
1119
|
+
void ensureInternet(reason).catch((err) => warn(`互联网通道启动异常:${err?.message ?? err}`));
|
|
1120
|
+
}
|
|
907
1121
|
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
1122
|
+
// ── ping 保活:只要还有一条通道活着就要跑;pingKnownPeers 自己按开关过滤 ──
|
|
1123
|
+
if ((wantLan || wantNet) && config.pingIntervalMs > 0) {
|
|
1124
|
+
const t = setInterval(
|
|
1125
|
+
() => pingKnownPeers({ discovery, config, warn }).catch(() => {}),
|
|
1126
|
+
config.pingIntervalMs,
|
|
1127
|
+
);
|
|
1128
|
+
t.unref?.();
|
|
1129
|
+
runtimeTimers.push(t);
|
|
1130
|
+
}
|
|
1131
|
+
};
|
|
916
1132
|
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
1133
|
+
/**
|
|
1134
|
+
* 对外回报的开关状态:期望值 + 真实运行情况 + 偏差说明。
|
|
1135
|
+
* 界面和 agent 都读这一份,避免两处各编一套说法。
|
|
1136
|
+
*/
|
|
1137
|
+
const switchStatus = () => {
|
|
1138
|
+
const lanOff = switchDesired.lan;
|
|
1139
|
+
const netOff = switchDesired.internet;
|
|
1140
|
+
const bind = peerServer?.host ?? "";
|
|
1141
|
+
let lanNote = switchNote.lan;
|
|
1142
|
+
// 说得到就要做得到:关闭状态下如果还听着 0.0.0.0,必须明说。
|
|
1143
|
+
if (lanOff && bind && bind !== "127.0.0.1" && bind !== "::1" && bind !== "::ffff:127.0.0.1") {
|
|
1144
|
+
lanNote = lanNote || "端口仍对局域网开放(未能收回回环,检查端口占用)";
|
|
1145
|
+
}
|
|
1146
|
+
const running = runningTailnetNodes().length;
|
|
1147
|
+
// 互联网侧的真实麻烦(连不上控制面 / 授权码失效)必须出现在这里:
|
|
1148
|
+
// 「开启但没连上」如果只说成"未连接",用户会以为是正常在等。
|
|
1149
|
+
const stalled = [...tailnetNodes.values()]
|
|
1150
|
+
.map((n) => n.status())
|
|
1151
|
+
.filter((s) => s && s.stalled);
|
|
1152
|
+
const internetNote =
|
|
1153
|
+
switchNote.internet ||
|
|
1154
|
+
(stalled.length > 0
|
|
1155
|
+
? `有 ${stalled.length} 条通道启动受阻:${stalled[0].stalledReason || "控制面没有回应"}` +
|
|
1156
|
+
(stalled[0].stalledHint ? `(${stalled[0].stalledHint})` : "")
|
|
1157
|
+
: "");
|
|
1158
|
+
return {
|
|
1159
|
+
lan: {
|
|
1160
|
+
off: lanOff,
|
|
1161
|
+
// active 表示"真的在监听",不是"用户说它开着" —— 绑定失败时要能看出来
|
|
1162
|
+
active: !lanOff && Boolean(peerServer),
|
|
1163
|
+
bind,
|
|
1164
|
+
port: peerServer?.port ?? 0,
|
|
1165
|
+
multicast: discoveryMulticast === true,
|
|
1166
|
+
note: lanNote,
|
|
1167
|
+
},
|
|
1168
|
+
internet: {
|
|
1169
|
+
off: netOff,
|
|
1170
|
+
active: !netOff && running > 0,
|
|
1171
|
+
running,
|
|
1172
|
+
configured: effectiveTailnetChannels(config).filter((c) => c.enabled).length,
|
|
1173
|
+
/** 启动受阻的通道数(卡在控制面/登录,界面要说话,不能一直转圈) */
|
|
1174
|
+
stalled: stalled.length,
|
|
1175
|
+
note: internetNote,
|
|
1176
|
+
},
|
|
1177
|
+
all: lanOff && netOff,
|
|
1178
|
+
at: switchDesired.at,
|
|
1179
|
+
by: switchDesired.by,
|
|
1180
|
+
summary: describeMeshSwitch(switchDesired),
|
|
1181
|
+
};
|
|
1182
|
+
};
|
|
1183
|
+
|
|
1184
|
+
/**
|
|
1185
|
+
* 执行一次开关操作(界面按钮与 mesh_switch 工具共用)。
|
|
1186
|
+
*
|
|
1187
|
+
* 先落盘再动运行时:写盘失败时**不**去停服务,避免"这一秒关了、重启又开着"
|
|
1188
|
+
* 这种更糟的半态。
|
|
1189
|
+
*/
|
|
1190
|
+
const setSwitch = (opts = {}) =>
|
|
1191
|
+
serialize(async () => {
|
|
1192
|
+
const scope = normalizeSwitchScope(opts.scope);
|
|
1193
|
+
if (!scope) throw new Error(`未知的开关范围:${String(opts.scope)}(应为 all / lan / internet)`);
|
|
1194
|
+
const next = applyMeshSwitch(switchDesired, { scope, off: opts.off, by: opts.by ?? "ui" });
|
|
1195
|
+
const before = { lan: switchDesired.lan, internet: switchDesired.internet };
|
|
1196
|
+
saveState({ shutdown: next });
|
|
1197
|
+
switchDesired = resolveMeshSwitch({ shutdown: next });
|
|
1198
|
+
const changed = before.lan !== switchDesired.lan || before.internet !== switchDesired.internet;
|
|
1199
|
+
if (changed) {
|
|
1200
|
+
const label = MESH_SWITCH_LABEL[scope] ?? scope;
|
|
1201
|
+
log(`一键关闭「${label}」→ ${describeMeshSwitch(switchDesired)}(来源 ${next.by},立即生效,重启后保持)`);
|
|
1202
|
+
await syncRuntime({ reason: `一键关闭:${label}` });
|
|
924
1203
|
}
|
|
925
|
-
|
|
926
|
-
|
|
1204
|
+
return { changed, scope, status: switchStatus() };
|
|
1205
|
+
});
|
|
1206
|
+
|
|
1207
|
+
// 1) 按开关状态起对端服务与发现;局域网/互联网各自独立
|
|
1208
|
+
(async () => {
|
|
1209
|
+
await syncRuntime({ reason: "启动" });
|
|
1210
|
+
log(
|
|
1211
|
+
`已启动 machine=${identity.name}(来源 ${identity.source})` +
|
|
1212
|
+
` 文件搬运 nonce=${FILE_TRANSFER_NONCE}` +
|
|
1213
|
+
` 地址=${preferredAddress()}:${discovery.port || "?"} 实例=${instanceId} ` +
|
|
1214
|
+
`配对要求=${config.requirePairing ? "开" : "关"} ` +
|
|
1215
|
+
`开关=${describeMeshSwitch(switchDesired)}`,
|
|
1216
|
+
);
|
|
1217
|
+
if (switchDesired.all) {
|
|
1218
|
+
log("上次退出前处于「全部关闭」状态:保持关闭,Mesh 面板里可以重新打开");
|
|
1219
|
+
}
|
|
1220
|
+
})().catch((err) => warn(`对端服务启动失败,发现功能未启用: ${err?.message ?? err}`));
|
|
927
1221
|
|
|
928
1222
|
// 2) 入站唤醒:注册一次 webhook 规则,之后每个任务只 dispatch
|
|
929
1223
|
setupInbound(ctx, config, log, warn, waker);
|
|
930
1224
|
|
|
1225
|
+
/** 一键关闭的对外门面:UI 路由与 agent 工具共用同一份实现。 */
|
|
1226
|
+
const meshSwitch = { status: switchStatus, set: setSwitch };
|
|
1227
|
+
|
|
931
1228
|
// 3) agent 工具
|
|
932
|
-
registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange: scheduleHistorySave });
|
|
1229
|
+
registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange: scheduleHistorySave, meshSwitch });
|
|
933
1230
|
|
|
934
1231
|
// 4) UI 接口
|
|
935
|
-
registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave, diagnostics: diagnosticsPayload });
|
|
1232
|
+
registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave, diagnostics: diagnosticsPayload, meshSwitch });
|
|
936
1233
|
|
|
937
1234
|
ctx.effect(() => () => {
|
|
1235
|
+
// 卸载时一并收干净:定时器、对端端口、tailnet sidecar。
|
|
1236
|
+
// 一键关闭只是"暂停",卸载才是"拆走"。
|
|
1237
|
+
lanGeneration += 1;
|
|
1238
|
+
shutRuntimeTimers();
|
|
1239
|
+
void closePeerServer();
|
|
1240
|
+
for (const node of tailnetNodes.values()) node.stop().catch(() => {});
|
|
1241
|
+
tailnetNodes.clear();
|
|
938
1242
|
discovery.stop();
|
|
939
1243
|
log("已停止");
|
|
940
1244
|
});
|
|
@@ -1645,8 +1949,24 @@ function endpointKeyOf(ep) {
|
|
|
1645
1949
|
*/
|
|
1646
1950
|
async function peerFetch(peer, path, opts = {}) {
|
|
1647
1951
|
const { timeoutMs = 20000, ...rest } = opts;
|
|
1648
|
-
const
|
|
1649
|
-
if (
|
|
1952
|
+
const all = orderedEndpoints(peer);
|
|
1953
|
+
if (all.length === 0) throw new Error(`对端 ${peer?.machine ?? "?"} 没有任何已知通道`);
|
|
1954
|
+
|
|
1955
|
+
// 一键关闭掉的路径不许用于出站。
|
|
1956
|
+
// 宁可明确说"这条通道关了",也不要让它退化成"所有通道都失败" —— 后者会让
|
|
1957
|
+
// 用户以为对端掉线了,实际是本机自己关的(这类误判在这个项目里踩过)。
|
|
1958
|
+
const eps = all.filter((ep) => (ep.transport === "tsnet" ? transportGate.internet : transportGate.lan));
|
|
1959
|
+
if (eps.length === 0) {
|
|
1960
|
+
const closed = new Set();
|
|
1961
|
+
for (const ep of all) {
|
|
1962
|
+
const transport = ep.transport === "tsnet" ? "internet" : "lan";
|
|
1963
|
+
if (!transportGate[transport]) closed.add(transport === "internet" ? "互联网 mesh" : "局域网 mesh");
|
|
1964
|
+
}
|
|
1965
|
+
throw new Error(
|
|
1966
|
+
`本机已关闭${[...closed].join("、")},对端 ${peer?.machine ?? "?"} 没有可用通道。` +
|
|
1967
|
+
"可在 Mesh 面板「连接 → 一键关闭」里打开后重试。",
|
|
1968
|
+
);
|
|
1969
|
+
}
|
|
1650
1970
|
|
|
1651
1971
|
const failures = [];
|
|
1652
1972
|
for (const ep of eps) {
|
|
@@ -1727,6 +2047,9 @@ async function fetchViaTailnet(ep, url, opts = {}) {
|
|
|
1727
2047
|
* @param channelId 只扫某一条通道;省略 = 所有在跑的通道
|
|
1728
2048
|
*/
|
|
1729
2049
|
async function scanTailnet({ discovery, config, log, reason, ports, channelId = "" }) {
|
|
2050
|
+
// 互联网 mesh 被一键关闭时一律不扫:sidecar 已经停了,扫也只会报一堆
|
|
2051
|
+
// "节点未启动",反而像故障。
|
|
2052
|
+
if (!transportGate.internet) return { scanned: 0, found: 0, channels: [], closed: true };
|
|
1730
2053
|
const nodes = runningTailnetNodes().filter((n) => !channelId || n.channelKey === channelId);
|
|
1731
2054
|
if (nodes.length === 0) return { scanned: 0, found: 0, channels: [] };
|
|
1732
2055
|
|
|
@@ -1827,6 +2150,14 @@ async function runScan({ discovery, config, log, warn, signal, reason = "扫描"
|
|
|
1827
2150
|
const ports = scanPortList(discovery, config);
|
|
1828
2151
|
let lanFound = 0;
|
|
1829
2152
|
|
|
2153
|
+
// 局域网 mesh 一键关闭后不再发任何探测包(这是一条真实的出网行为,
|
|
2154
|
+
// 不能因为"只是扫描"就留着)。tailnet 那半段仍按各自的开关决定。
|
|
2155
|
+
if (!transportGate.lan) {
|
|
2156
|
+
log(`${reason}: 局域网 mesh 已关闭,只扫互联网通道`);
|
|
2157
|
+
const tailOnly = await scanTailnet({ discovery, config, log, reason, ports });
|
|
2158
|
+
return { scanned: tailOnly.scanned, found: tailOnly.found, lan: false, tailnet: tailOnly };
|
|
2159
|
+
}
|
|
2160
|
+
|
|
1830
2161
|
if (addresses.length === 0) {
|
|
1831
2162
|
warn(`${reason}: 没有可扫描的地址(检查 scanRanges 是否合法 / 网卡是否存在)`);
|
|
1832
2163
|
}
|
|
@@ -1881,7 +2212,7 @@ async function pingKnownPeers({ discovery, config, warn }) {
|
|
|
1881
2212
|
// tailnet 按 tsnetProbeIntervalMs(默认 60s)低频验证;另外**还没探通过的
|
|
1882
2213
|
// 通道立刻探一次**,让它尽快有个真实状态而不是停在"未探测"。
|
|
1883
2214
|
const tsnetInterval = Math.max(config.pingIntervalMs, config.tsnetProbeIntervalMs ?? 60000);
|
|
1884
|
-
const targets = endpoints.filter((ep) => {
|
|
2215
|
+
const targets = endpoints.filter((ep) => (ep.transport === "tsnet" ? transportGate.internet : transportGate.lan)).filter((ep) => {
|
|
1885
2216
|
const interval = ep.transport === "tsnet" ? tsnetInterval : config.pingIntervalMs;
|
|
1886
2217
|
if (ep.verified === false) {
|
|
1887
2218
|
// 首次立刻探一次;失败后按通道节奏重试,并尊重 markEndpoint 记下
|
|
@@ -1948,7 +2279,18 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
|
|
|
1948
2279
|
|
|
1949
2280
|
// ───────────────────────── 对端 HTTP 服务 ─────────────────────────
|
|
1950
2281
|
|
|
1951
|
-
|
|
2282
|
+
/**
|
|
2283
|
+
* 起一个对端 HTTP 服务。
|
|
2284
|
+
*
|
|
2285
|
+
* 返回值从"端口号"改成了句柄 `{ port, host, server }`:一键关闭需要把监听
|
|
2286
|
+
* 从 0.0.0.0 收回到 127.0.0.1(局域网不可达,tailnet 的 sidecar 反代仍在
|
|
2287
|
+
* 本机回环上),恢复时再重新绑回去。没有句柄就没法做这件事。
|
|
2288
|
+
*
|
|
2289
|
+
* @param options.port 指定端口;省略用 config.port。重绑时传上一次的真实端口,
|
|
2290
|
+
* 否则对端记着的端口会变(tailnet 的 forward 也会失效)。
|
|
2291
|
+
* @param options.bindHost 监听地址。局域网关着时传 "127.0.0.1"。
|
|
2292
|
+
*/
|
|
2293
|
+
function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange, diagnostics, port: fixedPort, bindHost = "0.0.0.0" }) {
|
|
1952
2294
|
const send = (res, code, payload) => {
|
|
1953
2295
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
1954
2296
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -1961,11 +2303,29 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
|
|
|
1961
2303
|
const authed = (req) =>
|
|
1962
2304
|
!pairingRequired(config) || safeEqual(req.headers["x-dsh-mesh-token"], currentSecret());
|
|
1963
2305
|
|
|
2306
|
+
/**
|
|
2307
|
+
* 一键关闭的入站闸门。
|
|
2308
|
+
*
|
|
2309
|
+
* 只绑回环已经能挡住局域网(连接直接被拒),但这一层仍必须有:重绑失败
|
|
2310
|
+
* (端口被占、系统限制)时不能变成"界面显示关了、实际还收任务"。tailnet
|
|
2311
|
+
* 的入站由 sidecar 反代到回环,带 X-Forwarded-For,按 transport 区分。
|
|
2312
|
+
*/
|
|
2313
|
+
const inboundClosedReason = (req) => {
|
|
2314
|
+
const origin = tailnetOrigin(req);
|
|
2315
|
+
if (origin.transport === "tsnet") return transportGate.internet ? "" : "互联网 mesh 已关闭";
|
|
2316
|
+
return transportGate.lan ? "" : "局域网 mesh 已关闭";
|
|
2317
|
+
};
|
|
2318
|
+
|
|
1964
2319
|
const server = createServer(async (req, res) => {
|
|
1965
2320
|
const url = new URL(req.url, "http://localhost");
|
|
1966
2321
|
const path = url.pathname;
|
|
1967
2322
|
const self = { ...discovery.selfRecord(), instanceId: discovery.instanceId };
|
|
1968
2323
|
|
|
2324
|
+
// 关闭期间连 health 都不答(否则对端会认为我们还活着)。503 带上原因,
|
|
2325
|
+
// 排障时能一眼看出是本机自己关的,而不是网络不通。
|
|
2326
|
+
const closed = inboundClosedReason(req);
|
|
2327
|
+
if (closed) return send(res, 503, { ok: false, closed: true, error: `本机已关闭${closed}(Mesh 面板可重新打开)` });
|
|
2328
|
+
|
|
1969
2329
|
// 免鉴权:只暴露身份,用于连通性探测、主动扫描与配对握手
|
|
1970
2330
|
if (path === "/mesh/v1/health") return send(res, 200, { ok: true, ...self, requirePairing: pairingRequired(config) });
|
|
1971
2331
|
if (path === "/mesh/v1/hello") {
|
|
@@ -1981,9 +2341,70 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
|
|
|
1981
2341
|
|
|
1982
2342
|
if (!authed(req)) return send(res, 403, { ok: false, error: "未配对:两台机器的配对码不一致(本机开启了 requirePairing)" });
|
|
1983
2343
|
|
|
2344
|
+
// 一次性文件搬运:给对端取本机插件包里的文件(同版本部署用)。
|
|
2345
|
+
// 只认启动时生成的 nonce,且路径必须落在插件包目录内 —— 不是通用文件服务。
|
|
2346
|
+
if (path === "/mesh/v1/file" && req.method === "GET") {
|
|
2347
|
+
const nonce = url.searchParams.get("k") ?? "";
|
|
2348
|
+
// 两个都认:进程内的随机 nonce,或本机的 mesh 密钥(可从 state.json 读到,
|
|
2349
|
+
// 方便"人在旁边"时一次搬运;两者都不用改配置)。
|
|
2350
|
+
if (!safeEqual(nonce, FILE_TRANSFER_NONCE) && !safeEqual(nonce, currentSecret())) {
|
|
2351
|
+
return send(res, 403, { ok: false, error: "nonce 不对" });
|
|
2352
|
+
}
|
|
2353
|
+
const wanted = url.searchParams.get("path") ?? "";
|
|
2354
|
+
const packageRoot = resolve(ENTRY_INFO.path, "..", "..");
|
|
2355
|
+
const absolute = resolve(wanted);
|
|
2356
|
+
if (!absolute.startsWith(`${packageRoot}/`)) {
|
|
2357
|
+
return send(res, 400, { ok: false, error: "路径超出插件包目录" });
|
|
2358
|
+
}
|
|
2359
|
+
try {
|
|
2360
|
+
const body = readFileSync(absolute);
|
|
2361
|
+
res.writeHead(200, {
|
|
2362
|
+
"content-type": "application/octet-stream",
|
|
2363
|
+
"content-length": String(body.length),
|
|
2364
|
+
});
|
|
2365
|
+
res.end(body);
|
|
2366
|
+
return;
|
|
2367
|
+
} catch (err) {
|
|
2368
|
+
return send(res, 404, { ok: false, error: String(err?.message ?? err) });
|
|
2369
|
+
}
|
|
2370
|
+
}
|
|
2371
|
+
|
|
1984
2372
|
// 诊断:进程版本 vs 磁盘版本。**必须在对端鉴权之后** —— 里面有本机路径。
|
|
1985
2373
|
if (path === "/mesh/v1/diagnostics") return send(res, 200, diagnostics());
|
|
1986
2374
|
|
|
2375
|
+
// 本机 DSH Web GUI 的入口地址(带启动 token)。
|
|
2376
|
+
//
|
|
2377
|
+
// 只在这里按需发放,**绝不**放进 discovery 广播:那条是明文组播,
|
|
2378
|
+
// 谁加入组播谁就能读到 token,等于把本机的 RCE 交给整个网段。
|
|
2379
|
+
// 走这条路径时要过 authed(),也就是跟着配对开关一起受保护。
|
|
2380
|
+
//
|
|
2381
|
+
// token 是进程级的、随重启轮换;浏览器第一次带 token 打开后会拿到
|
|
2382
|
+
// 一枚 30 天、绑定 authority 的签名 cookie,之后不带 token 也能开。
|
|
2383
|
+
if (path === "/mesh/v1/web-url" && req.method === "GET") {
|
|
2384
|
+
try {
|
|
2385
|
+
const connection = ctx.get("connection");
|
|
2386
|
+
const port = ctx.get("webServer")?.port;
|
|
2387
|
+
const bind = ctx.get("webServer")?.host ?? "";
|
|
2388
|
+
if (!connection || typeof connection.authenticatedUrl !== "function" || !port) {
|
|
2389
|
+
return send(res, 200, { ok: false, supported: false, error: "本端没有可用的 Web GUI(不是 web profile)" });
|
|
2390
|
+
}
|
|
2391
|
+
const lanHost = preferredAddress();
|
|
2392
|
+
// 只绑了回环时如实说:地址虽然给得出来,但局域网里连不通。
|
|
2393
|
+
const lanReachable = bind === "0.0.0.0" && !!lanHost;
|
|
2394
|
+
const host = lanReachable ? lanHost : "127.0.0.1";
|
|
2395
|
+
return send(res, 200, {
|
|
2396
|
+
ok: true,
|
|
2397
|
+
supported: true,
|
|
2398
|
+
url: connection.authenticatedUrl(`http://${host}:${port}/`),
|
|
2399
|
+
bind,
|
|
2400
|
+
lanReachable,
|
|
2401
|
+
port,
|
|
2402
|
+
});
|
|
2403
|
+
} catch (err) {
|
|
2404
|
+
return send(res, 200, { ok: false, supported: false, error: String(err?.message ?? err) });
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
|
|
1987
2408
|
if (path === "/mesh/v1/peers") return send(res, 200, { ok: true, peers: discovery.peers() });
|
|
1988
2409
|
|
|
1989
2410
|
if (path === "/mesh/v1/tasks" && req.method === "GET") {
|
|
@@ -2034,7 +2455,7 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
|
|
|
2034
2455
|
});
|
|
2035
2456
|
|
|
2036
2457
|
return new Promise((resolvePromise, rejectPromise) => {
|
|
2037
|
-
const wanted = config.port ?? MESH_DEFAULT_PORT;
|
|
2458
|
+
const wanted = fixedPort ?? config.port ?? MESH_DEFAULT_PORT;
|
|
2038
2459
|
const start = (port, isFallback) => {
|
|
2039
2460
|
server.once("error", (err) => {
|
|
2040
2461
|
if (!isFallback && err?.code === "EADDRINUSE") {
|
|
@@ -2044,11 +2465,10 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
|
|
|
2044
2465
|
}
|
|
2045
2466
|
rejectPromise(err);
|
|
2046
2467
|
});
|
|
2047
|
-
server.listen(port,
|
|
2468
|
+
server.listen(port, bindHost, () => {
|
|
2048
2469
|
const addr = server.address();
|
|
2049
|
-
log(`对端服务监听
|
|
2050
|
-
|
|
2051
|
-
resolvePromise(addr.port);
|
|
2470
|
+
log(`对端服务监听 ${addr.address}:${addr.port}${isFallback ? "(随机)" : "(固定)"}`);
|
|
2471
|
+
resolvePromise({ port: addr.port, host: addr.address, server });
|
|
2052
2472
|
});
|
|
2053
2473
|
};
|
|
2054
2474
|
start(wanted, false);
|
|
@@ -2081,8 +2501,17 @@ function readJson(req) {
|
|
|
2081
2501
|
|
|
2082
2502
|
// ───────────────────────── agent 工具 ─────────────────────────
|
|
2083
2503
|
|
|
2084
|
-
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange }) {
|
|
2504
|
+
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, hostDispatched, onHistoryChange, meshSwitch }) {
|
|
2085
2505
|
const text = (v) => [{ type: "text", text: v }];
|
|
2506
|
+
/**
|
|
2507
|
+
* 当前开关的一行摘要。所有工具的输出都带上它 —— agent 看到"没有对端"
|
|
2508
|
+
* 时,第一件要能分清的事是"真没有"还是"本机自己关了"(这个项目里
|
|
2509
|
+
* 把"没答"当成"没有"已经出过一次事故)。
|
|
2510
|
+
*/
|
|
2511
|
+
const switchLine = () => (meshSwitch ? meshSwitch.status().summary : "局域网 开启 · 互联网 开启");
|
|
2512
|
+
const lanOff = () => !!(meshSwitch && meshSwitch.status().lan.off);
|
|
2513
|
+
const netOff = () => !!(meshSwitch && meshSwitch.status().internet.off);
|
|
2514
|
+
const allOff = () => !!(meshSwitch && meshSwitch.status().all);
|
|
2086
2515
|
|
|
2087
2516
|
ctx.tools.register(
|
|
2088
2517
|
defineTool({
|
|
@@ -2098,12 +2527,24 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
2098
2527
|
const peers = discovery.peers();
|
|
2099
2528
|
const list = args?.includeOffline === false ? peers.filter((p) => p.online) : peers;
|
|
2100
2529
|
if (list.length === 0) {
|
|
2530
|
+
if (allOff()) {
|
|
2531
|
+
return (
|
|
2532
|
+
`本机 mesh 已全部关闭(${switchLine()}),所以看不到任何对端 —— 这不代表网络里没有机器。\n` +
|
|
2533
|
+
"需要时用 mesh_switch(scope=all, action=on)打开,或让用户在 Mesh 面板「连接 → 一键关闭」里打开。"
|
|
2534
|
+
);
|
|
2535
|
+
}
|
|
2536
|
+
if (lanOff()) {
|
|
2537
|
+
return (
|
|
2538
|
+
`本机局域网 mesh 已关闭(${switchLine()}),本网段的机器目前不可见。\n` +
|
|
2539
|
+
"互联网通道若已配置,可继续用 mesh_peers 看到 tailnet 上的机器。"
|
|
2540
|
+
);
|
|
2541
|
+
}
|
|
2101
2542
|
return (
|
|
2102
2543
|
"没有发现其他 DSH 机器。\n" +
|
|
2103
2544
|
"用 mesh_scan 主动扫一次本网段(组播常被路由器/防火墙挡住)。\n" +
|
|
2104
2545
|
"仍找不到就排查:1) 两台机器是否同一网段 2) 对端是否装了 dsh-plugin-mesh 并已重启 DSH " +
|
|
2105
2546
|
"3) 对端防火墙是否放行这个 TCP 端口\n" +
|
|
2106
|
-
`本机: ${machineOf(discovery)} (${preferredAddress()})`
|
|
2547
|
+
`本机: ${machineOf(discovery)} (${preferredAddress()}) · 开关: ${switchLine()}`
|
|
2107
2548
|
);
|
|
2108
2549
|
}
|
|
2109
2550
|
const lines = list.map((p) => {
|
|
@@ -2115,7 +2556,10 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
2115
2556
|
(caps ? `\n${caps}` : "")
|
|
2116
2557
|
);
|
|
2117
2558
|
});
|
|
2118
|
-
return
|
|
2559
|
+
return (
|
|
2560
|
+
`发现 ${list.length} 台机器:\n${lines.join("\n")}\n\n` +
|
|
2561
|
+
`本机: ${machineOf(discovery)} (${preferredAddress()}) · 开关: ${switchLine()}`
|
|
2562
|
+
);
|
|
2119
2563
|
},
|
|
2120
2564
|
}),
|
|
2121
2565
|
);
|
|
@@ -2129,6 +2573,17 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
2129
2573
|
parameters: {},
|
|
2130
2574
|
output: { schema: { type: "string" }, render: (_a, v) => text(v) },
|
|
2131
2575
|
async execute() {
|
|
2576
|
+
if (allOff()) {
|
|
2577
|
+
return "未扫描:本机 mesh 已全部关闭。用 mesh_switch(scope=all, action=on)打开后再扫。";
|
|
2578
|
+
}
|
|
2579
|
+
if (lanOff()) {
|
|
2580
|
+
return (
|
|
2581
|
+
"未扫描:本机局域网 mesh 已关闭(不会向本网段发包)。\n" +
|
|
2582
|
+
(netOff()
|
|
2583
|
+
? "互联网 mesh 也关着,所以两条路径都不可用。"
|
|
2584
|
+
: "互联网通道仍可用:需要找 tailnet 上的机器请用 mesh_switch 之外的方式,或先打开局域网。")
|
|
2585
|
+
);
|
|
2586
|
+
}
|
|
2132
2587
|
const before = discovery.peers().length;
|
|
2133
2588
|
const r = await runScan({ discovery, config, log, warn, reason: "agent 触发扫描" });
|
|
2134
2589
|
const after = discovery.peers();
|
|
@@ -2173,6 +2628,12 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
2173
2628
|
const peerName = String(args?.peer ?? "").trim();
|
|
2174
2629
|
const task = String(args?.task ?? "").trim();
|
|
2175
2630
|
if (!peerName || !task) return "peer 和 task 都必填。";
|
|
2631
|
+
if (allOff()) {
|
|
2632
|
+
return (
|
|
2633
|
+
"任务未派发:本机 mesh 已全部关闭(局域网 + 互联网)。\n" +
|
|
2634
|
+
"用 mesh_switch(scope=all, action=on)打开,或请用户在 Mesh 面板「连接 → 一键关闭」里打开。"
|
|
2635
|
+
);
|
|
2636
|
+
}
|
|
2176
2637
|
|
|
2177
2638
|
const matches = findPeersByName(discovery, peerName);
|
|
2178
2639
|
if (matches.length === 0) {
|
|
@@ -2273,12 +2734,78 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
2273
2734
|
}),
|
|
2274
2735
|
);
|
|
2275
2736
|
|
|
2276
|
-
|
|
2737
|
+
/**
|
|
2738
|
+
* 一键关闭 / 打开。
|
|
2739
|
+
*
|
|
2740
|
+
* 为什么做成工具而不只是界面按钮:用户经常是在对话里说"把 mesh 关了",
|
|
2741
|
+
* 而且关掉之后往往正是要 agent 继续干活(离线跑长任务)。做成工具,agent
|
|
2742
|
+
* 能自己执行并立刻回报"现在还有哪条通道是活的"。
|
|
2743
|
+
*
|
|
2744
|
+
* 默认动作是**关闭**:这是主动作,也是用户说"关掉"时的意思;打开必须显式传。
|
|
2745
|
+
*/
|
|
2746
|
+
ctx.tools.register(
|
|
2747
|
+
defineTool({
|
|
2748
|
+
name: "mesh_switch",
|
|
2749
|
+
description:
|
|
2750
|
+
"一键关闭 / 打开本机 mesh。三种范围:all(全部)、lan(局域网)、internet(互联网 tailnet)。" +
|
|
2751
|
+
"关闭立即生效:局域网关闭后不再组播广播、不再扫本网段,对端端口只绑回环;" +
|
|
2752
|
+
"互联网关闭后停掉全部 tailnet sidecar(通道配置保留)。" +
|
|
2753
|
+
"状态写入 state.json,重启 DSH 后仍保持,直到显式打开。" +
|
|
2754
|
+
"界面上同一组开关在 Mesh 面板「连接 → 一键关闭」。",
|
|
2755
|
+
parameters: {
|
|
2756
|
+
scope: {
|
|
2757
|
+
type: "string",
|
|
2758
|
+
required: true,
|
|
2759
|
+
description: "关闭/打开的范围:all(全部 mesh)、lan(局域网 mesh)、internet(互联网 mesh)",
|
|
2760
|
+
},
|
|
2761
|
+
action: {
|
|
2762
|
+
type: "string",
|
|
2763
|
+
description: "off = 关闭(默认),on = 打开",
|
|
2764
|
+
},
|
|
2765
|
+
},
|
|
2766
|
+
output: { schema: { type: "string" }, render: (_a, v) => text(v) },
|
|
2767
|
+
async execute(args) {
|
|
2768
|
+
if (!meshSwitch) return "本机没有可用的 mesh 开关实现(插件版本过旧)。";
|
|
2769
|
+
const scope = normalizeSwitchScope(args?.scope);
|
|
2770
|
+
if (!scope) {
|
|
2771
|
+
return `scope 不合法:${String(args?.scope ?? "")}。用 all / lan / internet 之一。`;
|
|
2772
|
+
}
|
|
2773
|
+
const rawAction = String(args?.action ?? "off").trim().toLowerCase();
|
|
2774
|
+
if (!["off", "on", "close", "open", "disable", "enable"].includes(rawAction)) {
|
|
2775
|
+
return `action 不合法:${rawAction}。用 off(关闭)或 on(打开)。`;
|
|
2776
|
+
}
|
|
2777
|
+
const wantOff = ["off", "close", "disable"].includes(rawAction);
|
|
2778
|
+
const result = await meshSwitch.set({ scope, off: wantOff, by: "tool" });
|
|
2779
|
+
const st = result.status;
|
|
2780
|
+
const label = MESH_SWITCH_LABEL[scope] ?? scope;
|
|
2781
|
+
const lines = [
|
|
2782
|
+
`${label}已${wantOff ? "关闭" : "打开"}${result.changed ? "" : "(状态本来就是这样,没有变化)"}。`,
|
|
2783
|
+
`当前:${st.summary}`,
|
|
2784
|
+
`局域网:${st.lan.off ? "已关闭" : "开启"}` +
|
|
2785
|
+
(st.lan.off
|
|
2786
|
+
? ` · 对端端口${st.lan.bind ? `只绑 ${st.lan.bind}` : "已停"}`
|
|
2787
|
+
: ` · 监听 ${st.lan.bind || "—"}:${st.lan.port || "—"} · 组播 ${st.lan.multicast ? "开" : "关"}`) +
|
|
2788
|
+
(st.lan.note ? ` · 注意:${st.lan.note}` : ""),
|
|
2789
|
+
`互联网:${st.internet.off ? "已关闭" : "开启"}` +
|
|
2790
|
+
(st.internet.off
|
|
2791
|
+
? ` · 运行中 sidecar ${st.internet.running} 条(配置里启用 ${st.internet.configured} 条,配置保留)`
|
|
2792
|
+
: ` · 运行中 ${st.internet.running}/${st.internet.configured} 条`) +
|
|
2793
|
+
(st.internet.note ? ` · 注意:${st.internet.note}` : ""),
|
|
2794
|
+
];
|
|
2795
|
+
if (!wantOff && scope !== "lan" && st.internet.configured === 0) {
|
|
2796
|
+
lines.push("提示:互联网 mesh 没有启用的 tailnet 通道,需要在 Mesh 面板里添加授权码。");
|
|
2797
|
+
}
|
|
2798
|
+
return lines.join("\n");
|
|
2799
|
+
},
|
|
2800
|
+
}),
|
|
2801
|
+
);
|
|
2802
|
+
|
|
2803
|
+
log("已注册工具 mesh_peers / mesh_run / mesh_tasks / mesh_switch");
|
|
2277
2804
|
}
|
|
2278
2805
|
|
|
2279
2806
|
// ───────────────────────── UI 接口(本地回环) ─────────────────────────
|
|
2280
2807
|
|
|
2281
|
-
function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange, diagnostics }) {
|
|
2808
|
+
function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, hostDispatched, capFor, capOverrides, throttled, waker, onHistoryChange, diagnostics, meshSwitch }) {
|
|
2282
2809
|
const send = (res, code, payload) => {
|
|
2283
2810
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
2284
2811
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -2431,6 +2958,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2431
2958
|
node: primary?.node ?? null,
|
|
2432
2959
|
recentEvents: primary?.recentEvents ?? [],
|
|
2433
2960
|
},
|
|
2961
|
+
// 一键关闭:期望值 + 真实运行情况 + 偏差说明(界面按它渲染三个开关)
|
|
2962
|
+
switch: meshSwitch ? meshSwitch.status() : null,
|
|
2434
2963
|
peers: discovery.peers(),
|
|
2435
2964
|
duplicateNames: duplicateNames(),
|
|
2436
2965
|
inbound: inbound.slice(-30).reverse(),
|
|
@@ -2533,11 +3062,22 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2533
3062
|
});
|
|
2534
3063
|
|
|
2535
3064
|
post("/mesh/api/refresh", (_req, res) => {
|
|
2536
|
-
|
|
2537
|
-
|
|
3065
|
+
const st = meshSwitch ? meshSwitch.status() : null;
|
|
3066
|
+
// 关着局域网时 announceNow 是空操作。如实回报,别让界面以为"广播过了"。
|
|
3067
|
+
const announced = Boolean(st && !st.lan.off && st.lan.multicast);
|
|
3068
|
+
if (announced) discovery.announceNow();
|
|
3069
|
+
send(res, 200, { ok: true, announced });
|
|
2538
3070
|
});
|
|
2539
3071
|
|
|
2540
3072
|
post("/mesh/api/scan", async (_req, res) => {
|
|
3073
|
+
// 局域网关着就别发包(按钮叫「局域网探测」,不能偷偷改成只扫 tailnet)
|
|
3074
|
+
if (meshSwitch && meshSwitch.status().lan.off) {
|
|
3075
|
+
return send(res, 409, {
|
|
3076
|
+
ok: false,
|
|
3077
|
+
closed: true,
|
|
3078
|
+
error: "局域网 mesh 已关闭 —— 在「连接 → 一键关闭」里打开后再探测",
|
|
3079
|
+
});
|
|
3080
|
+
}
|
|
2541
3081
|
try {
|
|
2542
3082
|
const result = await runScan({ discovery, config, log, warn, reason: "手动扫描" });
|
|
2543
3083
|
send(res, 200, { ok: true, ...result, peers: discovery.peers() });
|
|
@@ -2574,6 +3114,37 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2574
3114
|
return send(res, 200, { ok: true, requirePairing: want });
|
|
2575
3115
|
});
|
|
2576
3116
|
|
|
3117
|
+
/**
|
|
3118
|
+
* 界面上的「一键关闭」。
|
|
3119
|
+
*
|
|
3120
|
+
* body: `{ scope: "all"|"lan"|"internet", off: boolean }`
|
|
3121
|
+
*
|
|
3122
|
+
* 和配对码开关一样写 state.json(不改用户的 cordis.patch.yml),
|
|
3123
|
+
* 但**会跨重启保持**:一键关闭的语义是"我现在不想让这台机器被找到、被派活",
|
|
3124
|
+
* 重启后自己悄悄恢复是最坏的结果。
|
|
3125
|
+
*
|
|
3126
|
+
* `off` 必须是布尔值:`body?.off === true` 这种写法在 GET/空 body 上会变成
|
|
3127
|
+
* false,那是"悄悄打开"—— 和 pairing 那次 fail-open 同一类错误,这里直接
|
|
3128
|
+
* 400 拒掉。
|
|
3129
|
+
*/
|
|
3130
|
+
post("/mesh/api/switch", async (req, res) => {
|
|
3131
|
+
const body = await readJson(req);
|
|
3132
|
+
const scope = normalizeSwitchScope(body?.scope);
|
|
3133
|
+
if (!scope) {
|
|
3134
|
+
return send(res, 400, { ok: false, error: "scope 必须是 all / lan / internet 之一" });
|
|
3135
|
+
}
|
|
3136
|
+
if (typeof body?.off !== "boolean") {
|
|
3137
|
+
return send(res, 400, { ok: false, error: "off 必须是布尔值(true = 关闭,false = 打开)" });
|
|
3138
|
+
}
|
|
3139
|
+
if (!meshSwitch) return send(res, 503, { ok: false, error: "开关实现不可用(插件版本过旧)" });
|
|
3140
|
+
try {
|
|
3141
|
+
const result = await meshSwitch.set({ scope, off: body.off, by: "ui" });
|
|
3142
|
+
return send(res, 200, { ok: true, changed: result.changed, scope, switch: result.status });
|
|
3143
|
+
} catch (err) {
|
|
3144
|
+
return send(res, 500, { ok: false, error: String(err?.message ?? err) });
|
|
3145
|
+
}
|
|
3146
|
+
});
|
|
3147
|
+
|
|
2577
3148
|
post("/mesh/api/secret", async (req, res) => {
|
|
2578
3149
|
const body = await readJson(req);
|
|
2579
3150
|
const secret = String(body?.secret ?? "").trim();
|
|
@@ -2756,6 +3327,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2756
3327
|
* body.id 省略 = 启动所有启用的通道(兼容旧页面点「只启动」)。
|
|
2757
3328
|
*/
|
|
2758
3329
|
post("/mesh/api/tsnet/start", async (req, res) => {
|
|
3330
|
+
if (meshSwitch && meshSwitch.status().internet.off) {
|
|
3331
|
+
return send(res, 409, {
|
|
3332
|
+
ok: false,
|
|
3333
|
+
closed: true,
|
|
3334
|
+
error: "互联网 mesh 已关闭 —— 在「连接 → 一键关闭」里打开后再启动通道",
|
|
3335
|
+
});
|
|
3336
|
+
}
|
|
2759
3337
|
const body = await readJson(req);
|
|
2760
3338
|
const wantId = String(body?.id ?? "").trim();
|
|
2761
3339
|
const all = effectiveTailnetChannels(config);
|
|
@@ -2857,6 +3435,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2857
3435
|
|
|
2858
3436
|
/** 只扫 tailnet,不扫局域网。body.id 省略 = 所有在跑的通道。 */
|
|
2859
3437
|
post("/mesh/api/tsnet/scan", async (req, res) => {
|
|
3438
|
+
if (meshSwitch && meshSwitch.status().internet.off) {
|
|
3439
|
+
return send(res, 409, {
|
|
3440
|
+
ok: false,
|
|
3441
|
+
closed: true,
|
|
3442
|
+
error: "互联网 mesh 已关闭 —— 在「连接 → 一键关闭」里打开后再扫描",
|
|
3443
|
+
});
|
|
3444
|
+
}
|
|
2860
3445
|
const body = await readJson(req);
|
|
2861
3446
|
const wantId = String(body?.id ?? "").trim();
|
|
2862
3447
|
const before = new Set(discovery.peers().map((p) => p.id));
|
|
@@ -2881,6 +3466,13 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2881
3466
|
const peerName = String(body?.peer ?? "").trim();
|
|
2882
3467
|
const task = String(body?.task ?? "").trim();
|
|
2883
3468
|
if (!peerName || !task) return send(res, 400, { ok: false, error: "peer 和 task 必填" });
|
|
3469
|
+
if (meshSwitch && meshSwitch.status().all) {
|
|
3470
|
+
return send(res, 409, {
|
|
3471
|
+
ok: false,
|
|
3472
|
+
closed: true,
|
|
3473
|
+
error: "本机 mesh 已全部关闭 —— 在「连接 → 一键关闭」里打开后再派发",
|
|
3474
|
+
});
|
|
3475
|
+
}
|
|
2884
3476
|
const found = findPeer(peerName);
|
|
2885
3477
|
if (found.error) return send(res, found.error.startsWith("名字") ? 409 : 404, { ok: false, error: found.error });
|
|
2886
3478
|
const target = found.peer;
|
|
@@ -2987,5 +3579,326 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2987
3579
|
}
|
|
2988
3580
|
});
|
|
2989
3581
|
|
|
2990
|
-
|
|
3582
|
+
post("/mesh/api/web-url", async (req, res) => {
|
|
3583
|
+
const body = await readJson(req);
|
|
3584
|
+
const found = findPeer(String(body?.peer ?? "").trim());
|
|
3585
|
+
if (found.error) return send(res, 404, { ok: false, error: found.error });
|
|
3586
|
+
const target = found.peer;
|
|
3587
|
+
try {
|
|
3588
|
+
const r = await peerFetch(target, "/mesh/v1/web-url", {
|
|
3589
|
+
headers: { "X-Dsh-Mesh-Token": currentSecret() },
|
|
3590
|
+
timeoutMs: 5000,
|
|
3591
|
+
});
|
|
3592
|
+
const rb = await r.json().catch(() => ({}));
|
|
3593
|
+
// 400/404 = 对端是老版本插件,没有这条路由。如实区分"不支持"和"取不到"。
|
|
3594
|
+
if (!r.ok || rb?.ok !== true || typeof rb?.url !== "string") {
|
|
3595
|
+
return send(res, 200, {
|
|
3596
|
+
ok: false,
|
|
3597
|
+
supported: rb?.supported === true,
|
|
3598
|
+
error: rb?.error || `对端 HTTP ${r.status}`,
|
|
3599
|
+
});
|
|
3600
|
+
}
|
|
3601
|
+
return send(res, 200, {
|
|
3602
|
+
ok: true,
|
|
3603
|
+
url: rb.url,
|
|
3604
|
+
bind: rb.bind ?? "",
|
|
3605
|
+
lanReachable: rb.lanReachable === true,
|
|
3606
|
+
port: rb.port ?? 0,
|
|
3607
|
+
});
|
|
3608
|
+
} catch (err) {
|
|
3609
|
+
return send(res, 200, { ok: false, supported: false, error: String(err?.message ?? err) });
|
|
3610
|
+
}
|
|
3611
|
+
});
|
|
3612
|
+
|
|
3613
|
+
// ── 对端 DSH Web 的应用内面板(回环反代 + 服务端认证)─────────────────
|
|
3614
|
+
//
|
|
3615
|
+
// 为什么不直接把对端地址塞进 iframe:对端会话 cookie 是 SameSite=Strict,
|
|
3616
|
+
// 跨站 iframe 里不发送,token 又随对端重启轮换 —— 页面会永远停在 401。
|
|
3617
|
+
// 所以认证搬到服务端:代理用 token 换一次 cookie,之后每个请求自己带;
|
|
3618
|
+
// 浏览器只跟本机 127.0.0.1 的这个端口说话。
|
|
3619
|
+
const webPanels = new Map(); // 机器名 -> { proxy, remote }
|
|
3620
|
+
|
|
3621
|
+
// 对端会话 cookie 落盘:token 每次重启都会轮换,而 cookie 是 30 天、由对端
|
|
3622
|
+
// 持久密钥签名的 —— 存住它就等于以后不必再问 token(到期或换密钥再补一次)。
|
|
3623
|
+
const panelStatePath = () => join(stateDir(), "web-panels.json");
|
|
3624
|
+
const readPanelCookies = () => {
|
|
3625
|
+
try {
|
|
3626
|
+
const value = JSON.parse(readFileSync(panelStatePath(), "utf8"));
|
|
3627
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
3628
|
+
} catch {
|
|
3629
|
+
return {};
|
|
3630
|
+
}
|
|
3631
|
+
};
|
|
3632
|
+
const writePanelCookie = (origin, cookie) => {
|
|
3633
|
+
try {
|
|
3634
|
+
const all = readPanelCookies();
|
|
3635
|
+
all[origin] = cookie;
|
|
3636
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
3637
|
+
writeFileSync(panelStatePath(), JSON.stringify(all, null, 2));
|
|
3638
|
+
} catch (err) {
|
|
3639
|
+
warn(`保存对端 cookie 失败:${err?.message ?? err}`);
|
|
3640
|
+
}
|
|
3641
|
+
};
|
|
3642
|
+
|
|
3643
|
+
const closeWebPanels = async () => {
|
|
3644
|
+
const entries = [...webPanels.values()];
|
|
3645
|
+
webPanels.clear();
|
|
3646
|
+
for (const entry of entries) {
|
|
3647
|
+
try {
|
|
3648
|
+
await entry.proxy.close();
|
|
3649
|
+
} catch (err) {
|
|
3650
|
+
warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3653
|
+
};
|
|
3654
|
+
ctx.effect(() => () => {
|
|
3655
|
+
void closeWebPanels();
|
|
3656
|
+
});
|
|
3657
|
+
|
|
3658
|
+
/** 取对端的 Web 地址与启动 token;老版本对端只能退回按约定拼地址。 */
|
|
3659
|
+
/**
|
|
3660
|
+
* 取对端的 Web 地址与启动 token。
|
|
3661
|
+
* @param target - 对端名片
|
|
3662
|
+
* @param tokenOverride - 调用方手工给的 token(对端插件还没升级时的逃生口)
|
|
3663
|
+
*/
|
|
3664
|
+
async function resolveWebTarget(target, tokenOverride = "") {
|
|
3665
|
+
// 优先:对端开了 desktopWebPort 时,会有一条 /mesh/web/ 前缀转发到它自己的
|
|
3666
|
+
// 另一个引擎(桌面 App 那个,有历史会话)。有就直接用它,认证在对端完成。
|
|
3667
|
+
// 端点可能有多个(局域网 + tailnet),且顺序会变 —— 逐个试,别只认第一个。
|
|
3668
|
+
for (const ep of orderedEndpoints(target)) {
|
|
3669
|
+
if (!ep?.host) continue;
|
|
3670
|
+
const base = `http://${ep.host}:${WEB_PANEL_DEFAULT_PORT}`;
|
|
3671
|
+
try {
|
|
3672
|
+
const probe = await fetch(`${base}${DESKTOP_WEB_PREFIX}/__probe`, { signal: AbortSignal.timeout(2000) });
|
|
3673
|
+
const body = await probe.json().catch(() => ({}));
|
|
3674
|
+
if (probe.ok && body?.ok === true) {
|
|
3675
|
+
return {
|
|
3676
|
+
remoteBase: `${base}/`,
|
|
3677
|
+
pathPrefix: DESKTOP_WEB_PREFIX,
|
|
3678
|
+
passthrough: true,
|
|
3679
|
+
lanReachable: true,
|
|
3680
|
+
note: `转发到对端 ${body.target}`,
|
|
3681
|
+
};
|
|
3682
|
+
}
|
|
3683
|
+
} catch {
|
|
3684
|
+
/* 这条端点不通,试下一条 */
|
|
3685
|
+
}
|
|
3686
|
+
}
|
|
3687
|
+
|
|
3688
|
+
let remoteBase = "";
|
|
3689
|
+
let token = tokenOverride;
|
|
3690
|
+
let lanReachable;
|
|
3691
|
+
let note = "";
|
|
3692
|
+
try {
|
|
3693
|
+
const r = await peerFetch(target, "/mesh/v1/web-url", {
|
|
3694
|
+
headers: { "X-Dsh-Mesh-Token": currentSecret() },
|
|
3695
|
+
timeoutMs: 5000,
|
|
3696
|
+
});
|
|
3697
|
+
const rb = await r.json().catch(() => ({}));
|
|
3698
|
+
if (rb?.ok === true && typeof rb.url === "string") {
|
|
3699
|
+
const parsed = new URL(rb.url);
|
|
3700
|
+
token = parsed.searchParams.get("token") || token;
|
|
3701
|
+
// token 只用来换 cookie,别留在浏览器的地址栏里。
|
|
3702
|
+
parsed.searchParams.delete("token");
|
|
3703
|
+
remoteBase = parsed.href;
|
|
3704
|
+
lanReachable = rb.lanReachable === true;
|
|
3705
|
+
} else {
|
|
3706
|
+
note = rb?.error ? String(rb.error) : `对端 HTTP ${r.status}`;
|
|
3707
|
+
}
|
|
3708
|
+
} catch (err) {
|
|
3709
|
+
note = String(err?.message ?? err);
|
|
3710
|
+
}
|
|
3711
|
+
if (!remoteBase) {
|
|
3712
|
+
const ep = orderedEndpoints(target)[0];
|
|
3713
|
+
if (!ep?.host) return { error: note || "对端没有上报地址" };
|
|
3714
|
+
remoteBase = `http://${ep.host}:${WEB_PANEL_DEFAULT_PORT}/`;
|
|
3715
|
+
}
|
|
3716
|
+
if (!token) note = note || "对端没有给出 token(对端插件需升级到带 /mesh/v1/web-url 的版本)";
|
|
3717
|
+
return { remoteBase, token, lanReachable, note };
|
|
3718
|
+
}
|
|
3719
|
+
|
|
3720
|
+
post("/mesh/api/web-panel", async (req, res) => {
|
|
3721
|
+
const body = await readJson(req);
|
|
3722
|
+
const found = findPeer(String(body?.peer ?? "").trim());
|
|
3723
|
+
if (found.error) return send(res, 404, { ok: false, error: found.error });
|
|
3724
|
+
const target = found.peer;
|
|
3725
|
+
const machine = target.machine || String(body?.peer ?? "");
|
|
3726
|
+
|
|
3727
|
+
const resolved = await resolveWebTarget(
|
|
3728
|
+
target,
|
|
3729
|
+
typeof body?.token === "string" ? body.token.trim() : "",
|
|
3730
|
+
);
|
|
3731
|
+
if (resolved.error) return send(res, 400, { ok: false, error: resolved.error });
|
|
3732
|
+
|
|
3733
|
+
const signature = `${resolved.remoteBase}|${resolved.pathPrefix || ""}|${resolved.passthrough ? "p" : "c"}`;
|
|
3734
|
+
try {
|
|
3735
|
+
const existing = webPanels.get(machine);
|
|
3736
|
+
if (existing && existing.signature === signature) {
|
|
3737
|
+
return send(res, 200, {
|
|
3738
|
+
ok: true,
|
|
3739
|
+
url: existing.proxy.url,
|
|
3740
|
+
remote: existing.proxy.remote,
|
|
3741
|
+
hasSession: existing.proxy.hasSession(),
|
|
3742
|
+
note: resolved.note,
|
|
3743
|
+
lanReachable: resolved.lanReachable,
|
|
3744
|
+
});
|
|
3745
|
+
}
|
|
3746
|
+
if (existing) {
|
|
3747
|
+
webPanels.delete(machine);
|
|
3748
|
+
await existing.proxy.close();
|
|
3749
|
+
}
|
|
3750
|
+
const proxy = await createWebProxy({
|
|
3751
|
+
remoteBase: resolved.remoteBase,
|
|
3752
|
+
token: resolved.token,
|
|
3753
|
+
nonce: randomBytes(18).toString("base64url"),
|
|
3754
|
+
initialCookie: readPanelCookies()[resolved.remoteBase] || "",
|
|
3755
|
+
onCookie: (cookie) => writePanelCookie(resolved.remoteBase, cookie),
|
|
3756
|
+
pathPrefix: resolved.pathPrefix || "",
|
|
3757
|
+
passthrough: resolved.passthrough === true,
|
|
3758
|
+
log,
|
|
3759
|
+
warn,
|
|
3760
|
+
});
|
|
3761
|
+
webPanels.set(machine, { proxy, remote: resolved.remoteBase, signature });
|
|
3762
|
+
return send(res, 200, {
|
|
3763
|
+
ok: true,
|
|
3764
|
+
url: proxy.url,
|
|
3765
|
+
remote: proxy.remote,
|
|
3766
|
+
hasSession: proxy.hasSession(),
|
|
3767
|
+
note: resolved.note,
|
|
3768
|
+
lanReachable: resolved.lanReachable,
|
|
3769
|
+
});
|
|
3770
|
+
} catch (err) {
|
|
3771
|
+
return send(res, 502, { ok: false, error: String(err?.message ?? err) });
|
|
3772
|
+
}
|
|
3773
|
+
});
|
|
3774
|
+
|
|
3775
|
+
post("/mesh/api/web-panel/close", async (req, res) => {
|
|
3776
|
+
const body = await readJson(req);
|
|
3777
|
+
const machine = String(body?.peer ?? "").trim();
|
|
3778
|
+
const entry = webPanels.get(machine);
|
|
3779
|
+
if (entry) {
|
|
3780
|
+
webPanels.delete(machine);
|
|
3781
|
+
try {
|
|
3782
|
+
await entry.proxy.close();
|
|
3783
|
+
} catch (err) {
|
|
3784
|
+
warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
|
|
3785
|
+
}
|
|
3786
|
+
}
|
|
3787
|
+
return send(res, 200, { ok: true });
|
|
3788
|
+
});
|
|
3789
|
+
|
|
3790
|
+
// ── 「本机另一个引擎」的前缀转发(desktopWebPort > 0 才开)────────────
|
|
3791
|
+
//
|
|
3792
|
+
// 同一台机器上通常有两个引擎:桌面 App(有历史会话,只听 loopback)和
|
|
3793
|
+
// CLI/web 引擎(就是我们)。手机要看的往往是前者,所以这里开一条
|
|
3794
|
+
// `/mesh/web/...`:去掉前缀转发到 127.0.0.1:<desktopWebPort>,并自带
|
|
3795
|
+
// 签名 cookie(密钥与那个引擎共用,见 desktop-auth.js)。
|
|
3796
|
+
if (typeof config.desktopWebPort === "number" && config.desktopWebPort > 0) {
|
|
3797
|
+
const dshHome = process.env.DSH_HOME || join(homedir(), ".dsh");
|
|
3798
|
+
const secretOf = createSecretReader(join(dshHome, ".credentials.yaml"));
|
|
3799
|
+
const targetPort = config.desktopWebPort;
|
|
3800
|
+
const handle = createDesktopWebForwarder({ port: targetPort, secretOf, log, warn });
|
|
3801
|
+
ctx.effect(() =>
|
|
3802
|
+
ctx.webServer.register({
|
|
3803
|
+
kind: "prefix",
|
|
3804
|
+
path: DESKTOP_WEB_PREFIX,
|
|
3805
|
+
handler: async (req, res) => {
|
|
3806
|
+
try {
|
|
3807
|
+
await handle(req, res);
|
|
3808
|
+
} catch (err) {
|
|
3809
|
+
warn(`桌面引擎转发异常:${err?.message ?? err}`);
|
|
3810
|
+
if (!res.headersSent) {
|
|
3811
|
+
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
3812
|
+
res.end("monitor forwarder failed\n");
|
|
3813
|
+
}
|
|
3814
|
+
}
|
|
3815
|
+
},
|
|
3816
|
+
}),
|
|
3817
|
+
);
|
|
3818
|
+
// 流式载波(WebSocket):工作区/会话的实时数据走它,缺了这条前端会一直"自动重连中"。
|
|
3819
|
+
const upgrade = createDesktopWebUpgrade({ port: targetPort, secretOf, log, warn });
|
|
3820
|
+
ctx.effect(() => ctx.webServer.registerUpgrade({ path: DESKTOP_WEB_STREAM_PATH, handler: upgrade }));
|
|
3821
|
+
log(`已开启本机引擎转发:${DESKTOP_WEB_PREFIX}/* → 127.0.0.1:${targetPort}(含 ${DESKTOP_WEB_STREAM_PATH})`);
|
|
3822
|
+
}
|
|
3823
|
+
|
|
3824
|
+
// ── 应用内 SSH 终端 ───────────────────────────────────────────────────
|
|
3825
|
+
//
|
|
3826
|
+
// 入口在设备行(与「访问 DSH Web」同一位置)。会话由本机发起,凭据只存本机;
|
|
3827
|
+
// 传输走同源 WebSocket(/mesh/api/ssh/ws),所以不需要经过上面对端的 web 转发。
|
|
3828
|
+
const ssh = createSshManager({
|
|
3829
|
+
stateDir: stateDir(),
|
|
3830
|
+
credentialsPath: join(stateDir(), "ssh-credentials.json"),
|
|
3831
|
+
log,
|
|
3832
|
+
warn,
|
|
3833
|
+
});
|
|
3834
|
+
ctx.effect(() => () => ssh.closeAll());
|
|
3835
|
+
|
|
3836
|
+
post("/mesh/api/ssh/known", async (req, res) => {
|
|
3837
|
+
const body = await readJson(req);
|
|
3838
|
+
const machine = String(body?.machine ?? "").trim();
|
|
3839
|
+
// 只回用户名与"是否已部署密钥",不回密码:密码没有再穿过一次网络的理由
|
|
3840
|
+
const info = ssh.describe(machine);
|
|
3841
|
+
return send(res, 200, { ok: true, username: info.username, hasKey: info.hasKey, saved: !!info.username });
|
|
3842
|
+
});
|
|
3843
|
+
|
|
3844
|
+
post("/mesh/api/ssh/sessions", (_req, res) => send(res, 200, { ok: true, sessions: ssh.list() }));
|
|
3845
|
+
|
|
3846
|
+
// 一条 upgrade 路由承载所有终端(按会话 id 多路复用)
|
|
3847
|
+
const sshUpgrade = (req, socket, head) => {
|
|
3848
|
+
const chan = acceptUpgrade(req, socket, head, {
|
|
3849
|
+
onMessage: async (raw) => {
|
|
3850
|
+
let msg;
|
|
3851
|
+
try {
|
|
3852
|
+
msg = JSON.parse(raw);
|
|
3853
|
+
} catch {
|
|
3854
|
+
return;
|
|
3855
|
+
}
|
|
3856
|
+
try {
|
|
3857
|
+
if (msg?.type === "open") {
|
|
3858
|
+
const cols = Number(msg.cols) > 0 ? Number(msg.cols) : 80;
|
|
3859
|
+
const rows = Number(msg.rows) > 0 ? Number(msg.rows) : 24;
|
|
3860
|
+
// 地址不要直接信客户端传来的 peer.host:端点顺序会变(tailnet 可能排前面),
|
|
3861
|
+
// 用 tailnet 地址去连 22 端口会卡到 "timed out waiting for handshake"。
|
|
3862
|
+
// 这里按 discover 的端点表优先挑局域网地址,其次才用它给的。
|
|
3863
|
+
const machine = String(msg.machine ?? "");
|
|
3864
|
+
let host = String(msg.host ?? "");
|
|
3865
|
+
try {
|
|
3866
|
+
const found = machine ? findPeer(machine) : { error: "缺少机器名" };
|
|
3867
|
+
const target = found && found.peer;
|
|
3868
|
+
if (target) {
|
|
3869
|
+
const eps = orderedEndpoints(target);
|
|
3870
|
+
const isPrivate = (h) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(String(h ?? ""));
|
|
3871
|
+
host = (eps.find((e) => isPrivate(e.host)) ?? eps.find((e) => e.host))?.host ?? host;
|
|
3872
|
+
}
|
|
3873
|
+
} catch {
|
|
3874
|
+
/* 解析失败就用客户端给的地址 */
|
|
3875
|
+
}
|
|
3876
|
+
const id = await ssh.open({
|
|
3877
|
+
host,
|
|
3878
|
+
port: Number(msg.port) > 0 ? Number(msg.port) : 22,
|
|
3879
|
+
username: String(msg.username ?? ""),
|
|
3880
|
+
password: typeof msg.password === "string" ? msg.password : "",
|
|
3881
|
+
cols,
|
|
3882
|
+
rows,
|
|
3883
|
+
machine,
|
|
3884
|
+
});
|
|
3885
|
+
chan.send(JSON.stringify({ type: "ready", id, buffer: ssh.ring(id) }));
|
|
3886
|
+
ssh.subscribe(id, (chunk) => {
|
|
3887
|
+
chan.send(JSON.stringify(chunk === null ? { type: "exit", id } : { type: "data", id, data: chunk }));
|
|
3888
|
+
});
|
|
3889
|
+
return;
|
|
3890
|
+
}
|
|
3891
|
+
const id = String(msg?.id ?? "");
|
|
3892
|
+
if (msg?.type === "input") ssh.write(id, String(msg.data ?? ""));
|
|
3893
|
+
else if (msg?.type === "resize") ssh.resize(id, Number(msg.cols) || 80, Number(msg.rows) || 24);
|
|
3894
|
+
else if (msg?.type === "close") ssh.close(id);
|
|
3895
|
+
} catch (error) {
|
|
3896
|
+
chan.send(JSON.stringify({ type: "error", message: String(error?.message ?? error) }));
|
|
3897
|
+
}
|
|
3898
|
+
},
|
|
3899
|
+
});
|
|
3900
|
+
};
|
|
3901
|
+
ctx.effect(() => ctx.webServer.registerUpgrade({ path: "/mesh/api/ssh/ws", handler: sshUpgrade }));
|
|
3902
|
+
|
|
3903
|
+
log("UI 接口已挂载: /mesh/api/state|refresh|secret|send|probe|web-url|web-panel|ssh");
|
|
2991
3904
|
}
|