dsh-plugin-mesh 0.5.12 → 0.5.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -15,6 +15,7 @@
15
15
  * 首次运行自动生成配对码,用户在 UI 上复制到另一台机器即可。
16
16
  */
17
17
  import { createServer } from "node:http";
18
+ import { connect as netConnect } from "node:net";
18
19
  import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
19
20
  import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
20
21
  import { join, basename, isAbsolute, resolve } from "node:path";
@@ -105,9 +106,18 @@ import {
105
106
  } from "./persist.js";
106
107
  import { TsnetNode, channelKey, channelSignature } from "./tsnet/manager.js";
107
108
  import { resolveTailnetChannels } from "./tsnet/channels.js";
108
- import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
109
+ import { tailnetFetch, tailnetOrigin, isTailnetAddress } from "./tsnet/bridge.js";
109
110
  import { createWebProxy } from "./web-proxy.js";
111
+ import { planWebTarget, needsReachabilityProbe } from "./web-target.js";
112
+ import { planSshTarget, sshDirectCandidates } from "./ssh-target.js";
110
113
  import { createSecretReader } from "./desktop-auth.js";
114
+ import {
115
+ PEER_WEB_PREFIX,
116
+ PEER_WEB_TICKET_HEADER,
117
+ createPeerWebForwarder,
118
+ createPeerWebTicket,
119
+ verifyPeerWebTicket,
120
+ } from "./peer-web.js";
111
121
  import { acceptUpgrade } from "./ws-mini.js";
112
122
  import {
113
123
  createDesktopWebForwarder,
@@ -119,7 +129,7 @@ import {
119
129
  export const name = "dsh-plugin-mesh";
120
130
  export const inject = ["tools", "webServer"];
121
131
 
122
- const VERSION = "0.5.12";
132
+ const VERSION = "0.5.14";
123
133
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
124
134
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
125
135
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -147,6 +157,15 @@ export const MESH_DEFAULT_PORT = 45917;
147
157
  export const DEBUG_REQUIRE_APPROVAL = process.env.DSH_MESH_REQUIRE_APPROVAL === "1";
148
158
  /** 对端 DSH Web 的部署默认端口(回环代理拿不到对端自报地址时按它拼)。 */
149
159
  const WEB_PANEL_DEFAULT_PORT = 3080;
160
+ /**
161
+ * 探测「对端自报的 GUI 地址从本机能不能到」的超时。
162
+ *
163
+ * 只有**跨网段**地址才会走这项探测(同网段失败会立刻报错,不必等);
164
+ * 1.5 秒是上限而不是目标:局域网/Tailscale 直连都在几十毫秒内出结果。
165
+ */
166
+ const WEB_DIRECT_PROBE_MS = 1500;
167
+ /** SSH 直连候选的探测超时:局域网内几毫秒就有结果,1.2 秒只用于兜住黑洞地址。 */
168
+ const SSH_PROBE_MS = 1200;
150
169
 
151
170
  /**
152
171
  * 互联网自组网(tailnet)通道:通道 id → 节点句柄。
@@ -666,6 +685,22 @@ function runningTailnetNodes() {
666
685
  return [...tailnetNodes.values()].filter((n) => n.phase === "running");
667
686
  }
668
687
 
688
+ /**
689
+ * 端点 → 能拨它的通道节点。
690
+ *
691
+ * 端点的 `channel` 形如 `tsnet:<id>`(`endpointKeyOf` 的约定)。名字对不上
692
+ * (老名片、或 sidecar 重启后换了 id)时退回"任意一条在跑的通道":100.x 属于
693
+ * 哪条 tailnet 由连通性说话,猜不如试。
694
+ */
695
+ function tailnetNodeForEndpoint(ep) {
696
+ const key = String(ep?.channel ?? "");
697
+ if (key.startsWith("tsnet:")) {
698
+ const node = tailnetNodes.get(key.slice("tsnet:".length));
699
+ if (node?.phase === "running") return node;
700
+ }
701
+ return runningTailnetNodes()[0] ?? null;
702
+ }
703
+
669
704
  /**
670
705
  * 启动(或重建)一条 tailnet 通道。
671
706
  *
@@ -3026,6 +3061,17 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
3026
3061
  * @param options.bindHost 监听地址。局域网关着时传 "127.0.0.1"。
3027
3062
  */
3028
3063
  function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange, diagnostics, port: fixedPort, bindHost = "0.0.0.0" }) {
3064
+ // mesh 口的**实际**监听端口(被占用时会退回随机),隧道地址要用它而不是配置值。
3065
+ let meshPort = 0;
3066
+ // 对端 GUI 的隧道:请求进到这里就转发给本机 127.0.0.1:<Web 端口>,
3067
+ // 认证(会话 cookie)与来源改写都在 peer-web.js 里完成。
3068
+ const peerWeb = createPeerWebForwarder({
3069
+ portOf: () => ctx.get("webServer")?.port ?? 0,
3070
+ secretOf: createSecretReader(join(process.env.DSH_HOME || join(homedir(), ".dsh"), ".credentials.yaml")),
3071
+ log,
3072
+ warn,
3073
+ });
3074
+
3029
3075
  const send = (res, code, payload) => {
3030
3076
  const body = Buffer.from(JSON.stringify(payload), "utf8");
3031
3077
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -3074,6 +3120,25 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3074
3120
  });
