dsh-plugin-mesh 0.5.5 → 0.5.6
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/README.md +24 -0
- package/client/client.js +758 -14
- package/lib/desktop-auth.js +88 -0
- package/lib/desktop-web.js +146 -0
- package/lib/index.js +405 -2
- package/lib/ssh-host.js +380 -0
- package/lib/web-proxy.js +333 -0
- package/lib/ws-mini.js +156 -0
- package/llms.txt +21 -0
- package/package.json +4 -1
package/lib/ssh-host.js
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 本机到对端的 SSH 终端会话管理(含密钥自动登录)。
|
|
3
|
+
*
|
|
4
|
+
* 认证策略:
|
|
5
|
+
* 1. 本机有私钥 → 先用密钥登录;
|
|
6
|
+
* 2. 密钥不可用且给了密码 → 用密码登录,**成功后顺手把公钥部署过去**,
|
|
7
|
+
* 并用"只有私钥"的新连接自测一次;通过后以后不用再输密码。
|
|
8
|
+
*
|
|
9
|
+
* 安全边界:私钥与(可选的)密码只存本机 profile 的 mesh 状态目录,0600;
|
|
10
|
+
* 部署公钥只是往对端 ~/.ssh/authorized_keys 追加一行(幂等),不需要 sudo,
|
|
11
|
+
* 也不改 sshd_config。
|
|
12
|
+
*/
|
|
13
|
+
import { createRequire } from "node:module";
|
|
14
|
+
import { randomUUID, generateKeyPairSync } from "node:crypto";
|
|
15
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
|
|
16
|
+
import { dirname, join } from "node:path";
|
|
17
|
+
|
|
18
|
+
/** 每个会话在内存里保留的最近输出上限。 */
|
|
19
|
+
const RING_LIMIT = 200 * 1024;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* ssh2 必须**懒加载**,不能在模块顶层静态 import。
|
|
23
|
+
*
|
|
24
|
+
* 为什么:CI 里跑 `npm test` 的机器不装依赖(这个项目原来零运行时依赖,测试
|
|
25
|
+
* 也不需要 node_modules);静态 import 会让 `lib/index.js` 一被加载就
|
|
26
|
+
* ERR_MODULE_NOT_FOUND,连不碰 SSH 的整套自测都红(实测 2026-10-29,ci 三条
|
|
27
|
+
* job 全红)。改成用 createRequire 在真正要连 SSH 时再取,缺依赖就给出
|
|
28
|
+
* 一句能动手的话,而不是把插件拖垮。
|
|
29
|
+
*/
|
|
30
|
+
let ssh2Module;
|
|
31
|
+
function loadSsh2() {
|
|
32
|
+
if (ssh2Module) return ssh2Module;
|
|
33
|
+
try {
|
|
34
|
+
const req = createRequire(import.meta.url);
|
|
35
|
+
const mod = req("ssh2");
|
|
36
|
+
ssh2Module = mod?.Client ? mod : mod?.default?.Client ? mod.default : mod;
|
|
37
|
+
if (!ssh2Module?.Client) throw new Error("模块里没有 Client");
|
|
38
|
+
return ssh2Module;
|
|
39
|
+
} catch (err) {
|
|
40
|
+
throw new Error(
|
|
41
|
+
`SSH 依赖 ssh2 不可用(插件安装不完整):${err?.message ?? err}。` +
|
|
42
|
+
"重装插件(会自动装依赖),或在插件目录执行 npm i ssh2。",
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** SSH 的 mpint 编码:4 字节长度 + 大端字节(最高位为 1 时补 0x00)。 */
|
|
48
|
+
function mpint(bytes) {
|
|
49
|
+
let body = Buffer.from(bytes);
|
|
50
|
+
while (body.length > 1 && body[0] === 0) body = body.subarray(1);
|
|
51
|
+
if (body[0] & 0x80) body = Buffer.concat([Buffer.from([0]), body]);
|
|
52
|
+
const len = Buffer.alloc(4);
|
|
53
|
+
len.writeUInt32BE(body.length);
|
|
54
|
+
return Buffer.concat([len, body]);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 生成 OpenSSH 单行公钥(RSA)。 */
|
|
58
|
+
function publicKeyLine(keyObject) {
|
|
59
|
+
const jwk = keyObject.export({ format: "jwk" });
|
|
60
|
+
const e = Buffer.from(jwk.e, "base64url");
|
|
61
|
+
const n = Buffer.from(jwk.n, "base64url");
|
|
62
|
+
const type = Buffer.from("ssh-rsa");
|
|
63
|
+
const len = Buffer.alloc(4);
|
|
64
|
+
len.writeUInt32BE(type.length);
|
|
65
|
+
return `ssh-rsa ${Buffer.concat([len, type, mpint(e), mpint(n)]).toString("base64")} dsh-mesh`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 造一个 SSH 会话管理器。
|
|
70
|
+
* @param options - stateDir(存私钥)、credentialsPath(存用户名/是否已部署)、log、warn
|
|
71
|
+
*/
|
|
72
|
+
export function createSshManager({ stateDir, credentialsPath, log = () => {}, warn = () => {} }) {
|
|
73
|
+
const sessions = new Map();
|
|
74
|
+
const keyPath = join(stateDir, "ssh-key", "id_rsa");
|
|
75
|
+
let cache;
|
|
76
|
+
|
|
77
|
+
const loadCredentials = () => {
|
|
78
|
+
if (cache !== undefined) return cache;
|
|
79
|
+
try {
|
|
80
|
+
const raw = JSON.parse(readFileSync(credentialsPath, "utf8"));
|
|
81
|
+
cache = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
82
|
+
} catch {
|
|
83
|
+
cache = {};
|
|
84
|
+
}
|
|
85
|
+
return cache;
|
|
86
|
+
};
|
|
87
|
+
const saveCredentials = () => {
|
|
88
|
+
try {
|
|
89
|
+
mkdirSync(dirname(credentialsPath), { recursive: true });
|
|
90
|
+
writeFileSync(credentialsPath, JSON.stringify(loadCredentials(), null, 2), { mode: 0o600 });
|
|
91
|
+
} catch (error) {
|
|
92
|
+
warn(`保存 SSH 凭据失败:${error?.message ?? error}`);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const remember = (machine, patch) => {
|
|
96
|
+
if (!machine) return;
|
|
97
|
+
loadCredentials()[machine] = { ...(loadCredentials()[machine] ?? {}), ...patch };
|
|
98
|
+
saveCredentials();
|
|
99
|
+
};
|
|
100
|
+
const known = (machine) => loadCredentials()[machine] ?? undefined;
|
|
101
|
+
|
|
102
|
+
/** 读(必要时生成)本机密钥对。 */
|
|
103
|
+
const ensureKey = () => {
|
|
104
|
+
try {
|
|
105
|
+
if (existsSync(keyPath)) return { pem: readFileSync(keyPath, "utf8"), path: keyPath };
|
|
106
|
+
// 用 RSA 而不是 ed25519:ssh2 只认 OpenSSH 格式的 ed25519 私钥,
|
|
107
|
+
// 而 Node 导不出那个格式;PKCS#1 的 RSA PEM 两边都认。
|
|
108
|
+
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 3072 });
|
|
109
|
+
mkdirSync(dirname(keyPath), { recursive: true });
|
|
110
|
+
writeFileSync(keyPath, privateKey.export({ type: "pkcs1", format: "pem" }), { mode: 0o600 });
|
|
111
|
+
writeFileSync(`${keyPath}.pub`, `${publicKeyLine(publicKey)}\n`, { mode: 0o644 });
|
|
112
|
+
log(`已生成 SSH 密钥:${keyPath}`);
|
|
113
|
+
return { pem: readFileSync(keyPath, "utf8"), path: keyPath };
|
|
114
|
+
} catch (error) {
|
|
115
|
+
warn(`读/生成 SSH 密钥失败:${error?.message ?? error}`);
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const publicLine = () => {
|
|
120
|
+
try {
|
|
121
|
+
return readFileSync(`${keyPath}.pub`, "utf8").trim();
|
|
122
|
+
} catch {
|
|
123
|
+
return "";
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/** 在已建立的连接上执行一条命令,收集输出。 */
|
|
128
|
+
const exec = (client, command) =>
|
|
129
|
+
new Promise((resolve) => {
|
|
130
|
+
client.exec(command, (error, stream) => {
|
|
131
|
+
if (error) {
|
|
132
|
+
resolve({ ok: false, output: error.message });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
let output = "";
|
|
136
|
+
stream.on("data", (chunk) => (output += chunk.toString()));
|
|
137
|
+
stream.stderr.on("data", (chunk) => (output += chunk.toString()));
|
|
138
|
+
stream.on("close", (code) => resolve({ ok: code === 0 || code === undefined, output: output.trim() }));
|
|
139
|
+
});
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
/** 用"只有私钥"的新连接自测一次,确认免密可用。 */
|
|
143
|
+
const verifyKeyLogin = ({ host, port, username, pem }) =>
|
|
144
|
+
new Promise((resolve) => {
|
|
145
|
+
const probe = new (loadSsh2().Client)();
|
|
146
|
+
let settled = false;
|
|
147
|
+
const done = (ok) => {
|
|
148
|
+
if (settled) return;
|
|
149
|
+
settled = true;
|
|
150
|
+
try {
|
|
151
|
+
probe.end();
|
|
152
|
+
} catch {
|
|
153
|
+
/* 已断 */
|
|
154
|
+
}
|
|
155
|
+
resolve(ok);
|
|
156
|
+
};
|
|
157
|
+
probe.on("ready", () => done(true));
|
|
158
|
+
probe.on("error", () => done(false));
|
|
159
|
+
try {
|
|
160
|
+
probe.connect({ host, port, username, privateKey: pem, readyTimeout: 12000 });
|
|
161
|
+
} catch {
|
|
162
|
+
done(false);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
/** 把公钥追加到对端(幂等),然后自测。 */
|
|
167
|
+
const deployKey = async (client, { host, port, username, machine }) => {
|
|
168
|
+
const pub = publicLine();
|
|
169
|
+
if (!pub) return false;
|
|
170
|
+
const quoted = pub.replace(/'/g, "'\\''");
|
|
171
|
+
const command =
|
|
172
|
+
"mkdir -p ~/.ssh && chmod 700 ~/.ssh && " +
|
|
173
|
+
"touch ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys && " +
|
|
174
|
+
`grep -qF '${quoted}' ~/.ssh/authorized_keys || echo '${quoted}' >> ~/.ssh/authorized_keys`;
|
|
175
|
+
const result = await exec(client, command);
|
|
176
|
+
if (!result.ok) {
|
|
177
|
+
warn(`部署公钥失败:${result.output.slice(0, 200)}`);
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
const ok = await verifyKeyLogin({ host, port, username, pem: ensureKey()?.pem ?? "" });
|
|
181
|
+
if (!ok) {
|
|
182
|
+
warn(`公钥已写入,但密钥登录自测没通过(${username}@${host})`);
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
remember(machine, { username, hasKey: true });
|
|
186
|
+
log(`已为 ${machine || host} 部署公钥,之后免密登录`);
|
|
187
|
+
return true;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
/** 建立一个会话(给定连接参数)。 */
|
|
191
|
+
const startSession = ({ host, port, username, password, privateKey, cols, rows, machine }) =>
|
|
192
|
+
new Promise((resolve, reject) => {
|
|
193
|
+
const id = randomUUID();
|
|
194
|
+
const client = new (loadSsh2().Client)();
|
|
195
|
+
const session = { id, client, stream: undefined, ring: "", listeners: new Set(), machine: machine ?? "", closed: false };
|
|
196
|
+
let settled = false;
|
|
197
|
+
const finish = (error) => {
|
|
198
|
+
if (settled) return;
|
|
199
|
+
settled = true;
|
|
200
|
+
error ? reject(error) : resolve({ session, client });
|
|
201
|
+
};
|
|
202
|
+
const fail = (error) => {
|
|
203
|
+
session.closed = true;
|
|
204
|
+
sessions.delete(id);
|
|
205
|
+
try {
|
|
206
|
+
client.end();
|
|
207
|
+
} catch {
|
|
208
|
+
/* 已断 */
|
|
209
|
+
}
|
|
210
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
client.on("ready", () => {
|
|
214
|
+
client.shell({ term: "xterm-256color", cols, rows }, (error, stream) => {
|
|
215
|
+
if (error) {
|
|
216
|
+
fail(new Error(`开 shell 失败:${error.message}`));
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
session.stream = stream;
|
|
220
|
+
stream.on("data", (chunk) => {
|
|
221
|
+
const text = chunk.toString("utf8");
|
|
222
|
+
session.ring = (session.ring + text).slice(-RING_LIMIT);
|
|
223
|
+
for (const listener of session.listeners) {
|
|
224
|
+
try {
|
|
225
|
+
listener(text);
|
|
226
|
+
} catch {
|
|
227
|
+
/* 单个订阅者失败不影响其它 */
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
stream.on("close", () => {
|
|
232
|
+
session.closed = true;
|
|
233
|
+
sessions.delete(id);
|
|
234
|
+
for (const listener of session.listeners) {
|
|
235
|
+
try {
|
|
236
|
+
listener(null);
|
|
237
|
+
} catch {
|
|
238
|
+
/* 同上 */
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
sessions.set(id, session);
|
|
243
|
+
finish();
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
client.on("error", (error) => fail(new Error(error.message)));
|
|
247
|
+
client.on("close", () => {
|
|
248
|
+
if (session.closed) return;
|
|
249
|
+
session.closed = true;
|
|
250
|
+
sessions.delete(id);
|
|
251
|
+
for (const listener of session.listeners) {
|
|
252
|
+
try {
|
|
253
|
+
listener(null);
|
|
254
|
+
} catch {
|
|
255
|
+
/* 同上 */
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const options = {
|
|
261
|
+
host,
|
|
262
|
+
port,
|
|
263
|
+
username,
|
|
264
|
+
readyTimeout: 15000,
|
|
265
|
+
keepaliveInterval: 15000,
|
|
266
|
+
// 不做 known_hosts:对端是自己的机器,这是明确取舍(写在这里而不是假装做到)
|
|
267
|
+
};
|
|
268
|
+
if (privateKey) options.privateKey = privateKey;
|
|
269
|
+
else options.password = password;
|
|
270
|
+
|
|
271
|
+
try {
|
|
272
|
+
client.connect(options);
|
|
273
|
+
} catch (error) {
|
|
274
|
+
fail(error);
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 开一个交互式 shell:先试密钥,再试密码;密码首登成功后自动部署公钥。
|
|
280
|
+
* @returns {Promise<string>} 会话 id
|
|
281
|
+
*/
|
|
282
|
+
const open = async ({ host, port = 22, username, password = "", cols = 80, rows = 24, machine = "" }) => {
|
|
283
|
+
const key = ensureKey();
|
|
284
|
+
const saved = known(machine) ?? {};
|
|
285
|
+
// 密钥只对"当初部署它的那个用户名"有意义:换了用户名先试密钥只会换来一次
|
|
286
|
+
// 认证失败,还多等一轮。所以用户名不一致时直接走密码。
|
|
287
|
+
const keyApplies = !!key?.pem && (!saved.username || saved.username === username);
|
|
288
|
+
const attempts = [];
|
|
289
|
+
if (keyApplies) attempts.push("key");
|
|
290
|
+
if (password) attempts.push("password");
|
|
291
|
+
if (attempts.length === 0) throw new Error("没有可用凭据:请输入密码,或先部署密钥");
|
|
292
|
+
|
|
293
|
+
let lastError;
|
|
294
|
+
for (const mode of attempts) {
|
|
295
|
+
try {
|
|
296
|
+
const { session, client } = await startSession({
|
|
297
|
+
host,
|
|
298
|
+
port,
|
|
299
|
+
username,
|
|
300
|
+
cols,
|
|
301
|
+
rows,
|
|
302
|
+
machine,
|
|
303
|
+
password,
|
|
304
|
+
...(mode === "key" ? { privateKey: key.pem } : {}),
|
|
305
|
+
});
|
|
306
|
+
log(`SSH 已连接 ${username}@${host}:${port}(${session.id.slice(0, 8)},${mode === "key" ? "密钥" : "密码"})`);
|
|
307
|
+
if (mode === "password" && key?.pem && known(machine)?.hasKey !== true) {
|
|
308
|
+
// 不阻塞会话:后台部署公钥 + 自测
|
|
309
|
+
void deployKey(client, { host, port, username, machine });
|
|
310
|
+
}
|
|
311
|
+
return session.id;
|
|
312
|
+
} catch (error) {
|
|
313
|
+
lastError = error;
|
|
314
|
+
warn(`SSH ${mode === "key" ? "密钥" : "密码"}登录失败 ${username}@${host}: ${error.message}`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
throw lastError ?? new Error("连接失败");
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
const subscribe = (id, listener) => {
|
|
321
|
+
const session = sessions.get(id);
|
|
322
|
+
if (!session) return () => {};
|
|
323
|
+
session.listeners.add(listener);
|
|
324
|
+
return () => session.listeners.delete(listener);
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const write = (id, data) => {
|
|
328
|
+
const session = sessions.get(id);
|
|
329
|
+
if (!session?.stream) return false;
|
|
330
|
+
try {
|
|
331
|
+
session.stream.write(data);
|
|
332
|
+
return true;
|
|
333
|
+
} catch {
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
const resize = (id, cols, rows) => {
|
|
339
|
+
const session = sessions.get(id);
|
|
340
|
+
if (!session?.stream) return false;
|
|
341
|
+
try {
|
|
342
|
+
session.stream.setWindow(rows, cols, 0, 0);
|
|
343
|
+
return true;
|
|
344
|
+
} catch {
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
const close = (id) => {
|
|
350
|
+
const session = sessions.get(id);
|
|
351
|
+
if (!session) return;
|
|
352
|
+
sessions.delete(id);
|
|
353
|
+
session.closed = true;
|
|
354
|
+
try {
|
|
355
|
+
session.stream?.end();
|
|
356
|
+
} catch {
|
|
357
|
+
/* 已断 */
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
session.client.end();
|
|
361
|
+
} catch {
|
|
362
|
+
/* 已断 */
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
const closeAll = () => {
|
|
367
|
+
for (const id of [...sessions.keys()]) close(id);
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
const list = () => [...sessions.values()].map((s) => ({ id: s.id, machine: s.machine, alive: !!s.stream, buffered: s.ring.length }));
|
|
371
|
+
const ring = (id) => sessions.get(id)?.ring ?? "";
|
|
372
|
+
|
|
373
|
+
/** 供面板使用:已知用户名 + 是否已部署密钥。 */
|
|
374
|
+
const describe = (machine) => {
|
|
375
|
+
const saved = known(machine) ?? {};
|
|
376
|
+
return { username: saved.username ?? "", hasKey: saved.hasKey === true, keyPath };
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
return { open, subscribe, write, resize, close, closeAll, list, ring, describe, remember };
|
|
380
|
+
}
|