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/client/client.js +55 -9
- package/lib/_selftest-ssh-target.mjs +106 -0
- package/lib/_selftest-web-target.mjs +218 -0
- package/lib/index.js +323 -54
- package/lib/ssh-host.js +124 -19
- package/lib/ssh-target.js +98 -0
- package/lib/tsnet/manager.js +119 -0
- package/lib/web-target.js +191 -0
- package/package.json +6 -4
- package/sidecar/main.go +242 -1
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(
|
|
106
|
-
|
|
107
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
181
|
-
if (!
|
|
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
|
-
|
|
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 === "
|
|
382
|
+
...(mode === "password" ? {} : { privateKey: key.pem }),
|
|
305
383
|
});
|
|
306
|
-
log(`SSH 已连接 ${username}@${host}:${port}(${session.id.slice(0, 8)},${mode
|
|
307
|
-
|
|
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
|
|
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
|
-
|
|
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
|
+
}
|
package/lib/tsnet/manager.js
CHANGED
|
@@ -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(非本实例拉起)");
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「在我这台机器上,怎么才能真的打开对端的 DSH 界面」—— 纯决策,不做 IO。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要单独一层:对端 `GET /mesh/v1/web-url` 的自报地址是**站在它自己角度**
|
|
5
|
+
* 算出来的(`preferredAddress()`),手机在移动数据下那会是运营商 CGNAT 的 10.x;
|
|
6
|
+
* 它再顺带自报一个 `lanReachable`(判据只是"我绑了 0.0.0.0")。这两样都不是
|
|
7
|
+
* "观看端能不能到"的证据,照单全收的结果就是面板永远 502:
|
|
8
|
+
*
|
|
9
|
+
* 连不上对端 10.12.225.124:3080:socket hang up
|
|
10
|
+
*
|
|
11
|
+
* 所以判断权必须留在观看端:
|
|
12
|
+
* 1. 地址能拨通(真的拿到 HTTP 响应)→ 直接用它,行为和以前一致;
|
|
13
|
+
* 2. 拨不通,但对端有一条 tailnet 通道 → 在本机开一个回环端口,由 sidecar
|
|
14
|
+
* 把字节流打进 tailnet(宿主机路由不到 100.x,且 WebSocket 升级也走这条);
|
|
15
|
+
* 3. 两条都不可用 → 如实说"哪一条试过、怎么失败的",不许把探测失败伪装成
|
|
16
|
+
* 对端已关闭(AGENTS.md 硬约束 1)。
|
|
17
|
+
*
|
|
18
|
+
* @typedef {{ prefix: string, ticket: string, header: string } | null} TunnelInfo
|
|
19
|
+
* @typedef {{ mode: "direct" | "stream" | "none", remoteBase?: string, address?: string,
|
|
20
|
+
* prefix?: string, ticket?: string, header?: string, note: string }} WebTargetPlan
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 从对端给的 tunnel 描述里取出**相对前缀**。
|
|
25
|
+
*
|
|
26
|
+
* 新版本对端发 `{ prefix: "/mesh/peer-web", ticket }`;老版本发的是一条绝对地址
|
|
27
|
+
* `{ url: "http://<它自己的地址>:<mesh端口>/mesh/peer-web/" }` —— 那种地址的主机
|
|
28
|
+
* 部分同样可能是不可达的 10.x,所以**只取路径**,主机由观看端用自己的通道决定。
|
|
29
|
+
* @returns {string} 带前导斜杠、不带尾斜杠的前缀;无则空串。
|
|
30
|
+
*/
|
|
31
|
+
export function tunnelPrefixOf(tunnel) {
|
|
32
|
+
if (!tunnel || typeof tunnel !== "object") return "";
|
|
33
|
+
const raw = String(tunnel.prefix ?? "").trim();
|
|
34
|
+
if (raw) {
|
|
35
|
+
const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
|
|
36
|
+
return withSlash.replace(/\/+$/, "");
|
|
37
|
+
}
|
|
38
|
+
const url = String(tunnel.url ?? "").trim();
|
|
39
|
+
if (!url) return "";
|
|
40
|
+
try {
|
|
41
|
+
return new URL(url).pathname.replace(/\/+$/, "");
|
|
42
|
+
} catch {
|
|
43
|
+
// 解析不了的地址当"没有前缀",不要凭空猜一个出来。
|
|
44
|
+
return "";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 决定观看端用哪条路。
|
|
50
|
+
*
|
|
51
|
+
* @param {object} input
|
|
52
|
+
* @param {string} input.reportedBase 对端自报的绝对地址(`http://host:port/`)
|
|
53
|
+
* @param {number} [input.reportedPort] 对端 GUI 端口,缺省取地址里的端口
|
|
54
|
+
* @param {boolean} [input.reachable] 本机真的拨通过没有;`undefined` = 没测(按可达处理,保持旧行为)
|
|
55
|
+
* @param {TunnelInfo} [input.tunnel] 对端 mesh 口隧道
|
|
56
|
+
* @param {string} [input.tsnetHost] 对端的 tailnet 地址(100.64/10);没有就走不了公网
|
|
57
|
+
* @param {number} [input.meshPort] 对端 mesh 口端口(隧道挂在它上面)
|
|
58
|
+
* @param {boolean} [input.guiBoundEverywhere] 对端 GUI 是否绑在所有网卡(bind=0.0.0.0);
|
|
59
|
+
* `undefined` = 对端没报(老版本),按"绑了"处理以保持旧行为
|
|
60
|
+
* @param {string} [input.probeNote] 探测失败时的原始描述,需原样带进 note
|
|
61
|
+
* @returns {WebTargetPlan}
|
|
62
|
+
*/
|
|
63
|
+
export function planWebTarget({
|
|
64
|
+
reportedBase,
|
|
65
|
+
reportedPort,
|
|
66
|
+
reachable,
|
|
67
|
+
tunnel = null,
|
|
68
|
+
tsnetHost = "",
|
|
69
|
+
meshPort = 0,
|
|
70
|
+
guiBoundEverywhere,
|
|
71
|
+
probeNote = "",
|
|
72
|
+
} = {}) {
|
|
73
|
+
const base = String(reportedBase ?? "");
|
|
74
|
+
const port = Number(reportedPort) || portOf(base) || 0;
|
|
75
|
+
const reportedHost = hostOf(base);
|
|
76
|
+
|
|
77
|
+
// 对端自报 `127.0.0.1` 表示「我的 GUI 只听回环」——那不是本机能直连的地址,
|
|
78
|
+
// 直连过去只会打到**本机自己**的 3080(一个非常难查的假成功)。
|
|
79
|
+
// 所以这类地址一律不按直连处理,只能走它给的 mesh 口隧道。
|
|
80
|
+
const loopbackReport = isLoopbackHost(reportedHost);
|
|
81
|
+
const direct = reachable !== false && !loopbackReport;
|
|
82
|
+
|
|
83
|
+
// 没探测 / 探测通过 → 照旧直连。局域网路径上不多花一毫秒。
|
|
84
|
+
if (direct) {
|
|
85
|
+
return { mode: "direct", remoteBase: base, note: "" };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const host = String(tsnetHost ?? "").trim();
|
|
89
|
+
if (!host) {
|
|
90
|
+
return {
|
|
91
|
+
mode: "none",
|
|
92
|
+
remoteBase: base,
|
|
93
|
+
note: loopbackReport
|
|
94
|
+
? `对端只报了回环地址 ${base}(它的 GUI 只听 127.0.0.1),且没有 tailnet 通道可用`
|
|
95
|
+
: `对端自报地址 ${base} 从本机拨不通(${probeNote || "无响应"}),且没有 tailnet 通道可用`,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const prefix = tunnelPrefixOf(tunnel);
|
|
100
|
+
const ticket = String(tunnel?.ticket ?? "");
|
|
101
|
+
const header = String(tunnel?.header ?? "x-dsh-peer-web");
|
|
102
|
+
|
|
103
|
+
// 隧道挂在**对端的 mesh 口**上:目标是对端 mesh 端口 + 相对前缀。
|
|
104
|
+
// 这条路把 Host/Origin/会话 cookie 的改写留在对端进程里完成,所以对端 GUI
|
|
105
|
+
// 只绑回环也能看;WebSocket(/api/remote.mux)同样走这条。
|
|
106
|
+
if (prefix && ticket && meshPort > 0) {
|
|
107
|
+
return {
|
|
108
|
+
mode: "stream",
|
|
109
|
+
address: `${host}:${meshPort}`,
|
|
110
|
+
prefix,
|
|
111
|
+
ticket,
|
|
112
|
+
header,
|
|
113
|
+
note: `经对端 mesh 口隧道(对端自报地址 ${base} 不可达)`,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// 没有隧道(对端认为它"局域网可达",其实只有运营商地址):直接打通它的 GUI。
|
|
118
|
+
// 前提是**对端 GUI 真的绑在所有网卡上**(它报的 bind=0.0.0.0)。只绑回环的
|
|
119
|
+
// 宿主连它自己的 tailnet 地址都不听,拨过去只会被拒。
|
|
120
|
+
const boundEverywhere = guiBoundEverywhere !== false;
|
|
121
|
+
if (port > 0 && boundEverywhere && !loopbackReport) {
|
|
122
|
+
return {
|
|
123
|
+
mode: "stream",
|
|
124
|
+
address: `${host}:${port}`,
|
|
125
|
+
prefix: "",
|
|
126
|
+
ticket: "",
|
|
127
|
+
header,
|
|
128
|
+
note: `经本机 tailnet 通道直连对端 GUI ${host}:${port}(对端自报地址 ${base} 不可达)`,
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
mode: "none",
|
|
134
|
+
remoteBase: base,
|
|
135
|
+
note: loopbackReport || !boundEverywhere
|
|
136
|
+
? `对端 GUI 只听回环(${base}),且没给 mesh 口隧道 —— 需要把对端插件升级到带隧道的版本`
|
|
137
|
+
: `对端自报地址 ${base} 从本机拨不通(${probeNote || "无响应"}),且没拿到对端 GUI 端口`,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 从 `http://host:port/` 里取主机名;取不到返回空串。 */
|
|
142
|
+
function hostOf(base) {
|
|
143
|
+
try {
|
|
144
|
+
return new URL(String(base ?? "")).hostname;
|
|
145
|
+
} catch {
|
|
146
|
+
return "";
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 这个主机名是不是"本机回环"(对端自称只听回环时会给它)。 */
|
|
151
|
+
export function isLoopbackHost(host) {
|
|
152
|
+
const text = String(host ?? "").trim().toLowerCase();
|
|
153
|
+
if (!text) return false;
|
|
154
|
+
if (text === "localhost" || text.endsWith(".localhost")) return true;
|
|
155
|
+
if (text === "::1" || text === "0:0:0:0:0:0:0:1") return true;
|
|
156
|
+
if (/^127\./.test(text)) return true;
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 从 `http://host:port/` 里取端口;取不到返回 0。 */
|
|
161
|
+
function portOf(base) {
|
|
162
|
+
try {
|
|
163
|
+
const parsed = new URL(base);
|
|
164
|
+
if (parsed.port) return Number(parsed.port);
|
|
165
|
+
return parsed.protocol === "https:" ? 443 : 80;
|
|
166
|
+
} catch {
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* 这个主机名需不需要先探测一次可达性。
|
|
173
|
+
*
|
|
174
|
+
* 只用来决定"要不要探测":同网段地址拨不通会在面板里立刻明确报出来,没必要
|
|
175
|
+
* 每次都先花 1.5 秒探测;跨网段的地址(运营商 CGNAT、别的子网)才是对端自报
|
|
176
|
+
* 地址最容易骗人的地方 —— 10.x 尤其:手机在移动数据下的自报地址就长这样。
|
|
177
|
+
* @param {string} host
|
|
178
|
+
* @param {string[]} localAddresses 本机 IPv4 列表
|
|
179
|
+
*/
|
|
180
|
+
export function needsReachabilityProbe(host, localAddresses = []) {
|
|
181
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(String(host ?? ""));
|
|
182
|
+
if (!m) return true;
|
|
183
|
+
if (m[1] === "127") return false;
|
|
184
|
+
const wanted = `${m[1]}.${m[2]}.${m[3]}`;
|
|
185
|
+
for (const address of localAddresses) {
|
|
186
|
+
const n = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.\d{1,3}$/.exec(String(address ?? ""));
|
|
187
|
+
if (!n) continue;
|
|
188
|
+
if (`${n[1]}.${n[2]}.${n[3]}` === wanted) return false;
|
|
189
|
+
}
|
|
190
|
+
return true;
|
|
191
|
+
}
|