@nsyan/ssh 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,50 @@
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 || candidate.secretRef?.startsWith("pending:")
39
+ ? undefined
40
+ : candidate.secretRef,
41
+ },
42
+ tags: candidate.tags,
43
+ createdAt: file.hosts[name]?.createdAt ?? new Date().toISOString(),
44
+ };
45
+ return {
46
+ saved: true,
47
+ name,
48
+ file: { ...file, hosts: { ...file.hosts, [name]: profile } },
49
+ };
50
+ }
@@ -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,101 @@
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
+ const client = new Client();
23
+ const secure = profile.transport === "ftps" ? (profile.secure === "implicit" ? "implicit" : true) : false;
24
+ await client.access({
25
+ host: profile.host,
26
+ port: profile.port ?? (profile.secure === "implicit" ? 990 : 21),
27
+ user: profile.user,
28
+ password: profile.auth.secretRef,
29
+ secure,
30
+ secureOptions: profile.insecure ? { rejectUnauthorized: false } : undefined,
31
+ });
32
+ return client;
33
+ }
34
+
35
+ export async function ftpPut(profile: HostProfile, localPath: string, remotePath: string, backup = false): Promise<{ bytes: number; backupPath?: string }> {
36
+ const client = await open(profile);
37
+ try {
38
+ const part = `${remotePath}.part`;
39
+ let start = 0;
40
+ try {
41
+ start = await client.size(part);
42
+ } catch {
43
+ start = 0;
44
+ }
45
+ if (start > 0) await client.appendFrom(localPath, part, { localStart: start });
46
+ else await client.uploadFrom(localPath, part);
47
+ const bytes = statSync(localPath).size;
48
+ const remoteBytes = await client.size(part);
49
+ if (remoteBytes !== bytes) throw new TransferMismatchError(`FTP 字节数不一致:本地 ${bytes},远端 ${remoteBytes}。${part} 保留,原文件未动`);
50
+ let backupPath: string | undefined;
51
+ if (backup) {
52
+ const stamp = `${remotePath}.bak.${Date.now()}`;
53
+ try {
54
+ await client.rename(remotePath, stamp);
55
+ backupPath = stamp;
56
+ } catch {
57
+ backupPath = undefined;
58
+ }
59
+ }
60
+ await client.rename(part, remotePath);
61
+ return { bytes, backupPath };
62
+ } finally {
63
+ client.close();
64
+ }
65
+ }
66
+
67
+ export async function ftpExists(profile: HostProfile, remotePath: string): Promise<boolean> {
68
+ const client = await open(profile);
69
+ try {
70
+ await client.size(remotePath);
71
+ return true;
72
+ } catch {
73
+ return false;
74
+ } finally {
75
+ client.close();
76
+ }
77
+ }
78
+
79
+ export async function ftpGet(profile: HostProfile, remotePath: string, localPath: string): Promise<{ bytes: number }> {
80
+ const client = await open(profile);
81
+ try {
82
+ await client.downloadTo(localPath, remotePath);
83
+ return { bytes: statSync(localPath).size };
84
+ } finally {
85
+ client.close();
86
+ }
87
+ }
88
+
89
+ export async function ftpList(profile: HostProfile, remotePath: string): Promise<Array<{ name: string; size: number; directory: boolean }>> {
90
+ const client = await open(profile);
91
+ try {
92
+ const entries = await client.list(remotePath);
93
+ return entries.map((entry) => ({ name: entry.name, size: entry.size, directory: entry.isDirectory }));
94
+ } finally {
95
+ client.close();
96
+ }
97
+ }
98
+
99
+ export function ftpExecRejected(): never {
100
+ throw new UnsupportedError("这台主机是 FTP/FTPS,只能传文件,不能执行命令。");
101
+ }
@@ -0,0 +1,109 @@
1
+ // transports/openssh.ts —— 调用本机 ssh。继承 ~/.ssh/config、代理跳转和密钥。
2
+ import { spawn } from "node:child_process";
3
+ import { chmodSync, mkdirSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { shellQuote, wrapWithWatchdog } from "../core/guard.js";
7
+ import { 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
+ function sshOptions(profile: HostProfile): string[] {
18
+ if (profile.auth.kind === "password") {
19
+ throw new UnsupportedError("openssh 传输不接受密码或 MFA。需要密码时改用 ssh2;ProxyJump、证书和 agent 继续走 openssh。");
20
+ }
21
+ return [
22
+ "-o", "BatchMode=yes",
23
+ "-o", "ControlMaster=auto",
24
+ "-o", `ControlPath=${controlPath()}`,
25
+ "-o", "ControlPersist=5m",
26
+ ];
27
+ }
28
+
29
+ export interface OpenSshRequest {
30
+ command: string;
31
+ cwd?: string;
32
+ timeoutMs?: number;
33
+ signal?: AbortSignal;
34
+ }
35
+
36
+ export function execOpenSsh(profile: HostProfile, request: OpenSshRequest): Promise<{ stdout: string; stderr: string; exitCode: number | null; durationMs: number }> {
37
+ const remote = request.cwd ? `cd ${shellQuote(request.cwd)} && ${request.command}` : request.command;
38
+ const args = [
39
+ ...sshOptions(profile),
40
+ "-o", "ServerAliveInterval=30",
41
+ "-p", String(profile.port ?? 22),
42
+ ];
43
+ if (profile.auth.privateKeyPath) args.push("-i", profile.auth.privateKeyPath);
44
+ args.push("-l", profile.user, profile.host, wrapWithWatchdog(remote));
45
+ const started = Date.now();
46
+ return new Promise((resolve, reject) => {
47
+ const child = spawn("ssh", args, { stdio: ["ignore", "pipe", "pipe"] });
48
+ let stdout = "";
49
+ let stderr = "";
50
+ const timer = request.timeoutMs
51
+ ? setTimeout(() => child.kill("SIGTERM"), request.timeoutMs)
52
+ : undefined;
53
+ const abort = () => child.kill("SIGTERM");
54
+ request.signal?.addEventListener("abort", abort, { once: true });
55
+ child.stdout.on("data", (chunk: Buffer) => {
56
+ stdout += chunk.toString("utf8");
57
+ });
58
+ child.stderr.on("data", (chunk: Buffer) => {
59
+ stderr += chunk.toString("utf8");
60
+ });
61
+ child.on("error", (error) => {
62
+ clearTimeout(timer);
63
+ reject(error);
64
+ });
65
+ child.on("close", (code) => {
66
+ clearTimeout(timer);
67
+ request.signal?.removeEventListener("abort", abort);
68
+ resolve({ stdout, stderr, exitCode: code, durationMs: Date.now() - started });
69
+ });
70
+ });
71
+ }
72
+
73
+ export function copyOpenSsh(profile: HostProfile, direction: "put" | "get", localPath: string, remotePath: string): Promise<void> {
74
+ const remote = `${profile.user}@${profile.host}:${remotePath}`;
75
+ const args = ["-P", String(profile.port ?? 22), ...sshOptions(profile)];
76
+ if (profile.auth.privateKeyPath) args.push("-i", profile.auth.privateKeyPath);
77
+ if (direction === "put") args.push(localPath, remote);
78
+ else args.push(remote, localPath);
79
+ return new Promise((resolve, reject) => {
80
+ const child = spawn("scp", args, { stdio: ["ignore", "pipe", "pipe"] });
81
+ let stderr = "";
82
+ child.stderr.on("data", (chunk: Buffer) => {
83
+ stderr += chunk.toString("utf8");
84
+ });
85
+ child.on("error", reject);
86
+ child.on("close", (code) => {
87
+ if (code === 0) resolve();
88
+ else reject(new Error(stderr.trim() || `scp 退出码 ${code}`));
89
+ });
90
+ });
91
+ }
92
+
93
+ export async function putOpenSsh(profile: HostProfile, localPath: string, remotePath: string, backupPath?: string): Promise<{ bytes: number; sha256: string; backupPath?: string }> {
94
+ const local = await sha256File(localPath);
95
+ const part = `${remotePath}.part`;
96
+ await copyOpenSsh(profile, "put", localPath, part);
97
+ const checked = await execOpenSsh(profile, { command: remoteHashCommand(part) });
98
+ const remote = parseRemoteHash(checked.stdout);
99
+ if (checked.exitCode !== 0 || remote !== local.hash) {
100
+ throw new TransferMismatchError(`sha256 不一致:本地 ${local.hash},远端 ${remote ?? "无"}。${part} 保留,原文件未动`);
101
+ }
102
+ if (backupPath) {
103
+ const moved = await execOpenSsh(profile, { command: `if [ -e ${shellQuote(remotePath)} ]; then mv ${shellQuote(remotePath)} ${shellQuote(backupPath)}; fi` });
104
+ if (moved.exitCode !== 0) throw new TransferMismatchError(`备份失败:${moved.stderr || moved.stdout}`);
105
+ }
106
+ const renamed = await execOpenSsh(profile, { command: `mv ${shellQuote(part)} ${shellQuote(remotePath)}` });
107
+ if (renamed.exitCode !== 0) throw new TransferMismatchError(`转正失败:${renamed.stderr || renamed.stdout}`);
108
+ return { bytes: local.bytes, sha256: local.hash, backupPath };
109
+ }