@nsyan/ssh 0.1.0 → 0.1.1

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 CHANGED
@@ -6,11 +6,12 @@ import { appendAudit, defaultAuditPath } from "./core/audit.js";
6
6
  import { backupLocation, checkReleaseId, healthLoopCommand, planRelease, rejectArchiveMembers, releaseIdNow, staleBackups } from "./core/deploy.js";
7
7
  import { waitCommand, type WaitFor } from "./core/wait.js";
8
8
  import { loadHosts } from "./core/config.js";
9
- import { shellQuote } from "./core/guard.js";
9
+ import { shellQuote, withinRoot } from "./core/guard.js";
10
10
  import { getSecret, platformKeychain } from "./core/secrets.js";
11
11
  import { appendKnownHost, checkHostKey, hostKeyFingerprint } from "./core/known-hosts.js";
12
12
  import { classify, decide, isProdHost, type Policy } from "./core/policy.js";
13
13
  import {
14
+ AuthFailedError,
14
15
  BoundsError,
15
16
  ConfirmRejectedError,
16
17
  HostKeyChangedError,
@@ -22,7 +23,7 @@ import {
22
23
  } from "./core/types.js";
23
24
  import { Ssh2Pool, type ConnectHooks } from "./transports/ssh2.js";
24
25
  import { chooseTransport } from "./scan/auto.js";
25
- import { copyOpenSsh, execOpenSsh, putOpenSsh } from "./transports/openssh.js";
26
+ import { copyOpenSsh, execOpenSsh, getOpenSsh, listOpenSsh, putOpenSsh, readOpenSsh, scpPutVerified } from "./transports/openssh.js";
26
27
  import { ftpExecRejected, ftpExists, ftpGet, ftpList, ftpPut } from "./transports/ftp.js";
27
28
 
28
29
  const OUTPUT_LIMIT = 50_000;
@@ -147,15 +148,115 @@ export function createRuntime(options: RuntimeOptions = {}) {
147
148
  await pool.connect(ready, hooks).catch((error: Error) => {
148
149
  throw keyError ?? error;
149
150
  });
151
+ // 连接复用时 hostVerifier 不会再跑,指纹要从池里取回来。
152
+ if (!identity.fingerprint) identity.fingerprint = pool.fingerprintOf(ready.id);
150
153
  return identity;
151
154
  }
152
155
 
156
+ async function testProfile(host: HostProfile, acceptNewHostKey: boolean) {
157
+ const started = Date.now();
158
+ const latencyMs = () => Date.now() - started;
159
+ // FTP/FTPS 没有主机密钥,只能验证能不能登录,不报指纹。
160
+ if (host.transport === "ftp" || host.transport === "ftps") {
161
+ await ftpList(await resolveProfile(host), ".");
162
+ return { ok: true, auth: host.auth.kind, fingerprint: "", keyType: "", latencyMs: latencyMs(), transport: host.transport };
163
+ }
164
+ // openssh 的主机密钥由系统 ssh 自己管,指纹不经我们手。
165
+ if (host.transport === "openssh") {
166
+ const result = await execOpenSsh(await resolveProfile(host), { command: "echo ok" });
167
+ if (result.exitCode !== 0) throw new AuthFailedError(result.stderr || `ssh 退出码 ${result.exitCode}`);
168
+ return { ok: true, auth: host.auth.kind, fingerprint: "", keyType: "", latencyMs: latencyMs(), transport: host.transport };
169
+ }
170
+ const identity = await connect(host, acceptNewHostKey);
171
+ const result = await pool.exec(host.id, { command: "echo ok" });
172
+ if (result.exitCode !== 0) throw new AuthFailedError(result.stderr || `echo ok 退出码 ${result.exitCode}`);
173
+ return {
174
+ ok: true,
175
+ auth: identity.auth,
176
+ fingerprint: identity.fingerprint,
177
+ keyType: identity.keyType,
178
+ latencyMs: latencyMs(),
179
+ transport: host.transport,
180
+ };
181
+ }
182
+
153
183
  function requireReason(host: HostProfile, danger: string, reason?: string): void {
154
184
  if (isProdHost(host) && danger === "destructive" && !reason?.trim()) {
155
185
  throw new PolicyDeniedError("生产主机的破坏性操作必须填写 reason,说明动机和影响范围。");
156
186
  }
157
187
  }
158
188
 
189
+ /** 同一个备份修剪逻辑要在 ssh2 和 openssh 两条路上都能跑,所以只依赖这两个动作。 */
190
+ interface RemoteRunner {
191
+ lines(command: string): Promise<string[]>;
192
+ checked(command: string): Promise<{ stdout: string; stderr: string; exitCode: number | null }>;
193
+ /** 不抛错的版本:调用方要自己看退出码(健康检查、重启这类需要分支处理的)。 */
194
+ tryRun(command: string): Promise<{ stdout: string; stderr: string; exitCode: number | null }>;
195
+ }
196
+
197
+ function poolRunner(profileId: string, signal?: AbortSignal): RemoteRunner {
198
+ const run = (command: string) => pool.exec(profileId, { command, timeoutMs: 120_000, signal });
199
+ return {
200
+ async lines(command) {
201
+ const listed = await run(command);
202
+ return listed.stdout.split(/\n/).map((item) => item.trim()).filter(Boolean);
203
+ },
204
+ async checked(command) {
205
+ const result = await run(command);
206
+ if (result.exitCode !== 0) {
207
+ throw new PolicyDeniedError(`远端命令失败(退出码 ${result.exitCode}):${result.stderr || result.stdout || command}`);
208
+ }
209
+ return result;
210
+ },
211
+ async tryRun(command) {
212
+ return run(command).catch((error: Error) => ({ stdout: "", stderr: error.message, exitCode: 1 }));
213
+ },
214
+ };
215
+ }
216
+
217
+ function opensshRunner(profile: HostProfile, signal?: AbortSignal): RemoteRunner {
218
+ const run = (command: string) => execOpenSsh(profile, { command, signal });
219
+ return {
220
+ async lines(command) {
221
+ const listed = await run(command);
222
+ return listed.stdout.split(/\n/).map((item) => item.trim()).filter(Boolean);
223
+ },
224
+ async checked(command) {
225
+ const result = await run(command);
226
+ if (result.exitCode !== 0) {
227
+ throw new PolicyDeniedError(`远端命令失败(退出码 ${result.exitCode}):${result.stderr || result.stdout || command}`);
228
+ }
229
+ return result;
230
+ },
231
+ async tryRun(command) {
232
+ return run(command).catch((error: Error) => ({ stdout: "", stderr: error.message, exitCode: 1 }));
233
+ },
234
+ };
235
+ }
236
+
237
+ /**
238
+ * 按主机的 transport 选执行/上传路径。部署与回滚都走这里,
239
+ * 不能无条件 `connect()` + `pool.*`:那会把 openssh 主机(ProxyJump/agent/证书)
240
+ * 静默改走 ssh2 直连,把 FTP 主机错报成 ECONNREFUSED。
241
+ */
242
+ async function runnerFor(host: HostProfile, signal?: AbortSignal) {
243
+ if (host.transport === "ftp" || host.transport === "ftps") {
244
+ throw new UnsupportedError(`${host.name} 是 FTP/FTPS,只能传文件,不能部署或回滚。请用 SSH/SFTP 主机。`);
245
+ }
246
+ if (host.transport === "openssh") {
247
+ const ready = await resolveProfile(host);
248
+ return {
249
+ runner: opensshRunner(ready, signal),
250
+ put: (localPath: string, remotePath: string) => scpPutVerified(ready, localPath, remotePath, signal),
251
+ };
252
+ }
253
+ await connect(host);
254
+ return {
255
+ runner: poolRunner(host.id, signal),
256
+ put: (localPath: string, remotePath: string) => pool.put(host.id, { localPath, remotePath, signal }),
257
+ };
258
+ }
259
+
159
260
  async function remoteLines(profileId: string, command: string, signal?: AbortSignal): Promise<string[]> {
160
261
  const listed = await pool.exec(profileId, { command, timeoutMs: 120_000, signal });
161
262
  return listed.stdout.split(/\n/).map((item) => item.trim()).filter(Boolean);
@@ -169,16 +270,17 @@ export function createRuntime(options: RuntimeOptions = {}) {
169
270
  return result;
170
271
  }
171
272
 
172
- async function pruneBackups(profileId: string, backupPath: string): Promise<void> {
273
+ /** 同一路径只留最近 3 份备份。删的范围限制在备份所在目录。 */
274
+ async function pruneBackups(runner: RemoteRunner, backupPath: string): Promise<void> {
173
275
  const slash = backupPath.lastIndexOf("/");
174
276
  if (slash < 0) return;
175
277
  const dir = backupPath.slice(0, slash);
176
278
  const name = backupPath.slice(slash + 1);
177
279
  const stamp = name.lastIndexOf(".");
178
280
  const stem = stamp > 0 ? name.slice(0, stamp) : name;
179
- const names = await remoteLines(profileId, `ls -1 ${shellQuote(dir)} 2>/dev/null || true`);
281
+ const names = await runner.lines(`ls -1 ${shellQuote(dir)} 2>/dev/null || true`);
180
282
  for (const old of staleBackups(names, stem)) {
181
- await checked(profileId, `rm -f ${shellQuote(`${dir}/${old}`)}`);
283
+ await runner.checked(`rm -f ${shellQuote(`${dir}/${old}`)}`);
182
284
  }
183
285
  }
184
286
 
@@ -212,19 +314,13 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
212
314
  if (isProdHost(host)) throw new PolicyDeniedError("生产主机不能授予会话级写授权。");
213
315
  grants.set(host.id, Date.now() + minutes * 60_000);
214
316
  },
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
- };
317
+ async testHost(input: { host?: string; acceptNewHostKey?: boolean; allowActive?: boolean }) {
318
+ const host = concrete(selectHost(hosts(), input.host, input.allowActive === true));
319
+ return testProfile(host, input.acceptNewHostKey === true);
320
+ },
321
+ /** 测一个还没入库的候选。建连必须发生在写盘之前。 */
322
+ async testProfile(candidate: HostProfile, acceptNewHostKey = false) {
323
+ return testProfile(concrete(candidate), acceptNewHostKey);
228
324
  },
229
325
  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
326
  const file = hosts();
@@ -273,18 +369,23 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
273
369
  ? result.spillPath
274
370
  : undefined;
275
371
  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 };