3075
3121
  }
3076
3122
 
3123
+ // 对端 GUI 隧道:票据自证,所以放在配对闸门之前 —— 票据本身是
3124
+ // /mesh/v1/web-url 在**鉴权之后**签发的,等于"拿得到地址的人才用得了这条通道"。
3125
+ if (path === PEER_WEB_PREFIX || path.startsWith(`${PEER_WEB_PREFIX}/`)) {
3126
+ // 安全策略与 mesh 口其它路由**完全一致**:配对码打开时,每个请求都必须带
3127
+ // 共享密钥(观看端代理会把 X-Dsh-Mesh-Token 附在每个转发请求上);关闭时
3128
+ // 与派发任务同权。票据是**额外**一层:只在鉴权后的 /mesh/v1/web-url 发放、
3129
+ // 12 小时过期,用来把"看得见地址"和"能一直用"分开。
3130
+ if (!authed(req)) return send(res, 403, { ok: false, error: "未配对:两台机器的配对码不一致(本机开启了 requirePairing)" });
3131
+ const ticket = String(req.headers[PEER_WEB_TICKET_HEADER] ?? url.searchParams.get("t") ?? "");
3132
+ const verdict = verifyPeerWebTicket(currentSecret(), ticket);
3133
+ if (!verdict) return send(res, 403, { ok: false, error: "隧道票据无效或已过期,请在对端重新打开面板" });
3134
+ // 帧路由(页面/WS 传输)没有 pipe,也不该被当成 HTTP 转发。
3135
+ if (typeof req.pipe !== "function") {
3136
+ return send(res, 400, { ok: false, error: "GUI 隧道只接受 HTTP 载体" });
3137
+ }
3138
+ peerWeb.handle(req, res);
3139
+ return;
3140
+ }
3141
+
3077
3142
  if (!authed(req)) return send(res, 403, { ok: false, error: "未配对:两台机器的配对码不一致(本机开启了 requirePairing)" });
3078
3143
 
3079
3144
  // 一次性文件搬运:给对端取本机插件包里的文件(同版本部署用)。
@@ -3127,6 +3192,20 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3127
3192
  // 只绑了回环时如实说:地址虽然给得出来,但局域网里连不通。
3128
3193
  const lanReachable = bind === "0.0.0.0" && !!lanHost;
3129
3194
  const host = lanReachable ? lanHost : "127.0.0.1";
