@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/src/runtime.ts ADDED
@@ -0,0 +1,585 @@
1
+ // runtime.ts —— 工具背后的执行。选主机、确认、审计,然后交给连接池。
2
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { appendAudit, defaultAuditPath } from "./core/audit.js";
6
+ import { backupLocation, checkReleaseId, healthLoopCommand, planRelease, rejectArchiveMembers, releaseIdNow, staleBackups } from "./core/deploy.js";
7
+ import { waitCommand, type WaitFor } from "./core/wait.js";
8
+ import { loadHosts } from "./core/config.js";
9
+ import { shellQuote } from "./core/guard.js";
10
+ import { getSecret, platformKeychain } from "./core/secrets.js";
11
+ import { appendKnownHost, checkHostKey, hostKeyFingerprint } from "./core/known-hosts.js";
12
+ import { classify, decide, isProdHost, type Policy } from "./core/policy.js";
13
+ import {
14
+ BoundsError,
15
+ ConfirmRejectedError,
16
+ HostKeyChangedError,
17
+ HostKeyUnknownError,
18
+ PolicyDeniedError,
19
+ UnsupportedError,
20
+ type HostFile,
21
+ type HostProfile,
22
+ } from "./core/types.js";
23
+ import { Ssh2Pool, type ConnectHooks } from "./transports/ssh2.js";
24
+ import { chooseTransport } from "./scan/auto.js";
25
+ import { copyOpenSsh, execOpenSsh, putOpenSsh } from "./transports/openssh.js";
26
+ import { ftpExecRejected, ftpExists, ftpGet, ftpList, ftpPut } from "./transports/ftp.js";
27
+
28
+ const OUTPUT_LIMIT = 50_000;
29
+
30
+ export interface ConfirmUi {
31
+ confirm(title: string, message: string): Promise<boolean>;
32
+ secret?(title: string, prompt: string): Promise<string | undefined>;
33
+ }
34
+
35
+ export interface RuntimeOptions {
36
+ pool?: Ssh2Pool;
37
+ hosts?: () => HostFile;
38
+ auditPath?: string;
39
+ knownHostsPath?: string;
40
+ }
41
+
42
+ export function selectHost(file: HostFile, name?: string, allowActive = false): HostProfile {
43
+ const names = Object.keys(file.hosts);
44
+ if (name) {
45
+ const found = file.hosts[name];
46
+ if (!found) throw new PolicyDeniedError(`没有名为 ${name} 的主机。已有:${names.join("、") || "无"}`);
47
+ return found;
48
+ }
49
+ if (names.length === 1) return file.hosts[names[0]];
50
+ if (allowActive && file.activeHost && file.hosts[file.activeHost]) return file.hosts[file.activeHost];
51
+ if (names.length === 0) throw new PolicyDeniedError("还没有主机。先用 /ssh add 添加。");
52
+ throw new PolicyDeniedError(`已配置 ${names.length} 台主机,调用必须传 host:${names.join("、")}`);
53
+ }
54
+
55
+ function policyOf(file: HostFile): Policy {
56
+ return {
57
+ readonly: file.policy?.readonly === true,
58
+ confirm: file.policy?.confirm ?? "destructive",
59
+ };
60
+ }
61
+
62
+ function withPassword(profile: HostProfile): HostProfile {
63
+ const ref = profile.auth.secretRef;
64
+ let next = profile;
65
+ if (profile.auth.kind === "password" && ref?.startsWith("file:")) {
66
+ const [file, name] = ref.slice("file:".length).split("#");
67
+ next = { ...next, auth: { ...next.auth, password: getSecret(file, name) } };
68
+ }
69
+ return next;
70
+ }
71
+
72
+ function keyType(blob: Buffer): string {
73
+ if (blob.length < 4) return "unknown";
74
+ const length = blob.readUInt32BE(0);
75
+ return blob.subarray(4, 4 + length).toString("utf8");
76
+ }
77
+
78
+ function tail(text: string, spillPath?: string): { text: string; truncated: boolean; spillPath?: string } {
79
+ const lines = text.split("\n");
80
+ if (!spillPath && text.length <= OUTPUT_LIMIT && lines.length <= 2000) return { text, truncated: false };
81
+ const path = spillPath ?? join(tmpdir(), `pi-ssh-${Date.now()}.log`);
82
+ if (!spillPath) {
83
+ mkdirSync(tmpdir(), { recursive: true });
84
+ writeFileSync(path, text);
85
+ }
86
+ const clipped = lines.slice(-2000).join("\n").slice(-OUTPUT_LIMIT);
87
+ return {
88
+ text: `${clipped}\n\n[输出已截断,全文在 ${path}]`,
89
+ truncated: true,
90
+ spillPath: path,
91
+ };
92
+ }
93
+
94
+ function boundedTimeoutMs(requested: number | undefined, fallback: number | undefined): number {
95
+ const seconds = requested ?? fallback ?? 120;
96
+ if (!Number.isFinite(seconds) || seconds <= 0) return 120_000;
97
+ return Math.min(3600, Math.floor(seconds)) * 1000;
98
+ }
99
+
100
+ export function createRuntime(options: RuntimeOptions = {}) {
101
+ const pool = options.pool ?? new Ssh2Pool();
102
+ const hosts = options.hosts ?? loadHosts;
103
+ const auditPath = options.auditPath ?? defaultAuditPath();
104
+ const tunnels: Array<{ close: () => Promise<void> }> = [];
105
+ const grants = new Map<string, number>();
106
+
107
+ async function resolveProfile(profile: HostProfile): Promise<HostProfile> {
108
+ const ready = withPassword(profile);
109
+ const auth = ready.auth;
110
+ if (auth.passphraseRef?.startsWith("keychain:")) {
111
+ const passphrase = await platformKeychain().get("pi-ssh", auth.passphraseRef.slice("keychain:".length));
112
+ ready.auth = { ...ready.auth, passphrase };
113
+ } else if (auth.passphraseRef?.startsWith("file:")) {
114
+ const [file, name] = auth.passphraseRef.slice("file:".length).split("#");
115
+ ready.auth = { ...ready.auth, passphrase: getSecret(file, name) };
116
+ }
117
+ if (!auth.secretRef?.startsWith("keychain:")) return ready;
118
+ const account = auth.secretRef.slice("keychain:".length);
119
+ const secret = await platformKeychain().get("pi-ssh", account);
120
+ return { ...ready, auth: { ...ready.auth, password: secret } };
121
+ }
122
+
123
+ async function connect(profile: HostProfile, acceptNewHostKey = false): Promise<{ fingerprint: string; keyType: string; auth: string }> {
124
+ const ready = await resolveProfile(profile);
125
+ const knownFile = options.knownHostsPath ?? join(process.env.HOME ?? "", ".ssh", "known_hosts");
126
+ let keyError: Error | undefined;
127
+ const identity = { fingerprint: "", keyType: "", auth: ready.auth.kind };
128
+ const hooks: ConnectHooks = {
129
+ verifyHostKey: (key) => {
130
+ const type = keyType(key);
131
+ const encoded = key.toString("base64");
132
+ identity.fingerprint = hostKeyFingerprint(key);
133
+ identity.keyType = type;
134
+ if (ready.strictHostKey === false) return true;
135
+ const status = checkHostKey(knownFile, ready.host, ready.port ?? 22, type, encoded);
136
+ if (status === "match") return true;
137
+ if (status === "unknown" && acceptNewHostKey) {
138
+ appendKnownHost(knownFile, ready.host, ready.port ?? 22, type, encoded);
139
+ return true;
140
+ }
141
+ keyError = status === "changed" || status === "revoked"
142
+ ? new HostKeyChangedError(`主机密钥已变化或被吊销(${identity.fingerprint})。确认后用 ssh-keygen -R 删除旧记录。`)
143
+ : new HostKeyUnknownError(`主机密钥不在 known_hosts(${identity.fingerprint})。先用 ssh_hosts 的 test 并带 acceptNewHostKey 核对指纹。`);
144
+ return false;
145
+ },
146
+ };
147
+ await pool.connect(ready, hooks).catch((error: Error) => {
148
+ throw keyError ?? error;
149
+ });
150
+ return identity;
151
+ }
152
+
153
+ function requireReason(host: HostProfile, danger: string, reason?: string): void {
154
+ if (isProdHost(host) && danger === "destructive" && !reason?.trim()) {
155
+ throw new PolicyDeniedError("生产主机的破坏性操作必须填写 reason,说明动机和影响范围。");
156
+ }
157
+ }
158
+
159
+ async function remoteLines(profileId: string, command: string, signal?: AbortSignal): Promise<string[]> {
160
+ const listed = await pool.exec(profileId, { command, timeoutMs: 120_000, signal });
161
+ return listed.stdout.split(/\n/).map((item) => item.trim()).filter(Boolean);
162
+ }
163
+
164
+ async function checked(profileId: string, command: string, signal?: AbortSignal) {
165
+ const result = await pool.exec(profileId, { command, timeoutMs: 120_000, signal });
166
+ if (result.exitCode !== 0) {
167
+ throw new PolicyDeniedError(`远端命令失败(退出码 ${result.exitCode}):${result.stderr || result.stdout || command}`);
168
+ }
169
+ return result;
170
+ }
171
+
172
+ async function pruneBackups(profileId: string, backupPath: string): Promise<void> {
173
+ const slash = backupPath.lastIndexOf("/");
174
+ if (slash < 0) return;
175
+ const dir = backupPath.slice(0, slash);
176
+ const name = backupPath.slice(slash + 1);
177
+ const stamp = name.lastIndexOf(".");
178
+ const stem = stamp > 0 ? name.slice(0, stamp) : name;
179
+ const names = await remoteLines(profileId, `ls -1 ${shellQuote(dir)} 2>/dev/null || true`);
180
+ for (const old of staleBackups(names, stem)) {
181
+ await checked(profileId, `rm -f ${shellQuote(`${dir}/${old}`)}`);
182
+ }
183
+ }
184
+
185
+ function concrete(profile: HostProfile): HostProfile {
186
+ if (profile.transport !== "auto") return profile;
187
+ let text = "";
188
+ try {
189
+ text = readFileSync(join(homedir(), ".ssh", "config"), "utf8");
190
+ } catch {
191
+ text = "";
192
+ }
193
+ return { ...profile, transport: chooseTransport(profile, text) };
194
+ }
195
+
196
+ async function ask(ui: ConfirmUi | undefined, title: string, message: string): Promise<void> {
197
+ if (!ui) throw new PolicyDeniedError("这次操作需要确认,但当前没有界面。");
198
+ const accepted = await ui.confirm(title, message);
199
+ if (!accepted) throw new ConfirmRejectedError("用户拒绝了这次操作,停止,不要换一种写法重试。");
200
+ }
201
+
202
+ return {
203
+ pool,
204
+ async closeTunnels() {
205
+ const open = tunnels.splice(0);
206
+ grants.clear();
207
+ await Promise.all(open.map((item) => item.close()));
208
+ await pool.close();
209
+ },
210
+ grantWrite(hostName: string, minutes: number) {
211
+ const host = selectHost(hosts(), hostName);
212
+ if (isProdHost(host)) throw new PolicyDeniedError("生产主机不能授予会话级写授权。");
213
+ grants.set(host.id, Date.now() + minutes * 60_000);
214
+ },
215
+ async testHost(input: { host?: string; acceptNewHostKey?: boolean }) {
216
+ const host = concrete(selectHost(hosts(), input.host));
217
+ const started = Date.now();
218
+ const identity = await connect(host, input.acceptNewHostKey === true);
219
+ const result = await pool.exec(host.id, { command: "echo ok" });
220
+ return {
221
+ ok: result.exitCode === 0,
222
+ auth: identity.auth,
223
+ fingerprint: identity.fingerprint,
224
+ keyType: identity.keyType,
225
+ latencyMs: Date.now() - started,
226
+ transport: host.transport,
227
+ };
228
+ },
229
+ async exec(input: { host?: string; command: string; cwd?: string; timeoutSec?: number; signal?: AbortSignal; reason?: string; waitFor?: WaitFor; onData?: (chunk: string) => void; allowActive?: boolean; ui?: ConfirmUi }) {
230
+ const file = hosts();
231
+ const host = concrete(selectHost(file, input.host, input.allowActive === true));
232
+ const verdict = classify(input.command);
233
+ requireReason(host, verdict.danger, input.reason);
234
+ const grant = grants.get(host.id);
235
+ const decision = decide(verdict, policyOf(file), host, grant ? { hostId: host.id, untilMs: grant } : null);
236
+ if (decision === "deny") throw new PolicyDeniedError(`只读模式拒绝这条${verdict.danger === "destructive" ? "破坏性" : "写"}命令:${verdict.summary}`);
237
+ if (host.transport === "ftp" || host.transport === "ftps") ftpExecRejected();
238
+ if (decision === "confirm") await ask(input.ui, `${host.name}:${verdict.summary}`, input.command);
239
+ if (isProdHost(host) && verdict.danger === "destructive") {
240
+ appendAudit(auditPath, {
241
+ host: host.name,
242
+ tool: "ssh_exec",
243
+ danger: verdict.danger,
244
+ summary: verdict.summary,
245
+ command: input.command,
246
+ reason: input.reason,
247
+ confirmed: decision === "confirm",
248
+ }, { required: true });
249
+ }
250
+ const command = input.waitFor ? `${input.command} && ${waitCommand(input.waitFor)}` : input.command;
251
+ const request = {
252
+ command,
253
+ cwd: input.cwd,
254
+ timeoutMs: boundedTimeoutMs(input.timeoutSec, host.defaults?.timeoutSec),
255
+ signal: input.signal,
256
+ onData: input.onData,
257
+ };
258
+ let result;
259
+ if (host.transport === "openssh") {
260
+ result = await execOpenSsh(host, request);
261
+ } else {
262
+ try {
263
+ await connect(host);
264
+ } catch (error) {
265
+ const message = error instanceof Error ? error.message : String(error);
266
+ if (!/Not connected|ECONNRESET|EPIPE|closed/i.test(message)) throw error;
267
+ pool.discard(host.id);
268
+ await connect(host);
269
+ }
270
+ result = await pool.exec(host.id, request);
271
+ }
272
+ const spill = result && typeof result === "object" && "spillPath" in result && typeof result.spillPath === "string"
273
+ ? result.spillPath
274
+ : undefined;
275
+ const output = tail(`${result.stdout}${result.stderr ? `\n${result.stderr}` : ""}`, spill);
276
+ appendAudit(auditPath, {
277
+ host: host.name,
278
+ tool: "ssh_exec",
279
+ danger: verdict.danger,
280
+ summary: verdict.summary,
281
+ command: input.command,
282
+ reason: input.reason,
283
+ confirmed: decision === "confirm",
284
+ exitCode: result.exitCode,
285
+ durationMs: result.durationMs,
286
+ });
287
+ return { ...result, text: output.text, truncated: output.truncated };
288
+ },
289
+ async sudo(input: { host?: string; command: string; reason?: string; ui?: ConfirmUi }) {
290
+ const file = hosts();
291
+ const host = concrete(selectHost(file, input.host));
292
+ if (policyOf(file).readonly) throw new PolicyDeniedError("只读模式拒绝 sudo。");
293
+ if (host.transport === "openssh") throw new PolicyDeniedError("sudo 目前只走 ssh2 连接。");
294
+ const verdict = classify(input.command);
295
+ requireReason(host, verdict.danger, input.reason);
296
+ await ask(input.ui, `${host.name}:sudo ${verdict.summary}`, input.command);
297
+ const password = await input.ui?.secret?.(`${host.name} 的 sudo 密码`, "密码不进入对话记录");
298
+ if (!password) throw new ConfirmRejectedError("没有拿到 sudo 密码,已停止。");
299
+ appendAudit(auditPath, {
300
+ host: host.name,
301
+ tool: "ssh_sudo",
302
+ danger: verdict.danger,
303
+ summary: verdict.summary,
304
+ command: input.command,
305
+ stdin: password,
306
+ confirmed: true,
307
+ }, { required: isProdHost(host) && verdict.danger === "destructive" });
308
+ await connect(host);
309
+ const result = await pool.exec(host.id, {
310
+ command: input.command,
311
+ sudo: true,
312
+ stdin: password,
313
+ timeoutMs: boundedTimeoutMs(undefined, host.defaults?.timeoutSec),
314
+ });
315
+ const output = tail(`${result.stdout}${result.stderr ? `\n${result.stderr}` : ""}`, result.spillPath);
316
+ return { ...result, text: output.text };
317
+ },
318
+ async put(input: { host?: string; localPath: string; remotePath: string; ui?: ConfirmUi; onProgress?: (sent: number, total: number) => void }) {
319
+ const file = hosts();
320
+ const host = concrete(selectHost(file, input.host));
321
+ if (policyOf(file).readonly) throw new PolicyDeniedError("只读模式拒绝上传。");
322
+ const backupPath = backupLocation(input.remotePath, host.deploy?.root);
323
+ let exists = false;
324
+ if (host.transport === "ftp" || host.transport === "ftps") {
325
+ exists = await ftpExists(withPassword(host), input.remotePath);
326
+ if (isProdHost(host) || exists) {
327
+ await ask(input.ui, `${host.name}:上传${exists ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
328
+ }
329
+ const result = await ftpPut(withPassword(host), input.localPath, input.remotePath, exists);
330
+ appendAudit(auditPath, { host: host.name, tool: "ssh_put", danger: "write", summary: exists ? "FTP 覆盖上传" : "FTP 上传", command: input.remotePath, confirmed: isProdHost(host) || exists });
331
+ return { bytes: result.bytes, sha256: "local-only", backupPath: result.backupPath };
332
+ }
333
+ if (host.transport === "openssh") {
334
+ exists = (await execOpenSsh(host, { command: `if [ -e ${shellQuote(input.remotePath)} ]; then echo yes; fi` })).stdout.includes("yes");
335
+ if (isProdHost(host) || exists) await ask(input.ui, `${host.name}:上传${exists ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
336
+ const result = await putOpenSsh(host, input.localPath, input.remotePath, exists ? backupPath : undefined);
337
+ appendAudit(auditPath, { host: host.name, tool: "ssh_put", danger: "write", summary: "scp 上传", command: input.remotePath, confirmed: isProdHost(host) || exists });
338
+ return result;
339
+ }
340
+ await connect(host);
341
+ const listed = await pool.exec(host.id, { command: `if [ -e ${shellQuote(input.remotePath)} ]; then echo yes; fi` });
342
+ const overwrite = listed.stdout.includes("yes");
343
+ if (isProdHost(host) || overwrite) {
344
+ await ask(input.ui, `${host.name}:上传${overwrite ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
345
+ }
346
+ const result = await pool.put(host.id, { localPath: input.localPath, remotePath: input.remotePath, backupPath: overwrite ? backupPath : undefined, onProgress: input.onProgress });
347
+ if (overwrite && result.backupPath) await pruneBackups(host.id, result.backupPath);
348
+ appendAudit(auditPath, {
349
+ host: host.name,
350
+ tool: "ssh_put",
351
+ danger: "write",
352
+ summary: overwrite ? "覆盖远端文件" : "上传新文件",
353
+ command: `${input.localPath} -> ${input.remotePath}`,
354
+ confirmed: isProdHost(host) || overwrite,
355
+ });
356
+ return result;
357
+ },
358
+ async list(input: { host?: string; path: string }) {
359
+ const host = concrete(selectHost(hosts(), input.host));
360
+ if (host.transport === "ftp" || host.transport === "ftps") {
361
+ const entries = await ftpList(withPassword(host), input.path);
362
+ return entries.map((entry) => `${entry.directory ? "d" : "-"} ${entry.size}\t${entry.name}`).join("\n");
363
+ }
364
+ if (host.transport === "openssh") throw new UnsupportedError("系统 ssh 传输暂不支持列目录,请把这台主机的传输改成 ssh2。");
365
+ await connect(host);
366
+ const entries = await pool.list(host.id, input.path);
367
+ return entries.map((entry) => `${entry.directory ? "d" : "-"} ${entry.size}\t${entry.name}`).join("\n");
368
+ },
369
+ async read(input: { host?: string; path: string; offset?: number; limit?: number }) {
370
+ const host = concrete(selectHost(hosts(), input.host));
371
+ if (host.transport === "ftp" || host.transport === "ftps" || host.transport === "openssh") {
372
+ throw new UnsupportedError("读取文件目前只走 ssh2。FTP 和 openssh 请改用 ssh_get。");
373
+ }
374
+ await connect(host);
375
+ return pool.read(host.id, input.path, input.offset, input.limit);
376
+ },
377
+ async deploy(input: {
378
+ host?: string;
379
+ localPath: string;
380
+ kind?: "file" | "tar";
381
+ releaseId?: string;
382
+ dryRun?: boolean;
383
+ reason?: string;
384
+ signal?: AbortSignal;
385
+ onStep?: (message: string) => void;
386
+ ui?: ConfirmUi;
387
+ }) {
388
+ const file = hosts();
389
+ const host = concrete(selectHost(file, input.host));
390
+ if (policyOf(file).readonly) throw new PolicyDeniedError("只读模式拒绝部署。");
391
+ const layout = host.deploy;
392
+ if (!layout?.root) throw new PolicyDeniedError(`${host.name} 没有 deploy 布局。先在主机配置里写 root,不接受调用时临时给路径。`);
393
+ const signal = input.signal;
394
+ const releaseId = input.releaseId ?? releaseIdNow();
395
+ checkReleaseId(releaseId);
396
+ const fileName = input.localPath.split(/[\\/]/).pop() || "artifact";
397
+ const plan = planRelease(layout, releaseId, fileName);
398
+ const kind = input.kind ?? "tar";
399
+ const restartCmd = layout.restartCmd;
400
+ const healthCmd = layout.healthCmd;
401
+ requireReason(host, "destructive", input.reason);
402
+ if (input.dryRun) return { releaseId, current: plan.releaseDir, rolledBack: false, dryRun: true, plan };
403
+ await connect(host);
404
+ const step = (message: string) => input.onStep?.(message);
405
+ step("预检磁盘空间");
406
+ const existing = await remoteLines(host.id, `ls -1 ${shellQuote(plan.releasesDir)} 2>/dev/null || true`, signal);
407
+ const keep = layout.keepReleases ?? 5;
408
+ const doomed = existing.filter((item) => item !== releaseId).sort().slice(0, Math.max(0, existing.length + 1 - keep));
409
+ await ask(
410
+ input.ui,
411
+ `${host.name}:部署 ${releaseId}`,
412
+ [
413
+ `${input.localPath} -> ${plan.releaseDir}`,
414
+ `切换 ${plan.currentLink}`,
415
+ restartCmd ? `重启:${restartCmd}` : "没有重启命令",
416
+ healthCmd ? "健康检查失败会自动切回上一版,这一步不再次确认。" : "没有健康检查,失败不会自动回滚。",
417
+ doomed.length > 0 ? `将删除旧版本:${doomed.join("、")}` : "没有旧版本需要删除。",
418
+ "shared/ 不写入。",
419
+ ].join("\n"),
420
+ );
421
+ appendAudit(auditPath, {
422
+ host: host.name,
423
+ tool: "ssh_deploy",
424
+ danger: "destructive",
425
+ summary: "部署开始",
426
+ command: `${input.localPath} -> ${plan.releaseDir}`,
427
+ confirmed: true,
428
+ }, { required: isProdHost(host) });
429
+ const bytes = statSync(input.localPath).size;
430
+ const factor = kind === "tar" ? 3 : 2;
431
+ const space = await checked(host.id, `df -Pk ${shellQuote(layout.root)} | awk 'NR==2 { print $4 }'`, signal); const freeKb = Number(space.stdout.trim());
432
+ if (!Number.isFinite(freeKb)) throw new PolicyDeniedError(`读不到 ${layout.root} 的剩余空间,取消部署。`);
433
+ if (freeKb * 1024 < bytes * factor) {
434
+ throw new PolicyDeniedError(`${layout.root} 剩余 ${freeKb}KB,小于制品的 ${factor} 倍,取消部署。`);
435
+ }
436
+ step("创建目录");
437
+ await checked(host.id, `mkdir -p ${shellQuote(plan.sharedDir)} ${shellQuote(plan.releaseDir)}`, signal);
438
+ const previous = (await checked(host.id, `readlink ${shellQuote(plan.currentLink)} || true`, signal)).stdout.trim();
439
+ step(`上传 ${bytes} 字节`);
440
+ if (kind === "tar") {
441
+ await pool.put(host.id, { localPath: input.localPath, remotePath: plan.partPath, signal });
442
+ const listed = await checked(host.id, `tar -tzf ${shellQuote(plan.partPath)}`, signal);
443
+ const rejected = rejectArchiveMembers(listed.stdout.split(/\n/), plan.releaseDir);
444
+ if (rejected.length > 0) throw new BoundsError(`压缩包成员越界:${rejected.join(", ")}`);
445
+ await checked(host.id, `tar -xzf ${shellQuote(plan.partPath)} -C ${shellQuote(plan.releaseDir)} && rm -f ${shellQuote(plan.partPath)}`, signal);
446
+ } else {
447
+ await pool.put(host.id, { localPath: input.localPath, remotePath: `${plan.releaseDir}/${fileName}`, signal });
448
+ }
449
+ step("切换 current");
450
+ await checked(host.id, `ln -sfn ${shellQuote(plan.releaseDir)} ${shellQuote(plan.currentLink)}`, signal);
451
+ if (restartCmd) {
452
+ step(`重启:${restartCmd}`);
453
+ await checked(host.id, restartCmd, signal);
454
+ }
455
+ let rolledBack = false;
456
+ if (healthCmd) {
457
+ step("健康检查");
458
+ const health = await pool.exec(host.id, { command: healthLoopCommand(healthCmd), signal });
459
+ if (health.exitCode !== 0) {
460
+ if (!previous) throw new PolicyDeniedError(`健康检查失败,而且没有上一版可切回。当前停在 ${plan.releaseDir}\n${health.stdout}${health.stderr}`);
461
+ step("健康检查失败,切回上一版");
462
+ await checked(host.id, `ln -sfn ${shellQuote(previous)} ${shellQuote(plan.currentLink)}`, signal);
463
+ if (restartCmd) await checked(host.id, restartCmd, signal);
464
+ const again = await pool.exec(host.id, { command: healthLoopCommand(healthCmd), signal });
465
+ if (again.exitCode !== 0) {
466
+ const state = await pool.exec(host.id, {
467
+ command: `readlink ${shellQuote(plan.currentLink)}`,
468
+ signal,
469
+ });
470
+ throw new PolicyDeniedError(
471
+ `已切回 ${previous},但健康检查仍然失败,两个版本都不健康。\n` +
472
+ `current -> ${state.stdout.trim() || "未知"}\n` +
473
+ `新版本 ${plan.releaseDir}:${health.stdout}${health.stderr}\n` +
474
+ `上一版本 ${previous}:${again.stdout}${again.stderr}`,
475
+ );
476
+ }
477
+ rolledBack = true;
478
+ }
479
+ }
480
+ if (doomed.length > 0) {
481
+ step(`清理旧版本:${doomed.join("、")}`);
482
+ for (const old of doomed) {
483
+ if (previous.endsWith(`/${old}`)) continue;
484
+ checkReleaseId(old);
485
+ await checked(host.id, `rm -rf ${shellQuote(`${plan.releasesDir}/${old}`)}`, signal);
486
+ }
487
+ }
488
+ return { releaseId, current: rolledBack ? previous : plan.releaseDir, rolledBack };
489
+ },
490
+ async rollback(input: { host?: string; to?: string; file?: string; reason?: string; ui?: ConfirmUi }) {
491
+ const file = hosts();
492
+ const host = concrete(selectHost(file, input.host));
493
+ if (policyOf(file).readonly) throw new PolicyDeniedError("只读模式拒绝回滚。");
494
+ requireReason(host, "destructive", input.reason);
495
+ if (input.file) {
496
+ await ask(input.ui, `${host.name}:恢复文件`, input.file);
497
+ await connect(host);
498
+ const quoted = shellQuote(input.file);
499
+ const moved = await pool.exec(host.id, { command: `latest=$(ls -1t ${quoted}.bak.* 2>/dev/null | head -1); test -n "$latest" && mv "$latest" ${quoted}` });
500
+ if (moved.exitCode !== 0) throw new PolicyDeniedError(`没有可用备份,或恢复 ${input.file} 失败。`);
501
+ return { releaseId: "", current: input.file };
502
+ }
503
+ const root = host.deploy?.root;
504
+ if (!root) throw new PolicyDeniedError(`${host.name} 没有 deploy 布局,不能回滚 release。`);
505
+ const restartCmd = host.deploy?.restartCmd;
506
+ const plan = planRelease(host.deploy!, input.to && input.to !== "previous" ? input.to : "placeholder", "artifact");
507
+ await connect(host);
508
+ const current = (await pool.exec(host.id, { command: `readlink ${shellQuote(plan.currentLink)} || true` })).stdout.trim();
509
+ const listed = await pool.exec(host.id, { command: `ls -1 ${shellQuote(plan.releasesDir)}` });
510
+ const releases = listed.stdout.split(/\n/).map((item) => item.trim()).filter(Boolean).sort();
511
+ const target = input.to && input.to !== "previous"
512
+ ? input.to
513
+ : releases.filter((item) => !current.endsWith(`/${item}`)).at(-1);
514
+ if (!target) throw new PolicyDeniedError("没有可回滚的上一版。");
515
+ checkReleaseId(target);
516
+ const releaseDir = `${plan.releasesDir}/${target}`;
517
+ await ask(input.ui, `${host.name}:回滚到 ${target}`, [
518
+ `${plan.currentLink} -> ${releaseDir}`,
519
+ restartCmd ? `重启:${restartCmd}` : "没有重启命令",
520
+ ].join("\n"));
521
+ appendAudit(auditPath, {
522
+ host: host.name,
523
+ tool: "ssh_rollback",
524
+ danger: "destructive",
525
+ summary: `回滚到 ${target}`,
526
+ command: releaseDir,
527
+ confirmed: true,
528
+ }, { required: isProdHost(host) });
529
+ await checked(host.id, `ln -sfn ${shellQuote(releaseDir)} ${shellQuote(plan.currentLink)}`);
530
+ if (restartCmd) await checked(host.id, restartCmd);
531
+ return { releaseId: target, current: releaseDir };
532
+ },
533
+ async tunnel(input: { host?: string; listenPort: number; destHost: string; destPort: number; direction?: "local" | "remote"; ui?: ConfirmUi }) {
534
+ const host = concrete(selectHost(hosts(), input.host));
535
+ if (host.transport !== "ssh2") {
536
+ throw new PolicyDeniedError("端口转发目前只走 ssh2。");
537
+ }
538
+ if (!Number.isInteger(input.listenPort) || input.listenPort < 0 || input.listenPort > 65535) {
539
+ throw new PolicyDeniedError("listenPort 必须是 0 到 65535 的整数。0 表示由系统选空闲端口。");
540
+ }
541
+ await ask(
542
+ input.ui,
543
+ `${host.name}:端口转发`,
544
+ `本机 127.0.0.1:${input.listenPort || "自动"} -> ${input.destHost}:${input.destPort}`,
545
+ );
546
+ await connect(host);
547
+ const opened = input.direction === "remote"
548
+ ? await pool.tunnelRemote(host.id, input.listenPort, input.destHost, input.destPort)
549
+ : await pool.tunnel(host.id, input.listenPort, input.destHost, input.destPort);
550
+ tunnels.push(opened);
551
+ appendAudit(auditPath, {
552
+ host: host.name,
553
+ tool: "ssh_tunnel",
554
+ danger: "write",
555
+ summary: "本地端口转发",
556
+ command: `127.0.0.1:${opened.port} -> ${input.destHost}:${input.destPort}`,
557
+ confirmed: true,
558
+ });
559
+ return opened;
560
+ },
561
+ async get(input: { host?: string; remotePath: string; localPath: string }) {
562
+ const host = concrete(selectHost(hosts(), input.host));
563
+ if (host.transport === "ftp" || host.transport === "ftps") {
564
+ const result = await ftpGet(withPassword(host), input.remotePath, input.localPath);
565
+ appendAudit(auditPath, { host: host.name, tool: "ssh_get", danger: "read", summary: "FTP 下载", command: input.remotePath });
566
+ return { bytes: result.bytes, sha256: "local-only" };
567
+ }
568
+ if (host.transport === "openssh") {
569
+ await copyOpenSsh(host, "get", input.localPath, input.remotePath);
570
+ appendAudit(auditPath, { host: host.name, tool: "ssh_get", danger: "read", summary: "scp 下载", command: input.remotePath });
571
+ return { bytes: 0, sha256: "" };
572
+ }
573
+ await connect(host);
574
+ const result = await pool.get(host.id, { remotePath: input.remotePath, localPath: input.localPath });
575
+ appendAudit(auditPath, {
576
+ host: host.name,
577
+ tool: "ssh_get",
578
+ danger: "read",
579
+ summary: "下载远端文件",
580
+ command: `${input.remotePath} -> ${input.localPath}`,
581
+ });
582
+ return result;
583
+ },
584
+ };
585
+ }
@@ -0,0 +1,12 @@
1
+ // scan/auto.ts —— auto 每次连接时看 ~/.ssh/config,不把结果存进 profile。
2
+ import { parseSshConfig } from "./ssh-config.js";
3
+ import type { HostProfile, TransportKind } from "../core/types.js";
4
+
5
+ export function chooseTransport(profile: HostProfile, sshConfigText: string): Exclude<HostProfile["transport"], "auto"> {
6
+ if (profile.transport !== "auto") return profile.transport;
7
+ const hosts = parseSshConfig(sshConfigText);
8
+ const match = hosts.find((item) => item.hostName === profile.host || item.name === profile.name || item.aliases.includes(profile.host));
9
+ return match?.needsOpenSsh ? "openssh" : "ssh2";
10
+ }
11
+
12
+ export type ConcreteTransport = TransportKind;
@@ -0,0 +1,36 @@
1
+ // scan/project.ts —— 只返回可能含部署目标的路径,不解析内容。
2
+ import { readdirSync, statSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ const NAMES = new Set([".env", ".env.local", ".env.production", "Jenkinsfile", "ecosystem.config.js", "inventory", "hosts"]);
6
+
7
+ export function projectDeployFiles(root: string, depth = 3): string[] {
8
+ const found: string[] = [];
9
+ function walk(dir: string, level: number) {
10
+ if (level > depth || found.length >= 50) return;
11
+ let entries: string[] = [];
12
+ try {
13
+ entries = readdirSync(dir);
14
+ } catch {
15
+ return;
16
+ }
17
+ for (const name of entries) {
18
+ if (name === "node_modules" || name === ".git") continue;
19
+ const path = join(dir, name);
20
+ let info;
21
+ try {
22
+ info = statSync(path);
23
+ } catch {
24
+ continue;
25
+ }
26
+ if (info.isDirectory()) {
27
+ if (name === "deploy") found.push(path);
28
+ walk(path, level + 1);
29
+ } else if (NAMES.has(name) || name.startsWith(".env")) {
30
+ found.push(path);
31
+ }
32
+ }
33
+ }
34
+ walk(root, 0);
35
+ return found;
36
+ }