372
+ // 生产主机的 destructive 已经在动作之前写过一条(fail-closed),
373
+ // 这里再写会变成一次动作两条记录,`/ssh log` 会双计。
374
+ const alreadyAudited = isProdHost(host) && verdict.danger === "destructive";
375
+ if (!alreadyAudited) {
376
+ appendAudit(auditPath, {
377
+ host: host.name,
378
+ tool: "ssh_exec",
379
+ danger: verdict.danger,
380
+ summary: verdict.summary,
381
+ command: input.command,
382
+ reason: input.reason,
383
+ confirmed: decision === "confirm",
384
+ exitCode: result.exitCode,
385
+ durationMs: result.durationMs,
386
+ });
387
+ }
388
+ return { ...result, text: output.text, truncated: output.truncated, spillPath: output.spillPath };
288
389
  },
289
390
  async sudo(input: { host?: string; command: string; reason?: string; ui?: ConfirmUi }) {
290
391
  const file = hosts();
@@ -313,7 +414,7 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
313
414
  timeoutMs: boundedTimeoutMs(undefined, host.defaults?.timeoutSec),
314
415
  });
315
416
  const output = tail(`${result.stdout}${result.stderr ? `\n${result.stderr}` : ""}`, result.spillPath);
316
- return { ...result, text: output.text };
417
+ return { ...result, text: output.text, truncated: output.truncated, spillPath: output.spillPath };
317
418
  },