3195
+ // 走 mesh 口的隧道:零证书、零新端口,转发发生在**我这边**的进程里,
3196
+ // 所以 GUI 不必对外监听(DSH Desktop 甚至连改都改不了,硬编码回环)。
3197
+ //
3198
+ // 只要 mesh 口在,就**一律**给隧道,不再只限"我只听回环"的情况。
3199
+ // 判据必须留在观看端:我这边唯一说得准的是"我绑了哪个地址",而
3200
+ // `bind=0.0.0.0` 并不意味着观看端能到——手机在移动数据下 host 是运营商
3201
+ // CGNAT 的 10.x,而 tailnet 里能到的只有 mesh 口那一个端口(sidecar 只
3202
+ // 转发它)。那种对端以前既拿不到隧道、又拨不通自报地址,面板必然 502。
3203
+ //
3204
+ // 隧道只给**相对前缀**,不给绝对地址:主机部分必须由观看端用它自己能到
3205
+ // 的那条通道去填。`url` 字段留给老版本观看端(它只会照抄绝对地址)。
3206
+ const tunnelPrefix = meshPort ? PEER_WEB_PREFIX : "";
3207
+ const ticket = tunnelPrefix ? createPeerWebTicket(currentSecret()) : "";
3208
+ const tunnelUrl = tunnelPrefix && lanHost && meshPort ? `http://${lanHost}:${meshPort}${PEER_WEB_PREFIX}/` : "";
3130
3209
  return send(res, 200, {
3131
3210
  ok: true,
3132
3211
  supported: true,
@@ -3134,6 +3213,16 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3134
3213
  bind,
3135
3214
  lanReachable,
3136
3215
  port,
3216
+ ...(ticket
3217
+ ? {
3218
+ tunnel: {
3219
+ ...(tunnelUrl ? { url: tunnelUrl } : {}),
3220
+ prefix: tunnelPrefix,
3221
+ ticket,
3222
+ header: PEER_WEB_TICKET_HEADER,
3223
+ },
3224
+ }
3225
+ : {}),
3137
3226
  });
3138
3227
  } catch (err) {
3139
3228
  return send(res, 200, { ok: false, supported: false, error: String(err?.message ?? err) });
@@ -3286,6 +3375,21 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3286
3375
 
3287
3376
  server.on("upgrade", (req, socket, head) => {
3288
3377
  const url = new URL(req.url ?? "/", "http://localhost");
3378
+ // GUI 隧道的流式载波(/api/remote.mux):缺了这条,对端界面会一直"重新连接中"。
3379
+ if (url.pathname.startsWith(`${PEER_WEB_PREFIX}/`)) {
3380
+ // 与 HTTP 侧同一套:配对开启时升级请求也要带共享密钥。
3381
+ if (!authed(req)) {
3382
+ socket.destroy();
3383
+ return;
3384
+ }
3385
+ const ticket = String(req.headers[PEER_WEB_TICKET_HEADER] ?? url.searchParams.get("t") ?? "");
3386
+ if (!verifyPeerWebTicket(currentSecret(), ticket)) {
3387
+ socket.destroy();
3388
+ return;
3389
+ }
3390
+ peerWeb.upgrade(req, socket, head);
3391
+ return;
3392
+ }
3289
3393
  if (url.pathname !== "/mesh/v1/ws") {
3290
3394
  // Other upgrade routes belong to someone else on this origin; leave the
3291
3395
  // socket alone rather than destroying a desktop-web stream.
@@ -3347,6 +3451,7 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3347
3451
  });
3348
3452
  server.listen(port, bindHost, () => {
3349
3453
  const addr = server.address();
3454
+ meshPort = addr.port;
3350
3455
  log(`对端服务监听 ${addr.address}:${addr.port}${isFallback ? "(随机)" : "(固定)"}`);
3351
3456
  resolvePromise({ port: addr.port, host: addr.address, server });
3352
3457
  });
@@ -4703,6 +4808,10 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4703
4808
  bind: rb.bind ?? "",
4704
4809
  lanReachable: rb.lanReachable === true,
4705
4810
  port: rb.port ?? 0,
4811
+ // 隧道描述必须原样透出:这是诊断「对端到底给了没给隧道」的唯一凭据。
4812
+ // 以前这里只转发 url/bind/lanReachable,害得排障时把「对端已给隧道」
4813
+ // 误判成「对端还是老版本」——把证据吃掉比没有证据更糟(AGENTS.md 硬约束 1)。
4814
+ ...(rb.tunnel && typeof rb.tunnel === "object" ? { tunnel: rb.tunnel } : {}),
4706
4815
  });
4707
4816
  } catch (err) {
4708
4817
  return send(res, 200, { ok: false, supported: false, error: String(err?.message ?? err) });
@@ -4748,6 +4857,11 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4748
4857
  } catch (err) {
4749
4858
  warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
4750
4859
  }
