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.
@@ -0,0 +1,226 @@
1
+ /**
2
+ * 经 **mesh 口**把自己这台机器的 DSH Web GUI 转发给对端 —— 零证书、零新端口。
3
+ *
4
+ * 为什么需要它:DSH 的 Web GUI 默认只监听 127.0.0.1,而 DSH Desktop **连改都不让改**
5
+ * (`desktopWebServerHost()` 硬编码回环,LAN 意图只作用于它的 HTTPS 边缘)。于是
6
+ * "在另一台机器的面板里打开对端界面"这件事,靠"对端开个端口"是做不到的 —— 除非
7
+ * 额外起一个 web profile,或者让用户去装一张自签证书用 HTTPS 边缘。
8
+ *
9
+ * 这条通道走的是**本来就在局域网上**的 mesh 口:
10
+ * · 观看端:`GET http://<对端>:<mesh端口>/mesh/peer-web/<原路径>`,
11
+ * 带一枚 `/mesh/v1/web-url` 下发的票据(`x-dsh-peer-web` 头,或 `?t=`)。
12
+ * · 被看端:校验票据 → 转发到 `127.0.0.1:<本地 Web 端口>`,顺手把
13
+ * Host/Origin/Referer 改写成回环同源、并签好本机的会话 cookie。
14
+ *
15
+ * 票据 = `base64url(expiresAt).HMAC-SHA256(mesh 密钥, "peer-web:"+body)`,12 小时。
16
+ * 密钥是本机 state.json 里的 mesh 密钥;票据只在**过了鉴权**的 `/mesh/v1/web-url`
17
+ * 上发放(`requirePairing` 打开时就是配对过的对端)。
18
+ *
19
+ * 边界:这不是 TLS —— 局域网明文,和 mesh 通道本身同级;不可信网络请开配对码,
20
+ * 或者自己套 SSH/反代。转发只发生在被看端进程内部,所以它的 GUI 不必对外开端口。
21
+ *
22
+ * **鉴权策略与 mesh 口的其它路由完全一致**(不另立一套):
23
+ * · 一键关闭(局域网/互联网 mesh 关掉)时整条隧道跟着 503 —— 它在 mesh server
24
+ * 的请求处理里,和任务路由共用同一个闸门;
25
+ * · `requirePairing` 打开时,每个隧道请求都要带共享密钥(`x-dsh-mesh-token`,
26
+ * 由观看端代理附着),和派发任务同权;
27
+ * · 票据是额外一层:只在**鉴权之后**的 `/mesh/v1/web-url` 发放、12 小时过期,
28
+ * 用来把"见过地址"和"能长期用"分开;它不替代上面两道。
29
+ * 共享密钥与票据都**不转发给上游 GUI**(见 rewrite())。
30
+ */
31
+ import { createHmac, timingSafeEqual } from "node:crypto";
32
+ import { request as httpRequest } from "node:http";
33
+ import { connect as netConnect } from "node:net";
34
+ import { signSessionCookie } from "./desktop-auth.js";
35
+
36
+ /** 隧道前缀(挂在 mesh 口上,和 Web 口上的 /mesh/web 不是一回事)。 */
37
+ export const PEER_WEB_PREFIX = "/mesh/peer-web";
38
+ /** 票据头:观看端每个请求都带;也接受 `?t=` 方便 curl 手工验证。 */
39
+ export const PEER_WEB_TICKET_HEADER = "x-dsh-peer-web";
40
+ /** 票据有效期:一次浏览会话足够长,又不至于永久。 */
41
+ export const PEER_WEB_TICKET_TTL_MS = 12 * 3600 * 1000;
42
+
43
+ function b64u(buffer) {
44
+ return Buffer.from(buffer).toString("base64url");
45
+ }
46
+
47
+ /**
48
+ * 签一枚隧道票据。
49
+ * @param secret - mesh 密钥(state.json 里那条)
50
+ * @param options.ttlMs - 有效期,默认 12 小时
51
+ * @param options.now - 注入时间便于测试
52
+ * @returns {string} `body.signature`
53
+ */
54
+ export function createPeerWebTicket(secret, { ttlMs = PEER_WEB_TICKET_TTL_MS, now = Date.now() } = {}) {
55
+ const body = b64u(Buffer.from(String(now + ttlMs), "utf8"));
56
+ const signature = b64u(createHmac("sha256", String(secret)).update(`peer-web:${body}`).digest());
57
+ return `${body}.${signature}`;
58
+ }
59
+
60
+ /**
61
+ * 校验一枚隧道票据。
62
+ *
63
+ * 三条独立的拒绝理由都要能分开(AGENTS.md 硬约束 1:别把探测失败当成否定事实):
64
+ * 格式不对 / 签名不对 / 过期 —— 前两条是"不是我们发的",最后一条是"发过但超时"。
65
+ * @returns {{ ok: boolean, reason?: "malformed" | "signature" | "expired" }}
66
+ */
67
+ export function inspectPeerWebTicket(secret, ticket, { now = Date.now() } = {}) {
68
+ const text = String(ticket ?? "");
69
+ const cut = text.lastIndexOf(".");
70
+ if (cut <= 0 || cut === text.length - 1) return { ok: false, reason: "malformed" };
71
+ const body = text.slice(0, cut);
72
+ const signature = text.slice(cut + 1);
73
+ const expected = createHmac("sha256", String(secret)).update(`peer-web:${body}`).digest();
74
+ let given;
75
+ try {
76
+ given = Buffer.from(signature, "base64url");
77
+ } catch {
78
+ return { ok: false, reason: "malformed" };
79
+ }
80
+ if (given.byteLength !== expected.byteLength || !timingSafeEqual(given, expected)) {
81
+ return { ok: false, reason: "signature" };
82
+ }
83
+ const expiresAt = Number(Buffer.from(body, "base64url").toString("utf8"));
84
+ if (!Number.isFinite(expiresAt) || expiresAt <= now) return { ok: false, reason: "expired" };
85
+ return { ok: true };
86
+ }
87
+
88
+ /** 便捷布尔版(路由里只关心能不能过)。 */
89
+ export function verifyPeerWebTicket(secret, ticket, options) {
90
+ return inspectPeerWebTicket(secret, ticket, options).ok;
91
+ }
92
+
93
+ /**
94
+ * 把 `/mesh/peer-web/...` 还原成对端 Web 口上的原路径,并抹掉票据参数。
95
+ *
96
+ * ⚠️ 这里**必须按原字符串处理**,不能 `new URL()` + `searchParams` 转一圈:
97
+ * DSH 的插件脚本地址是 `/plugins/??a/client.js,b/client.js&rev=…` 这种
98
+ * 多问号 + 逗号的非常规形式,`URLSearchParams.toString()` 会把 `?` 编码成 `%3F`、
99
+ * `@`→`%40`、`/`→`%2F`,对端静态路由就匹配不上,兜底返回 index.html ——
100
+ * 浏览器拿到 HTML 当脚本解析,前端只报一句
101
+ * `client-modules: HTML did not preload @deepseek-ai/dsh-client-modules/client.js`。
102
+ * @returns {string | undefined} `undefined` 表示不在这个前缀下
103
+ */
104
+ export function peerWebRemainder(url) {
105
+ const text = String(url ?? "/");
106
+ const at = text.indexOf("?");
107
+ const pathname = at === -1 ? text : text.slice(0, at);
108
+ if (pathname !== PEER_WEB_PREFIX && !pathname.startsWith(`${PEER_WEB_PREFIX}/`)) return undefined;
109
+ const rest = pathname.slice(PEER_WEB_PREFIX.length) || "/";
110
+ if (at === -1) return rest;
111
+ // 只摘掉我们自己的票据参数(`t` / `t=`),其余逐字节保留。
112
+ const kept = text
113
+ .slice(at + 1)
114
+ .split("&")
115
+ .filter((part) => part !== "t" && !part.startsWith("t="));
116
+ return kept.length ? `${rest}?${kept.join("&")}` : rest;
117
+ }
118
+
119
+ /**
120
+ * 造一个「转发到本机 Web GUI」的处理器。
121
+ *
122
+ * 与 `desktop-web.js` 的区别只有一个:那里目标是**另一个**引擎的固定端口,
123
+ * 这里目标是**本进程自己的** Web 口,而且端口可能在运行期才确定(所以传函数)。
124
+ * 认证照旧在服务端完成:按目标 authority 签会话 cookie,浏览器侧永远不见 token。
125
+ *
126
+ * @param options.portOf - 返回本机 Web 端口(0/缺省表示没有 GUI)
127
+ * @param options.secretOf - 返回浏览器会话密钥(Buffer)
128
+ * @param options.log - 正常日志
129
+ * @param options.warn - 异常日志
130
+ * @returns {{ handle: (req, res) => void, upgrade: (req, socket, head) => void }}
131
+ */
132
+ export function createPeerWebForwarder({ portOf, secretOf, log = () => {}, warn = () => {} }) {
133
+ /**
134
+ * 把入站请求改写成"本机浏览器直接打开对端 GUI"的样子。
135
+ *
136
+ * 三件事缺一不可:
137
+ * 1. Host 换回环 —— 对端围栏按 Host 判断"是不是自己的 authority";
138
+ * 2. Origin/Referer 同步改写 —— 围栏要求 `new URL(origin).host === host.host`,
139
+ * 不改就会被判跨站 403(实测:Cordis 清单接口 403、`/api/remote.mux` 升级被拒,
140
+ * 界面停在「重新连接中…」);
141
+ * 3. 自己签会话 cookie —— 浏览器那条路要走 token 才能换到 cookie。
142
+ */
143
+ function rewrite(incoming, authority) {
144
+ const headers = { ...incoming, host: authority };
145
+ headers.origin = `http://${authority}`;
146
+ if (headers.referer !== undefined) headers.referer = `http://${authority}/`;
147
+ if (String(headers["sec-fetch-site"] ?? "") === "cross-site") headers["sec-fetch-site"] = "same-origin";
148
+ delete headers[PEER_WEB_TICKET_HEADER];
149
+ // mesh 密钥只属于 mesh 层,别带进上游 GUI 的请求/日志里。
150
+ delete headers["x-dsh-mesh-token"];
151
+ // 隧道票据不是给上游看的,Cookie 也由这里全权维护(浏览器那侧没有 token)。
152
+ const secret = secretOf();
153
+ if (secret) headers.cookie = signSessionCookie(secret, authority).header;
154
+ else delete headers.cookie;
155
+ return headers;
156
+ }
157
+
158
+ function handle(req, res) {
159
+ const port = portOf();
160
+ const path = peerWebRemainder(req.url ?? "/");
161
+ if (!port) {
162
+ res.writeHead(503, { "content-type": "text/plain; charset=utf-8" });
163
+ res.end("本端没有可用的 Web GUI(不是 web profile)。\n");
164
+ return;
165
+ }
166
+ if (path === undefined) {
167
+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
168
+ res.end("not found\n");
169
+ return;
170
+ }
171
+ const authority = `127.0.0.1:${port}`;
172
+ const up = httpRequest(
173
+ { host: "127.0.0.1", port, method: req.method, path, headers: rewrite(req.headers, authority) },
174
+ (reply) => {
175
+ const out = { ...reply.headers };
176
+ // 会话由本转发维护,别把 Set-Cookie 泄到隧道外(观看端没有对应的 authority)。
177
+ delete out["set-cookie"];
178
+ delete out["transfer-encoding"];
179
+ res.writeHead(reply.statusCode ?? 502, out);
180
+ reply.pipe(res);
181
+ },
182
+ );
183
+ up.on("error", (error) => {
184
+ warn(`对端 GUI 隧道转发失败(${authority}):${error?.message ?? error}`);
185
+ if (res.headersSent) {
186
+ res.destroy();
187
+ return;
188
+ }
189
+ res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
190
+ res.end("连不上本机 Web GUI。\n");
191
+ });
192
+ if (req.readableEnded) up.end();
193
+ else req.pipe(up);
194
+ }
195
+
196
+ /** 流式载波(`/api/remote.mux`):HTTP 代理不管 WS,必须单独搬字节。 */
197
+ function upgrade(req, socket, head) {
198
+ const port = portOf();
199
+ const path = peerWebRemainder(req.url ?? "/");
200
+ if (!port || path === undefined) {
201
+ socket.destroy();
202
+ return;
203
+ }
204
+ const authority = `127.0.0.1:${port}`;
205
+ const headers = rewrite(req.headers, authority);
206
+ const target = netConnect(port, "127.0.0.1", () => {
207
+ log(`对端 GUI 隧道已接通 ${path}`);
208
+ const lines = [`${req.method} ${path} HTTP/1.1`];
209
+ for (const [key, value] of Object.entries(headers)) {
210
+ if (value === undefined) continue;
211
+ for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
212
+ }
213
+ target.write(`${lines.join("\r\n")}\r\n\r\n`);
214
+ if (head && head.length) target.write(head);
215
+ target.pipe(socket);
216
+ socket.pipe(target);
217
+ });
218
+ target.on("error", (error) => {
219
+ warn(`对端 GUI 隧道升级失败(${authority}):${error?.message ?? error}`);
220
+ socket.destroy();
221
+ });
222
+ socket.on("error", () => target.destroy());
223
+ }
224
+
225
+ return { handle, upgrade };
226
+ }
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
+ }