@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.
@@ -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
+ }
@@ -0,0 +1,48 @@
1
+ // scan/save.ts —— 把已确认的候选写进主机清单。连接测试由调用方先做。
2
+ import { randomUUID } from "node:crypto";
3
+ import type { HostFile, HostProfile, TransportKind } from "../core/types.js";
4
+
5
+ export interface HostCandidate {
6
+ name: string;
7
+ host: string;
8
+ user: string;
9
+ port?: number;
10
+ transport?: TransportKind | "auto";
11
+ privateKeyPath?: string;
12
+ secretRef?: string;
13
+ tags?: string[];
14
+ }
15
+
16
+ export type SaveChoice = "overwrite" | "rename" | "skip";
17
+
18
+ export function saveHostCandidate(file: HostFile, candidate: HostCandidate, choice: SaveChoice = "overwrite"): { file: HostFile; saved: boolean; name: string } {
19
+ let name = candidate.name;
20
+ if (file.hosts[name]) {
21
+ if (choice === "skip") return { file, saved: false, name };
22
+ if (choice === "rename") {
23
+ let suffix = 2;
24
+ while (file.hosts[`${candidate.name}-${suffix}`]) suffix += 1;
25
+ name = `${candidate.name}-${suffix}`;
26
+ }
27
+ }
28
+ const profile: HostProfile = {
29
+ id: file.hosts[name]?.id ?? randomUUID(),
30
+ name,
31
+ transport: candidate.transport ?? "auto",
32
+ host: candidate.host,
33
+ port: candidate.port,
34
+ user: candidate.user,
35
+ auth: {
36
+ kind: candidate.privateKeyPath ? "key" : "password",
37
+ privateKeyPath: candidate.privateKeyPath,
38
+ secretRef: candidate.privateKeyPath ? undefined : candidate.secretRef,
39
+ },
40
+ tags: candidate.tags,
41
+ createdAt: file.hosts[name]?.createdAt ?? new Date().toISOString(),
42
+ };
43
+ return {
44
+ saved: true,
45
+ name,
46
+ file: { ...file, hosts: { ...file.hosts, [name]: profile } },
47
+ };
48
+ }
@@ -0,0 +1,67 @@
1
+ // scan/ssh-config.ts —— 只解析 OpenSSH 的 Host 块。不猜项目文件。
2
+
3
+ export interface SshConfigHost {
4
+ name: string;
5
+ aliases: string[];
6
+ hostName?: string;
7
+ user?: string;
8
+ port?: number;
9
+ identityFile?: string;
10
+ proxyJump?: string;
11
+ /** 这些指令 ssh2 做不到,auto 传输要改走系统 ssh。 */
12
+ needsOpenSsh: boolean;
13
+ }
14
+
15
+ const OPENSSH_ONLY = new Set(["proxyjump", "proxycommand", "pkcs11provider", "securitykeyprovider"]);
16
+
17
+ function unquote(value: string): string {
18
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
19
+ return value.slice(1, -1).replace(/\\/g, "\\");
20
+ }
21
+ return value;
22
+ }
23
+
24
+ function tokens(line: string): string[] {
25
+ const values: string[] = [];
26
+ const pattern = /"(?:\\.|[^"\\])*"|\S+/g;
27
+ for (const match of line.matchAll(pattern)) values.push(unquote(match[0]));
28
+ return values;
29
+ }
30
+
31
+ function usable(pattern: string): boolean {
32
+ return pattern !== "*" && !/[*?]/.test(pattern);
33
+ }
34
+
35
+ /** 一个 Host 块有多个具体别名时拆成多条。通配和否定匹配不产出候选。 */
36
+ export function parseSshConfig(text: string): SshConfigHost[] {
37
+ const hosts: SshConfigHost[] = [];
38
+ let current: SshConfigHost | undefined;
39
+
40
+ for (const raw of text.split(/\r?\n/)) {
41
+ const line = raw.trim();
42
+ if (line === "" || line.startsWith("#")) continue;
43
+ const words = tokens(line);
44
+ const keyword = words[0]?.toLowerCase();
45
+ if (!keyword) continue;
46
+
47
+ if (keyword === "host") {
48
+ const aliases = words.slice(1).filter(usable);
49
+ current = undefined;
50
+ if (aliases.length === 0) continue;
51
+ current = { name: aliases[0], aliases, needsOpenSsh: false };
52
+ hosts.push(current);
53
+ continue;
54
+ }
55
+ if (!current) continue;
56
+
57
+ const value = words.slice(1).join(" ");
58
+ if (keyword === "hostname") current.hostName = value;
59
+ else if (keyword === "user") current.user = value;
60
+ else if (keyword === "port") current.port = Number(value);
61
+ else if (keyword === "identityfile" && !current.identityFile) current.identityFile = value;
62
+ else if (keyword === "proxyjump") current.proxyJump = value;
63
+ if (OPENSSH_ONLY.has(keyword)) current.needsOpenSsh = true;
64
+ }
65
+
66
+ return hosts;
67
+ }
@@ -0,0 +1,106 @@
1
+ // transports/ftp.ts —— FTP/FTPS 只有文件传输。没有远端 sha256。
2
+ import { createRequire } from "node:module";
3
+ import { statSync } from "node:fs";
4
+ import { TransferMismatchError, UnsupportedError, type HostProfile } from "../core/types.js";
5
+
6
+ const { Client } = createRequire(import.meta.url)("basic-ftp") as {
7
+ Client: new () => {
8
+ ftp: { verbose: boolean };
9
+ access(options: Record<string, unknown>): Promise<void>;
10
+ uploadFrom(local: string, remote: string, options?: { localStart?: number }): Promise<void>;
11
+ appendFrom(local: string, remote: string, options?: { localStart?: number }): Promise<void>;
12
+ downloadTo(local: string, remote: string): Promise<void>;
13
+ rename(from: string, to: string): Promise<void>;
14
+ size(path: string): Promise<number>;
15
+ list(path: string): Promise<Array<{ name: string; size: number; isDirectory: boolean }>>;
16
+ close(): void;
17
+ };
18
+ };
19
+
20
+ async function open(profile: HostProfile) {
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 里有这台主机的条目。");
27
+ const client = new Client();
28
+ const secure = profile.transport === "ftps" ? (profile.secure === "implicit" ? "implicit" : true) : false;
29
+ await client.access({
30
+ host: profile.host,
31
+ port: profile.port ?? (profile.secure === "implicit" ? 990 : 21),
32
+ user: profile.user,
33
+ password,
34
+ secure,
35
+ secureOptions: profile.insecure ? { rejectUnauthorized: false } : undefined,
36
+ });
37
+ return client;
38
+ }
39
+
40
+ export async function ftpPut(profile: HostProfile, localPath: string, remotePath: string, backup = false): Promise<{ bytes: number; backupPath?: string }> {
41
+ const client = await open(profile);
42
+ try {
43
+ const part = `${remotePath}.part`;
44
+ let start = 0;
45
+ try {
46
+ start = await client.size(part);
47
+ } catch {
48
+ start = 0;
49
+ }
50
+ if (start > 0) await client.appendFrom(localPath, part, { localStart: start });
51
+ else await client.uploadFrom(localPath, part);
52
+ const bytes = statSync(localPath).size;
53
+ const remoteBytes = await client.size(part);
54
+ if (remoteBytes !== bytes) throw new TransferMismatchError(`FTP 字节数不一致:本地 ${bytes},远端 ${remoteBytes}。${part} 保留,原文件未动`);
55
+ let backupPath: string | undefined;
56
+ if (backup) {
57
+ const stamp = `${remotePath}.bak.${Date.now()}`;
58
+ try {
59
+ await client.rename(remotePath, stamp);
60
+ backupPath = stamp;
61
+ } catch {
62
+ backupPath = undefined;
63
+ }
64
+ }
65
+ await client.rename(part, remotePath);
66
+ return { bytes, backupPath };
67
+ } finally {
68
+ client.close();
69
+ }
70
+ }
71
+
72
+ export async function ftpExists(profile: HostProfile, remotePath: string): Promise<boolean> {
73
+ const client = await open(profile);
74
+ try {
75
+ await client.size(remotePath);
76
+ return true;
77
+ } catch {
78
+ return false;
79
+ } finally {
80
+ client.close();
81
+ }
82
+ }
83
+
84
+ export async function ftpGet(profile: HostProfile, remotePath: string, localPath: string): Promise<{ bytes: number }> {
85
+ const client = await open(profile);
86
+ try {
87
+ await client.downloadTo(localPath, remotePath);
88
+ return { bytes: statSync(localPath).size };
89
+ } finally {
90
+ client.close();
91
+ }
92
+ }
93
+
94
+ export async function ftpList(profile: HostProfile, remotePath: string): Promise<Array<{ name: string; size: number; directory: boolean }>> {
95
+ const client = await open(profile);
96
+ try {
97
+ const entries = await client.list(remotePath);
98
+ return entries.map((entry) => ({ name: entry.name, size: entry.size, directory: entry.isDirectory }));
99
+ } finally {
100
+ client.close();
101
+ }
102
+ }
103
+
104
+ export function ftpExecRejected(): never {
105
+ throw new UnsupportedError("这台主机是 FTP/FTPS,只能传文件,不能执行命令。");
106
+ }
@@ -0,0 +1,283 @@
1
+ // transports/openssh.ts —— 调用本机 ssh。继承 ~/.ssh/config、代理跳转和密钥。
2
+ import { spawn } from "node:child_process";
3
+ import { chmodSync, mkdirSync, readFileSync, rmSync } from "node:fs";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { shellQuote, wrapWithWatchdog } from "../core/guard.js";
7
+ import { clipUtf8, parseRemoteHash, remoteHashCommand, sha256File } from "../core/hash.js";
8
+ import { TransferMismatchError, UnsupportedError, type HostProfile } from "../core/types.js";
9
+
10
+ export function controlPath(): string {
11
+ const dir = join(homedir(), ".pi", "agent", "ssh-cm");
12
+ mkdirSync(dir, { recursive: true });
13
+ chmodSync(dir, 0o700);
14
+ return join(dir, "%C");
15
+ }
16
+
17
+ /** ssh 与 sftp 共用的选项。`-i` 必须在这里,否则 sftp 走不到密钥认证。 */
18
+ function sshOptions(profile: HostProfile): string[] {
19
+ if (profile.auth.kind === "password") {
20
+ throw new UnsupportedError("openssh 传输不接受密码或 MFA。需要密码时改用 ssh2;ProxyJump、证书和 agent 继续走 openssh。");
21
+ }
22
+ const args = [
23
+ "-o", "BatchMode=yes",
24
+ "-o", "ControlMaster=auto",
25
+ "-o", `ControlPath=${controlPath()}`,
26
+ "-o", "ControlPersist=5m",
27
+ ];
28
+ if (profile.auth.privateKeyPath) args.push("-i", profile.auth.privateKeyPath);
29
+ return args;
30
+ }
31
+
32
+ /**
33
+ * sftp / scp 自己不会留下常驻 master(只有 ssh 会),
34
+ * 所以不先把 master 起起来,ControlPath 就是摆设,每次都重新握手。
35
+ * `-O check` 只碰本地 socket,不走网络,比一次握手便宜得多。
36
+ * 起 master 失败不当致命:后续 sftp 会自己握手,并报出自己的错。
37
+ */
38
+ async function ensureControlMaster(profile: HostProfile): Promise<void> {
39
+ const target = `${profile.user}@${profile.host}`;
40
+ const cp = controlPath();
41
+ const check = await runQuiet("ssh", ["-o", `ControlPath=${cp}`, "-O", "check", target]);
42
+ if (check.code === 0) return;
43
+ const started = await runQuiet("ssh", [
44
+ ...sshOptions(profile),
45
+ "-p", String(profile.port ?? 22),
46
+ "-f", "-N", target,
47
+ ]);
48
+ if (started.code !== 0) return;
49
+ masters.add(target);
50
+ }
51
+
52
+ function runQuiet(command: string, args: string[]): Promise<{ code: number | null; stderr: string }> {
53
+ return new Promise((resolve) => {
54
+ const child = spawn(command, args, { stdio: ["ignore", "ignore", "pipe"] });
55
+ let stderr = "";
56
+ child.stderr.on("data", (chunk: Buffer) => {
57
+ stderr += chunk.toString("utf8");
58
+ });
59
+ child.on("error", () => resolve({ code: -1, stderr }));
60
+ child.on("close", (code) => resolve({ code, stderr }));
61
+ });
62
+ }
63
+
64
+ const masters = new Set<string>();
65
+
66
+ /** 会话结束时把后台 master 收掉,不留 5 分钟的孤儿进程。 */
67
+ export async function closeControlMasters(): Promise<void> {
68
+ const targets = [...masters];
69
+ masters.clear();
70
+ await Promise.all(targets.map((target) => runQuiet("ssh", ["-o", `ControlPath=${controlPath()}`, "-O", "exit", target])));
71
+ }
72
+
73
+ /**
74
+ * 用 `sftp -b -` 跑一批命令,复用同一条 ControlMaster 连接,不另开握手。
75
+ * 退出码非 0 就报错,不默默返回半个结果。
76
+ */
77
+ async function sftpBatch(profile: HostProfile, commands: string[]): Promise<string> {
78
+ await ensureControlMaster(profile);
79
+ const args = [...sshOptions(profile), "-P", String(profile.port ?? 22), "-b", "-", `${profile.user}@${profile.host}`];
80
+ return new Promise((resolve, reject) => {
81
+ const child = spawn("sftp", args, { stdio: ["pipe", "pipe", "pipe"] });
82
+ let stdout = "";
83
+ let stderr = "";
84
+ child.stdin.end(`${commands.join("\n")}\n`);
85
+ child.stdout.on("data", (chunk: Buffer) => {
86
+ stdout += chunk.toString("utf8");
87
+ });
88
+ child.stderr.on("data", (chunk: Buffer) => {
89
+ stderr += chunk.toString("utf8");
90
+ });
91
+ child.on("error", reject);
92
+ child.on("close", (code) => {
93
+ if (code === 0) resolve(stdout);
94
+ else reject(new Error(stderr.trim() || `sftp 退出码 ${code}`));
95
+ });
96
+ });
97
+ }
98
+
99
+ /**
100
+ * 解 `sftp` 的 `ls -l` 输出。longname 是 SFTP 协议给的,不是 shell 的 ls:
101
+ * 首列是权限串,第 5 列是字节数,名字从第 9 列起(名字里可以有空格)。
102
+ */
103
+ export function parseSftpLongNames(output: string): Array<{ name: string; size: number; directory: boolean }> {
104
+ return output
105
+ .split("\n")
106
+ .map((line) => line.trim())
107
+ .filter((line) => /^[-dlbcps][rwxstT-]{9}/.test(line))
108
+ .map((line) => {
109
+ const fields = line.split(/\s+/);
110
+ return {
111
+ name: fields.slice(8).join(" "),
112
+ size: Number(fields[4]) || 0,
113
+ directory: line.startsWith("d"),
114
+ };
115
+ })
116
+ .filter((entry) => entry.name !== "" && entry.name !== "." && entry.name !== "..");
117
+ }
118
+
119
+ export async function listOpenSsh(profile: HostProfile, remotePath: string): Promise<Array<{ name: string; size: number; directory: boolean }>> {
120
+ const out = await sftpBatch(profile, [`ls -l ${shellQuote(remotePath)}`]);
121
+ return parseSftpLongNames(out);
122
+ }
123
+
124
+ /** 不解析远端文本:get 到本地临时文件,再按行切。 */
125
+ export async function readOpenSsh(profile: HostProfile, remotePath: string, offset = 1, limit = 200): Promise<string> {
126
+ const tmp = join(tmpdir(), `pi-ssh-read-${process.pid}-${Date.now()}`);
127
+ try {
128
+ await sftpBatch(profile, [`get ${shellQuote(remotePath)} ${shellQuote(tmp)}`]);
129
+ const whole = readFileSync(tmp, "utf8");
130
+ const maxBytes = 512 * 1024;
131
+ const picked: string[] = [];
132
+ let seen = 0;
133
+ let bytes = 0;
134
+ for (const line of whole.split("\n")) {
135
+ seen += 1;
136
+ if (seen < offset || picked.length >= limit) continue;
137
+ const room = maxBytes - bytes;
138
+ if (room <= 0) break;
139
+ const clipped = clipUtf8(line, room);
140
+ picked.push(clipped);
141
+ bytes += Buffer.byteLength(clipped) + 1;
142
+ if (clipped !== line) break;
143
+ }
144
+ return picked.join("\n");
145
+ } finally {
146
+ rmSync(tmp, { force: true });
147
+ }
148
+ }
149
+
150
+ /**
151
+ * OpenSSH 对老服务器会打一串 post-quantum 警告。它是 ssh 自己的提示,
152
+ * 不是命令的输出;合进结果里会让「退出码 0」看起来像出错。
153
+ */
154
+ export function stripSshNoise(text: string): string {
155
+ return text
156
+ .split(/\r?\n/)
157
+ .filter((line) => !/WARNING: connection is not using a post-quantum key exchange algorithm/.test(line))
158
+ .filter((line) => !/This session may be vulnerable to "store now, decrypt later" attacks/.test(line))
159
+ .filter((line) => !/The server may need to be upgraded\. See https:\/\/openssh\.com\/pq\.html/.test(line))
160
+ .join("\n");
161
+ }
162
+
163
+ export interface OpenSshRequest {
164
+ command: string;
165
+ cwd?: string;
166
+ timeoutMs?: number;
167
+ signal?: AbortSignal;
168
+ onData?: (chunk: string) => void;
169
+ }
170
+
171
+ export function execOpenSsh(profile: HostProfile, request: OpenSshRequest): Promise<{ stdout: string; stderr: string; exitCode: number | null; durationMs: number }> {
172
+ const remote = request.cwd ? `cd ${shellQuote(request.cwd)} && ${request.command}` : request.command;
173
+ const args = [
174
+ ...sshOptions(profile),
175
+ "-o", "ServerAliveInterval=30",
176
+ "-p", String(profile.port ?? 22),
177
+ ];
178
+ args.push("-l", profile.user, profile.host, wrapWithWatchdog(remote));
179
+ const started = Date.now();
180
+ return new Promise((resolve, reject) => {
181
+ // stdin 必须是 pipe 且不能 end():watchdog 脚本靠 `exec 3<&0` 拿一条通道,
182
+ // 通道 EOF 就当作「客户端放弃」立即 kill 命令。stdio 用 "ignore" 时 fd 0 是
183
+ // /dev/null,fd 3 立刻 EOF,命令会被自己的 watcher 秒杀(exit 143 + 空输出)。
184
+ const child = spawn("ssh", args, { stdio: ["pipe", "pipe", "pipe"] });
185
+ let stdout = "";
186
+ let stderr = "";
187
+ const timer = request.timeoutMs
188
+ ? setTimeout(() => child.kill("SIGTERM"), request.timeoutMs)
189
+ : undefined;
190
+ const abort = () => child.kill("SIGTERM");
191
+ request.signal?.addEventListener("abort", abort, { once: true });
192
+ child.stdout.on("data", (chunk: Buffer) => {
193
+ const text = chunk.toString("utf8");
194
+ stdout += text;
195
+ request.onData?.(text);
196
+ });
197
+ child.stderr.on("data", (chunk: Buffer) => {
198
+ stderr += chunk.toString("utf8");
199
+ });
200
+ child.on("error", (error) => {
201
+ clearTimeout(timer);
202
+ reject(error);
203
+ });
204
+ child.on("close", (code) => {
205
+ clearTimeout(timer);
206
+ request.signal?.removeEventListener("abort", abort);
207
+ resolve({ stdout, stderr: stripSshNoise(stderr), exitCode: code, durationMs: Date.now() - started });
208
+ });
209
+ });
210
+ }
211
+
212
+ export function copyOpenSsh(profile: HostProfile, direction: "put" | "get", localPath: string, remotePath: string): Promise<void> {
213
+ const remote = `${profile.user}@${profile.host}:${remotePath}`;
214
+ const args = ["-P", String(profile.port ?? 22), ...sshOptions(profile)];
215
+ if (direction === "put") args.push(localPath, remote);
216
+ else args.push(remote, localPath);
217
+ return ensureControlMaster(profile).then(() => new Promise<void>((resolve, reject) => {
218
+ // 同上:scp 也走同一套 ControlMaster,stdin 必须保持 pipe。
219
+ const child = spawn("scp", args, { stdio: ["pipe", "pipe", "pipe"] });
220
+ let stderr = "";
221
+ child.stderr.on("data", (chunk: Buffer) => {
222
+ stderr += chunk.toString("utf8");
223
+ });
224
+ child.on("error", reject);
225
+ child.on("close", (code) => {
226
+ if (code === 0) resolve();
227
+ else reject(new Error(stderr.trim() || `scp 退出码 ${code}`));
228
+ });
229
+ }));
230
+ }
231
+
232
+ /**
233
+ * scp 直接传到目标路径并做双端 sha256 校验,不额外加 `.part` 后缀。
234
+ * 部署场景自己就把目标定成了 `<releaseDir>.part`,这里再加一层会变成 `.part.part`。
235
+ */
236
+ export async function scpPutVerified(profile: HostProfile, localPath: string, remotePath: string, signal?: AbortSignal): Promise<{ bytes: number; sha256: string }> {
237
+ const local = await sha256File(localPath);
238
+ await copyOpenSsh(profile, "put", localPath, remotePath);
239
+ const checked = await execOpenSsh(profile, { command: remoteHashCommand(remotePath), signal });
240
+ const remote = parseRemoteHash(checked.stdout);
241
+ if (checked.exitCode !== 0 || remote !== local.hash) {
242
+ throw new TransferMismatchError(`sha256 不一致:本地 ${local.hash},远端 ${remote ?? "无"}。${remotePath} 保留,原文件未动`);
243
+ }
244
+ return { bytes: local.bytes, sha256: local.hash };
245
+ }
246
+
247
+ /**
248
+ * scp 下载后做双端 sha256 比对。scp 退出码 0 不代表内容完整,
249
+ * 传输中断、磁盘满、服务端限流都可能静默截断。
250
+ */
251
+ export async function getOpenSsh(profile: HostProfile, remotePath: string, localPath: string): Promise<{ bytes: number; sha256: string }> {
252
+ await copyOpenSsh(profile, "get", localPath, remotePath);
253
+ const local = await sha256File(localPath);
254
+ const checked = await execOpenSsh(profile, { command: remoteHashCommand(remotePath) });
255
+ const remote = parseRemoteHash(checked.stdout);
256
+ if (checked.exitCode !== 0 || remote !== local.hash) {
257
+ throw new TransferMismatchError(`下载后 sha256 不一致:本地 ${local.hash},远端 ${remote ?? "无"}。${localPath} 可能不完整`);
258
+ }
259
+ return { bytes: local.bytes, sha256: local.hash };
260
+ }
261
+
262
+ export async function putOpenSsh(profile: HostProfile, localPath: string, remotePath: string, backupPath?: string): Promise<{ bytes: number; sha256: string; backupPath?: string; backupCopied?: boolean }> {
263
+ const local = await sha256File(localPath);
264
+ const part = `${remotePath}.part`;
265
+ await copyOpenSsh(profile, "put", localPath, part);
266
+ const checked = await execOpenSsh(profile, { command: remoteHashCommand(part) });
267
+ const remote = parseRemoteHash(checked.stdout);
268
+ if (checked.exitCode !== 0 || remote !== local.hash) {
269
+ throw new TransferMismatchError(`sha256 不一致:本地 ${local.hash},远端 ${remote ?? "无"}。${part} 保留,原文件未动`);
270
+ }
271
+ let backupCopied = false;
272
+ if (backupPath) {
273
+ const source = shellQuote(remotePath);
274
+ const dest = shellQuote(backupPath);
275
+ // rename 只改目录项。跨文件系统时 mv 报 EXDEV,降级为复制。
276
+ const moved = await execOpenSsh(profile, { command: `if [ -e ${source} ]; then mv ${source} ${dest} || { mkdir -p $(dirname ${dest}) && cp -p ${source} ${dest} && rm -f ${source} && echo __COPIED__; }; fi` });
277
+ if (moved.exitCode !== 0) throw new TransferMismatchError(`备份失败:${moved.stderr || moved.stdout}`);
278
+ backupCopied = moved.stdout.includes("__COPIED__");
279
+ }
280
+ const renamed = await execOpenSsh(profile, { command: `mv ${shellQuote(part)} ${shellQuote(remotePath)}` });
281
+ if (renamed.exitCode !== 0) throw new TransferMismatchError(`转正失败:${renamed.stderr || renamed.stdout}`);
282
+ return { bytes: local.bytes, sha256: local.hash, backupPath, backupCopied };
283
+ }