318
419
  async put(input: { host?: string; localPath: string; remotePath: string; ui?: ConfirmUi; onProgress?: (sent: number, total: number) => void }) {
319
420
  const file = hosts();
@@ -322,19 +423,42 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
322
423
  const backupPath = backupLocation(input.remotePath, host.deploy?.root);
323
424
  let exists = false;
324
425
  if (host.transport === "ftp" || host.transport === "ftps") {
325
- exists = await ftpExists(withPassword(host), input.remotePath);
426
+ // FTP 也要走 resolveProfile:`file:...#name` 与 keychain 引用必须先换成明文。
427
+ const ready = await resolveProfile(host);
428
+ exists = await ftpExists(ready, input.remotePath);
326
429
  if (isProdHost(host) || exists) {
327
430
  await ask(input.ui, `${host.name}:上传${exists ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
328
431
  }
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 });
432
+ const result = await ftpPut(ready, input.localPath, input.remotePath, exists);
433
+ appendAudit(auditPath, {
434
+ host: host.name,
435
+ tool: "ssh_put",
436
+ danger: "write",
437
+ summary: exists ? "FTP 覆盖上传" : "FTP 上传",
438
+ command: `${input.localPath} -> ${input.remotePath}`,
439
+ confirmed: isProdHost(host) || exists,
440
+ bytes: result.bytes,
441
+ sha256: "local-only",
442
+ backupPath: result.backupPath,
443
+ });
331
444
  return { bytes: result.bytes, sha256: "local-only", backupPath: result.backupPath };
332
445
  }
333
446
  if (host.transport === "openssh") {
334
447
  exists = (await execOpenSsh(host, { command: `if [ -e ${shellQuote(input.remotePath)} ]; then echo yes; fi` })).stdout.includes("yes");
335
448
  if (isProdHost(host) || exists) await ask(input.ui, `${host.name}:上传${exists ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
336
449
  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 });
450
+ if (exists && result.backupPath) await pruneBackups(opensshRunner(host), result.backupPath);
451
+ appendAudit(auditPath, {
452
+ host: host.name,
453
+ tool: "ssh_put",
454
+ danger: "write",
455
+ summary: exists ? "scp 覆盖上传" : "scp 上传",
456
+ command: `${input.localPath} -> ${input.remotePath}`,
457
+ confirmed: isProdHost(host) || exists,
458
+ bytes: result.bytes,
459
+ sha256: result.sha256,
460
+ backupPath: result.backupPath,
461
+ });
338
462
  return result;
339
463
  }
340
464
  await connect(host);
@@ -344,7 +468,7 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
344
468
  await ask(input.ui, `${host.name}:上传${overwrite ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
345
469
  }
346
470
  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);
471
+ if (overwrite && result.backupPath) await pruneBackups(poolRunner(host.id), result.backupPath);
348
472
  appendAudit(auditPath, {
349
473
  host: host.name,
350
474
  tool: "ssh_put",
@@ -352,24 +476,33 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
352
476
  summary: overwrite ? "覆盖远端文件" : "上传新文件",
353
477
  command: `${input.localPath} -> ${input.remotePath}`,
354
478
  confirmed: isProdHost(host) || overwrite,
479
+ bytes: result.bytes,
480
+ sha256: result.sha256,
481
+ backupPath: result.backupPath,
355
482
  });
356
483
  return result;
357
484
  },
358
485
  async list(input: { host?: string; path: string }) {
359
486
  const host = concrete(selectHost(hosts(), input.host));
360
487
  if (host.transport === "ftp" || host.transport === "ftps") {
361
- const entries = await ftpList(withPassword(host), input.path);
488
+ const entries = await ftpList(await resolveProfile(host), input.path);
489
+ return entries.map((entry) => `${entry.directory ? "d" : "-"} ${entry.size}\t${entry.name}`).join("\n");
490
+ }
491
+ if (host.transport === "openssh") {
492
+ const entries = await listOpenSsh(await resolveProfile(host), input.path);
362
493
  return entries.map((entry) => `${entry.directory ? "d" : "-"} ${entry.size}\t${entry.name}`).join("\n");
363
494
  }
364
- if (host.transport === "openssh") throw new UnsupportedError("系统 ssh 传输暂不支持列目录,请把这台主机的传输改成 ssh2。");
365
495
  await connect(host);
366
496
  const entries = await pool.list(host.id, input.path);
367
497
  return entries.map((entry) => `${entry.directory ? "d" : "-"} ${entry.size}\t${entry.name}`).join("\n");
368
498
  },
369
499
  async read(input: { host?: string; path: string; offset?: number; limit?: number }) {
370
500
  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。");
501
+ if (host.transport === "ftp" || host.transport === "ftps") {
502
+ throw new UnsupportedError("FTP 不能按行读,请用 ssh_get 拉回本地再读。");
503
+ }
504
+ if (host.transport === "openssh") {
505
+ return readOpenSsh(await resolveProfile(host), input.path, input.offset, input.limit);
373
506
  }
374
507
  await connect(host);
375
508
  return pool.read(host.id, input.path, input.offset, input.limit);
@@ -400,12 +533,17 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
400
533
  const healthCmd = layout.healthCmd;
401
534
  requireReason(host, "destructive", input.reason);
402
535
  if (input.dryRun) return { releaseId, current: plan.releaseDir, rolledBack: false, dryRun: true, plan };
403
- await connect(host);
536
+ const remote = await runnerFor(host, signal);
404
537
  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);
538
+ step("读当前版本与磁盘空间");
539
+ // 先读到上一版,确认框里列的「将删除」才不会把回滚点算进去。
540
+ const previous = (await remote.runner.lines(`readlink ${shellQuote(plan.currentLink)} || true`))[0] ?? "";
541
+ const existing = await remote.runner.lines(`ls -1 ${shellQuote(plan.releasesDir)} 2>/dev/null || true`);
407
542
  const keep = layout.keepReleases ?? 5;
408
- const doomed = existing.filter((item) => item !== releaseId).sort().slice(0, Math.max(0, existing.length + 1 - keep));
543
+ const doomed = existing
544
+ .filter((item) => item !== releaseId && !previous.endsWith(`/${item}`))
545
+ .sort()
546
+ .slice(0, Math.max(0, existing.length + 1 - keep));
409
547
  await ask(
410
548
  input.ui,
411
549
  `${host.name}:部署 ${releaseId}`,
@@ -428,61 +566,74 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
428
566
  }, { required: isProdHost(host) });
429
567
  const bytes = statSync(input.localPath).size;
430
568
  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());
569
+ const space = await remote.runner.checked(`df -Pk ${shellQuote(layout.root)} | awk 'NR==2 { print $4 }'`);
570
+ const freeKb = Number(space.stdout.trim());
432
571
  if (!Number.isFinite(freeKb)) throw new PolicyDeniedError(`读不到 ${layout.root} 的剩余空间,取消部署。`);
433
572
  if (freeKb * 1024 < bytes * factor) {
434
573
  throw new PolicyDeniedError(`${layout.root} 剩余 ${freeKb}KB,小于制品的 ${factor} 倍,取消部署。`);
435
574
  }
436
575
  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();
576
+ await remote.runner.checked(`mkdir -p ${shellQuote(plan.sharedDir)} ${shellQuote(plan.releaseDir)}`);
439
577
  step(`上传 ${bytes} 字节`);
440
578
  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);
579
+ await remote.put(input.localPath, plan.partPath);
580
+ const listed = await remote.runner.checked(`tar -tzf ${shellQuote(plan.partPath)}`);
443
581
  const rejected = rejectArchiveMembers(listed.stdout.split(/\n/), plan.releaseDir);
444
582
  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);
583
+ await remote.runner.checked(`tar -xzf ${shellQuote(plan.partPath)} -C ${shellQuote(plan.releaseDir)} && rm -f ${shellQuote(plan.partPath)}`);
446
584
  } else {
447
- await pool.put(host.id, { localPath: input.localPath, remotePath: `${plan.releaseDir}/${fileName}`, signal });
585
+ await remote.put(input.localPath, `${plan.releaseDir}/${fileName}`);
448
586
  }
449
587
  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
- }
588
+ await remote.runner.checked(`ln -sfn ${shellQuote(plan.releaseDir)} ${shellQuote(plan.currentLink)}`);
455
589
  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 });
590
+ /**
591
+ * 切回上一版并重启、复检。重启失败与健康检查失败走同一条回退路径。
592
+ * 回退时的重启用 tryRun:重启命令本身坏了(比如写错了 systemctl 服务名),
593
+ * 再抛一次只会把「已回退」这个关键信息盖掉。
594
+ */
595
+ const fallback = async (why: string, detail: string) => {
596
+ if (!previous) throw new PolicyDeniedError(`${why},而且没有上一版可切回。当前停在 ${plan.releaseDir}\n${detail}`);
597
+ step(`${why},切回上一版`);
598
+ await remote.runner.checked(`ln -sfn ${shellQuote(previous)} ${shellQuote(plan.currentLink)}`);
599
+ const restartAgain = restartCmd ? await remote.runner.tryRun(restartCmd) : undefined;
600
+ if (restartAgain && restartAgain.exitCode !== 0) {
601
+ step(`回退后的重启命令也失败了:${restartAgain.stderr || restartAgain.stdout}`);
602
+ }
603
+ if (healthCmd) {
604
+ const again = await remote.runner.tryRun(healthLoopCommand(healthCmd));
465
605
  if (again.exitCode !== 0) {
466
- const state = await pool.exec(host.id, {
467
- command: `readlink ${shellQuote(plan.currentLink)}`,
468
- signal,
469
- });
606
+ const state = await remote.runner.tryRun(`readlink ${shellQuote(plan.currentLink)}`);
470
607
  throw new PolicyDeniedError(
471
608
  `已切回 ${previous},但健康检查仍然失败,两个版本都不健康。\n` +
472
609
  `current -> ${state.stdout.trim() || "未知"}\n` +
473
- `新版本 ${plan.releaseDir}:${health.stdout}${health.stderr}\n` +
474
- `上一版本 ${previous}:${again.stdout}${again.stderr}`,
610
+ `新版本 ${plan.releaseDir}:${detail}\n` +
611
+ `上一版本 ${previous}:${again.stdout}${again.stderr}` +
612
+ (restartAgain && restartAgain.exitCode !== 0 ? `\n回退时的重启命令也失败:${restartAgain.stderr || restartAgain.stdout}` : ""),
475
613
  );
476
614
  }
477
- rolledBack = true;
615
+ }
616
+ rolledBack = true;
617
+ };
618
+ if (restartCmd) {
619
+ // 重启失败不能再往下走:新版本没生效,current 已经指向它。
620
+ step(`重启:${restartCmd}`);
621
+ const restarted = await remote.runner.tryRun(restartCmd);
622
+ if (restarted.exitCode !== 0) {
623
+ await fallback("重启失败", `${restarted.stdout}${restarted.stderr}`);
624
+ return { releaseId, current: previous, rolledBack };
478
625
  }
479
626
  }
627
+ if (healthCmd) {
628
+ step("健康检查");
629
+ const health = await remote.runner.tryRun(healthLoopCommand(healthCmd));
630
+ if (health.exitCode !== 0) await fallback("健康检查失败", `${health.stdout}${health.stderr}`);
631
+ }
480
632
  if (doomed.length > 0) {
481
633
  step(`清理旧版本:${doomed.join("、")}`);
482
634
  for (const old of doomed) {
483
- if (previous.endsWith(`/${old}`)) continue;
484
635
  checkReleaseId(old);
485
- await checked(host.id, `rm -rf ${shellQuote(`${plan.releasesDir}/${old}`)}`, signal);
636
+ await remote.runner.checked(`rm -rf ${shellQuote(`${plan.releasesDir}/${old}`)}`);
486
637
  }
487
638
  }
488
639
  return { releaseId, current: rolledBack ? previous : plan.releaseDir, rolledBack };
@@ -494,29 +645,46 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
494
645
  requireReason(host, "destructive", input.reason);
495
646
  if (input.file) {
496
647
  await ask(input.ui, `${host.name}:恢复文件`, input.file);
497
- await connect(host);
648
+ const remote = await runnerFor(host);
498
649
  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} 失败。`);
650
+ // 备份可能在两个位置:部署根内的 <root>/.pi-ssh-backup/<rel>.<ts>,
651
+ // 或同目录的 <path>.bak.<ts>。两处都要找,否则部署根内的文件永远回滚不了。
652
+ const root = host.deploy?.root;
653
+ const candidates: string[] = [`${quoted}.bak.*`];
654
+ if (root && withinRoot(root, input.file)) {
655
+ candidates.push(shellQuote(`${root}/.pi-ssh-backup/${input.file.slice(root.length + 1)}.*`));
656
+ }
657
+ const find = `for pat in ${candidates.join(" ")}; do latest=$(ls -1t $pat 2>/dev/null | head -1); [ -n "$latest" ] && break; done`;
658
+ const moved = await remote.runner.checked(`${find}; test -n "$latest" && mv "$latest" ${quoted}`)
659
+ .catch((error: Error) => {
660
+ throw new PolicyDeniedError(`没有可用备份,或恢复 ${input.file} 失败。找过:${candidates.join("、")}\n${error.message}`);
661
+ });
662
+ void moved;
501
663
  return { releaseId: "", current: input.file };
502
664
  }
503
665
  const root = host.deploy?.root;
504
666
  if (!root) throw new PolicyDeniedError(`${host.name} 没有 deploy 布局,不能回滚 release。`);
505
667
  const restartCmd = host.deploy?.restartCmd;
668
+ const healthCmd = host.deploy?.healthCmd;
506
669
  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);