4860
+ try {
4861
+ await entry.stream?.node?.closeStream(entry.stream.address);
4862
+ } catch (err) {
4863
+ warn(`关闭 tailnet 出站流失败:${err?.message ?? err}`);
4864
+ }
4751
4865
  }
4752
4866
  };
4753
4867
  ctx.effect(() => () => {
@@ -4788,6 +4902,12 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4788
4902
  let token = tokenOverride;
4789
4903
  let lanReachable;
4790
4904
  let note = "";
4905
+ /** 对端给的 mesh 口隧道描述(新版本是相对前缀,老版本是绝对地址)。 */
4906
+ let tunnel = null;
4907
+ /** 对端 GUI 自己监听的端口(不等于 mesh 口端口)。 */
4908
+ let guiPort = WEB_PANEL_DEFAULT_PORT;
4909
+ /** 对端 GUI 的 bind 地址;空串 = 对端没报(老版本)。 */
4910
+ let guiBind = "";
4791
4911
  try {
4792
4912
  const r = await peerFetch(target, "/mesh/v1/web-url", {
4793
4913
  headers: { "X-Dsh-Mesh-Token": currentSecret() },
@@ -4801,6 +4921,9 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4801
4921
  parsed.searchParams.delete("token");
4802
4922
  remoteBase = parsed.href;
4803
4923
  lanReachable = rb.lanReachable === true;
4924
+ if (Number(rb.port) > 0) guiPort = Number(rb.port);
4925
+ if (typeof rb.bind === "string") guiBind = rb.bind;
4926
+ tunnel = rb.tunnel && typeof rb.tunnel === "object" ? rb.tunnel : null;
4804
4927
  } else {
4805
4928
  note = rb?.error ? String(rb.error) : `对端 HTTP ${r.status}`;
4806
4929
  }
@@ -4813,7 +4936,124 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4813
4936
  remoteBase = `http://${ep.host}:${WEB_PANEL_DEFAULT_PORT}/`;
4814
4937
  }
4815
4938
  if (!token) note = note || "对端没有给出 token(对端插件需升级到带 /mesh/v1/web-url 的版本)";
4816
- return { remoteBase, token, lanReachable, note };
4939
+
4940
+ // 自报地址**不等于**本机能到的地址:手机在移动数据下把自己报成运营商
4941
+ // CGNAT 的 10.x,而 `lanReachable` 只是"我绑了 0.0.0.0"。所以这里补一道
4942
+ // 本机可达性判断,拨不通就改走 mesh 通道(tailnet 字节流)。
4943
+ const direct = await verifyWebBase(remoteBase);
4944
+ const plan = planWebTarget({
4945
+ reportedBase: remoteBase,
4946
+ reportedPort: guiPort,
4947
+ reachable: direct.reachable,
4948
+ tunnel,
4949
+ tsnetHost: tailnetHostOf(target, remoteBase),
4950
+ meshPort: meshPortOf(target),
4951
+ // 对端没报 bind 时不猜"只听回环":老版本做不到这条隧道,保持旧行为。
4952
+ guiBoundEverywhere: guiBind ? guiBind === "0.0.0.0" : undefined,
4953
+ probeNote: direct.note,
4954
+ });
4955
+ if (plan.mode === "stream") {
4956
+ const opened = await openWebStream(target, plan.address);
4957
+ if (opened.error) {
4958
+ return { error: `${plan.note},但${opened.error}` };
4959
+ }
4960
+ const passthrough = Boolean(plan.ticket);
4961
+ return {
4962
+ remoteBase: `http://127.0.0.1:${opened.port}/`,
4963
+ pathPrefix: plan.prefix || "",
4964
+ passthrough,
4965
+ lanReachable: true,
4966
+ token,
4967
+ guiPort,
4968
+ guiBind,
4969
+ stream: { address: plan.address, node: opened.node },
4970
+ upstreamHeaders: passthrough
4971
+ ? { [plan.header || PEER_WEB_TICKET_HEADER]: plan.ticket, "x-dsh-mesh-token": currentSecret() }
4972
+ : {},
4973
+ note: plan.note,
4974
+ };
4975
+ }
4976
+ if (plan.mode === "none") note = [plan.note, note].filter(Boolean).join(";");
4977
+ return { remoteBase, token, lanReachable, guiPort, guiBind, note };
4978
+ }
4979
+
4980
+ /**
4981
+ * 本机真的能从这个地址拿到 HTTP 响应吗?
4982
+ *
4983
+ * 只问"能不能拿到响应",不判 200:对端 401/403 也说明这条网络路径是通的。
4984
+ * 失败时如实返回原因 —— 超时只代表"1.5 秒内没有回答",不代表对端关着。
4985
+ */
4986
+ async function verifyWebBase(base) {
4987
+ let host = "";
4988
+ try {
4989
+ host = new URL(base).hostname;
4990
+ } catch {
4991
+ return { reachable: false, note: `地址 ${base} 解析不了` };
4992
+ }
4993
+ // 同网段与回环地址不多花那 1.5 秒:拨不通的报错本来就准确、也来得快。
4994
+ if (!needsReachabilityProbe(host, selfAddresses())) return { reachable: undefined, note: "" };
4995
+ try {
4996
+ const res = await fetch(base, {
4997
+ method: "GET",
4998
+ redirect: "manual",
4999
+ signal: AbortSignal.timeout(WEB_DIRECT_PROBE_MS),
5000
+ });
5001
+ return { reachable: true, note: `HTTP ${res.status}` };
5002
+ } catch (err) {
5003
+ return {
5004
+ reachable: false,
5005
+ note: `${WEB_DIRECT_PROBE_MS}ms 内没有响应(${err?.message ?? err})`,
5006
+ };
5007
+ }
5008
+ }
5009
+
5010
+ /** 在对端名片的 tailnet 端点(100.64/10)上开会话出口。 */
5011
+ async function openWebStream(target, address) {
5012
+ const ep = orderedEndpoints(target).find((item) => item?.transport === "tsnet" && item.host);
5013
+ const node = tailnetNodeForEndpoint(ep);
5014
+ if (!node) return { error: "本机没有在跑的 tailnet 通道(Mesh 面板可开启互联网)" };
5015
+ try {
5016
+ const port = await node.openStream(address);
5017
+ return { port, node };
5018
+ } catch (err) {
5019
+ return { error: `开启 tailnet 出站流失败:${err?.message ?? err}` };
5020
+ }
5021
+ }
5022
+
5023
+ /** 本机 IPv4 列表(同网段判断用)。 */
5024
+ function selfAddresses() {
5025
+ try {
5026
+ return lanIPv4Addresses().map((item) => item.address);
5027
+ } catch {
5028
+ return [];
5029
+ }
5030
+ }
5031
+
5032
+ /**
5033
+ * 对端能被 tailnet 通道到达的地址;没有就返回空串。
5034
+ *
5035
+ * 只认 100.64/10:别的地址(尤其 10.x)在 tailnet 里根本没有路由,拿它当
5036
+ * "通道地址"会把 502 换一个地方重现。
5037
+ */
5038
+ function tailnetHostOf(target, fallbackBase) {
5039
+ for (const ep of orderedEndpoints(target)) {
5040
+ if (ep?.transport === "tsnet" && ep.host && isTailnetAddress(ep.host)) return ep.host;
5041
+ }
5042
+ try {
5043
+ const host = new URL(fallbackBase).hostname;
5044
+ if (isTailnetAddress(host)) return host;
5045
+ } catch {
5046
+ /* 地址不可解析就当没有 */
5047
+ }
5048
+ return "";
5049
+ }
5050
+
5051
+ /** 对端 mesh 口的端口(隧道挂在这个端口上);不知道就 0。 */
5052
+ function meshPortOf(target) {
5053
+ for (const ep of orderedEndpoints(target)) {
5054
+ if (ep?.host && Number(ep.port) > 0) return Number(ep.port);
5055
+ }
5056
+ return 0;
4817
5057
  }
4818
5058
 
4819
5059
  post("/mesh/api/web-panel", async (req, res) => {
@@ -4829,7 +5069,9 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4829
5069
  );
4830
5070
  if (resolved.error) return send(res, 400, { ok: false, error: resolved.error });
4831
5071
 
4832
- const signature = `${resolved.remoteBase}|${resolved.pathPrefix || ""}|${resolved.passthrough ? "p" : "c"}`;
5072
+ // 票据与出口写进签名:隧道票据会过期、tailnet 出站端口会随通道重建而变,
5073
+ // 重开面板时拿到新的就该重建代理(别复用旧票据/旧端口)。
5074
+ const signature = `${resolved.remoteBase}|${resolved.pathPrefix || ""}|${resolved.passthrough ? "p" : "c"}|${resolved.ticket ?? ""}`;
4833
5075
  try {
4834
5076
  const existing = webPanels.get(machine);
4835
5077
  if (existing && existing.signature === signature) {
@@ -4845,6 +5087,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4845
5087
  if (existing) {
4846
5088
  webPanels.delete(machine);
4847
5089
  await existing.proxy.close();
5090
+ await closePanelStream(existing);
4848
5091
  }
4849
5092
  const proxy = await createWebProxy({
4850
5093
  remoteBase: resolved.remoteBase,
@@ -4854,10 +5097,20 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4854
5097
  onCookie: (cookie) => writePanelCookie(resolved.remoteBase, cookie),
4855
5098
  pathPrefix: resolved.pathPrefix || "",
4856
5099
  passthrough: resolved.passthrough === true,
5100
+ // 隧道票据 + mesh 密钥:走 mesh 口时每一跳都要带,配对码打开时对端还要校验。
5101
+ // tailnet 出站流(无票据那种)只带 mesh 密钥即可。
5102
+ upstreamHeaders: resolved.upstreamHeaders
5103
+ ? resolved.upstreamHeaders
5104
+ : resolved.ticket
5105
+ ? {
5106
+ [PEER_WEB_TICKET_HEADER]: resolved.ticket,
5107
+ "x-dsh-mesh-token": currentSecret(),
5108
+ }
5109
+ : {},
4857
5110
  log,
4858
5111
  warn,
4859
5112
  });
4860
- webPanels.set(machine, { proxy, remote: resolved.remoteBase, signature });
5113
+ webPanels.set(machine, { proxy, remote: resolved.remoteBase, signature, stream: resolved.stream });
4861
5114
  return send(res, 200, {
4862
5115
  ok: true,
4863
5116
  url: proxy.url,
@@ -4882,10 +5135,23 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4882
5135
  } catch (err) {
4883
5136
  warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
4884
5137
  }
5138
+ await closePanelStream(entry);
4885
5139
  }
4886
5140
  return send(res, 200, { ok: true });
4887
5141
  });
4888
5142
 
5143
+ /** 关掉面板时顺手收回它用的 tailnet 出站流(端口不回收会一直挂着)。 */
5144
+ async function closePanelStream(entry) {
5145
+ const address = entry?.stream?.address;
5146
+ const node = entry?.stream?.node;
5147
+ if (!address || !node) return;
5148
+ try {
5149
+ await node.closeStream(address);
5150
+ } catch (err) {
5151
+ warn(`关闭 tailnet 出站流失败:${err?.message ?? err}`);
5152
+ }
5153
+ }
5154
+
4889
5155
  // ── 「本机另一个引擎」的前缀转发(desktopWebPort > 0 才开)────────────
4890
5156
  //
4891
5157
  // 同一台机器上通常有两个引擎:桌面 App(有历史会话,只听 loopback)和
@@ -4928,6 +5194,59 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4928
5194
  // browser: it needs `crypto.generateKeyPairSync` and a raw socket. Ask for it
4929
5195
  // by a runtime-visible name so a page gets `undefined` here instead of a
4930
5196
  // module-loader failure that takes the whole plugin down with it.
5197
+ /**
5198
+ * 决定这次 SSH 连哪儿。
5199
+ *
5200
+ * 顺序:能直连的候选(局域网优先,逐个真实 TCP 探测)→ 都不通、但对端有 tailnet
5201
+ * 端点时,让 sidecar 在本机开回环端口把字节流打进 tailnet,SSH 连 127.0.0.1。
5202
+ * 两条都不成立就抛出**带原因**的错误,别让 ssh2 报一句笼统的 timed out。
5203
+ */
5204
+ async function resolveSshTarget(machine, requestedHost, port) {
5205
+ let target = null;
5206
+ try {
5207
+ const found = machine ? findPeer(machine) : { error: "缺少机器名" };
5208
+ target = found?.peer ?? null;
5209
+ } catch {
5210
+ /* 解析失败就当没名片,只用客户端给的地址 */
5211
+ }
5212
+ const endpoints = target ? orderedEndpoints(target) : [];
5213
+ for (const host of sshDirectCandidates(endpoints, requestedHost)) {
5214
+ if (await probeTcp(host, port, SSH_PROBE_MS)) return { host, port, note: `直连 ${host}:${port}` };
5215
+ }
5216
+ const tsnetEp = endpoints.find((ep) => ep?.transport === "tsnet" && ep.host && isTailnetAddress(ep.host));
5217
+ const plan = planSshTarget({ endpoints, port, requestedHost, tsnetHost: tsnetEp?.host ?? "" });
5218
+ if (plan.mode === "stream") {
5219
+ const node = tailnetNodeForEndpoint(tsnetEp);
5220
+ if (!node) throw new Error("本机没有在跑的 tailnet 通道(Mesh 面板可开启互联网)");
5221
+ const localPort = await node.openStream(plan.address);
5222
+ log(`SSH 经 tailnet:127.0.0.1:${localPort} → ${plan.address}`);
5223
+ return { host: "127.0.0.1", port: localPort, note: plan.note };
5224
+ }
5225
+ throw new Error(plan.note);
5226
+ }
5227
+
5228
+ /** 用一次真实 TCP 连接判断候选能不能连(不能只看地址长什么样)。 */
5229
+ function probeTcp(host, port, timeoutMs) {
5230
+ return new Promise((resolvePromise) => {
5231
+ let done = false;
5232
+ const socket = netConnect({ host, port });
5233
+ const finish = (ok) => {
5234
+ if (done) return;
5235
+ done = true;
5236
+ try {
5237
+ socket.destroy();
5238
+ } catch {
5239
+ /* 已关 */
5240
+ }
5241
+ resolvePromise(ok);
5242
+ };
5243
+ socket.setTimeout(timeoutMs);
5244
+ socket.once("connect", () => finish(true));
5245
+ socket.once("timeout", () => finish(false));
5246
+ socket.once("error", () => finish(false));
5247
+ });
5248
+ }
5249
+
4931
5250
  let ssh;
4932
5251
  {
4933
5252
  // Loaded on demand for the same reason the module no longer sits at the top
@@ -4955,11 +5274,41 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4955
5274
  // 只回用户名与"是否已部署密钥",不回密码:密码没有再穿过一次网络的理由
4956
5275
  if (ssh === undefined) return send(res, 503, { ok: false, error: "SSH 终端在这个环境里不可用" });
4957
5276
  const info = ssh.describe(machine);
4958
- return send(res, 200, { ok: true, username: info.username, hasKey: info.hasKey, saved: !!info.username });
5277
+ return send(res, 200, { ok: true, username: info.username, hasKey: info.hasKey, port: info.port, saved: !!info.username });
4959
5278
  });
4960
5279
 
4961
5280
  post("/mesh/api/ssh/sessions", (_req, res) => send(res, 200, { ok: true, sessions: ssh?.list() ?? [] }));
4962
5281
 
5282
+ /**
5283
+ * 把本机的 SSH 端口暴露到 tailnet(让对端能 `ssh` 过来)。
5284
+ *
5285
+ * 只接受同源回环请求:这是"把本机 sshd 放到 tailnet 上"的开关,不能让页面上
5286
+ * 任意来源随手打开。暴露是裸 TCP(sidecar 的 /__tsnet/listen),只存在于
5287
+ * userspace tailnet 里 —— 宿主与局域网看不到,比现在 sshd 监听 0.0.0.0 更收敛。
5288
+ */
5289
+ post("/mesh/api/ssh/expose", async (req, res) => {
5290
+ if (!trustedControlRequest(req)) return send(res, 403, { ok: false, error: "只接受同源回环请求" });
5291
+ const body = await readJson(req);
5292
+ const port = Number(body?.port) > 0 ? Number(body.port) : 22;
5293
+ const on = body?.on !== false;
5294
+ const nodes = runningTailnetNodes();
5295
+ if (nodes.length === 0) return send(res, 503, { ok: false, error: "本机没有在跑的 tailnet 通道" });
5296
+ const results = [];
5297
+ for (const [index, node] of nodes.entries()) {
5298
+ const channel = `channel#${index + 1}`;
5299
+ try {
5300
+ if (on) await node.exposePort(port);
5301
+ else await node.unexposePort(port);
5302
+ results.push({ channel, ok: true });
5303
+ } catch (err) {
5304
+ results.push({ channel, ok: false, error: String(err?.message ?? err) });
5305
+ }
5306
+ }
5307
+ const ok = results.some((item) => item.ok);
5308
+ log(`SSH ${on ? "暴露到" : "从"} tailnet${on ? "" : " 收回"} :${port}(${results.map((r) => `${r.channel}:${r.ok ? "ok" : "失败"}`).join(" ")})`);
5309
+ return send(res, ok ? 200 : 502, { ok, port, on, results });
5310
+ });
5311
+
4963
5312
  // 一条 upgrade 路由承载所有终端(按会话 id 多路复用)
4964
5313
  const sshUpgrade = (req, socket, head) => {
4965
5314
  if (ssh === undefined) {
@@ -4982,22 +5331,19 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4982
5331
  // 用 tailnet 地址去连 22 端口会卡到 "timed out waiting for handshake"。
4983
5332
  // 这里按 discover 的端点表优先挑局域网地址,其次才用它给的。
4984
5333
  const machine = String(msg.machine ?? "");
4985
- let host = String(msg.host ?? "");
4986
- try {
4987
- const found = machine ? findPeer(machine) : { error: "缺少机器名" };
4988
- const target = found && found.peer;
4989
- if (target) {
4990
- const eps = orderedEndpoints(target);
4991
- const isPrivate = (h) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(String(h ?? ""));
4992
- host = (eps.find((e) => isPrivate(e.host)) ?? eps.find((e) => e.host))?.host ?? host;
4993
- }
4994
- } catch {
4995
- /* 解析失败就用客户端给的地址 */
4996
- }
5334
+ const port = Number(msg.port) > 0 ? Number(msg.port) : 22;
5335
+ const username = String(msg.username ?? "");
5336
+ // 先把「用户想用的端口」记到设备上,再解析路径:resolved.port 在走 tailnet
5337
+ // 出站流时会变成一次性回环端口,那个绝对不能当回填值存下来。
5338
+ ssh.remember(machine, { username, port });
5339
+ // 不再按"端点顺序"猜地址:宿主没有 100.x 路由,拿 tailnet 地址去连
5340
+ // 22 端口必然卡在 "timed out waiting for handshake"。这里实测哪个
5341
+ // 候选能连上,连不上再让 sidecar 开一条 tailnet 字节流。
5342
+ const resolved = await resolveSshTarget(machine, String(msg.host ?? ""), port);
4997
5343
  const id = await ssh.open({
4998
- host,
4999
- port: Number(msg.port) > 0 ? Number(msg.port) : 22,
5000
- username: String(msg.username ?? ""),
5344
+ host: resolved.host,
5345
+ port: resolved.port,
5346
+ username,
5001
5347
  password: typeof msg.password === "string" ? msg.password : "",
5002
5348
  cols,
5003
5349
  rows,
@@ -5014,7 +5360,17 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5014
5360
  else if (msg?.type === "resize") ssh.resize(id, Number(msg.cols) || 80, Number(msg.rows) || 24);
5015
5361
  else if (msg?.type === "close") ssh.close(id);
5016
5362
  } catch (error) {
5017
- chan.send(JSON.stringify({ type: "error", message: String(error?.message ?? error) }));
5363
+ // 端口填错时 ssh2 只会给一句 read ECONNRESET / ECONNREFUSED,看不出是端口问题;
5364
+ // 补一句人话,省得人以为是密码错或者网络断。
5365
+ const raw = String(error?.message ?? error);
5366
+ const netFail = /ECONNRESET|ECONNREFUSED|ETIMEDOUT|timed out/i.test(raw);
5367
+ const where = `${String(msg?.machine ?? "") || "对端"}:${Number(msg?.port) > 0 ? Number(msg.port) : 22}`;
5368
+ chan.send(
5369
+ JSON.stringify({
5370
+ type: "error",
5371
+ message: netFail ? `${raw}(连不上 ${where}:确认对端 sshd 监听端口,面板里可以改端口)` : raw,
5372
+ }),
5373
+ );
5018
5374
  }
5019
5375
  },
5020
5376
  });