dsh-plugin-mesh 0.5.13 → 0.5.15

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/ssh-host.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * 也不改 sshd_config。
12
12
  */
13
13
  import { createRequire } from "node:module";
14
- import { randomUUID, generateKeyPairSync } from "node:crypto";
14
+ import { randomUUID, generateKeyPairSync, createHash } from "node:crypto";
15
15
  import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
16
16
  import { dirname, join } from "node:path";
17
17
 
@@ -72,6 +72,8 @@ function publicKeyLine(keyObject) {
72
72
  export function createSshManager({ stateDir, credentialsPath, log = () => {}, warn = () => {} }) {
73
73
  const sessions = new Map();
74
74
  const keyPath = join(stateDir, "ssh-key", "id_rsa");
75
+ // 新代密钥:ed25519。RSA 只作为 ssh2 不可用时的退路(原因见 ensureKey)。
76
+ const edKeyPath = join(stateDir, "ssh-key", "id_ed25519");
75
77
  let cache;
76
78
 
77
79
  const loadCredentials = () => {
@@ -99,18 +101,61 @@ export function createSshManager({ stateDir, credentialsPath, log = () => {}, wa
99
101
  };
100
102
  const known = (machine) => loadCredentials()[machine] ?? undefined;
101
103
 
102
- /** 读(必要时生成)本机密钥对。 */
104
+ /** 已经确定过的私钥,避免每次调用都读盘/重新判断。 */
105
+ let activeKey;
106
+
107
+ /**
108
+ * 读(必要时生成)本机密钥对。
109
+ *
110
+ * 优先 ed25519,而不是最初那版无条件 RSA。两个理由:
111
+ * 1. Node 的 crypto 导不出 OpenSSH 格式的 ed25519 私钥,所以老版只能退而用
112
+ * PKCS#1 RSA;但 ssh2 自带的 utils.generateKeyPairSync 能生成并解析
113
+ * OpenSSH 格式的 ed25519,这条路已经通了。
114
+ * 2. RSA 还有一层额外风险:一部分自实现 sshd(例如手机侧基于 ssh2 的那套)
115
+ * 只按老 ssh-rsa(SHA-1) 格式验签,而 ssh2 客户端会跟随对端 server-sig-algs
116
+ * 优先用 rsa-sha2-256 签名,结果是「服务器接受了公钥、随后仍认证失败」,
117
+ * 并且 1.17 没有客户端开关能强制降级(实测 algorithms.pubKey 不被支持)。
118
+ * ed25519 不走这套验签逻辑,从根上绕开。
119
+ *
120
+ * @returns {{pem: string, path: string} | undefined}
121
+ */
103
122
  const ensureKey = () => {
123
+ if (activeKey) return activeKey;
124
+ const read = (path) => ({ pem: readFileSync(path, "utf8"), path });
104
125
  try {
105
- if (existsSync(keyPath)) return { pem: readFileSync(keyPath, "utf8"), path: keyPath };
106
- // 用 RSA 而不是 ed25519:ssh2 只认 OpenSSH 格式的 ed25519 私钥,
107
- // 而 Node 导不出那个格式;PKCS#1 的 RSA PEM 两边都认。
126
+ if (existsSync(edKeyPath)) {
127
+ activeKey = read(edKeyPath);
128
+ return activeKey;
129
+ }
130
+ // ssh2 可用就生成 ed25519(懒加载失败会抛,落到下面的 RSA 退路)
131
+ try {
132
+ const { utils } = loadSsh2();
133
+ if (typeof utils?.generateKeyPairSync === "function") {
134
+ const pair = utils.generateKeyPairSync("ed25519");
135
+ if (pair?.private && pair?.public) {
136
+ mkdirSync(dirname(edKeyPath), { recursive: true });
137
+ writeFileSync(edKeyPath, pair.private, { mode: 0o600 });
138
+ writeFileSync(`${edKeyPath}.pub`, `${String(pair.public).trim()}\n`, { mode: 0o644 });
139
+ log(`已生成 SSH 密钥(ed25519):${edKeyPath}`);
140
+ activeKey = read(edKeyPath);
141
+ return activeKey;
142
+ }
143
+ }
144
+ } catch (error) {
145
+ warn(`生成 ed25519 密钥失败,退回 RSA:${error?.message ?? error}`);
146
+ }
147
+ if (existsSync(keyPath)) {
148
+ activeKey = read(keyPath);
149
+ return activeKey;
150
+ }
151
+ // 最后退路:Node 自己生成的 PKCS#1 RSA
108
152
  const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 3072 });
109
153
  mkdirSync(dirname(keyPath), { recursive: true });
110
154
  writeFileSync(keyPath, privateKey.export({ type: "pkcs1", format: "pem" }), { mode: 0o600 });
111
155
  writeFileSync(`${keyPath}.pub`, `${publicKeyLine(publicKey)}\n`, { mode: 0o644 });
112
156
  log(`已生成 SSH 密钥:${keyPath}`);
113
- return { pem: readFileSync(keyPath, "utf8"), path: keyPath };
157
+ activeKey = read(keyPath);
158
+ return activeKey;
114
159
  } catch (error) {
115
160
  warn(`读/生成 SSH 密钥失败:${error?.message ?? error}`);
116
161
  return undefined;
@@ -118,12 +163,28 @@ export function createSshManager({ stateDir, credentialsPath, log = () => {}, wa
118
163
  };
119
164
  const publicLine = () => {
120
165
  try {
121
- return readFileSync(`${keyPath}.pub`, "utf8").trim();
166
+ const key = activeKey ?? ensureKey();
167
+ if (!key?.path) return "";
168
+ return readFileSync(`${key.path}.pub`, "utf8").trim();
122
169
  } catch {
123
170
  return "";
124
171
  }
125
172
  };
126
173
 
174
+ /** 公钥指纹(base64 主体部分的 sha256 前 16 位十六进制),用来判断对端那份是不是当前这把。 */
175
+ const fingerprint = (pubLine) => {
176
+ const body = String(pubLine).trim().split(/\s+/)[1] ?? "";
177
+ if (!body) return "";
178
+ return createHash("sha256").update(body).digest("hex").slice(0, 16);
179
+ };
180
+
181
+ /** 当前这把公钥是否确实已经部署到这台对端。 */
182
+ const isDeployed = (machine) => {
183
+ const saved = known(machine) ?? {};
184
+ const fp = fingerprint(publicLine());
185
+ return saved.hasKey === true && !!fp && saved.keyFp === fp;
186
+ };
187
+
127
188
  /** 在已建立的连接上执行一条命令,收集输出。 */
128
189
  const exec = (client, command) =>
129
190
  new Promise((resolve) => {
@@ -139,7 +200,13 @@ export function createSshManager({ stateDir, credentialsPath, log = () => {}, wa
139
200
  });
140
201
  });
141
202
 
142
- /** 用"只有私钥"的新连接自测一次,确认免密可用。 */
203
+ /**
204
+ * 只用私钥连一次,确认免密可用。
205
+ *
206
+ * 注:这里**不给** ssh2 传任何签名算法偏好。1.17 的 Client 没有能强制
207
+ * ssh-rsa(SHA-1) 的开关(algorithms.pubKey 不被支持),签名算法由对端的
208
+ * server-sig-algs 决定;这也是把密钥换成 ed25519 的原因。
209
+ */
143
210
  const verifyKeyLogin = ({ host, port, username, pem }) =>
144
211
  new Promise((resolve) => {
145
212
  const probe = new (loadSsh2().Client)();
@@ -177,12 +244,13 @@ export function createSshManager({ stateDir, credentialsPath, log = () => {}, wa
177
244
  warn(`部署公钥失败:${result.output.slice(0, 200)}`);
178
245
  return false;
179
246
  }
180
- const ok = await verifyKeyLogin({ host, port, username, pem: ensureKey()?.pem ?? "" });
181
- if (!ok) {
247
+ const how = await verifyKeyLogin({ host, port, username, pem: ensureKey()?.pem ?? "" });
248
+ if (!how) {
182
249
  warn(`公钥已写入,但密钥登录自测没通过(${username}@${host})`);
183
250
  return false;
184
251
  }
185
- remember(machine, { username, hasKey: true });
252
+ // 连指纹一起落盘:换过密钥(RSA→ed25519)以后,旧记录里的 hasKey 就不该再被当真
253
+ remember(machine, { username, hasKey: true, keyFp: fingerprint(pub) });
186
254
  log(`已为 ${machine || host} 部署公钥,之后免密登录`);
187
255
  return true;
188
256
  };
@@ -282,14 +350,24 @@ export function createSshManager({ stateDir, credentialsPath, log = () => {}, wa
282
350
  const open = async ({ host, port = 22, username, password = "", cols = 80, rows = 24, machine = "" }) => {
283
351
  const key = ensureKey();
284
352
  const saved = known(machine) ?? {};
353
+ // 这里的 port 是**实际连接用的端口**:直连时是用户的端口,走 tailnet 出站流时
354
+ // 是本机回环端口。所以绝不能当"用户想用的端口"记下来——曾经就这么错过,
355
+ // 面板回填成 55889 这种一次性隧道端口,下次必然连不上。用户意图那个端口
356
+ // 由调用方(/mesh/api/ssh/ws)用 remember() 单独记。
357
+ //
285
358
  // 密钥只对"当初部署它的那个用户名"有意义:换了用户名先试密钥只会换来一次
286
359
  // 认证失败,还多等一轮。所以用户名不一致时直接走密码。
287
360
  const keyApplies = !!key?.pem && (!saved.username || saved.username === username);
361
+ // 用户这次明确给了密码、而本机这把密钥并不知道已部署到这台对端时,直接走密码:
362
+ // 先拿密钥去试只会多一次注定失败的认证,还可能让对端多记一次失败次数。
363
+ const deployed = isDeployed(machine);
288
364
  const attempts = [];
289
- if (keyApplies) attempts.push("key");
365
+ if (keyApplies && (deployed || !password)) attempts.push("key");
290
366
  if (password) attempts.push("password");
291
367
  if (attempts.length === 0) throw new Error("没有可用凭据:请输入密码,或先部署密钥");
292
368
 
369
+ const label = (mode) => (mode === "password" ? "密码" : "密钥");
370
+
293
371
  let lastError;
294
372
  for (const mode of attempts) {
295
373
  try {
@@ -301,19 +379,35 @@ export function createSshManager({ stateDir, credentialsPath, log = () => {}, wa
301
379
  rows,
302
380
  machine,
303
381
  password,
304
- ...(mode === "key" ? { privateKey: key.pem } : {}),
382
+ ...(mode === "password" ? {} : { privateKey: key.pem }),
305
383
  });
306
- log(`SSH 已连接 ${username}@${host}:${port}(${session.id.slice(0, 8)},${mode === "key" ? "密钥" : "密码"})`);
307
- if (mode === "password" && key?.pem && known(machine)?.hasKey !== true) {
308
- // 不阻塞会话:后台部署公钥 + 自测
384
+ log(`SSH 已连接 ${username}@${host}:${port}(${session.id.slice(0, 8)},${label(mode)})`);
385
+ // 只固化"这台对端认不认本机这把密钥";端口由调用方记,别在这里猜
386
+ remember(machine, {
387
+ username,
388
+ ...(mode === "password" ? {} : { hasKey: true, keyFp: fingerprint(publicLine()) }),
389
+ });
390
+ if (mode === "password" && key?.pem && !deployed) {
391
+ // 不阻塞会话:后台部署公钥 + 自测,成功后下次就是免密
309
392
  void deployKey(client, { host, port, username, machine });
310
393
  }
311
394
  return session.id;
312
395
  } catch (error) {
313
396
  lastError = error;
314
- warn(`SSH ${mode === "key" ? "密钥" : "密码"}登录失败 ${username}@${host}: ${error.message}`);
397
+ warn(`SSH ${label(mode)}登录失败 ${username}@${host}: ${error.message}`);
315
398
  }
316
399
  }
400
+ // 只试过密钥就全灭时,必须说清"是密钥被拒",别让人以为是网络不通:
401
+ // 历史上部署过的公钥会堆在 authorized_keys 里,当前那把对不上时密钥认证
402
+ // 必然失败,而这时用户往往还没填密码 —— 笼统一句"认证失败"会把人带偏。
403
+ const keyOnly = !attempts.includes("password");
404
+ if (keyOnly) {
405
+ throw new Error(
406
+ `对端拒绝了本机保存的密钥(${lastError?.message ?? "认证失败"})。` +
407
+ "改用密码登录一次即可;要恢复密钥登录,请在设备行里重新部署密钥。" +
408
+ "(如果对端 authorized_keys 里堆了多个历史 dsh-mesh 公钥,那些旧项不会被新密钥取代。)",
409
+ );
410
+ }
317
411
  throw lastError ?? new Error("连接失败");
318
412
  };
319
413
 
@@ -370,10 +464,21 @@ export function createSshManager({ stateDir, credentialsPath, log = () => {}, wa
370
464
  const list = () => [...sessions.values()].map((s) => ({ id: s.id, machine: s.machine, alive: !!s.stream, buffered: s.ring.length }));
371
465
  const ring = (id) => sessions.get(id)?.ring ?? "";
372
466
 
373
- /** 供面板使用:已知用户名 + 是否已部署密钥。 */
467
+ /**
468
+ * 供面板使用:已知用户名 + 是否已部署密钥 + 上次用过的端口。
469
+ *
470
+ * hasKey 只在对端那份公钥就是本机当前这把时为真:换了密钥(RSA→ed25519)
471
+ * 之后旧记录必须失效,否则面板会骗人地说"免密可用",然后连接失败。
472
+ */
374
473
  const describe = (machine) => {
375
474
  const saved = known(machine) ?? {};
376
- return { username: saved.username ?? "", hasKey: saved.hasKey === true, keyPath };
475
+ const key = activeKey ?? ensureKey();
476
+ return {
477
+ username: saved.username ?? "",
478
+ hasKey: isDeployed(machine),
479
+ port: Number(saved.port) > 0 ? Number(saved.port) : 0,
480
+ keyPath: key?.path ?? keyPath,
481
+ };
377
482
  };
378
483
 
379
484
  return { open, subscribe, write, resize, close, closeAll, list, ring, describe, remember };
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 「这次 SSH 该连哪个地址」—— 纯决策,不做 IO。
3
+ *
4
+ * 背景:SSH 是裸 TCP,而 tailnet 在这台机器上是**用户态**的(tsnet sidecar),
5
+ * 宿主根本没有 100.x 的路由。所以「用对端的 tailnet 地址去连 22 端口」永远
6
+ * 只会卡到 `timed out waiting for handshake` —— index.js 里原先那句注释就是
7
+ * 踩过这个坑之后写的。
8
+ *
9
+ * 正确做法分两步:
10
+ * 1. 先在**能直连**的地址里挑一个(局域网/局域网同段);
11
+ * 2. 都不通、但对端有 tailnet 端点时,让 sidecar 在本机开一个回环端口,
12
+ * 把字节流打进 tailnet(`openStream`),SSH 再连 127.0.0.1:<那个端口>。
13
+ *
14
+ * 这样「SSH 走 tailnet」在两端都成立,且不需要系统级 tailscaled、不需要改 sshd。
15
+ *
16
+ * @typedef {{ mode: "direct" | "stream" | "none", host?: string, port?: number,
17
+ * address?: string, note: string }} SshTargetPlan
18
+ */
19
+
20
+ /**
21
+ * 从对端的端点候选里挑出 SSH 要用的地址。
22
+ *
23
+ * @param {object} input
24
+ * @param {Array<{host?: string, transport?: string}>} [input.endpoints] 对端端点(已按健康排序)
25
+ * @param {number} [input.port] SSH 端口,缺省 22
26
+ * @param {string} [input.requestedHost] 客户端指定的主机(兜底)
27
+ * @param {string} [input.tsnetHost] 对端 tailnet 地址(100.64/10);有它才可能走通道
28
+ * @param {string} [input.reachableHost] 探测下来**确实连得上**的主机;没有则不直连
29
+ * @returns {SshTargetPlan}
30
+ */
31
+ export function planSshTarget({
32
+ endpoints = [],
33
+ port = 22,
34
+ requestedHost = "",
35
+ tsnetHost = "",
36
+ reachableHost = "",
37
+ } = {}) {
38
+ const wanted = Number(port) > 0 ? Number(port) : 22;
39
+
40
+ // 1) 探测已经证明能连 → 直连(局域网最快,且不占 sidecar 端口)。
41
+ const direct = String(reachableHost ?? "").trim();
42
+ if (direct) {
43
+ return { mode: "direct", host: direct, port: wanted, note: `直连 ${direct}:${wanted}` };
44
+ }
45
+
46
+ // 2) 拨不通,但对端在 tailnet 上 → 本机回环端口 + tailnet 字节流。
47
+ const tailnet = String(tsnetHost ?? "").trim();
48
+ if (tailnet) {
49
+ return {
50
+ mode: "stream",
51
+ address: `${tailnet}:${wanted}`,
52
+ port: wanted,
53
+ note: `经本机 tailnet 通道直连 ${tailnet}:${wanted}(对端 ${wanted} 端口在 tailnet 上)`,
54
+ };
55
+ }
56
+
57
+ // 3) 两条都不成立:如实说清"没有 tailnet 端点",不要编一个地址出来。
58
+ const requested = String(requestedHost ?? "").trim();
59
+ const candidates = endpoints.map((ep) => String(ep?.host ?? "").trim()).filter(Boolean);
60
+ return {
61
+ mode: "none",
62
+ host: requested,
63
+ port: wanted,
64
+ note:
65
+ `对端没有可用的 tailnet 端点,直连候选(${candidates.join("、") || requested || "无"})` +
66
+ `也都拨不通 —— SSH 需要局域网可达,或对端插件带 tailnet 通道`,
67
+ };
68
+ }
69
+
70
+ /**
71
+ * SSH 的直连候选顺序:**局域网地址优先**,其次才是其它(tailnet 地址不进候选,
72
+ * 因为宿主拨不到;它只作为 `tsnetHost` 走通道)。
73
+ *
74
+ * @param {Array<{host?: string, transport?: string}>} endpoints
75
+ * @param {string} requestedHost
76
+ * @returns {string[]}
77
+ */
78
+ export function sshDirectCandidates(endpoints = [], requestedHost = "") {
79
+ const isPrivate = (h) =>
80
+ /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(String(h ?? ""));
81
+ const out = [];
82
+ const push = (host) => {
83
+ const value = String(host ?? "").trim();
84
+ if (value && !out.includes(value)) out.push(value);
85
+ };
86
+ for (const ep of endpoints) {
87
+ if (ep?.transport === "tsnet") continue;
88
+ if (isPrivate(ep?.host)) push(ep.host);
89
+ }
90
+ const requested = String(requestedHost ?? "").trim();
91
+ if (isPrivate(requested)) push(requested);
92
+ for (const ep of endpoints) {
93
+ if (ep?.transport === "tsnet") continue;
94
+ push(ep?.host);
95
+ }
96
+ push(requested);
97
+ return out;
98
+ }
@@ -9,11 +9,11 @@
9
9
  * 键是资产名,值是 gzip 压缩后的 sha256。
10
10
  */
11
11
  export const PINNED_CHECKSUMS = {
12
- "dsh-mesh-tsnet-android-amd64.gz": "2b97c82036f361dfda83551fb5a80f84edfc86630df393cc06153f277725e95f",
13
- "dsh-mesh-tsnet-android-arm64.gz": "e88385ad8e1746620564543d201fb9f7d4cb3b26b4a12b5c45e56b35cafba449",
14
- "dsh-mesh-tsnet-darwin-amd64.gz": "793c775bd6b65c491cfa754fe3df3533ef423c0a1d43b95a1a537c7cbe53c8d3",
15
- "dsh-mesh-tsnet-darwin-arm64.gz": "9256a636787956de4a62a651b999e6a336aeffbf8e6eff4f0b558cf22f9fa321",
16
- "dsh-mesh-tsnet-linux-amd64.gz": "1a8df647bba95524c32eb277aeb1eec89a2991e9b0ef04f18255379e0fe35d21",
17
- "dsh-mesh-tsnet-linux-arm64.gz": "c8a3d8d4cad7bf3e28a265b27d79f74c4c807ebb50cb76baef87b8c3cf962bcd",
18
- "dsh-mesh-tsnet-windows-amd64.exe.gz": "4e9676fe371656a91c8d019c9483e0836cea8d28f46a625780cb593419cd6637",
12
+ "dsh-mesh-tsnet-android-amd64.gz": "5bdaaae79ba6530a89b2abcbeb9b3ab211bc9c9bb789cd400575208ef8e4289b",
13
+ "dsh-mesh-tsnet-android-arm64.gz": "b10f13079b5b699d56009890a876f8cef8d391d393da37d348b4012684ffa2cd",
14
+ "dsh-mesh-tsnet-darwin-amd64.gz": "1bdb986591c5bfee6ec1539cf2f7322f4067a700626199254f77d2d9905416f9",
15
+ "dsh-mesh-tsnet-darwin-arm64.gz": "bfe1b07a5be5c4f1841131afbfc319017dd79c3440860e829d8151187845e218",
16
+ "dsh-mesh-tsnet-linux-amd64.gz": "9e5800927abbda33e7c0828ecd882381c8fcab3a7b066491a5eaaee97a22714e",
17
+ "dsh-mesh-tsnet-linux-arm64.gz": "226b6478c35ad893b4d53705103cc4c5233fc4016ee7da2b00b277b1d915a86e",
18
+ "dsh-mesh-tsnet-windows-amd64.exe.gz": "d86b269bdf5d7b04615f911c0462ff5437433e26652cbe65a7780be5a31606ed",
19
19
  };
@@ -25,8 +25,14 @@ import { dirname, join } from "node:path";
25
25
  import { homedir } from "node:os";
26
26
  import { PINNED_CHECKSUMS } from "./checksums.js";
27
27
 
28
- /** Sidecar 控制协议版本;与 sidecar/main.go 的 ProtocolVersion 必须一致。 */
29
- export const SIDECAR_PROTOCOL = 1;
28
+ /**
29
+ * Sidecar 控制协议版本;与 sidecar/main.go 的 ProtocolVersion 必须一致。
30
+ *
31
+ * v2 起才有 /__tsnet/dial(出站流)与 /__tsnet/listen(入站暴露)。v1 的二进制
32
+ * 没有这两个端点,且老插件钉着 v1 那批 sha256 —— 换二进制必须新开 sidecar-v<N>,
33
+ * 覆盖同名资产会让老版本校验失败。
34
+ */
35
+ export const SIDECAR_PROTOCOL = 2;
30
36
  const RELEASE_TAG = `sidecar-v${SIDECAR_PROTOCOL}`;
31
37
  const REPO = "peng456/dsh-plugin-mesh";
32
38
  const ASSET_BASE = `https://github.com/${REPO}/releases/download/${RELEASE_TAG}`;
@@ -274,6 +274,8 @@ export class TsnetNode extends EventEmitter {
274
274
  #restarts = 0;
275
275
  #stopping = false;
276
276
  #forwards = new Set();
277
+ #streams = new Map();
278
+ #exposed = new Set();
277
279
  #hostname;
278
280
 
279
281
  /**
@@ -465,6 +467,104 @@ export class TsnetNode extends EventEmitter {
465
467
  this.#log(`tailnet 入站已开启::${port} → 127.0.0.1:${port}`);
466
468
  }
467
469
 
470
+ /**
471
+ * 在本机开一个回环端口,把每个连上来的字节流打进 tailnet。
472
+ *
473
+ * 与 `fetchOverTailnet` 的分工:那个只做"一问一答、整包缓冲"的 HTTP,WebSocket
474
+ * 升级和长连接一律不行(`/api/remote.mux` 就是 WS)。要看对端 GUI 就必须有
475
+ * 裸字节流,所以这里让 sidecar 监听 127.0.0.1 并双向 copy —— 拿到端口之后,
476
+ * 上层(web-proxy)当普通 http 源用即可,ES/WS 全自动成立。
477
+ *
478
+ * 同一个地址复用同一只端口:重开面板不该每次换端口(换了就等于换了一个源,
479
+ * 对端签的会话 cookie 也跟着作废)。
480
+ * @param {string} address - 形如 `100.64.0.5:3080` 的 tailnet 目标
481
+ * @returns {Promise<number>} 本机回环端口
482
+ */
483
+ async openStream(address) {
484
+ const key = String(address ?? "").trim();
485
+ if (!key) throw new Error("openStream 需要 tailnet 目标地址");
486
+ const cached = this.#streams.get(key);
487
+ if (cached?.port) return cached.port;
488
+ if (cached?.pending) return cached.pending;
489
+ const pending = (async () => {
490
+ let res;
491
+ try {
492
+ res = await this.#call("/__tsnet/dial", { method: "POST", body: { address: key }, timeoutMs: 15000 });
493
+ } catch (err) {
494
+ // 老 sidecar 没有这个接口:Go 的 mux 直接回 404 文本,#call 会报"非 JSON"。
495
+ // 说清楚是**本机二进制过旧**,不是对端不通(AGENTS.md 硬约束 1)。
496
+ const text = String(err?.message ?? err);
497
+ if (/非 JSON|404/.test(text)) {
498
+ throw new Error(`本机 tsnet sidecar 版本过旧(没有出站流接口 /__tsnet/dial),需要随插件一起升级 sidecar`);
499
+ }
500
+ throw err;
501
+ }
502
+ if (!res?.ok) throw new Error(res?.error ?? `tailnet 拨号 ${key} 失败`);
503
+ const port = Number(res.port);
504
+ if (!port) throw new Error(`tailnet 拨号 ${key} 没有返回端口`);
505
+ this.#streams.set(key, { port });
506
+ this.#log(`tailnet 出站流已开启:127.0.0.1:${port} → ${key}`);
507
+ return port;
508
+ })();
509
+ this.#streams.set(key, { pending });
510
+ try {
511
+ return await pending;
512
+ } catch (err) {
513
+ this.#streams.delete(key);
514
+ throw err;
515
+ }
516
+ }
517
+
518
+ /** 关闭某个目标地址的出站流(地址不认识时静默,幂等)。 */
519
+ async closeStream(address) {
520
+ const key = String(address ?? "").trim();
521
+ const entry = this.#streams.get(key);
522
+ if (!entry?.port) {
523
+ this.#streams.delete(key);
524
+ return;
525
+ }
526
+ this.#streams.delete(key);
527
+ await this.#call("/__tsnet/undial", { method: "POST", body: { port: entry.port }, timeoutMs: 8000 }).catch(() => {});
528
+ this.#log(`tailnet 出站流已关闭:127.0.0.1:${entry.port} → ${key}`);
529
+ }
530
+
531
+ /**
532
+ * 把本机某个回环端口**暴露到 tailnet**(tailnet :port → 127.0.0.1:port,裸字节流)。
533
+ *
534
+ * 与 `registerForward` 的区别:那个是 HTTP 反代(SSH 的握手字节进不去);
535
+ * 这个是纯 TCP 管道。两侧合起来才有「SSH 走 tailnet」——本机用 openStream
536
+ * 拨过去,对端用 exposePort 暴露自己的 sshd。
537
+ *
538
+ * 注意:暴露只发生在 userspace tailnet 里,宿主与局域网看不到它;但 tailnet
539
+ * 内部按 ACL 可达,所以只该暴露确实要共享的端口(SSH),别当通用开关用。
540
+ * @param {number} port - 本机监听端口(通常 22 或 8022)
541
+ */
542
+ async exposePort(port) {
543
+ const value = Number(port);
544
+ if (!Number.isInteger(value) || value <= 0 || value > 65535) throw new Error(`端口不合法:${port}`);
545
+ if (this.#exposed.has(value)) return { port: value, already: true };
546
+ const res = await this.#call("/__tsnet/listen", { method: "POST", body: { port: value }, timeoutMs: 15000 });
547
+ if (!res?.ok) throw new Error(res?.error ?? `暴露 tailnet :${value} 失败`);
548
+ this.#exposed.add(value);
549
+ this.#log(`tailnet 入站裸流已开启::${value} → 127.0.0.1:${value}`);
550
+ return { port: value, already: res.already === true };
551
+ }
552
+
553
+ /** 收回某个已暴露的端口(幂等)。 */
554
+ async unexposePort(port) {
555
+ const value = Number(port);
556
+ if (!this.#exposed.has(value)) return { port: value, absent: true };
557
+ this.#exposed.delete(value);
558
+ await this.#call("/__tsnet/unlisten", { method: "POST", body: { port: value }, timeoutMs: 8000 }).catch(() => {});
559
+ this.#log(`tailnet 入站裸流已关闭::${value}`);
560
+ return { port: value, absent: false };
561
+ }
562
+
563
+ /** 当前暴露到 tailnet 的端口(诊断用)。 */
564
+ exposedPorts() {
565
+ return [...this.#exposed];
566
+ }
567
+
468
568
  // ───────────────────────── 启动 ─────────────────────────
469
569
 
470
570
  /**
@@ -882,6 +982,25 @@ export class TsnetNode extends EventEmitter {
882
982
  }
883
983
  }
884
984
  this.#forwards.clear();
985
+ // 出站流同理:只关自己开的那几只端口。
986
+ for (const entry of this.#streams.values()) {
987
+ if (!entry?.port) continue;
988
+ try {
989
+ await this.#call("/__tsnet/undial", { method: "POST", body: { port: entry.port }, timeoutMs: 5000 });
990
+ } catch {
991
+ /* 尽力而为 */
992
+ }
993
+ }
994
+ this.#streams.clear();
995
+ // 出站监听同理:只收自己开的那几个端口。
996
+ for (const port of this.#exposed) {
997
+ try {
998
+ await this.#call("/__tsnet/unlisten", { method: "POST", body: { port }, timeoutMs: 5000 });
999
+ } catch {
1000
+ /* 尽力而为 */
1001
+ }
1002
+ }
1003
+ this.#exposed.clear();
885
1004
 
886
1005
  if (!this.#ownsProcess || keepRemote) {
887
1006
  this.#log("保留共享的 sidecar(非本实例拉起)");