dsh-plugin-mesh 0.5.5 → 0.5.7
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/README.md +49 -0
- package/client/client.js +983 -20
- package/lib/_selftest-update.mjs +267 -0
- package/lib/_selftest-workbench.mjs +141 -0
- package/lib/desktop-auth.js +88 -0
- package/lib/desktop-web.js +146 -0
- package/lib/index.js +445 -2
- package/lib/ssh-host.js +380 -0
- package/lib/update.js +232 -0
- package/lib/web-proxy.js +333 -0
- package/lib/ws-mini.js +156 -0
- package/llms.txt +23 -0
- package/package.json +7 -3
- package/scripts/check-tdz.mjs +1 -1
package/lib/index.js
CHANGED
|
@@ -46,6 +46,7 @@ import {
|
|
|
46
46
|
} from "./capabilities.js";
|
|
47
47
|
import { conversationKey, replyTarget } from "./conversation.js";
|
|
48
48
|
import { buildDiagnostics, entryInfo, readPackageVersion } from "./diagnostics.js";
|
|
49
|
+
import { buildUpdateReport, fetchLatestVersion, pluginDirFromUrl } from "./update.js";
|
|
49
50
|
import { buildPrompt } from "./prompt.js";
|
|
50
51
|
import { resolvePairing } from "./pairing.js";
|
|
51
52
|
import {
|
|
@@ -64,23 +65,39 @@ import {
|
|
|
64
65
|
import { TsnetNode, channelKey, channelSignature } from "./tsnet/manager.js";
|
|
65
66
|
import { resolveTailnetChannels } from "./tsnet/channels.js";
|
|
66
67
|
import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
|
|
68
|
+
import { createWebProxy } from "./web-proxy.js";
|
|
69
|
+
import { createSecretReader } from "./desktop-auth.js";
|
|
70
|
+
import { createSshManager } from "./ssh-host.js";
|
|
71
|
+
import { acceptUpgrade } from "./ws-mini.js";
|
|
72
|
+
import {
|
|
73
|
+
createDesktopWebForwarder,
|
|
74
|
+
createDesktopWebUpgrade,
|
|
75
|
+
DESKTOP_WEB_PREFIX,
|
|
76
|
+
DESKTOP_WEB_STREAM_PATH,
|
|
77
|
+
} from "./desktop-web.js";
|
|
67
78
|
|
|
68
79
|
export const name = "dsh-plugin-mesh";
|
|
69
80
|
export const inject = ["tools", "webServer"];
|
|
70
81
|
|
|
71
|
-
const VERSION = "0.5.
|
|
82
|
+
const VERSION = "0.5.7";
|
|
72
83
|
// 诊断用:进程启动时间、入口真实路径、**磁盘上** package.json 的版本。
|
|
73
84
|
// 这三样放一起才能回答"现在跑的到底是哪份代码" —— 只看 state.json 或重启日志
|
|
74
85
|
// 都答不了(真踩过:磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
|
|
75
86
|
const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
|
|
76
87
|
const ENTRY_INFO = entryInfo(import.meta.url);
|
|
77
88
|
const DISK_VERSION = readPackageVersion(import.meta.url);
|
|
89
|
+
/** 本插件的安装目录:界面生成「升级命令」时直接用它,不让人再猜 <PLUGIN> 是什么。 */
|
|
90
|
+
const PLUGIN_DIR = pluginDirFromUrl(import.meta.url);
|
|
91
|
+
/** 一次性取文件用的 nonce:进程每次启动都换,写进日志给运维/agent 取。 */
|
|
92
|
+
const FILE_TRANSFER_NONCE = randomBytes(9).toString("base64url");
|
|
78
93
|
const RULE_ID = "mesh-inbound";
|
|
79
94
|
const RULE_KIND = "mesh";
|
|
80
95
|
const MAX_BODY = 256 * 1024;
|
|
81
96
|
const MAX_HISTORY = 200;
|
|
82
97
|
/** 默认固定端口:内网里"扫这个端口 + ping 一下"就能建立连接,无需任何配置。 */
|
|
83
98
|
export const MESH_DEFAULT_PORT = 45917;
|
|
99
|
+
/** 对端 DSH Web 的部署默认端口(回环代理拿不到对端自报地址时按它拼)。 */
|
|
100
|
+
const WEB_PANEL_DEFAULT_PORT = 3080;
|
|
84
101
|
|
|
85
102
|
/**
|
|
86
103
|
* 互联网自组网(tailnet)通道:通道 id → 节点句柄。
|
|
@@ -154,6 +171,12 @@ export const Config = z.object({
|
|
|
154
171
|
* 同机跑多个实例时会被占用,此时自动退回随机端口(仍能用组播互相发现)。
|
|
155
172
|
*/
|
|
156
173
|
port: z.natural().default(MESH_DEFAULT_PORT),
|
|
174
|
+
/**
|
|
175
|
+
* 本机另一个 DSH 引擎(通常是桌面 App)的 Web 端口:0 = 关闭这条前缀代理。
|
|
176
|
+
* 开了之后 `<本机>:<port>/mesh/web/...` 会转发到 127.0.0.1:<desktopWebPort>,
|
|
177
|
+
* 并自带签名 cookie —— 供手机在应用内查看"有历史会话的那个引擎"。
|
|
178
|
+
*/
|
|
179
|
+
desktopWebPort: z.natural().max(65535).default(0),
|
|
157
180
|
announceIntervalMs: z.natural().default(5000),
|
|
158
181
|
/** 超过这么久没心跳、也没 ping 通,算离线 */
|
|
159
182
|
peerTtlMs: z.natural().default(20000),
|
|
@@ -1189,6 +1212,7 @@ function applyUnsafe(ctx, config) {
|
|
|
1189
1212
|
await syncRuntime({ reason: "启动" });
|
|
1190
1213
|
log(
|
|
1191
1214
|
`已启动 machine=${identity.name}(来源 ${identity.source})` +
|
|
1215
|
+
` 文件搬运 nonce=${FILE_TRANSFER_NONCE}` +
|
|
1192
1216
|
` 地址=${preferredAddress()}:${discovery.port || "?"} 实例=${instanceId} ` +
|
|
1193
1217
|
`配对要求=${config.requirePairing ? "开" : "关"} ` +
|
|
1194
1218
|
`开关=${describeMeshSwitch(switchDesired)}`,
|
|
@@ -2320,9 +2344,70 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
|
|
|
2320
2344
|
|
|
2321
2345
|
if (!authed(req)) return send(res, 403, { ok: false, error: "未配对:两台机器的配对码不一致(本机开启了 requirePairing)" });
|
|
2322
2346
|
|
|
2347
|
+
// 一次性文件搬运:给对端取本机插件包里的文件(同版本部署用)。
|
|
2348
|
+
// 只认启动时生成的 nonce,且路径必须落在插件包目录内 —— 不是通用文件服务。
|
|
2349
|
+
if (path === "/mesh/v1/file" && req.method === "GET") {
|
|
2350
|
+
const nonce = url.searchParams.get("k") ?? "";
|
|
2351
|
+
// 两个都认:进程内的随机 nonce,或本机的 mesh 密钥(可从 state.json 读到,
|
|
2352
|
+
// 方便"人在旁边"时一次搬运;两者都不用改配置)。
|
|
2353
|
+
if (!safeEqual(nonce, FILE_TRANSFER_NONCE) && !safeEqual(nonce, currentSecret())) {
|
|
2354
|
+
return send(res, 403, { ok: false, error: "nonce 不对" });
|
|
2355
|
+
}
|
|
2356
|
+
const wanted = url.searchParams.get("path") ?? "";
|
|
2357
|
+
const packageRoot = resolve(ENTRY_INFO.path, "..", "..");
|
|
2358
|
+
const absolute = resolve(wanted);
|
|
2359
|
+
if (!absolute.startsWith(`${packageRoot}/`)) {
|
|
2360
|
+
return send(res, 400, { ok: false, error: "路径超出插件包目录" });
|
|
2361
|
+
}
|
|
2362
|
+
try {
|
|
2363
|
+
const body = readFileSync(absolute);
|
|
2364
|
+
res.writeHead(200, {
|
|
2365
|
+
"content-type": "application/octet-stream",
|
|
2366
|
+
"content-length": String(body.length),
|
|
2367
|
+
});
|
|
2368
|
+
res.end(body);
|
|
2369
|
+
return;
|
|
2370
|
+
} catch (err) {
|
|
2371
|
+
return send(res, 404, { ok: false, error: String(err?.message ?? err) });
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
|
|
2323
2375
|
// 诊断:进程版本 vs 磁盘版本。**必须在对端鉴权之后** —— 里面有本机路径。
|
|
2324
2376
|
if (path === "/mesh/v1/diagnostics") return send(res, 200, diagnostics());
|
|
2325
2377
|
|
|
2378
|
+
// 本机 DSH Web GUI 的入口地址(带启动 token)。
|
|
2379
|
+
//
|
|
2380
|
+
// 只在这里按需发放,**绝不**放进 discovery 广播:那条是明文组播,
|
|
2381
|
+
// 谁加入组播谁就能读到 token,等于把本机的 RCE 交给整个网段。
|
|
2382
|
+
// 走这条路径时要过 authed(),也就是跟着配对开关一起受保护。
|
|
2383
|
+
//
|
|
2384
|
+
// token 是进程级的、随重启轮换;浏览器第一次带 token 打开后会拿到
|
|
2385
|
+
// 一枚 30 天、绑定 authority 的签名 cookie,之后不带 token 也能开。
|
|
2386
|
+
if (path === "/mesh/v1/web-url" && req.method === "GET") {
|
|
2387
|
+
try {
|
|
2388
|
+
const connection = ctx.get("connection");
|
|
2389
|
+
const port = ctx.get("webServer")?.port;
|
|
2390
|
+
const bind = ctx.get("webServer")?.host ?? "";
|
|
2391
|
+
if (!connection || typeof connection.authenticatedUrl !== "function" || !port) {
|
|
2392
|
+
return send(res, 200, { ok: false, supported: false, error: "本端没有可用的 Web GUI(不是 web profile)" });
|
|
2393
|
+
}
|
|
2394
|
+
const lanHost = preferredAddress();
|
|
2395
|
+
// 只绑了回环时如实说:地址虽然给得出来,但局域网里连不通。
|
|
2396
|
+
const lanReachable = bind === "0.0.0.0" && !!lanHost;
|
|
2397
|
+
const host = lanReachable ? lanHost : "127.0.0.1";
|
|
2398
|
+
return send(res, 200, {
|
|
2399
|
+
ok: true,
|
|
2400
|
+
supported: true,
|
|
2401
|
+
url: connection.authenticatedUrl(`http://${host}:${port}/`),
|
|
2402
|
+
bind,
|
|
2403
|
+
lanReachable,
|
|
2404
|
+
port,
|
|
2405
|
+
});
|
|
2406
|
+
} catch (err) {
|
|
2407
|
+
return send(res, 200, { ok: false, supported: false, error: String(err?.message ?? err) });
|
|
2408
|
+
}
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2326
2411
|
if (path === "/mesh/v1/peers") return send(res, 200, { ok: true, peers: discovery.peers() });
|
|
2327
2412
|
|
|
2328
2413
|
if (path === "/mesh/v1/tasks" && req.method === "GET") {
|
|
@@ -2901,6 +2986,43 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2901
2986
|
// 只读诊断:UI 的「诊断」卡片用它;与 /mesh/v1/diagnostics 同一份数据。
|
|
2902
2987
|
route("/mesh/api/diagnostics", (_req, res) => send(res, 200, diagnostics()));
|
|
2903
2988
|
|
|
2989
|
+
/**
|
|
2990
|
+
* 检查更新:向 npm registry 问一次最新版本。
|
|
2991
|
+
*
|
|
2992
|
+
* 只读(GET),但要带缓存:
|
|
2993
|
+
* · 成功缓存 30 分钟 —— 主页每次进入都会问一次,不能让面板变成 registry 的
|
|
2994
|
+
* 高频客户端;
|
|
2995
|
+
* · 失败只缓存 1 分钟 —— 网络刚恢复时用户点「重新检查」应该马上能成功,
|
|
2996
|
+
* 但也不能让离线状态下的反复点按变成打点风暴。
|
|
2997
|
+
* 失败一律返回 200 + `{ok:false,error}`:这是「没问到」,不是 HTTP 故障,
|
|
2998
|
+
* 界面要把它和「已是最新」分开显示。
|
|
2999
|
+
*/
|
|
3000
|
+
const UPDATE_OK_TTL_MS = 30 * 60 * 1000;
|
|
3001
|
+
const UPDATE_FAIL_TTL_MS = 60 * 1000;
|
|
3002
|
+
let updateCache = null;
|
|
3003
|
+
route("/mesh/api/update", async (req, res) => {
|
|
3004
|
+
const force = /[?&]force=1(?:&|$)/.test(String(req.url || ""));
|
|
3005
|
+
const now = Date.now();
|
|
3006
|
+
if (!force && updateCache) {
|
|
3007
|
+
const ttl = updateCache.report.ok ? UPDATE_OK_TTL_MS : UPDATE_FAIL_TTL_MS;
|
|
3008
|
+
if (now - updateCache.at < ttl) {
|
|
3009
|
+
return send(res, 200, { ...updateCache.report, cached: true });
|
|
3010
|
+
}
|
|
3011
|
+
}
|
|
3012
|
+
// 5 秒:主页是首屏,等不起更久;两源合计最坏也就 10 秒。
|
|
3013
|
+
const latest = await fetchLatestVersion({ timeoutMs: 5000 });
|
|
3014
|
+
const report = buildUpdateReport({
|
|
3015
|
+
current: VERSION,
|
|
3016
|
+
diskVersion: DISK_VERSION,
|
|
3017
|
+
latest,
|
|
3018
|
+
pluginDir: PLUGIN_DIR,
|
|
3019
|
+
now: Date.now(),
|
|
3020
|
+
});
|
|
3021
|
+
updateCache = { at: Date.now(), report };
|
|
3022
|
+
if (!report.ok) log(`检查更新失败(不是「已是最新」): ${report.error}`);
|
|
3023
|
+
send(res, 200, report);
|
|
3024
|
+
});
|
|
3025
|
+
|
|
2904
3026
|
/**
|
|
2905
3027
|
* 用户决定提高某个 thread 的限速上限。
|
|
2906
3028
|
*
|
|
@@ -3497,5 +3619,326 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
3497
3619
|
}
|
|
3498
3620
|
});
|
|
3499
3621
|
|
|
3500
|
-
|
|
3622
|
+
post("/mesh/api/web-url", async (req, res) => {
|
|
3623
|
+
const body = await readJson(req);
|
|
3624
|
+
const found = findPeer(String(body?.peer ?? "").trim());
|
|
3625
|
+
if (found.error) return send(res, 404, { ok: false, error: found.error });
|
|
3626
|
+
const target = found.peer;
|
|
3627
|
+
try {
|
|
3628
|
+
const r = await peerFetch(target, "/mesh/v1/web-url", {
|
|
3629
|
+
headers: { "X-Dsh-Mesh-Token": currentSecret() },
|
|
3630
|
+
timeoutMs: 5000,
|
|
3631
|
+
});
|
|
3632
|
+
const rb = await r.json().catch(() => ({}));
|
|
3633
|
+
// 400/404 = 对端是老版本插件,没有这条路由。如实区分"不支持"和"取不到"。
|
|
3634
|
+
if (!r.ok || rb?.ok !== true || typeof rb?.url !== "string") {
|
|
3635
|
+
return send(res, 200, {
|
|
3636
|
+
ok: false,
|
|
3637
|
+
supported: rb?.supported === true,
|
|
3638
|
+
error: rb?.error || `对端 HTTP ${r.status}`,
|
|
3639
|
+
});
|
|
3640
|
+
}
|
|
3641
|
+
return send(res, 200, {
|
|
3642
|
+
ok: true,
|
|
3643
|
+
url: rb.url,
|
|
3644
|
+
bind: rb.bind ?? "",
|
|
3645
|
+
lanReachable: rb.lanReachable === true,
|
|
3646
|
+
port: rb.port ?? 0,
|
|
3647
|
+
});
|
|
3648
|
+
} catch (err) {
|
|
3649
|
+
return send(res, 200, { ok: false, supported: false, error: String(err?.message ?? err) });
|
|
3650
|
+
}
|
|
3651
|
+
});
|
|
3652
|
+
|
|
3653
|
+
// ── 对端 DSH Web 的应用内面板(回环反代 + 服务端认证)─────────────────
|
|
3654
|
+
//
|
|
3655
|
+
// 为什么不直接把对端地址塞进 iframe:对端会话 cookie 是 SameSite=Strict,
|
|
3656
|
+
// 跨站 iframe 里不发送,token 又随对端重启轮换 —— 页面会永远停在 401。
|
|
3657
|
+
// 所以认证搬到服务端:代理用 token 换一次 cookie,之后每个请求自己带;
|
|
3658
|
+
// 浏览器只跟本机 127.0.0.1 的这个端口说话。
|
|
3659
|
+
const webPanels = new Map(); // 机器名 -> { proxy, remote }
|
|
3660
|
+
|
|
3661
|
+
// 对端会话 cookie 落盘:token 每次重启都会轮换,而 cookie 是 30 天、由对端
|
|
3662
|
+
// 持久密钥签名的 —— 存住它就等于以后不必再问 token(到期或换密钥再补一次)。
|
|
3663
|
+
const panelStatePath = () => join(stateDir(), "web-panels.json");
|
|
3664
|
+
const readPanelCookies = () => {
|
|
3665
|
+
try {
|
|
3666
|
+
const value = JSON.parse(readFileSync(panelStatePath(), "utf8"));
|
|
3667
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
3668
|
+
} catch {
|
|
3669
|
+
return {};
|
|
3670
|
+
}
|
|
3671
|
+
};
|
|
3672
|
+
const writePanelCookie = (origin, cookie) => {
|
|
3673
|
+
try {
|
|
3674
|
+
const all = readPanelCookies();
|
|
3675
|
+
all[origin] = cookie;
|
|
3676
|
+
mkdirSync(stateDir(), { recursive: true });
|
|
3677
|
+
writeFileSync(panelStatePath(), JSON.stringify(all, null, 2));
|
|
3678
|
+
} catch (err) {
|
|
3679
|
+
warn(`保存对端 cookie 失败:${err?.message ?? err}`);
|
|
3680
|
+
}
|
|
3681
|
+
};
|
|
3682
|
+
|
|
3683
|
+
const closeWebPanels = async () => {
|
|
3684
|
+
const entries = [...webPanels.values()];
|
|
3685
|
+
webPanels.clear();
|
|
3686
|
+
for (const entry of entries) {
|
|
3687
|
+
try {
|
|
3688
|
+
await entry.proxy.close();
|
|
3689
|
+
} catch (err) {
|
|
3690
|
+
warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
|
|
3691
|
+
}
|
|
3692
|
+
}
|
|
3693
|
+
};
|
|
3694
|
+
ctx.effect(() => () => {
|
|
3695
|
+
void closeWebPanels();
|
|
3696
|
+
});
|
|
3697
|
+
|
|
3698
|
+
/** 取对端的 Web 地址与启动 token;老版本对端只能退回按约定拼地址。 */
|
|
3699
|
+
/**
|
|
3700
|
+
* 取对端的 Web 地址与启动 token。
|
|
3701
|
+
* @param target - 对端名片
|
|
3702
|
+
* @param tokenOverride - 调用方手工给的 token(对端插件还没升级时的逃生口)
|
|
3703
|
+
*/
|
|
3704
|
+
async function resolveWebTarget(target, tokenOverride = "") {
|
|
3705
|
+
// 优先:对端开了 desktopWebPort 时,会有一条 /mesh/web/ 前缀转发到它自己的
|
|
3706
|
+
// 另一个引擎(桌面 App 那个,有历史会话)。有就直接用它,认证在对端完成。
|
|
3707
|
+
// 端点可能有多个(局域网 + tailnet),且顺序会变 —— 逐个试,别只认第一个。
|
|
3708
|
+
for (const ep of orderedEndpoints(target)) {
|
|
3709
|
+
if (!ep?.host) continue;
|
|
3710
|
+
const base = `http://${ep.host}:${WEB_PANEL_DEFAULT_PORT}`;
|
|
3711
|
+
try {
|
|
3712
|
+
const probe = await fetch(`${base}${DESKTOP_WEB_PREFIX}/__probe`, { signal: AbortSignal.timeout(2000) });
|
|
3713
|
+
const body = await probe.json().catch(() => ({}));
|
|
3714
|
+
if (probe.ok && body?.ok === true) {
|
|
3715
|
+
return {
|
|
3716
|
+
remoteBase: `${base}/`,
|
|
3717
|
+
pathPrefix: DESKTOP_WEB_PREFIX,
|
|
3718
|
+
passthrough: true,
|
|
3719
|
+
lanReachable: true,
|
|
3720
|
+
note: `转发到对端 ${body.target}`,
|
|
3721
|
+
};
|
|
3722
|
+
}
|
|
3723
|
+
} catch {
|
|
3724
|
+
/* 这条端点不通,试下一条 */
|
|
3725
|
+
}
|
|
3726
|
+
}
|
|
3727
|
+
|
|
3728
|
+
let remoteBase = "";
|
|
3729
|
+
let token = tokenOverride;
|
|
3730
|
+
let lanReachable;
|
|
3731
|
+
let note = "";
|
|
3732
|
+
try {
|
|
3733
|
+
const r = await peerFetch(target, "/mesh/v1/web-url", {
|
|
3734
|
+
headers: { "X-Dsh-Mesh-Token": currentSecret() },
|
|
3735
|
+
timeoutMs: 5000,
|
|
3736
|
+
});
|
|
3737
|
+
const rb = await r.json().catch(() => ({}));
|
|
3738
|
+
if (rb?.ok === true && typeof rb.url === "string") {
|
|
3739
|
+
const parsed = new URL(rb.url);
|
|
3740
|
+
token = parsed.searchParams.get("token") || token;
|
|
3741
|
+
// token 只用来换 cookie,别留在浏览器的地址栏里。
|
|
3742
|
+
parsed.searchParams.delete("token");
|
|
3743
|
+
remoteBase = parsed.href;
|
|
3744
|
+
lanReachable = rb.lanReachable === true;
|
|
3745
|
+
} else {
|
|
3746
|
+
note = rb?.error ? String(rb.error) : `对端 HTTP ${r.status}`;
|
|
3747
|
+
}
|
|
3748
|
+
} catch (err) {
|
|
3749
|
+
note = String(err?.message ?? err);
|
|
3750
|
+
}
|
|
3751
|
+
if (!remoteBase) {
|
|
3752
|
+
const ep = orderedEndpoints(target)[0];
|
|
3753
|
+
if (!ep?.host) return { error: note || "对端没有上报地址" };
|
|
3754
|
+
remoteBase = `http://${ep.host}:${WEB_PANEL_DEFAULT_PORT}/`;
|
|
3755
|
+
}
|
|
3756
|
+
if (!token) note = note || "对端没有给出 token(对端插件需升级到带 /mesh/v1/web-url 的版本)";
|
|
3757
|
+
return { remoteBase, token, lanReachable, note };
|
|
3758
|
+
}
|
|
3759
|
+
|
|
3760
|
+
post("/mesh/api/web-panel", async (req, res) => {
|
|
3761
|
+
const body = await readJson(req);
|
|
3762
|
+
const found = findPeer(String(body?.peer ?? "").trim());
|
|
3763
|
+
if (found.error) return send(res, 404, { ok: false, error: found.error });
|
|
3764
|
+
const target = found.peer;
|
|
3765
|
+
const machine = target.machine || String(body?.peer ?? "");
|
|
3766
|
+
|
|
3767
|
+
const resolved = await resolveWebTarget(
|
|
3768
|
+
target,
|
|
3769
|
+
typeof body?.token === "string" ? body.token.trim() : "",
|
|
3770
|
+
);
|
|
3771
|
+
if (resolved.error) return send(res, 400, { ok: false, error: resolved.error });
|
|
3772
|
+
|
|
3773
|
+
const signature = `${resolved.remoteBase}|${resolved.pathPrefix || ""}|${resolved.passthrough ? "p" : "c"}`;
|
|
3774
|
+
try {
|
|
3775
|
+
const existing = webPanels.get(machine);
|
|
3776
|
+
if (existing && existing.signature === signature) {
|
|
3777
|
+
return send(res, 200, {
|
|
3778
|
+
ok: true,
|
|
3779
|
+
url: existing.proxy.url,
|
|
3780
|
+
remote: existing.proxy.remote,
|
|
3781
|
+
hasSession: existing.proxy.hasSession(),
|
|
3782
|
+
note: resolved.note,
|
|
3783
|
+
lanReachable: resolved.lanReachable,
|
|
3784
|
+
});
|
|
3785
|
+
}
|
|
3786
|
+
if (existing) {
|
|
3787
|
+
webPanels.delete(machine);
|
|
3788
|
+
await existing.proxy.close();
|
|
3789
|
+
}
|
|
3790
|
+
const proxy = await createWebProxy({
|
|
3791
|
+
remoteBase: resolved.remoteBase,
|
|
3792
|
+
token: resolved.token,
|
|
3793
|
+
nonce: randomBytes(18).toString("base64url"),
|
|
3794
|
+
initialCookie: readPanelCookies()[resolved.remoteBase] || "",
|
|
3795
|
+
onCookie: (cookie) => writePanelCookie(resolved.remoteBase, cookie),
|
|
3796
|
+
pathPrefix: resolved.pathPrefix || "",
|
|
3797
|
+
passthrough: resolved.passthrough === true,
|
|
3798
|
+
log,
|
|
3799
|
+
warn,
|
|
3800
|
+
});
|
|
3801
|
+
webPanels.set(machine, { proxy, remote: resolved.remoteBase, signature });
|
|
3802
|
+
return send(res, 200, {
|
|
3803
|
+
ok: true,
|
|
3804
|
+
url: proxy.url,
|
|
3805
|
+
remote: proxy.remote,
|
|
3806
|
+
hasSession: proxy.hasSession(),
|
|
3807
|
+
note: resolved.note,
|
|
3808
|
+
lanReachable: resolved.lanReachable,
|
|
3809
|
+
});
|
|
3810
|
+
} catch (err) {
|
|
3811
|
+
return send(res, 502, { ok: false, error: String(err?.message ?? err) });
|
|
3812
|
+
}
|
|
3813
|
+
});
|
|
3814
|
+
|
|
3815
|
+
post("/mesh/api/web-panel/close", async (req, res) => {
|
|
3816
|
+
const body = await readJson(req);
|
|
3817
|
+
const machine = String(body?.peer ?? "").trim();
|
|
3818
|
+
const entry = webPanels.get(machine);
|
|
3819
|
+
if (entry) {
|
|
3820
|
+
webPanels.delete(machine);
|
|
3821
|
+
try {
|
|
3822
|
+
await entry.proxy.close();
|
|
3823
|
+
} catch (err) {
|
|
3824
|
+
warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
|
|
3825
|
+
}
|
|
3826
|
+
}
|
|
3827
|
+
return send(res, 200, { ok: true });
|
|
3828
|
+
});
|
|
3829
|
+
|
|
3830
|
+
// ── 「本机另一个引擎」的前缀转发(desktopWebPort > 0 才开)────────────
|
|
3831
|
+
//
|
|
3832
|
+
// 同一台机器上通常有两个引擎:桌面 App(有历史会话,只听 loopback)和
|
|
3833
|
+
// CLI/web 引擎(就是我们)。手机要看的往往是前者,所以这里开一条
|
|
3834
|
+
// `/mesh/web/...`:去掉前缀转发到 127.0.0.1:<desktopWebPort>,并自带
|
|
3835
|
+
// 签名 cookie(密钥与那个引擎共用,见 desktop-auth.js)。
|
|
3836
|
+
if (typeof config.desktopWebPort === "number" && config.desktopWebPort > 0) {
|
|
3837
|
+
const dshHome = process.env.DSH_HOME || join(homedir(), ".dsh");
|
|
3838
|
+
const secretOf = createSecretReader(join(dshHome, ".credentials.yaml"));
|
|
3839
|
+
const targetPort = config.desktopWebPort;
|
|
3840
|
+
const handle = createDesktopWebForwarder({ port: targetPort, secretOf, log, warn });
|
|
3841
|
+
ctx.effect(() =>
|
|
3842
|
+
ctx.webServer.register({
|
|
3843
|
+
kind: "prefix",
|
|
3844
|
+
path: DESKTOP_WEB_PREFIX,
|
|
3845
|
+
handler: async (req, res) => {
|
|
3846
|
+
try {
|
|
3847
|
+
await handle(req, res);
|
|
3848
|
+
} catch (err) {
|
|
3849
|
+
warn(`桌面引擎转发异常:${err?.message ?? err}`);
|
|
3850
|
+
if (!res.headersSent) {
|
|
3851
|
+
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
|
3852
|
+
res.end("monitor forwarder failed\n");
|
|
3853
|
+
}
|
|
3854
|
+
}
|
|
3855
|
+
},
|
|
3856
|
+
}),
|
|
3857
|
+
);
|
|
3858
|
+
// 流式载波(WebSocket):工作区/会话的实时数据走它,缺了这条前端会一直"自动重连中"。
|
|
3859
|
+
const upgrade = createDesktopWebUpgrade({ port: targetPort, secretOf, log, warn });
|
|
3860
|
+
ctx.effect(() => ctx.webServer.registerUpgrade({ path: DESKTOP_WEB_STREAM_PATH, handler: upgrade }));
|
|
3861
|
+
log(`已开启本机引擎转发:${DESKTOP_WEB_PREFIX}/* → 127.0.0.1:${targetPort}(含 ${DESKTOP_WEB_STREAM_PATH})`);
|
|
3862
|
+
}
|
|
3863
|
+
|
|
3864
|
+
// ── 应用内 SSH 终端 ───────────────────────────────────────────────────
|
|
3865
|
+
//
|
|
3866
|
+
// 入口在设备行(与「访问 DSH Web」同一位置)。会话由本机发起,凭据只存本机;
|
|
3867
|
+
// 传输走同源 WebSocket(/mesh/api/ssh/ws),所以不需要经过上面对端的 web 转发。
|
|
3868
|
+
const ssh = createSshManager({
|
|
3869
|
+
stateDir: stateDir(),
|
|
3870
|
+
credentialsPath: join(stateDir(), "ssh-credentials.json"),
|
|
3871
|
+
log,
|
|
3872
|
+
warn,
|
|
3873
|
+
});
|
|
3874
|
+
ctx.effect(() => () => ssh.closeAll());
|
|
3875
|
+
|
|
3876
|
+
post("/mesh/api/ssh/known", async (req, res) => {
|
|
3877
|
+
const body = await readJson(req);
|
|
3878
|
+
const machine = String(body?.machine ?? "").trim();
|
|
3879
|
+
// 只回用户名与"是否已部署密钥",不回密码:密码没有再穿过一次网络的理由
|
|
3880
|
+
const info = ssh.describe(machine);
|
|
3881
|
+
return send(res, 200, { ok: true, username: info.username, hasKey: info.hasKey, saved: !!info.username });
|
|
3882
|
+
});
|
|
3883
|
+
|
|
3884
|
+
post("/mesh/api/ssh/sessions", (_req, res) => send(res, 200, { ok: true, sessions: ssh.list() }));
|
|
3885
|
+
|
|
3886
|
+
// 一条 upgrade 路由承载所有终端(按会话 id 多路复用)
|
|
3887
|
+
const sshUpgrade = (req, socket, head) => {
|
|
3888
|
+
const chan = acceptUpgrade(req, socket, head, {
|
|
3889
|
+
onMessage: async (raw) => {
|
|
3890
|
+
let msg;
|
|
3891
|
+
try {
|
|
3892
|
+
msg = JSON.parse(raw);
|
|
3893
|
+
} catch {
|
|
3894
|
+
return;
|
|
3895
|
+
}
|
|
3896
|
+
try {
|
|
3897
|
+
if (msg?.type === "open") {
|
|
3898
|
+
const cols = Number(msg.cols) > 0 ? Number(msg.cols) : 80;
|
|
3899
|
+
const rows = Number(msg.rows) > 0 ? Number(msg.rows) : 24;
|
|
3900
|
+
// 地址不要直接信客户端传来的 peer.host:端点顺序会变(tailnet 可能排前面),
|
|
3901
|
+
// 用 tailnet 地址去连 22 端口会卡到 "timed out waiting for handshake"。
|
|
3902
|
+
// 这里按 discover 的端点表优先挑局域网地址,其次才用它给的。
|
|
3903
|
+
const machine = String(msg.machine ?? "");
|
|
3904
|
+
let host = String(msg.host ?? "");
|
|
3905
|
+
try {
|
|
3906
|
+
const found = machine ? findPeer(machine) : { error: "缺少机器名" };
|
|
3907
|
+
const target = found && found.peer;
|
|
3908
|
+
if (target) {
|
|
3909
|
+
const eps = orderedEndpoints(target);
|
|
3910
|
+
const isPrivate = (h) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(String(h ?? ""));
|
|
3911
|
+
host = (eps.find((e) => isPrivate(e.host)) ?? eps.find((e) => e.host))?.host ?? host;
|
|
3912
|
+
}
|
|
3913
|
+
} catch {
|
|
3914
|
+
/* 解析失败就用客户端给的地址 */
|
|
3915
|
+
}
|
|
3916
|
+
const id = await ssh.open({
|
|
3917
|
+
host,
|
|
3918
|
+
port: Number(msg.port) > 0 ? Number(msg.port) : 22,
|
|
3919
|
+
username: String(msg.username ?? ""),
|
|
3920
|
+
password: typeof msg.password === "string" ? msg.password : "",
|
|
3921
|
+
cols,
|
|
3922
|
+
rows,
|
|
3923
|
+
machine,
|
|
3924
|
+
});
|
|
3925
|
+
chan.send(JSON.stringify({ type: "ready", id, buffer: ssh.ring(id) }));
|
|
3926
|
+
ssh.subscribe(id, (chunk) => {
|
|
3927
|
+
chan.send(JSON.stringify(chunk === null ? { type: "exit", id } : { type: "data", id, data: chunk }));
|
|
3928
|
+
});
|
|
3929
|
+
return;
|
|
3930
|
+
}
|
|
3931
|
+
const id = String(msg?.id ?? "");
|
|
3932
|
+
if (msg?.type === "input") ssh.write(id, String(msg.data ?? ""));
|
|
3933
|
+
else if (msg?.type === "resize") ssh.resize(id, Number(msg.cols) || 80, Number(msg.rows) || 24);
|
|
3934
|
+
else if (msg?.type === "close") ssh.close(id);
|
|
3935
|
+
} catch (error) {
|
|
3936
|
+
chan.send(JSON.stringify({ type: "error", message: String(error?.message ?? error) }));
|
|
3937
|
+
}
|
|
3938
|
+
},
|
|
3939
|
+
});
|
|
3940
|
+
};
|
|
3941
|
+
ctx.effect(() => ctx.webServer.registerUpgrade({ path: "/mesh/api/ssh/ws", handler: sshUpgrade }));
|
|
3942
|
+
|
|
3943
|
+
log("UI 接口已挂载: /mesh/api/state|diagnostics|update|refresh|secret|send|probe|web-url|web-panel|ssh");
|
|
3501
3944
|
}
|