670
+ const remote = await runnerFor(host);
671
+ const current = (await remote.runner.lines(`readlink ${shellQuote(plan.currentLink)} || true`))[0] ?? "";
672
+ const listed = await remote.runner.lines(`ls -1 ${shellQuote(plan.releasesDir)}`);
673
+ const releases = listed.filter(Boolean).sort();
674
+ let target = input.to && input.to !== "previous" ? input.to : undefined;
675
+ if (!target) {
676
+ // 只认目录。部署中断会留下 `<id>.part`,它排序靠后,当 release 切上去就是 404。
677
+ const dirs = releases.filter((item) => !item.endsWith(".part") && !current.endsWith(`/${item}`));
678
+ target = dirs.at(-1);
679
+ }
514
680
  if (!target) throw new PolicyDeniedError("没有可回滚的上一版。");
681
+ if (target.endsWith(".part")) throw new PolicyDeniedError(`${target} 是上传中的 .part 残留,不是发布目录,不能回滚到它。`);
515
682
  checkReleaseId(target);
516
683
  const releaseDir = `${plan.releasesDir}/${target}`;
517
684
  await ask(input.ui, `${host.name}:回滚到 ${target}`, [
518
685
  `${plan.currentLink} -> ${releaseDir}`,
519
686
  restartCmd ? `重启:${restartCmd}` : "没有重启命令",
687
+ healthCmd ? "回滚后跑健康检查;不通过会报出两个版本的状态。" : "没有健康检查,回滚后不会自动验证。",
520
688
  ].join("\n"));
