dsh-plugin-mesh 0.5.13 → 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,8 +106,10 @@ 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";
111
114
  import {
112
115
  PEER_WEB_PREFIX,
@@ -126,7 +129,7 @@ import {
126
129
  export const name = "dsh-plugin-mesh";
127
130
  export const inject = ["tools", "webServer"];
128
131
 
129
- const VERSION = "0.5.13";
132
+ const VERSION = "0.5.14";
130
133
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
131
134
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
132
135
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -154,6 +157,15 @@ export const MESH_DEFAULT_PORT = 45917;
154
157
  export const DEBUG_REQUIRE_APPROVAL = process.env.DSH_MESH_REQUIRE_APPROVAL === "1";
155
158
  /** 对端 DSH Web 的部署默认端口(回环代理拿不到对端自报地址时按它拼)。 */
156
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;
157
169
 
158
170
  /**
159
171
  * 互联网自组网(tailnet)通道:通道 id → 节点句柄。
@@ -673,6 +685,22 @@ function runningTailnetNodes() {
673
685
  return [...tailnetNodes.values()].filter((n) => n.phase === "running");
674
686
  }
675
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
+
676
704
  /**
677
705
  * 启动(或重建)一条 tailnet 通道。
678
706
  *
@@ -3164,12 +3192,20 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3164
3192
  // 只绑了回环时如实说:地址虽然给得出来,但局域网里连不通。
3165
3193
  const lanReachable = bind === "0.0.0.0" && !!lanHost;
3166
3194
  const host = lanReachable ? lanHost : "127.0.0.1";
3167
- // 回环-only 的宿主(尤其 DSH Desktop:它把 host 硬编码成 127.0.0.1,
3168
- // 改配置也开不了端口)给一条走 mesh 口的隧道:零证书、零新端口,
3169
- // 转发发生在**我这边**的进程里,所以 GUI 不必对外监听。
3170
- const tunnelUrl = !lanReachable && lanHost && meshPort
3171
- ? `http://${lanHost}:${meshPort}${PEER_WEB_PREFIX}/`
3172
- : "";
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}/` : "";
3173
3209
  return send(res, 200, {
3174
3210
  ok: true,
3175
3211
  supported: true,
@@ -3177,8 +3213,15 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
3177
3213
  bind,
3178
3214
  lanReachable,
3179
3215
  port,
3180
- ...(tunnelUrl
3181
- ? { tunnel: { url: tunnelUrl, ticket: createPeerWebTicket(currentSecret()), header: PEER_WEB_TICKET_HEADER } }
3216
+ ...(ticket
3217
+ ? {
3218
+ tunnel: {
3219
+ ...(tunnelUrl ? { url: tunnelUrl } : {}),
3220
+ prefix: tunnelPrefix,
3221
+ ticket,
3222
+ header: PEER_WEB_TICKET_HEADER,
3223
+ },
3224
+ }
3182
3225
  : {}),
3183
3226
  });
3184
3227
  } catch (err) {
@@ -4765,6 +4808,10 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4765
4808
  bind: rb.bind ?? "",
4766
4809
  lanReachable: rb.lanReachable === true,
4767
4810
  port: rb.port ?? 0,
4811
+ // 隧道描述必须原样透出:这是诊断「对端到底给了没给隧道」的唯一凭据。
4812
+ // 以前这里只转发 url/bind/lanReachable,害得排障时把「对端已给隧道」
4813
+ // 误判成「对端还是老版本」——把证据吃掉比没有证据更糟(AGENTS.md 硬约束 1)。
4814
+ ...(rb.tunnel && typeof rb.tunnel === "object" ? { tunnel: rb.tunnel } : {}),
4768
4815
  });
4769
4816
  } catch (err) {
4770
4817
  return send(res, 200, { ok: false, supported: false, error: String(err?.message ?? err) });
@@ -4810,6 +4857,11 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4810
4857
  } catch (err) {
4811
4858
  warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
4812
4859
  }
4860
+ try {
4861
+ await entry.stream?.node?.closeStream(entry.stream.address);
4862
+ } catch (err) {
4863
+ warn(`关闭 tailnet 出站流失败:${err?.message ?? err}`);
4864
+ }
4813
4865
  }
4814
4866
  };
4815
4867
  ctx.effect(() => () => {
@@ -4850,6 +4902,12 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4850
4902
  let token = tokenOverride;
4851
4903
  let lanReachable;
4852
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 = "";
4853
4911
  try {
4854
4912
  const r = await peerFetch(target, "/mesh/v1/web-url", {
4855
4913
  headers: { "X-Dsh-Mesh-Token": currentSecret() },
@@ -4863,23 +4921,9 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4863
4921
  parsed.searchParams.delete("token");
4864
4922
  remoteBase = parsed.href;
4865
4923
  lanReachable = rb.lanReachable === true;
4866
- // 对端自报回环-only,但给了 mesh 口隧道:直接用它。
4867
- // 这是零证书路径,且不需要对端开任何端口(Desktop 也适用)。
4868
- const tunnel = rb.tunnel;
4869
- if (!lanReachable && tunnel && typeof tunnel.url === "string" && tunnel.url) {
4870
- if (typeof tunnel.ticket !== "string" || !tunnel.ticket) {
4871
- note = "对端给了隧道地址但没给票据(对端插件版本不一致)";
4872
- } else {
4873
- return {
4874
- remoteBase: tunnel.url,
4875
- pathPrefix: PEER_WEB_PREFIX,
4876
- passthrough: true,
4877
- lanReachable: true,
4878
- ticket: tunnel.ticket,
4879
- note: "经对端 mesh 口隧道(对端 GUI 仍只听回环)",
4880
- };
4881
- }
4882
- }
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;
4883
4927
  } else {
4884
4928
  note = rb?.error ? String(rb.error) : `对端 HTTP ${r.status}`;
4885
4929
  }
@@ -4892,7 +4936,124 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4892
4936
  remoteBase = `http://${ep.host}:${WEB_PANEL_DEFAULT_PORT}/`;
4893
4937
  }
4894
4938
  if (!token) note = note || "对端没有给出 token(对端插件需升级到带 /mesh/v1/web-url 的版本)";
4895
- 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;
4896
5057
  }
4897
5058
 
4898
5059
  post("/mesh/api/web-panel", async (req, res) => {
@@ -4908,7 +5069,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4908
5069
  );
4909
5070
  if (resolved.error) return send(res, 400, { ok: false, error: resolved.error });
4910
5071
 
4911
- // 票据写进签名:隧道票据会过期,重开面板时拿到新的就该重建代理(别复用旧票据)。
5072
+ // 票据与出口写进签名:隧道票据会过期、tailnet 出站端口会随通道重建而变,
5073
+ // 重开面板时拿到新的就该重建代理(别复用旧票据/旧端口)。
4912
5074
  const signature = `${resolved.remoteBase}|${resolved.pathPrefix || ""}|${resolved.passthrough ? "p" : "c"}|${resolved.ticket ?? ""}`;
4913
5075
  try {
4914
5076
  const existing = webPanels.get(machine);
@@ -4925,6 +5087,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4925
5087
  if (existing) {
4926
5088
  webPanels.delete(machine);
4927
5089
  await existing.proxy.close();
5090
+ await closePanelStream(existing);
4928
5091
  }
4929
5092
  const proxy = await createWebProxy({
4930
5093
  remoteBase: resolved.remoteBase,
@@ -4934,17 +5097,20 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4934
5097
  onCookie: (cookie) => writePanelCookie(resolved.remoteBase, cookie),
4935
5098
  pathPrefix: resolved.pathPrefix || "",
4936
5099
  passthrough: resolved.passthrough === true,
4937
- upstreamHeaders: resolved.ticket
4938
- ? {
4939
- [PEER_WEB_TICKET_HEADER]: resolved.ticket,
4940
- // 与 mesh 口其它路由同一套鉴权:配对码打开时对端会校验这个头。
4941
- "x-dsh-mesh-token": currentSecret(),
4942
- }
4943
- : {},
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
+ : {},
4944
5110
  log,
4945
5111
  warn,
4946
5112
  });
4947
- webPanels.set(machine, { proxy, remote: resolved.remoteBase, signature });
5113
+ webPanels.set(machine, { proxy, remote: resolved.remoteBase, signature, stream: resolved.stream });
4948
5114
  return send(res, 200, {
4949
5115
  ok: true,
4950
5116
  url: proxy.url,
@@ -4969,10 +5135,23 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4969
5135
  } catch (err) {
4970
5136
  warn(`关闭 Web 面板代理失败:${err?.message ?? err}`);
4971
5137
  }
5138
+ await closePanelStream(entry);
4972
5139
  }
4973
5140
  return send(res, 200, { ok: true });
4974
5141
  });
4975
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
+
4976
5155
  // ── 「本机另一个引擎」的前缀转发(desktopWebPort > 0 才开)────────────
4977
5156
  //
4978
5157
  // 同一台机器上通常有两个引擎:桌面 App(有历史会话,只听 loopback)和
@@ -5015,6 +5194,59 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5015
5194
  // browser: it needs `crypto.generateKeyPairSync` and a raw socket. Ask for it
5016
5195
  // by a runtime-visible name so a page gets `undefined` here instead of a
5017
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
+
5018
5250
  let ssh;
5019
5251
  {
5020
5252
  // Loaded on demand for the same reason the module no longer sits at the top
@@ -5042,11 +5274,41 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5042
5274
  // 只回用户名与"是否已部署密钥",不回密码:密码没有再穿过一次网络的理由
5043
5275
  if (ssh === undefined) return send(res, 503, { ok: false, error: "SSH 终端在这个环境里不可用" });
5044
5276
  const info = ssh.describe(machine);
5045
- 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 });
5046
5278
  });
5047
5279
 
5048
5280
  post("/mesh/api/ssh/sessions", (_req, res) => send(res, 200, { ok: true, sessions: ssh?.list() ?? [] }));
5049
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
+
5050
5312
  // 一条 upgrade 路由承载所有终端(按会话 id 多路复用)
5051
5313
  const sshUpgrade = (req, socket, head) => {
5052
5314
  if (ssh === undefined) {
@@ -5069,22 +5331,19 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5069
5331
  // 用 tailnet 地址去连 22 端口会卡到 "timed out waiting for handshake"。
5070
5332
  // 这里按 discover 的端点表优先挑局域网地址,其次才用它给的。
5071
5333
  const machine = String(msg.machine ?? "");
5072
- let host = String(msg.host ?? "");
5073
- try {
5074
- const found = machine ? findPeer(machine) : { error: "缺少机器名" };
5075
- const target = found && found.peer;
5076
- if (target) {
5077
- const eps = orderedEndpoints(target);
5078
- const isPrivate = (h) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(String(h ?? ""));
5079
- host = (eps.find((e) => isPrivate(e.host)) ?? eps.find((e) => e.host))?.host ?? host;
5080
- }
5081
- } catch {
5082
- /* 解析失败就用客户端给的地址 */
5083
- }
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);
5084
5343
  const id = await ssh.open({
5085
- host,
5086
- port: Number(msg.port) > 0 ? Number(msg.port) : 22,
5087
- username: String(msg.username ?? ""),
5344
+ host: resolved.host,
5345
+ port: resolved.port,
5346
+ username,
5088
5347
  password: typeof msg.password === "string" ? msg.password : "",
5089
5348
  cols,
5090
5349
  rows,
@@ -5101,7 +5360,17 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
5101
5360
  else if (msg?.type === "resize") ssh.resize(id, Number(msg.cols) || 80, Number(msg.rows) || 24);
5102
5361
  else if (msg?.type === "close") ssh.close(id);
5103
5362
  } catch (error) {
5104
- 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
+ );
5105
5374
  }
5106
5375
  },
5107
5376
  });