@nsyan/ssh 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +10 -2
- package/index.ts +600 -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 +113 -0
- package/src/core/doctor.ts +76 -0
- package/src/core/guard.ts +139 -0
- package/src/core/hash.ts +39 -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 +782 -0
- package/src/scan/auto.ts +12 -0
- package/src/scan/project.ts +36 -0
- package/src/scan/save.ts +48 -0
- package/src/scan/ssh-config.ts +67 -0
- package/src/transports/ftp.ts +106 -0
- package/src/transports/openssh.ts +283 -0
- package/src/transports/ssh2.ts +549 -0
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
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, withinRoot } 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
|
+
AuthFailedError,
|
|
15
|
+
BoundsError,
|
|
16
|
+
ConfirmRejectedError,
|
|
17
|
+
HostKeyChangedError,
|
|
18
|
+
HostKeyUnknownError,
|
|
19
|
+
PolicyDeniedError,
|
|
20
|
+
UnsupportedError,
|
|
21
|
+
type HostFile,
|
|
22
|
+
type HostProfile,
|
|
23
|
+
} from "./core/types.js";
|
|
24
|
+
import { Ssh2Pool, type ConnectHooks } from "./transports/ssh2.js";
|
|
25
|
+
import { chooseTransport } from "./scan/auto.js";
|
|
26
|
+
import { copyOpenSsh, execOpenSsh, getOpenSsh, listOpenSsh, putOpenSsh, readOpenSsh, scpPutVerified } from "./transports/openssh.js";
|
|
27
|
+
import { ftpExecRejected, ftpExists, ftpGet, ftpList, ftpPut } from "./transports/ftp.js";
|
|
28
|
+
|
|
29
|
+
const OUTPUT_LIMIT = 50_000;
|
|
30
|
+
|
|
31
|
+
export interface ConfirmUi {
|
|
32
|
+
confirm(title: string, message: string): Promise<boolean>;
|
|
33
|
+
secret?(title: string, prompt: string): Promise<string | undefined>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface RuntimeOptions {
|
|
37
|
+
pool?: Ssh2Pool;
|
|
38
|
+
hosts?: () => HostFile;
|
|
39
|
+
auditPath?: string;
|
|
40
|
+
knownHostsPath?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function selectHost(file: HostFile, name?: string, allowActive = false): HostProfile {
|
|
44
|
+
const names = Object.keys(file.hosts);
|
|
45
|
+
if (name) {
|
|
46
|
+
const found = file.hosts[name];
|
|
47
|
+
if (!found) throw new PolicyDeniedError(`没有名为 ${name} 的主机。已有:${names.join("、") || "无"}`);
|
|
48
|
+
return found;
|
|
49
|
+
}
|
|
50
|
+
if (names.length === 1) return file.hosts[names[0]];
|
|
51
|
+
if (allowActive && file.activeHost && file.hosts[file.activeHost]) return file.hosts[file.activeHost];
|
|
52
|
+
if (names.length === 0) throw new PolicyDeniedError("还没有主机。先用 /ssh add 添加。");
|
|
53
|
+
throw new PolicyDeniedError(`已配置 ${names.length} 台主机,调用必须传 host:${names.join("、")}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function policyOf(file: HostFile): Policy {
|
|
57
|
+
return {
|
|
58
|
+
readonly: file.policy?.readonly === true,
|
|
59
|
+
confirm: file.policy?.confirm ?? "destructive",
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function withPassword(profile: HostProfile): HostProfile {
|
|
64
|
+
const ref = profile.auth.secretRef;
|
|
65
|
+
let next = profile;
|
|
66
|
+
if (profile.auth.kind === "password" && ref?.startsWith("file:")) {
|
|
67
|
+
const [file, name] = ref.slice("file:".length).split("#");
|
|
68
|
+
next = { ...next, auth: { ...next.auth, password: getSecret(file, name) } };
|
|
69
|
+
}
|
|
70
|
+
return next;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function keyType(blob: Buffer): string {
|
|
74
|
+
if (blob.length < 4) return "unknown";
|
|
75
|
+
const length = blob.readUInt32BE(0);
|
|
76
|
+
return blob.subarray(4, 4 + length).toString("utf8");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function tail(text: string, spillPath?: string): { text: string; truncated: boolean; spillPath?: string } {
|
|
80
|
+
const lines = text.split("\n");
|
|
81
|
+
if (!spillPath && text.length <= OUTPUT_LIMIT && lines.length <= 2000) return { text, truncated: false };
|
|
82
|
+
const path = spillPath ?? join(tmpdir(), `pi-ssh-${Date.now()}.log`);
|
|
83
|
+
if (!spillPath) {
|
|
84
|
+
mkdirSync(tmpdir(), { recursive: true });
|
|
85
|
+
writeFileSync(path, text);
|
|
86
|
+
}
|
|
87
|
+
const clipped = lines.slice(-2000).join("\n").slice(-OUTPUT_LIMIT);
|
|
88
|
+
return {
|
|
89
|
+
text: `${clipped}\n\n[输出已截断,全文在 ${path}]`,
|
|
90
|
+
truncated: true,
|
|
91
|
+
spillPath: path,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function boundedTimeoutMs(requested: number | undefined, fallback: number | undefined): number {
|
|
96
|
+
const seconds = requested ?? fallback ?? 120;
|
|
97
|
+
if (!Number.isFinite(seconds) || seconds <= 0) return 120_000;
|
|
98
|
+
return Math.min(3600, Math.floor(seconds)) * 1000;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function createRuntime(options: RuntimeOptions = {}) {
|
|
102
|
+
const pool = options.pool ?? new Ssh2Pool();
|
|
103
|
+
const hosts = options.hosts ?? loadHosts;
|
|
104
|
+
const auditPath = options.auditPath ?? defaultAuditPath();
|
|
105
|
+
const tunnels: Array<{ close: () => Promise<void> }> = [];
|
|
106
|
+
const grants = new Map<string, number>();
|
|
107
|
+
|
|
108
|
+
async function resolveProfile(profile: HostProfile): Promise<HostProfile> {
|
|
109
|
+
const ready = withPassword(profile);
|
|
110
|
+
const auth = ready.auth;
|
|
111
|
+
if (auth.passphraseRef?.startsWith("keychain:")) {
|
|
112
|
+
const passphrase = await platformKeychain().get("pi-ssh", auth.passphraseRef.slice("keychain:".length));
|
|
113
|
+
ready.auth = { ...ready.auth, passphrase };
|
|
114
|
+
} else if (auth.passphraseRef?.startsWith("file:")) {
|
|
115
|
+
const [file, name] = auth.passphraseRef.slice("file:".length).split("#");
|
|
116
|
+
ready.auth = { ...ready.auth, passphrase: getSecret(file, name) };
|
|
117
|
+
}
|
|
118
|
+
if (!auth.secretRef?.startsWith("keychain:")) return ready;
|
|
119
|
+
const account = auth.secretRef.slice("keychain:".length);
|
|
120
|
+
const secret = await platformKeychain().get("pi-ssh", account);
|
|
121
|
+
return { ...ready, auth: { ...ready.auth, password: secret } };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function connect(profile: HostProfile, acceptNewHostKey = false): Promise<{ fingerprint: string; keyType: string; auth: string }> {
|
|
125
|
+
const ready = await resolveProfile(profile);
|
|
126
|
+
const knownFile = options.knownHostsPath ?? join(process.env.HOME ?? "", ".ssh", "known_hosts");
|
|
127
|
+
let keyError: Error | undefined;
|
|
128
|
+
const identity = { fingerprint: "", keyType: "", auth: ready.auth.kind };
|
|
129
|
+
const hooks: ConnectHooks = {
|
|
130
|
+
verifyHostKey: (key) => {
|
|
131
|
+
const type = keyType(key);
|
|
132
|
+
const encoded = key.toString("base64");
|
|
133
|
+
identity.fingerprint = hostKeyFingerprint(key);
|
|
134
|
+
identity.keyType = type;
|
|
135
|
+
if (ready.strictHostKey === false) return true;
|
|
136
|
+
const status = checkHostKey(knownFile, ready.host, ready.port ?? 22, type, encoded);
|
|
137
|
+
if (status === "match") return true;
|
|
138
|
+
if (status === "unknown" && acceptNewHostKey) {
|
|
139
|
+
appendKnownHost(knownFile, ready.host, ready.port ?? 22, type, encoded);
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
keyError = status === "changed" || status === "revoked"
|
|
143
|
+
? new HostKeyChangedError(`主机密钥已变化或被吊销(${identity.fingerprint})。确认后用 ssh-keygen -R 删除旧记录。`)
|
|
144
|
+
: new HostKeyUnknownError(`主机密钥不在 known_hosts(${identity.fingerprint})。先用 ssh_hosts 的 test 并带 acceptNewHostKey 核对指纹。`);
|
|
145
|
+
return false;
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
await pool.connect(ready, hooks).catch((error: Error) => {
|
|
149
|
+
throw keyError ?? error;
|
|
150
|
+
});
|
|
151
|
+
// 连接复用时 hostVerifier 不会再跑,指纹要从池里取回来。
|
|
152
|
+
if (!identity.fingerprint) identity.fingerprint = pool.fingerprintOf(ready.id);
|
|
153
|
+
return identity;
|
|
154
|
+
}
|
|
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
|
+
|
|
183
|
+
function requireReason(host: HostProfile, danger: string, reason?: string): void {
|
|
184
|
+
if (isProdHost(host) && danger === "destructive" && !reason?.trim()) {
|
|
185
|
+
throw new PolicyDeniedError("生产主机的破坏性操作必须填写 reason,说明动机和影响范围。");
|
|
186
|
+
}
|
|
187
|
+
}
|
|
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
|
+
|
|
260
|
+
async function remoteLines(profileId: string, command: string, signal?: AbortSignal): Promise<string[]> {
|
|
261
|
+
const listed = await pool.exec(profileId, { command, timeoutMs: 120_000, signal });
|
|
262
|
+
return listed.stdout.split(/\n/).map((item) => item.trim()).filter(Boolean);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function checked(profileId: string, command: string, signal?: AbortSignal) {
|
|
266
|
+
const result = await pool.exec(profileId, { command, timeoutMs: 120_000, signal });
|
|
267
|
+
if (result.exitCode !== 0) {
|
|
268
|
+
throw new PolicyDeniedError(`远端命令失败(退出码 ${result.exitCode}):${result.stderr || result.stdout || command}`);
|
|
269
|
+
}
|
|
270
|
+
return result;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** 同一路径只留最近 3 份备份。删的范围限制在备份所在目录。 */
|
|
274
|
+
async function pruneBackups(runner: RemoteRunner, backupPath: string): Promise<void> {
|
|
275
|
+
const slash = backupPath.lastIndexOf("/");
|
|
276
|
+
if (slash < 0) return;
|
|
277
|
+
const dir = backupPath.slice(0, slash);
|
|
278
|
+
const name = backupPath.slice(slash + 1);
|
|
279
|
+
const stamp = name.lastIndexOf(".");
|
|
280
|
+
const stem = stamp > 0 ? name.slice(0, stamp) : name;
|
|
281
|
+
const names = await runner.lines(`ls -1 ${shellQuote(dir)} 2>/dev/null || true`);
|
|
282
|
+
for (const old of staleBackups(names, stem)) {
|
|
283
|
+
await runner.checked(`rm -f ${shellQuote(`${dir}/${old}`)}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function concrete(profile: HostProfile): HostProfile {
|
|
288
|
+
if (profile.transport !== "auto") return profile;
|
|
289
|
+
let text = "";
|
|
290
|
+
try {
|
|
291
|
+
text = readFileSync(join(homedir(), ".ssh", "config"), "utf8");
|
|
292
|
+
} catch {
|
|
293
|
+
text = "";
|
|
294
|
+
}
|
|
295
|
+
return { ...profile, transport: chooseTransport(profile, text) };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function ask(ui: ConfirmUi | undefined, title: string, message: string): Promise<void> {
|
|
299
|
+
if (!ui) throw new PolicyDeniedError("这次操作需要确认,但当前没有界面。");
|
|
300
|
+
const accepted = await ui.confirm(title, message);
|
|
301
|
+
if (!accepted) throw new ConfirmRejectedError("用户拒绝了这次操作,停止,不要换一种写法重试。");
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return {
|
|
305
|
+
pool,
|
|
306
|
+
async closeTunnels() {
|
|
307
|
+
const open = tunnels.splice(0);
|
|
308
|
+
grants.clear();
|
|
309
|
+
await Promise.all(open.map((item) => item.close()));
|
|
310
|
+
await pool.close();
|
|
311
|
+
},
|
|
312
|
+
grantWrite(hostName: string, minutes: number) {
|
|
313
|
+
const host = selectHost(hosts(), hostName);
|
|
314
|
+
if (isProdHost(host)) throw new PolicyDeniedError("生产主机不能授予会话级写授权。");
|
|
315
|
+
grants.set(host.id, Date.now() + minutes * 60_000);
|
|
316
|
+
},
|
|
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);
|
|
324
|
+
},
|
|
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 }) {
|
|
326
|
+
const file = hosts();
|
|
327
|
+
const host = concrete(selectHost(file, input.host, input.allowActive === true));
|
|
328
|
+
const verdict = classify(input.command);
|
|
329
|
+
requireReason(host, verdict.danger, input.reason);
|
|
330
|
+
const grant = grants.get(host.id);
|
|
331
|
+
const decision = decide(verdict, policyOf(file), host, grant ? { hostId: host.id, untilMs: grant } : null);
|
|
332
|
+
if (decision === "deny") throw new PolicyDeniedError(`只读模式拒绝这条${verdict.danger === "destructive" ? "破坏性" : "写"}命令:${verdict.summary}`);
|
|
333
|
+
if (host.transport === "ftp" || host.transport === "ftps") ftpExecRejected();
|
|
334
|
+
if (decision === "confirm") await ask(input.ui, `${host.name}:${verdict.summary}`, input.command);
|
|
335
|
+
if (isProdHost(host) && verdict.danger === "destructive") {
|
|
336
|
+
appendAudit(auditPath, {
|
|
337
|
+
host: host.name,
|
|
338
|
+
tool: "ssh_exec",
|
|
339
|
+
danger: verdict.danger,
|
|
340
|
+
summary: verdict.summary,
|
|
341
|
+
command: input.command,
|
|
342
|
+
reason: input.reason,
|
|
343
|
+
confirmed: decision === "confirm",
|
|
344
|
+
}, { required: true });
|
|
345
|
+
}
|
|
346
|
+
const command = input.waitFor ? `${input.command} && ${waitCommand(input.waitFor)}` : input.command;
|
|
347
|
+
const request = {
|
|
348
|
+
command,
|
|
349
|
+
cwd: input.cwd,
|
|
350
|
+
timeoutMs: boundedTimeoutMs(input.timeoutSec, host.defaults?.timeoutSec),
|
|
351
|
+
signal: input.signal,
|
|
352
|
+
onData: input.onData,
|
|
353
|
+
};
|
|
354
|
+
let result;
|
|
355
|
+
if (host.transport === "openssh") {
|
|
356
|
+
result = await execOpenSsh(host, request);
|
|
357
|
+
} else {
|
|
358
|
+
try {
|
|
359
|
+
await connect(host);
|
|
360
|
+
} catch (error) {
|
|
361
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
362
|
+
if (!/Not connected|ECONNRESET|EPIPE|closed/i.test(message)) throw error;
|
|
363
|
+
pool.discard(host.id);
|
|
364
|
+
await connect(host);
|
|
365
|
+
}
|
|
366
|
+
result = await pool.exec(host.id, request);
|
|
367
|
+
}
|
|
368
|
+
const spill = result && typeof result === "object" && "spillPath" in result && typeof result.spillPath === "string"
|
|
369
|
+
? result.spillPath
|
|
370
|
+
: undefined;
|
|
371
|
+
const output = tail(`${result.stdout}${result.stderr ? `\n${result.stderr}` : ""}`, spill);
|
|
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 };
|
|
389
|
+
},
|
|
390
|
+
async sudo(input: { host?: string; command: string; reason?: string; ui?: ConfirmUi }) {
|
|
391
|
+
const file = hosts();
|
|
392
|
+
const host = concrete(selectHost(file, input.host));
|
|
393
|
+
if (policyOf(file).readonly) throw new PolicyDeniedError("只读模式拒绝 sudo。");
|
|
394
|
+
if (host.transport === "openssh") throw new PolicyDeniedError("sudo 目前只走 ssh2 连接。");
|
|
395
|
+
const verdict = classify(input.command);
|
|
396
|
+
requireReason(host, verdict.danger, input.reason);
|
|
397
|
+
await ask(input.ui, `${host.name}:sudo ${verdict.summary}`, input.command);
|
|
398
|
+
const password = await input.ui?.secret?.(`${host.name} 的 sudo 密码`, "密码不进入对话记录");
|
|
399
|
+
if (!password) throw new ConfirmRejectedError("没有拿到 sudo 密码,已停止。");
|
|
400
|
+
appendAudit(auditPath, {
|
|
401
|
+
host: host.name,
|
|
402
|
+
tool: "ssh_sudo",
|
|
403
|
+
danger: verdict.danger,
|
|
404
|
+
summary: verdict.summary,
|
|
405
|
+
command: input.command,
|
|
406
|
+
stdin: password,
|
|
407
|
+
confirmed: true,
|
|
408
|
+
}, { required: isProdHost(host) && verdict.danger === "destructive" });
|
|
409
|
+
await connect(host);
|
|
410
|
+
const result = await pool.exec(host.id, {
|
|
411
|
+
command: input.command,
|
|
412
|
+
sudo: true,
|
|
413
|
+
stdin: password,
|
|
414
|
+
timeoutMs: boundedTimeoutMs(undefined, host.defaults?.timeoutSec),
|
|
415
|
+
});
|
|
416
|
+
const output = tail(`${result.stdout}${result.stderr ? `\n${result.stderr}` : ""}`, result.spillPath);
|
|
417
|
+
return { ...result, text: output.text, truncated: output.truncated, spillPath: output.spillPath };
|
|
418
|
+
},
|
|
419
|
+
async put(input: { host?: string; localPath: string; remotePath: string; ui?: ConfirmUi; onProgress?: (sent: number, total: number) => void }) {
|
|
420
|
+
const file = hosts();
|
|
421
|
+
const host = concrete(selectHost(file, input.host));
|
|
422
|
+
if (policyOf(file).readonly) throw new PolicyDeniedError("只读模式拒绝上传。");
|
|
423
|
+
const backupPath = backupLocation(input.remotePath, host.deploy?.root);
|
|
424
|
+
let exists = false;
|
|
425
|
+
if (host.transport === "ftp" || host.transport === "ftps") {
|
|
426
|
+
// FTP 也要走 resolveProfile:`file:...#name` 与 keychain 引用必须先换成明文。
|
|
427
|
+
const ready = await resolveProfile(host);
|
|
428
|
+
exists = await ftpExists(ready, input.remotePath);
|
|
429
|
+
if (isProdHost(host) || exists) {
|
|
430
|
+
await ask(input.ui, `${host.name}:上传${exists ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
|
|
431
|
+
}
|
|
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
|
+
});
|
|
444
|
+
return { bytes: result.bytes, sha256: "local-only", backupPath: result.backupPath };
|
|
445
|
+
}
|
|
446
|
+
if (host.transport === "openssh") {
|
|
447
|
+
exists = (await execOpenSsh(host, { command: `if [ -e ${shellQuote(input.remotePath)} ]; then echo yes; fi` })).stdout.includes("yes");
|
|
448
|
+
if (isProdHost(host) || exists) await ask(input.ui, `${host.name}:上传${exists ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
|
|
449
|
+
const result = await putOpenSsh(host, input.localPath, input.remotePath, exists ? backupPath : undefined);
|
|
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
|
+
});
|
|
462
|
+
return result;
|
|
463
|
+
}
|
|
464
|
+
await connect(host);
|
|
465
|
+
const listed = await pool.exec(host.id, { command: `if [ -e ${shellQuote(input.remotePath)} ]; then echo yes; fi` });
|
|
466
|
+
const overwrite = listed.stdout.includes("yes");
|
|
467
|
+
if (isProdHost(host) || overwrite) {
|
|
468
|
+
await ask(input.ui, `${host.name}:上传${overwrite ? "并覆盖" : ""}`, `${input.localPath} -> ${input.remotePath}`);
|
|
469
|
+
}
|
|
470
|
+
const result = await pool.put(host.id, { localPath: input.localPath, remotePath: input.remotePath, backupPath: overwrite ? backupPath : undefined, onProgress: input.onProgress });
|
|
471
|
+
if (overwrite && result.backupPath) await pruneBackups(poolRunner(host.id), result.backupPath);
|
|
472
|
+
appendAudit(auditPath, {
|
|
473
|
+
host: host.name,
|
|
474
|
+
tool: "ssh_put",
|
|
475
|
+
danger: "write",
|
|
476
|
+
summary: overwrite ? "覆盖远端文件" : "上传新文件",
|
|
477
|
+
command: `${input.localPath} -> ${input.remotePath}`,
|
|
478
|
+
confirmed: isProdHost(host) || overwrite,
|
|
479
|
+
bytes: result.bytes,
|
|
480
|
+
sha256: result.sha256,
|
|
481
|
+
backupPath: result.backupPath,
|
|
482
|
+
});
|
|
483
|
+
return result;
|
|
484
|
+
},
|
|
485
|
+
async list(input: { host?: string; path: string }) {
|
|
486
|
+
const host = concrete(selectHost(hosts(), input.host));
|
|
487
|
+
if (host.transport === "ftp" || host.transport === "ftps") {
|
|
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);
|
|
493
|
+
return entries.map((entry) => `${entry.directory ? "d" : "-"} ${entry.size}\t${entry.name}`).join("\n");
|
|
494
|
+
}
|
|
495
|
+
await connect(host);
|
|
496
|
+
const entries = await pool.list(host.id, input.path);
|
|
497
|
+
return entries.map((entry) => `${entry.directory ? "d" : "-"} ${entry.size}\t${entry.name}`).join("\n");
|
|
498
|
+
},
|
|
499
|
+
async read(input: { host?: string; path: string; offset?: number; limit?: number }) {
|
|
500
|
+
const host = concrete(selectHost(hosts(), input.host));
|
|
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);
|
|
506
|
+
}
|
|
507
|
+
await connect(host);
|
|
508
|
+
return pool.read(host.id, input.path, input.offset, input.limit);
|
|
509
|
+
},
|
|
510
|
+
async deploy(input: {
|
|
511
|
+
host?: string;
|
|
512
|
+
localPath: string;
|
|
513
|
+
kind?: "file" | "tar";
|
|
514
|
+
releaseId?: string;
|
|
515
|
+
dryRun?: boolean;
|
|
516
|
+
reason?: string;
|
|
517
|
+
signal?: AbortSignal;
|
|
518
|
+
onStep?: (message: string) => void;
|
|
519
|
+
ui?: ConfirmUi;
|
|
520
|
+
}) {
|
|
521
|
+
const file = hosts();
|
|
522
|
+
const host = concrete(selectHost(file, input.host));
|
|
523
|
+
if (policyOf(file).readonly) throw new PolicyDeniedError("只读模式拒绝部署。");
|
|
524
|
+
const layout = host.deploy;
|
|
525
|
+
if (!layout?.root) throw new PolicyDeniedError(`${host.name} 没有 deploy 布局。先在主机配置里写 root,不接受调用时临时给路径。`);
|
|
526
|
+
const signal = input.signal;
|
|
527
|
+
const releaseId = input.releaseId ?? releaseIdNow();
|
|
528
|
+
checkReleaseId(releaseId);
|
|
529
|
+
const fileName = input.localPath.split(/[\\/]/).pop() || "artifact";
|
|
530
|
+
const plan = planRelease(layout, releaseId, fileName);
|
|
531
|
+
const kind = input.kind ?? "tar";
|
|
532
|
+
const restartCmd = layout.restartCmd;
|
|
533
|
+
const healthCmd = layout.healthCmd;
|
|
534
|
+
requireReason(host, "destructive", input.reason);
|
|
535
|
+
if (input.dryRun) return { releaseId, current: plan.releaseDir, rolledBack: false, dryRun: true, plan };
|
|
536
|
+
const remote = await runnerFor(host, signal);
|
|
537
|
+
const step = (message: string) => input.onStep?.(message);
|
|
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`);
|
|
542
|
+
const keep = layout.keepReleases ?? 5;
|
|
543
|
+
const doomed = existing
|
|
544
|
+
.filter((item) => item !== releaseId && !previous.endsWith(`/${item}`))
|
|
545
|
+
.sort()
|
|
546
|
+
.slice(0, Math.max(0, existing.length + 1 - keep));
|
|
547
|
+
await ask(
|
|
548
|
+
input.ui,
|
|
549
|
+
`${host.name}:部署 ${releaseId}`,
|
|
550
|
+
[
|
|
551
|
+
`${input.localPath} -> ${plan.releaseDir}`,
|
|
552
|
+
`切换 ${plan.currentLink}`,
|
|
553
|
+
restartCmd ? `重启:${restartCmd}` : "没有重启命令",
|
|
554
|
+
healthCmd ? "健康检查失败会自动切回上一版,这一步不再次确认。" : "没有健康检查,失败不会自动回滚。",
|
|
555
|
+
doomed.length > 0 ? `将删除旧版本:${doomed.join("、")}` : "没有旧版本需要删除。",
|
|
556
|
+
"shared/ 不写入。",
|
|
557
|
+
].join("\n"),
|
|
558
|
+
);
|
|
559
|
+
appendAudit(auditPath, {
|
|
560
|
+
host: host.name,
|
|
561
|
+
tool: "ssh_deploy",
|
|
562
|
+
danger: "destructive",
|
|
563
|
+
summary: "部署开始",
|
|
564
|
+
command: `${input.localPath} -> ${plan.releaseDir}`,
|
|
565
|
+
confirmed: true,
|
|
566
|
+
}, { required: isProdHost(host) });
|
|
567
|
+
const bytes = statSync(input.localPath).size;
|
|
568
|
+
const factor = kind === "tar" ? 3 : 2;
|
|
569
|
+
const space = await remote.runner.checked(`df -Pk ${shellQuote(layout.root)} | awk 'NR==2 { print $4 }'`);
|
|
570
|
+
const freeKb = Number(space.stdout.trim());
|
|
571
|
+
if (!Number.isFinite(freeKb)) throw new PolicyDeniedError(`读不到 ${layout.root} 的剩余空间,取消部署。`);
|
|
572
|
+
if (freeKb * 1024 < bytes * factor) {
|
|
573
|
+
throw new PolicyDeniedError(`${layout.root} 剩余 ${freeKb}KB,小于制品的 ${factor} 倍,取消部署。`);
|
|
574
|
+
}
|
|
575
|
+
step("创建目录");
|
|
576
|
+
await remote.runner.checked(`mkdir -p ${shellQuote(plan.sharedDir)} ${shellQuote(plan.releaseDir)}`);
|
|
577
|
+
step(`上传 ${bytes} 字节`);
|
|
578
|
+
if (kind === "tar") {
|
|
579
|
+
await remote.put(input.localPath, plan.partPath);
|
|
580
|
+
const listed = await remote.runner.checked(`tar -tzf ${shellQuote(plan.partPath)}`);
|
|
581
|
+
const rejected = rejectArchiveMembers(listed.stdout.split(/\n/), plan.releaseDir);
|
|
582
|
+
if (rejected.length > 0) throw new BoundsError(`压缩包成员越界:${rejected.join(", ")}`);
|
|
583
|
+
await remote.runner.checked(`tar -xzf ${shellQuote(plan.partPath)} -C ${shellQuote(plan.releaseDir)} && rm -f ${shellQuote(plan.partPath)}`);
|
|
584
|
+
} else {
|
|
585
|
+
await remote.put(input.localPath, `${plan.releaseDir}/${fileName}`);
|
|
586
|
+
}
|
|
587
|
+
step("切换 current");
|
|
588
|
+
await remote.runner.checked(`ln -sfn ${shellQuote(plan.releaseDir)} ${shellQuote(plan.currentLink)}`);
|
|
589
|
+
let rolledBack = false;
|
|
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));
|
|
605
|
+
if (again.exitCode !== 0) {
|
|
606
|
+
const state = await remote.runner.tryRun(`readlink ${shellQuote(plan.currentLink)}`);
|
|
607
|
+
throw new PolicyDeniedError(
|
|
608
|
+
`已切回 ${previous},但健康检查仍然失败,两个版本都不健康。\n` +
|
|
609
|
+
`current -> ${state.stdout.trim() || "未知"}\n` +
|
|
610
|
+
`新版本 ${plan.releaseDir}:${detail}\n` +
|
|
611
|
+
`上一版本 ${previous}:${again.stdout}${again.stderr}` +
|
|
612
|
+
(restartAgain && restartAgain.exitCode !== 0 ? `\n回退时的重启命令也失败:${restartAgain.stderr || restartAgain.stdout}` : ""),
|
|
613
|
+
);
|
|
614
|
+
}
|
|
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 };
|
|
625
|
+
}
|
|
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
|
+
}
|
|
632
|
+
if (doomed.length > 0) {
|
|
633
|
+
step(`清理旧版本:${doomed.join("、")}`);
|
|
634
|
+
for (const old of doomed) {
|
|
635
|
+
checkReleaseId(old);
|
|
636
|
+
await remote.runner.checked(`rm -rf ${shellQuote(`${plan.releasesDir}/${old}`)}`);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
return { releaseId, current: rolledBack ? previous : plan.releaseDir, rolledBack };
|
|
640
|
+
},
|
|
641
|
+
async rollback(input: { host?: string; to?: string; file?: string; reason?: string; ui?: ConfirmUi }) {
|
|
642
|
+
const file = hosts();
|
|
643
|
+
const host = concrete(selectHost(file, input.host));
|
|
644
|
+
if (policyOf(file).readonly) throw new PolicyDeniedError("只读模式拒绝回滚。");
|
|
645
|
+
requireReason(host, "destructive", input.reason);
|
|
646
|
+
if (input.file) {
|
|
647
|
+
await ask(input.ui, `${host.name}:恢复文件`, input.file);
|
|
648
|
+
const remote = await runnerFor(host);
|
|
649
|
+
const quoted = shellQuote(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;
|
|
663
|
+
return { releaseId: "", current: input.file };
|
|
664
|
+
}
|
|
665
|
+
const root = host.deploy?.root;
|
|
666
|
+
if (!root) throw new PolicyDeniedError(`${host.name} 没有 deploy 布局,不能回滚 release。`);
|
|
667
|
+
const restartCmd = host.deploy?.restartCmd;
|
|
668
|
+
const healthCmd = host.deploy?.healthCmd;
|
|
669
|
+
const plan = planRelease(host.deploy!, input.to && input.to !== "previous" ? input.to : "placeholder", "artifact");
|
|
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
|
+
}
|
|
680
|
+
if (!target) throw new PolicyDeniedError("没有可回滚的上一版。");
|
|
681
|
+
if (target.endsWith(".part")) throw new PolicyDeniedError(`${target} 是上传中的 .part 残留,不是发布目录,不能回滚到它。`);
|
|
682
|
+
checkReleaseId(target);
|
|
683
|
+
const releaseDir = `${plan.releasesDir}/${target}`;
|
|
684
|
+
await ask(input.ui, `${host.name}:回滚到 ${target}`, [
|
|
685
|
+
`${plan.currentLink} -> ${releaseDir}`,
|
|
686
|
+
restartCmd ? `重启:${restartCmd}` : "没有重启命令",
|
|
687
|
+
healthCmd ? "回滚后跑健康检查;不通过会报出两个版本的状态。" : "没有健康检查,回滚后不会自动验证。",
|
|
688
|
+
].join("\n"));
|
|
689
|
+
appendAudit(auditPath, {
|
|
690
|
+
host: host.name,
|
|
691
|
+
tool: "ssh_rollback",
|
|
692
|
+
danger: "destructive",
|
|
693
|
+
summary: `回滚到 ${target}`,
|
|
694
|
+
command: releaseDir,
|
|
695
|
+
confirmed: true,
|
|
696
|
+
}, { required: isProdHost(host) });
|
|
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
|
+
}
|
|
709
|
+
return { releaseId: target, current: releaseDir };
|
|
710
|
+
},
|
|
711
|
+
async tunnel(input: { host?: string; listenPort: number; destHost: string; destPort: number; direction?: "local" | "remote"; ui?: ConfirmUi }) {
|
|
712
|
+
const host = concrete(selectHost(hosts(), input.host));
|
|
713
|
+
if (host.transport !== "ssh2") {
|
|
714
|
+
throw new PolicyDeniedError("端口转发目前只走 ssh2。");
|
|
715
|
+
}
|
|
716
|
+
if (!Number.isInteger(input.listenPort) || input.listenPort < 0 || input.listenPort > 65535) {
|
|
717
|
+
throw new PolicyDeniedError("listenPort 必须是 0 到 65535 的整数。0 表示由系统选空闲端口。");
|
|
718
|
+
}
|
|
719
|
+
await ask(
|
|
720
|
+
input.ui,
|
|
721
|
+
`${host.name}:端口转发`,
|
|
722
|
+
`本机 127.0.0.1:${input.listenPort || "自动"} -> ${input.destHost}:${input.destPort}`,
|
|
723
|
+
);
|
|
724
|
+
await connect(host);
|
|
725
|
+
const opened = input.direction === "remote"
|
|
726
|
+
? await pool.tunnelRemote(host.id, input.listenPort, input.destHost, input.destPort)
|
|
727
|
+
: await pool.tunnel(host.id, input.listenPort, input.destHost, input.destPort);
|
|
728
|
+
tunnels.push(opened);
|
|
729
|
+
appendAudit(auditPath, {
|
|
730
|
+
host: host.name,
|
|
731
|
+
tool: "ssh_tunnel",
|
|
732
|
+
danger: "write",
|
|
733
|
+
summary: "本地端口转发",
|
|
734
|
+
command: `127.0.0.1:${opened.port} -> ${input.destHost}:${input.destPort}`,
|
|
735
|
+
confirmed: true,
|
|
736
|
+
});
|
|
737
|
+
return opened;
|
|
738
|
+
},
|
|
739
|
+
async get(input: { host?: string; remotePath: string; localPath: string }) {
|
|
740
|
+
const host = concrete(selectHost(hosts(), input.host));
|
|
741
|
+
if (host.transport === "ftp" || host.transport === "ftps") {
|
|
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
|
+
});
|
|
752
|
+
return { bytes: result.bytes, sha256: "local-only" };
|
|
753
|
+
}
|
|
754
|
+
if (host.transport === "openssh") {
|
|
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;
|
|
767
|
+
}
|
|
768
|
+
await connect(host);
|
|
769
|
+
const result = await pool.get(host.id, { remotePath: input.remotePath, localPath: input.localPath });
|
|
770
|
+
appendAudit(auditPath, {
|
|
771
|
+
host: host.name,
|
|
772
|
+
tool: "ssh_get",
|
|
773
|
+
danger: "read",
|
|
774
|
+
summary: "下载远端文件",
|
|
775
|
+
command: `${input.remotePath} -> ${input.localPath}`,
|
|
776
|
+
bytes: result.bytes,
|
|
777
|
+
sha256: result.sha256,
|
|
778
|
+
});
|
|
779
|
+
return result;
|
|
780
|
+
},
|
|
781
|
+
};
|
|
782
|
+
}
|