521
689
  appendAudit(auditPath, {
522
690
  host: host.name,
@@ -526,8 +694,18 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
526
694
  command: releaseDir,
527
695
  confirmed: true,
528
696
  }, { required: isProdHost(host) });
529
- await checked(host.id, `ln -sfn ${shellQuote(releaseDir)} ${shellQuote(plan.currentLink)}`);
530
- if (restartCmd) await checked(host.id, restartCmd);
697
+ await remote.runner.checked(`ln -sfn ${shellQuote(releaseDir)} ${shellQuote(plan.currentLink)}`);
698
+ if (restartCmd) await remote.runner.checked(restartCmd);
699
+ if (healthCmd) {
700
+ const health = await remote.runner.checked(healthLoopCommand(healthCmd))
701
+ .catch((error: Error) => ({ stdout: "", stderr: error.message, exitCode: 1 }));
702
+ if (health.exitCode !== 0) {
703
+ throw new PolicyDeniedError(
704
+ `已切到 ${target} 但健康检查未通过。current 仍指向 ${releaseDir},需要人工处理。\n` +
705
+ `${health.stdout}${health.stderr}`,
706
+ );
707
+ }
708
+ }
531
709
  return { releaseId: target, current: releaseDir };
532
710
  },
533
711
  async tunnel(input: { host?: string; listenPort: number; destHost: string; destPort: number; direction?: "local" | "remote"; ui?: ConfirmUi }) {
@@ -561,14 +739,31 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
561
739
  async get(input: { host?: string; remotePath: string; localPath: string }) {
562
740
  const host = concrete(selectHost(hosts(), input.host));
563
741
  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 });
