@nsyan/ssh 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +10 -2
- package/index.ts +573 -0
- package/package.json +62 -4
- package/skills/deploy/SKILL.md +8 -0
- package/skills/remote-ops/SKILL.md +7 -0
- package/src/core/audit.ts +74 -0
- package/src/core/config.ts +47 -0
- package/src/core/deploy.ts +107 -0
- package/src/core/doctor.ts +45 -0
- package/src/core/guard.ts +106 -0
- package/src/core/hash.ts +35 -0
- package/src/core/known-hosts.ts +87 -0
- package/src/core/policy.ts +181 -0
- package/src/core/secrets.ts +110 -0
- package/src/core/types.ts +69 -0
- package/src/core/wait.ts +29 -0
- package/src/prompt.ts +15 -0
- package/src/runtime.ts +585 -0
- package/src/scan/auto.ts +12 -0
- package/src/scan/project.ts +36 -0
- package/src/scan/save.ts +50 -0
- package/src/scan/ssh-config.ts +67 -0
- package/src/transports/ftp.ts +101 -0
- package/src/transports/openssh.ts +109 -0
- package/src/transports/ssh2.ts +534 -0
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
// transports/ssh2.ts —— 一条已认证连接上的多路 channel。最多 6 路,空闲 5 分钟关闭。
|
|
2
|
+
import { connect, createServer, type AddressInfo } from "node:net";
|
|
3
|
+
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import type { Client, ConnectConfig } from "ssh2";
|
|
8
|
+
|
|
9
|
+
const { Client: SshClient } = createRequire(import.meta.url)("ssh2") as typeof import("ssh2");
|
|
10
|
+
import { wrapSudo, wrapWithWatchdog } from "../core/guard.js";
|
|
11
|
+
import { clipUtf8, parseRemoteHash, remoteHashCommand, sha256File } from "../core/hash.js";
|
|
12
|
+
import { hostKeyFingerprint } from "../core/known-hosts.js";
|
|
13
|
+
import { AuthFailedError, HostKeyUnknownError, TransferMismatchError, type HostProfile } from "../core/types.js";
|
|
14
|
+
|
|
15
|
+
const MAX_CHANNELS = 6;
|
|
16
|
+
const IDLE_MS = 5 * 60 * 1000;
|
|
17
|
+
const KEEPALIVE_MS = 30 * 1000;
|
|
18
|
+
|
|
19
|
+
export interface ExecRequest {
|
|
20
|
+
command: string;
|
|
21
|
+
cwd?: string;
|
|
22
|
+
timeoutMs?: number;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
onData?: (chunk: string) => void;
|
|
25
|
+
maxBytes?: number;
|
|
26
|
+
/** 只给 sudo 用。写到通道后不进入命令文本。 */
|
|
27
|
+
stdin?: string;
|
|
28
|
+
sudo?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface ExecOutcome {
|
|
32
|
+
stdout: string;
|
|
33
|
+
stderr: string;
|
|
34
|
+
exitCode: number | null;
|
|
35
|
+
durationMs: number;
|
|
36
|
+
spillPath?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface TransferRequest {
|
|
40
|
+
localPath: string;
|
|
41
|
+
remotePath: string;
|
|
42
|
+
/** 覆盖前把原文件改到这里。不传就不备份。 */
|
|
43
|
+
backupPath?: string;
|
|
44
|
+
signal?: AbortSignal;
|
|
45
|
+
onProgress?: (sent: number, total: number) => void;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface TransferOutcome {
|
|
49
|
+
bytes: number;
|
|
50
|
+
sha256: string;
|
|
51
|
+
backupPath?: string;
|
|
52
|
+
backupCopied?: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface Lease {
|
|
56
|
+
release(): void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface Stored {
|
|
60
|
+
client: Client;
|
|
61
|
+
leases: number;
|
|
62
|
+
timer?: NodeJS.Timeout;
|
|
63
|
+
/** 握手阶段记下的主机密钥,供后续比对。 */
|
|
64
|
+
fingerprint: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ConnectHooks {
|
|
68
|
+
/** 返回 false 拒绝。未知主机由调用方决定记不记。 */
|
|
69
|
+
verifyHostKey?: (key: Buffer) => boolean;
|
|
70
|
+
/** 连接被远端踢掉时通知,池会丢掉它。 */
|
|
71
|
+
onLost?: () => void;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface PoolOptions {
|
|
75
|
+
idleMs?: number;
|
|
76
|
+
/** 第 5 路及以后开始排队时调用,测试用来观察上限。 */
|
|
77
|
+
onQueue?: (profileId: string, waiting: number) => void;
|
|
78
|
+
/** 测试用来替换远端 sha256 命令,制造校验失败。生产调用不传。 */
|
|
79
|
+
hashCommand?: (remotePath: string) => string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function quote(value: string): string {
|
|
83
|
+
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class Ssh2Pool {
|
|
87
|
+
private readonly connections = new Map<string, Stored>();
|
|
88
|
+
private readonly opening = new Map<string, Promise<Client>>();
|
|
89
|
+
private readonly idleMs: number;
|
|
90
|
+
private readonly onQueue?: PoolOptions["onQueue"];
|
|
91
|
+
private readonly hashCommand: (remotePath: string) => string;
|
|
92
|
+
|
|
93
|
+
constructor(options: PoolOptions | number = {}) {
|
|
94
|
+
const normalized = typeof options === "number" ? { idleMs: options } : options;
|
|
95
|
+
this.idleMs = normalized.idleMs ?? IDLE_MS;
|
|
96
|
+
this.onQueue = normalized.onQueue;
|
|
97
|
+
this.hashCommand = normalized.hashCommand ?? remoteHashCommand;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async connect(profile: HostProfile, hooks: ConnectHooks = {}): Promise<Client> {
|
|
101
|
+
const existing = this.connections.get(profile.id);
|
|
102
|
+
if (existing) return existing.client;
|
|
103
|
+
const pending = this.opening.get(profile.id);
|
|
104
|
+
if (pending) return pending;
|
|
105
|
+
const created = this.openConnection(profile, hooks);
|
|
106
|
+
this.opening.set(profile.id, created);
|
|
107
|
+
try {
|
|
108
|
+
return await created;
|
|
109
|
+
} finally {
|
|
110
|
+
if (this.opening.get(profile.id) === created) this.opening.delete(profile.id);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private async openConnection(profile: HostProfile, hooks: ConnectHooks): Promise<Client> {
|
|
115
|
+
const client = new SshClient();
|
|
116
|
+
let fingerprint = "";
|
|
117
|
+
const config: ConnectConfig = {
|
|
118
|
+
host: profile.host,
|
|
119
|
+
port: profile.port ?? 22,
|
|
120
|
+
username: profile.user,
|
|
121
|
+
readyTimeout: 20_000,
|
|
122
|
+
keepaliveInterval: KEEPALIVE_MS,
|
|
123
|
+
keepaliveCountMax: 3,
|
|
124
|
+
hostVerifier: (key: Buffer) => {
|
|
125
|
+
fingerprint = hostKeyFingerprint(key);
|
|
126
|
+
return hooks.verifyHostKey ? hooks.verifyHostKey(key) : true;
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
if (profile.auth.kind === "agent") {
|
|
130
|
+
if (!process.env.SSH_AUTH_SOCK) throw new AuthFailedError("没有 SSH_AUTH_SOCK,agent 认证不可用。");
|
|
131
|
+
config.agent = process.env.SSH_AUTH_SOCK;
|
|
132
|
+
} else if (profile.auth.kind === "key" && profile.auth.privateKeyPath) {
|
|
133
|
+
config.privateKey = readFileSync(profile.auth.privateKeyPath);
|
|
134
|
+
if (profile.auth.passphrase) config.passphrase = profile.auth.passphrase;
|
|
135
|
+
} else if (profile.auth.kind === "password") {
|
|
136
|
+
const secret = profile.auth.password ?? profile.auth.secretRef;
|
|
137
|
+
if (!secret || secret.startsWith("file:") || secret.startsWith("keychain:")) {
|
|
138
|
+
throw new AuthFailedError("没有可用的密码。");
|
|
139
|
+
}
|
|
140
|
+
config.password = secret;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
await new Promise<void>((resolve, reject) => {
|
|
144
|
+
client.once("ready", () => resolve());
|
|
145
|
+
client.once("error", (error: Error) => reject(error));
|
|
146
|
+
client.connect(config);
|
|
147
|
+
}).catch((error: Error) => {
|
|
148
|
+
client.end();
|
|
149
|
+
throw error;
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
const stored: Stored = { client, leases: 0, fingerprint };
|
|
153
|
+
client.on("close", () => {
|
|
154
|
+
if (this.connections.get(profile.id)?.client === client) {
|
|
155
|
+
this.connections.delete(profile.id);
|
|
156
|
+
hooks.onLost?.();
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
this.connections.set(profile.id, stored);
|
|
160
|
+
this.arm(profile.id);
|
|
161
|
+
return client;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 取一条已连接的客户端。没有就抛 HostKeyUnknownError,调用方先 connect。 */
|
|
165
|
+
require(profileId: string): Client {
|
|
166
|
+
const stored = this.connections.get(profileId);
|
|
167
|
+
if (!stored) throw new HostKeyUnknownError(`主机 ${profileId} 还没有连接`);
|
|
168
|
+
return stored.client;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** 占一个 channel 名额。满 4 个就等。 */
|
|
172
|
+
async acquire(profileId: string): Promise<Lease> {
|
|
173
|
+
const stored = this.connections.get(profileId);
|
|
174
|
+
if (!stored) throw new HostKeyUnknownError(`主机 ${profileId} 还没有连接`);
|
|
175
|
+
if (stored.leases >= MAX_CHANNELS) this.onQueue?.(profileId, stored.leases - MAX_CHANNELS + 1);
|
|
176
|
+
while (stored.leases >= MAX_CHANNELS) {
|
|
177
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
178
|
+
if (!this.connections.has(profileId)) throw new HostKeyUnknownError(`主机 ${profileId} 的连接已断开`);
|
|
179
|
+
}
|
|
180
|
+
if (!this.connections.has(profileId)) throw new HostKeyUnknownError(`主机 ${profileId} 的连接已断开`);
|
|
181
|
+
stored.leases += 1;
|
|
182
|
+
if (stored.timer) clearTimeout(stored.timer);
|
|
183
|
+
let released = false;
|
|
184
|
+
return {
|
|
185
|
+
release: () => {
|
|
186
|
+
if (released) return;
|
|
187
|
+
released = true;
|
|
188
|
+
stored.leases = Math.max(0, stored.leases - 1);
|
|
189
|
+
if (stored.leases === 0) this.arm(profileId);
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async exec(profileId: string, request: ExecRequest): Promise<ExecOutcome> {
|
|
195
|
+
const client = this.require(profileId);
|
|
196
|
+
const lease = await this.acquire(profileId);
|
|
197
|
+
const started = Date.now();
|
|
198
|
+
const remote = request.cwd
|
|
199
|
+
? `cd ${quote(request.cwd)} && ${request.command}`
|
|
200
|
+
: request.command;
|
|
201
|
+
const command = request.sudo ? wrapSudo(remote) : wrapWithWatchdog(remote);
|
|
202
|
+
try {
|
|
203
|
+
return await this.run(client, command, request, started);
|
|
204
|
+
} finally {
|
|
205
|
+
lease.release();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async put(profileId: string, request: TransferRequest): Promise<TransferOutcome> {
|
|
210
|
+
const local = await sha256File(request.localPath);
|
|
211
|
+
const part = `${request.remotePath}.part`;
|
|
212
|
+
const upload = await this.acquire(profileId);
|
|
213
|
+
try {
|
|
214
|
+
await this.fastPut(this.require(profileId), { ...request, remotePath: part });
|
|
215
|
+
} finally {
|
|
216
|
+
upload.release();
|
|
217
|
+
}
|
|
218
|
+
const checked = await this.execLeased(profileId, this.hashCommand(part));
|
|
219
|
+
if (checked.exitCode !== 0 || !checked.stdout.trim()) {
|
|
220
|
+
throw new TransferMismatchError(`远端校验失败:${checked.stderr || checked.stdout || "没有输出"}。${part} 保留,原文件未动`);
|
|
221
|
+
}
|
|
222
|
+
const remote = parseRemoteHash(checked.stdout);
|
|
223
|
+
if (remote !== local.hash) {
|
|
224
|
+
throw new TransferMismatchError(
|
|
225
|
+
`sha256 不一致:本地 ${local.hash},远端 ${remote}。原文件未动,${part} 保留`,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
const saved = await this.backup(profileId, request);
|
|
229
|
+
await this.execLeased(profileId, `mv ${quote(part)} ${quote(request.remotePath)}`);
|
|
230
|
+
return { bytes: local.bytes, sha256: local.hash, backupPath: saved.path, backupCopied: saved.copied };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async list(profileId: string, remotePath: string): Promise<Array<{ name: string; size: number; directory: boolean }>> {
|
|
234
|
+
const client = this.require(profileId);
|
|
235
|
+
const lease = await this.acquire(profileId);
|
|
236
|
+
try {
|
|
237
|
+
return await new Promise((resolve, reject) => {
|
|
238
|
+
client.sftp((error, sftp) => {
|
|
239
|
+
if (error) return reject(error);
|
|
240
|
+
sftp.readdir(remotePath, (listError, entries) => {
|
|
241
|
+
sftp.end();
|
|
242
|
+
if (listError) return reject(listError);
|
|
243
|
+
resolve(entries.map((entry) => ({
|
|
244
|
+
name: entry.filename,
|
|
245
|
+
size: entry.attrs.size,
|
|
246
|
+
directory: (entry.attrs.mode & 0o170000) === 0o040000,
|
|
247
|
+
})));
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
} finally {
|
|
252
|
+
lease.release();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async read(profileId: string, remotePath: string, offset = 1, limit = 200): Promise<string> {
|
|
257
|
+
const client = this.require(profileId);
|
|
258
|
+
const lease = await this.acquire(profileId);
|
|
259
|
+
try {
|
|
260
|
+
return await new Promise<string>((resolve, reject) => {
|
|
261
|
+
client.sftp((error, sftp) => {
|
|
262
|
+
if (error) return reject(error);
|
|
263
|
+
const picked: string[] = [];
|
|
264
|
+
let seen = 0;
|
|
265
|
+
let bytes = 0;
|
|
266
|
+
let pending = "";
|
|
267
|
+
const start = Math.max(1, offset);
|
|
268
|
+
const maxBytes = 512 * 1024;
|
|
269
|
+
const stream = sftp.createReadStream(remotePath);
|
|
270
|
+
let finished = false;
|
|
271
|
+
const finish = () => {
|
|
272
|
+
if (finished) return;
|
|
273
|
+
finished = true;
|
|
274
|
+
if (pending !== "" && seen + 1 >= start && picked.length < limit && bytes < maxBytes) {
|
|
275
|
+
picked.push(clipUtf8(pending, maxBytes - bytes));
|
|
276
|
+
}
|
|
277
|
+
sftp.end();
|
|
278
|
+
resolve(picked.join("\n"));
|
|
279
|
+
};
|
|
280
|
+
stream.on("data", (chunk: Buffer) => {
|
|
281
|
+
const parts = (pending + chunk.toString("utf8")).split(/\n/);
|
|
282
|
+
pending = parts.pop() ?? "";
|
|
283
|
+
for (const line of parts) {
|
|
284
|
+
seen += 1;
|
|
285
|
+
if (seen < start || picked.length >= limit) continue;
|
|
286
|
+
const room = maxBytes - bytes;
|
|
287
|
+
if (room <= 0) {
|
|
288
|
+
stream.destroy();
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
const clipped = clipUtf8(line, room);
|
|
292
|
+
picked.push(clipped);
|
|
293
|
+
bytes += Buffer.byteLength(clipped) + 1;
|
|
294
|
+
if (clipped !== line || bytes >= maxBytes) stream.destroy();
|
|
295
|
+
}
|
|
296
|
+
if (picked.length >= limit) stream.destroy();
|
|
297
|
+
});
|
|
298
|
+
stream.on("error", (readError: Error) => {
|
|
299
|
+
if (picked.length > 0 || seen > 0) finish();
|
|
300
|
+
else reject(readError);
|
|
301
|
+
});
|
|
302
|
+
stream.on("close", finish);
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
} finally {
|
|
306
|
+
lease.release();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async get(profileId: string, request: TransferRequest): Promise<TransferOutcome> {
|
|
311
|
+
const client = this.require(profileId);
|
|
312
|
+
const lease = await this.acquire(profileId);
|
|
313
|
+
try {
|
|
314
|
+
await new Promise<void>((resolve, reject) => {
|
|
315
|
+
client.sftp((error, sftp) => {
|
|
316
|
+
if (error) return reject(error);
|
|
317
|
+
sftp.fastGet(request.remotePath, request.localPath, (getError) => {
|
|
318
|
+
sftp.end();
|
|
319
|
+
if (getError) reject(getError);
|
|
320
|
+
else resolve();
|
|
321
|
+
});
|
|
322
|
+
});
|
|
323
|
+
});
|
|
324
|
+
const local = await sha256File(request.localPath);
|
|
325
|
+
const checked = await this.execRaw(client, { command: this.hashCommand(request.remotePath), timeoutMs: 120_000 });
|
|
326
|
+
const remote = parseRemoteHash(checked.stdout);
|
|
327
|
+
if (checked.exitCode !== 0 || remote !== local.hash) {
|
|
328
|
+
throw new TransferMismatchError(`下载后 sha256 不一致:本地 ${local.hash},远端 ${remote ?? "无"}`);
|
|
329
|
+
}
|
|
330
|
+
return { bytes: local.bytes, sha256: local.hash };
|
|
331
|
+
} finally {
|
|
332
|
+
lease.release();
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async tunnel(profileId: string, listenPort: number, destHost: string, destPort: number): Promise<{ port: number; close: () => Promise<void> }> {
|
|
337
|
+
const client = this.require(profileId);
|
|
338
|
+
const lease = await this.acquire(profileId);
|
|
339
|
+
const server = createServer((socket) => {
|
|
340
|
+
client.forwardOut("127.0.0.1", socket.localPort ?? 0, destHost, destPort, (error, stream) => {
|
|
341
|
+
if (error || !stream) {
|
|
342
|
+
socket.end();
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
socket.pipe(stream);
|
|
346
|
+
stream.pipe(socket);
|
|
347
|
+
});
|
|
348
|
+
});
|
|
349
|
+
try {
|
|
350
|
+
await new Promise<void>((resolve, reject) => {
|
|
351
|
+
server.once("error", reject);
|
|
352
|
+
server.listen(listenPort, "127.0.0.1", () => resolve());
|
|
353
|
+
});
|
|
354
|
+
} catch (error) {
|
|
355
|
+
lease.release();
|
|
356
|
+
throw error;
|
|
357
|
+
}
|
|
358
|
+
const address = server.address() as AddressInfo;
|
|
359
|
+
return {
|
|
360
|
+
port: address.port,
|
|
361
|
+
close: () => new Promise((resolve) => {
|
|
362
|
+
lease.release();
|
|
363
|
+
server.close(() => resolve());
|
|
364
|
+
}),
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async tunnelRemote(profileId: string, listenPort: number, destHost: string, destPort: number): Promise<{ port: number; close: () => Promise<void> }> {
|
|
369
|
+
const client = this.require(profileId);
|
|
370
|
+
const lease = await this.acquire(profileId);
|
|
371
|
+
try {
|
|
372
|
+
await new Promise<void>((resolve, reject) => {
|
|
373
|
+
client.forwardIn("127.0.0.1", listenPort, (error?: Error) => (error ? reject(error) : resolve()));
|
|
374
|
+
});
|
|
375
|
+
} catch (error) {
|
|
376
|
+
lease.release();
|
|
377
|
+
throw error;
|
|
378
|
+
}
|
|
379
|
+
const onConnection = (info: { destPort: number }, accept: () => NodeJS.ReadWriteStream) => {
|
|
380
|
+
const channel = accept();
|
|
381
|
+
if (info.destPort !== listenPort) {
|
|
382
|
+
channel.end();
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
const socket = connect(destPort, destHost);
|
|
386
|
+
channel.pipe(socket);
|
|
387
|
+
socket.pipe(channel);
|
|
388
|
+
};
|
|
389
|
+
(client as unknown as { on(event: string, listener: typeof onConnection): void }).on("tcp connection", onConnection);
|
|
390
|
+
return {
|
|
391
|
+
port: listenPort,
|
|
392
|
+
close: () => new Promise((resolve) => {
|
|
393
|
+
(client as unknown as { removeListener(event: string, listener: typeof onConnection): void }).removeListener("tcp connection", onConnection);
|
|
394
|
+
client.unforwardIn("127.0.0.1", listenPort, () => {
|
|
395
|
+
lease.release();
|
|
396
|
+
resolve();
|
|
397
|
+
});
|
|
398
|
+
}),
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
discard(profileId: string): void {
|
|
403
|
+
const stored = this.connections.get(profileId);
|
|
404
|
+
this.connections.delete(profileId);
|
|
405
|
+
if (!stored) return;
|
|
406
|
+
if (stored.timer) clearTimeout(stored.timer);
|
|
407
|
+
stored.client.end();
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
async close(profileId?: string): Promise<void> {
|
|
411
|
+
const ids = profileId ? [profileId] : [...this.connections.keys()];
|
|
412
|
+
for (const id of ids) {
|
|
413
|
+
const stored = this.connections.get(id);
|
|
414
|
+
if (!stored) continue;
|
|
415
|
+
if (stored.timer) clearTimeout(stored.timer);
|
|
416
|
+
stored.client.end();
|
|
417
|
+
this.connections.delete(id);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
private arm(profileId: string): void {
|
|
422
|
+
const stored = this.connections.get(profileId);
|
|
423
|
+
if (!stored) return;
|
|
424
|
+
if (stored.timer) clearTimeout(stored.timer);
|
|
425
|
+
stored.timer = setTimeout(() => {
|
|
426
|
+
if (stored.leases === 0) void this.close(profileId);
|
|
427
|
+
}, this.idleMs);
|
|
428
|
+
stored.timer.unref?.();
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
private run(client: Client, command: string, request: ExecRequest, started: number): Promise<ExecOutcome> {
|
|
432
|
+
return new Promise((resolve, reject) => {
|
|
433
|
+
client.exec(command, (error, channel) => {
|
|
434
|
+
if (error || !channel) return reject(error ?? new Error("exec channel missing"));
|
|
435
|
+
if (request.stdin !== undefined) channel.write(`${request.stdin}\n`);
|
|
436
|
+
let stdout = "";
|
|
437
|
+
let stderr = "";
|
|
438
|
+
let spillPath: string | undefined;
|
|
439
|
+
let finished = false;
|
|
440
|
+
const absorb = (which: "out" | "err", chunk: string) => {
|
|
441
|
+
const lines = stdout.split("\n").length + stderr.split("\n").length;
|
|
442
|
+
if (spillPath || stdout.length + stderr.length + chunk.length > 50_000 || lines > 2000) {
|
|
443
|
+
if (!spillPath) {
|
|
444
|
+
spillPath = join(tmpdir(), `pi-ssh-${process.pid}-${Date.now()}.log`);
|
|
445
|
+
mkdirSync(tmpdir(), { recursive: true });
|
|
446
|
+
writeFileSync(spillPath, stdout + stderr);
|
|
447
|
+
}
|
|
448
|
+
appendFileSync(spillPath, chunk);
|
|
449
|
+
}
|
|
450
|
+
if (which === "out") stdout = (stdout + chunk).slice(-50_000);
|
|
451
|
+
else stderr = (stderr + chunk).slice(-50_000);
|
|
452
|
+
};
|
|
453
|
+
const finish = (outcome: ExecOutcome) => {
|
|
454
|
+
if (finished) return;
|
|
455
|
+
finished = true;
|
|
456
|
+
clearTimeout(timer);
|
|
457
|
+
request.signal?.removeEventListener("abort", abort);
|
|
458
|
+
resolve({ ...outcome, spillPath });
|
|
459
|
+
};
|
|
460
|
+
const abort = () => {
|
|
461
|
+
channel.close();
|
|
462
|
+
finish({ stdout, stderr, exitCode: null, durationMs: Date.now() - started });
|
|
463
|
+
};
|
|
464
|
+
const timeoutMs = request.timeoutMs ?? 120_000;
|
|
465
|
+
const timer = setTimeout(() => {
|
|
466
|
+
channel.close();
|
|
467
|
+
finish({ stdout, stderr, exitCode: null, durationMs: Date.now() - started });
|
|
468
|
+
}, timeoutMs);
|
|
469
|
+
request.signal?.addEventListener("abort", abort, { once: true });
|
|
470
|
+
channel.on("data", (chunk: Buffer) => {
|
|
471
|
+
const text = chunk.toString("utf8");
|
|
472
|
+
absorb("out", text);
|
|
473
|
+
request.onData?.(text);
|
|
474
|
+
});
|
|
475
|
+
channel.stderr.on("data", (chunk: Buffer) => {
|
|
476
|
+
absorb("err", chunk.toString("utf8"));
|
|
477
|
+
});
|
|
478
|
+
channel.on("close", (code: number | null) => {
|
|
479
|
+
finish({ stdout, stderr, exitCode: code, durationMs: Date.now() - started });
|
|
480
|
+
});
|
|
481
|
+
});
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
private execRaw(client: Client, request: ExecRequest): Promise<ExecOutcome> {
|
|
486
|
+
return this.run(client, request.command, request, Date.now());
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
private fastPut(client: Client, request: TransferRequest): Promise<void> {
|
|
490
|
+
return new Promise((resolve, reject) => {
|
|
491
|
+
client.sftp((error, sftp) => {
|
|
492
|
+
if (error) return reject(error);
|
|
493
|
+
sftp.fastPut(request.localPath, request.remotePath, {
|
|
494
|
+
step: (sent: number, _chunk: number, total: number) => request.onProgress?.(sent, total),
|
|
495
|
+
}, (putError) => {
|
|
496
|
+
sftp.end();
|
|
497
|
+
if (putError) reject(putError);
|
|
498
|
+
else resolve();
|
|
499
|
+
});
|
|
500
|
+
});
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
private async execLeased(profileId: string, command: string): Promise<ExecOutcome> {
|
|
505
|
+
const client = this.require(profileId);
|
|
506
|
+
const lease = await this.acquire(profileId);
|
|
507
|
+
try {
|
|
508
|
+
return await this.execRaw(client, { command, timeoutMs: 120_000 });
|
|
509
|
+
} finally {
|
|
510
|
+
lease.release();
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
private async backup(profileId: string, request: TransferRequest): Promise<{ path?: string; copied: boolean }> {
|
|
515
|
+
if (!request.backupPath) return { copied: false };
|
|
516
|
+
const exists = await this.remoteExists(profileId, request.remotePath);
|
|
517
|
+
if (!exists) return { copied: false };
|
|
518
|
+
const source = quote(request.remotePath);
|
|
519
|
+
const dest = quote(request.backupPath);
|
|
520
|
+
const moved = await this.execLeased(profileId, `mv ${source} ${dest}`);
|
|
521
|
+
if (moved.exitCode === 0) return { path: request.backupPath, copied: false };
|
|
522
|
+
const copied = await this.execLeased(profileId, `cp -p ${source} ${dest} && rm -f ${source}`);
|
|
523
|
+
if (copied.exitCode !== 0) {
|
|
524
|
+
throw new TransferMismatchError(`备份失败:${moved.stderr || copied.stderr || "mv 与 cp 都失败"}`);
|
|
525
|
+
}
|
|
526
|
+
return { path: request.backupPath, copied: true };
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
private async remoteExists(profileId: string, remotePath: string): Promise<boolean> {
|
|
530
|
+
const result = await this.execLeased(profileId, `if [ -e ${quote(remotePath)} ]; then echo yes; fi`);
|
|
531
|
+
return result.stdout.trim() === "yes";
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|