742
+ const result = await ftpGet(await resolveProfile(host), input.remotePath, input.localPath);
743
+ appendAudit(auditPath, {
744
+ host: host.name,
745
+ tool: "ssh_get",
746
+ danger: "read",
747
+ summary: "FTP 下载",
748
+ command: `${input.remotePath} -> ${input.localPath}`,
749
+ bytes: result.bytes,
750
+ sha256: "local-only",
751
+ });
566
752
  return { bytes: result.bytes, sha256: "local-only" };
567
753
  }
568
754
  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: "" };
755
+ // 下载也要双端校验:scp 成功不代表内容一致(截断、磁盘满、编码问题)。
756
+ const result = await getOpenSsh(host, input.remotePath, input.localPath);
757
+ appendAudit(auditPath, {
758
+ host: host.name,
759
+ tool: "ssh_get",
760
+ danger: "read",
761
+ summary: "scp 下载",
762
+ command: `${input.remotePath} -> ${input.localPath}`,
763
+ bytes: result.bytes,
764
+ sha256: result.sha256,
765
+ });
766
+ return result;
572
767
  }
573
768
  await connect(host);
574
769
  const result = await pool.get(host.id, { remotePath: input.remotePath, localPath: input.localPath });
@@ -578,6 +773,8 @@ async function ask(ui: ConfirmUi | undefined, title: string, message: string): P
578
773
  danger: "read",
579
774
  summary: "下载远端文件",
580
775
  command: `${input.remotePath} -> ${input.localPath}`,
776
+ bytes: result.bytes,
777
+ sha256: result.sha256,
581
778
  });
582
779
  return result;
583
780
  },
package/src/scan/save.ts CHANGED
@@ -35,9 +35,7 @@ export function saveHostCandidate(file: HostFile, candidate: HostCandidate, choi
35
35
  auth: {
36
36
  kind: candidate.privateKeyPath ? "key" : "password",
37
37
  privateKeyPath: candidate.privateKeyPath,
38
- secretRef: candidate.privateKeyPath || candidate.secretRef?.startsWith("pending:")
39
- ? undefined
40
- : candidate.secretRef,
38
+ secretRef: candidate.privateKeyPath ? undefined : candidate.secretRef,
41
39
  },
42
40
  tags: candidate.tags,
43
41
  createdAt: file.hosts[name]?.createdAt ?? new Date().toISOString(),
@@ -19,13 +19,18 @@ const { Client } = createRequire(import.meta.url)("basic-ftp") as {
19
19
 
20
20
  async function open(profile: HostProfile) {
21
21
  if (profile.active) throw new UnsupportedError("basic-ftp 5 只支持被动模式,主动模式无法开启。");
22
+ // 密码必须是已解析的明文。`secretRef` 里的 `file:...#name` / `keychain:...` 是引用,
23
+ // 原样当密码发出去只会得到 530。解析由 runtime.resolveProfile 统一完成。
24
+ const password = profile.auth.password
25
+ ?? (profile.auth.secretRef && !/^(file|keychain):/.test(profile.auth.secretRef) ? profile.auth.secretRef : undefined);
26
+ if (!password) throw new UnsupportedError("没有可用的 FTP 密码。先确认 ssh-secrets.json 里有这台主机的条目。");
22
27
  const client = new Client();
23
28
  const secure = profile.transport === "ftps" ? (profile.secure === "implicit" ? "implicit" : true) : false;
24
29
  await client.access({
25
30
  host: profile.host,
26
31
  port: profile.port ?? (profile.secure === "implicit" ? 990 : 21),
27
32
  user: profile.user,
28
- password: profile.auth.secretRef,
33
+ password,
29
34
  secure,
30
35
  secureOptions: profile.insecure ? { rejectUnauthorized: false } : undefined,
31
36
  });