@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/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@nsyan/ssh",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "AI 远程运维扩展 for pi coding agent:SSH/SFTP/FTP 主机管理、危险命令确认、审计与可回滚部署 | Remote ops for the pi agent: SSH, SFTP and FTP with confirmation, audit and rollback",
5
+ "keywords": [
6
+ "pi-extension",
7
+ "pi-package",
8
+ "pi",
9
+ "pi-coding-agent",
10
+ "ssh",
11
+ "sftp",
12
+ "ftp",
13
+ "scp",
14
+ "remote",
15
+ "devops",
16
+ "deploy",
17
+ "rollback"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/nsyan/pi-plugins.git"
22
+ },
23
+ "license": "MIT",
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "type": "module",
28
+ "main": "index.ts",
29
+ "pi": {
30
+ "extensions": [
31
+ "./index.ts"
32
+ ],
33
+ "skills": [
34
+ "./skills"
35
+ ]
36
+ },
37
+ "files": [
38
+ "index.ts",
39
+ "src/",
40
+ "skills/",
41
+ "README.md",
42
+ "LICENSE"
43
+ ],
44
+ "scripts": {
45
+ "test": "tsx --test \"test/**/*.test.ts\"",
46
+ "typecheck": "tsc -p tsconfig.typecheck.json"
47
+ },
48
+ "peerDependencies": {
49
+ "@earendil-works/pi-coding-agent": "*",
50
+ "typebox": "*"
51
+ },
52
+ "devDependencies": {
53
+ "@earendil-works/pi-coding-agent": "^0.85.1",
54
+ "@types/node": "^22.20.2",
55
+ "@types/ssh2": "^1.15.5",
56
+ "tsx": "^4.23.13",
57
+ "typebox": "^1.3.27",
58
+ "typescript": "^7.0.2"
59
+ },
60
+ "dependencies": {
61
+ "basic-ftp": "^5.0.5",
62
+ "ssh2": "^1.17.0"
63
+ }
64
+ }
@@ -0,0 +1,8 @@
1
+ # 部署
2
+
3
+ 能走 ssh_deploy 的发布不要用 ssh_exec 拼 rm 或 docker rm。
4
+
5
+ - 先 dryRun 看剧本,再真正部署。
6
+ - 只使用主机配置里的 deploy 布局。不要在调用时临时传 root、restartCmd 或 healthCmd。
7
+ - 生产主机必须带 reason。
8
+ - 健康检查失败会自动切回上一版。
@@ -0,0 +1,7 @@
1
+ # 远端操作
2
+
3
+ 连上主机后再排查。已配置两台及以上时,每个 ssh_* 调用都要带 host。
4
+
5
+ - 先用 ssh_ls、ssh_read 和只读的 ssh_exec。
6
+ - 用户拒绝后不要改写命令再试。
7
+ - 需要 root 用 ssh_sudo,不要把密码写进命令。
@@ -0,0 +1,74 @@
1
+ // core/audit.ts —— 追加 JSONL。stdin 永不落明文。单文件超过 1MB 就滚动,只保留最近 7 份归档。
2
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join } from "node:path";
5
+ import { AuditUnavailableError } from "./types.js";
6
+
7
+ const MAX_AUDIT_BYTES = 1024 * 1024;
8
+ const MAX_AUDIT_ARCHIVES = 7;
9
+
10
+ export interface AuditEntry {
11
+ ts?: string;
12
+ host: string;
13
+ tool: string;
14
+ danger?: string;
15
+ summary?: string;
16
+ command?: string;
17
+ stdin?: string;
18
+ confirmed?: boolean;
19
+ reason?: string;
20
+ exitCode?: number | null;
21
+ durationMs?: number;
22
+ [key: string]: unknown;
23
+ }
24
+
25
+ export function defaultAuditPath(): string {
26
+ return join(homedir(), ".pi", "agent", "ssh-audit.jsonl");
27
+ }
28
+
29
+ export function redact(entry: AuditEntry): Record<string, unknown> {
30
+ const out: Record<string, unknown> = { ...entry, ts: entry.ts ?? new Date().toISOString() };
31
+ if (entry.stdin !== undefined) out.stdin = "<redacted>";
32
+ return out;
33
+ }
34
+
35
+ export function appendAudit(
36
+ file: string,
37
+ entry: AuditEntry,
38
+ opts?: { required?: boolean; maxBytes?: number; keep?: number },
39
+ ): void {
40
+ const line = JSON.stringify(redact(entry)) + "\n";
41
+ try {
42
+ mkdirSync(dirname(file), { recursive: true });
43
+ rotateAudit(file, opts?.maxBytes ?? MAX_AUDIT_BYTES, opts?.keep ?? MAX_AUDIT_ARCHIVES);
44
+ appendFileSync(file, line, { mode: 0o600 });
45
+ chmodSync(file, 0o600);
46
+ } catch (error) {
47
+ if (opts?.required) {
48
+ const message = error instanceof Error ? error.message : String(error);
49
+ throw new AuditUnavailableError(`审计日志不可写:${message}`);
50
+ }
51
+ }
52
+ }
53
+
54
+ function rotateAudit(file: string, maxBytes: number, keep: number): void {
55
+ if (!existsSync(file) || statSync(file).size < maxBytes) return;
56
+ const stamp = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
57
+ const archive = file.replace(/\.jsonl$/, `.${stamp}.jsonl`);
58
+ renameSync(file, archive);
59
+ chmodSync(archive, 0o600);
60
+ const prefix = `${basename(file, ".jsonl")}.`;
61
+ const old = readdirSync(dirname(file))
62
+ .filter((name) => name.startsWith(prefix) && name.endsWith(".jsonl"))
63
+ .map((name) => join(dirname(file), name))
64
+ .sort((a, b) => statSync(a).mtimeMs - statSync(b).mtimeMs);
65
+ for (const path of old.slice(0, Math.max(0, old.length - keep))) unlinkSync(path);
66
+ }
67
+
68
+ export function readAudit(file = defaultAuditPath()): Record<string, unknown>[] {
69
+ if (!existsSync(file)) return [];
70
+ return readFileSync(file, "utf8")
71
+ .split("\n")
72
+ .filter((line) => line.trim() !== "")
73
+ .map((line) => JSON.parse(line) as Record<string, unknown>);
74
+ }
@@ -0,0 +1,47 @@
1
+ // core/config.ts —— 主机配置。0600、原子写、按 mtime 缓存。不依赖 pi。
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ import { EMPTY_HOST_FILE, type HostFile } from "./types.js";
6
+
7
+ export function defaultConfigPath(): string {
8
+ return join(homedir(), ".pi", "agent", "ssh-hosts.json");
9
+ }
10
+
11
+ const cache = new Map<string, { mtimeMs: number; size: number; data: HostFile }>();
12
+
13
+ export function clearConfigCache(): void {
14
+ cache.clear();
15
+ }
16
+
17
+ export function loadHosts(file = defaultConfigPath()): HostFile {
18
+ if (!existsSync(file)) return structuredClone(EMPTY_HOST_FILE);
19
+ const stat = statSync(file);
20
+ const hit = cache.get(file);
21
+ if (hit && hit.mtimeMs === stat.mtimeMs && hit.size === stat.size) return structuredClone(hit.data);
22
+ try {
23
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as Partial<HostFile>;
24
+ const data: HostFile = {
25
+ hosts: parsed.hosts && typeof parsed.hosts === "object" ? parsed.hosts : {},
26
+ activeHost: typeof parsed.activeHost === "string" ? parsed.activeHost : undefined,
27
+ policy: parsed.policy,
28
+ };
29
+ cache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, data });
30
+ return structuredClone(data);
31
+ } catch {
32
+ return structuredClone(EMPTY_HOST_FILE);
33
+ }
34
+ }
35
+
36
+ export function saveHosts(file: string, data: HostFile): void {
37
+ const next = JSON.stringify(data, null, 2) + "\n";
38
+ if (existsSync(file) && readFileSync(file, "utf8") === next) return;
39
+ mkdirSync(dirname(file), { recursive: true });
40
+ const tmp = `${file}.${process.pid}.tmp`;
41
+ writeFileSync(tmp, next, { mode: 0o600 });
42
+ chmodSync(tmp, 0o600);
43
+ renameSync(tmp, file);
44
+ chmodSync(file, 0o600);
45
+ const stat = statSync(file);
46
+ cache.set(file, { mtimeMs: stat.mtimeMs, size: stat.size, data: structuredClone(data) });
47
+ }
@@ -0,0 +1,113 @@
1
+ // core/deploy.ts —— 发布路径和压缩包成员检查。只判断,不连远端。
2
+ import { withinRoot } from "./guard.js";
3
+
4
+ export interface ReleaseLayout {
5
+ root: string;
6
+ releasesDir?: string;
7
+ currentLink?: string;
8
+ sharedDir?: string;
9
+ }
10
+
11
+ export interface ReleasePlan {
12
+ releaseDir: string;
13
+ releasesDir: string;
14
+ currentLink: string;
15
+ sharedDir: string;
16
+ partPath: string;
17
+ }
18
+
19
+ function clean(value: string): string {
20
+ return value.replace(/^\/+|\/+$/g, "");
21
+ }
22
+
23
+ export function planRelease(layout: ReleaseLayout, releaseId: string, fileName: string): ReleasePlan {
24
+ const releases = clean(layout.releasesDir ?? "releases");
25
+ const current = clean(layout.currentLink ?? "current");
26
+ const shared = clean(layout.sharedDir ?? "shared");
27
+ const releaseDir = `${layout.root}/${releases}/${releaseId}`;
28
+ assertInside(layout.root, [releaseDir, `${layout.root}/${current}`, `${layout.root}/${shared}`]);
29
+ return {
30
+ releaseDir,
31
+ releasesDir: `${layout.root}/${releases}`,
32
+ currentLink: `${layout.root}/${current}`,
33
+ sharedDir: `${layout.root}/${shared}`,
34
+ partPath: `${releaseDir}.part`,
35
+ };
36
+ }
37
+
38
+ /** 部署根内的文件收进 .pi-ssh-backup,其余放在同目录的 .bak。 */
39
+ export function backupLocation(remotePath: string, root?: string, stamp = Date.now()): string {
40
+ if (root && withinRoot(root, remotePath)) {
41
+ return `${root}/.pi-ssh-backup/${remotePath.slice(root.length + 1)}.${stamp}`;
42
+ }
43
+ return `${remotePath}.bak.${stamp}`;
44
+ }
45
+
46
+ /** 同一路径只留最近 keep 份。返回要删的文件名,不含目录。 */
47
+ export function staleBackups(names: string[], fileName: string, keep = 3): string[] {
48
+ const mine = names.filter((name) => {
49
+ const mark = name.lastIndexOf(".");
50
+ if (mark <= 0) return false;
51
+ const stamp = name.slice(mark + 1);
52
+ const stem = name.slice(0, mark);
53
+ if (!/^\d+$/.test(stamp)) return false;
54
+ return stem === fileName || stem === `${fileName}.bak`;
55
+ });
56
+ return mine.sort().slice(0, Math.max(0, mine.length - keep));
57
+ }
58
+
59
+ /** 健康检查的预算(秒)。在这个窗口内反复跑,退出码 0 即通过。 */
60
+ export const HEALTH_BUDGET_SEC = 60;
61
+
62
+ /**
63
+ * 把 healthCmd 包成远端循环,一次往返。
64
+ * 最后一轮的输出保留在 stdout,失败时能看到原因。
65
+ */
66
+ export function healthLoopCommand(healthCmd: string, timeoutSec = HEALTH_BUDGET_SEC): string {
67
+ const ticks = Math.max(1, Math.floor(timeoutSec));
68
+ return [
69
+ `i=0; while [ "$i" -lt ${ticks} ]; do`,
70
+ ` if { ${healthCmd}; } >/dev/null 2>&1; then exit 0; fi`,
71
+ " i=$((i+1))",
72
+ ` [ "$i" -lt ${ticks} ] && sleep 1`,
73
+ "done",
74
+ healthCmd,
75
+ "exit 1",
76
+ ].join("\n");
77
+ }
78
+
79
+ /**
80
+ * 压缩包里任一成员逃出目标目录,整包拒绝。绝对路径和 `..` 都算逃逸。
81
+ * 空行必须在这里滤掉:`tar -tzf` 的输出总以换行结尾,split 之后最后一项是空串,
82
+ * 当成成员会让任何一个合法压缩包都被判越界。
83
+ */
84
+ export function rejectArchiveMembers(members: string[], destination: string): string[] {
85
+ return members
86
+ .map((member) => member.trim())
87
+ .filter((value) => value !== "")
88
+ .filter((value) => {
89
+ if (value.startsWith("/") || value.includes("\\")) return true;
90
+ return !withinRoot(destination, `${destination}/${value}`) && normalizeMember(value) !== "";
91
+ });
92
+ }
93
+
94
+ function normalizeMember(value: string): string {
95
+ return value
96
+ .split("/")
97
+ .filter((part) => part !== "" && part !== ".")
98
+ .join("/");
99
+ }
100
+
101
+ export function releaseIdNow(date = new Date()): string {
102
+ return date.toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-");
103
+ }
104
+
105
+ export function checkReleaseId(releaseId: string): void {
106
+ if (!/^[A-Za-z0-9._-]{1,80}$/.test(releaseId)) throw new Error(`发布号只能包含字母、数字、点、下划线和横线:${releaseId}`);
107
+ }
108
+
109
+ function assertInside(root: string, paths: string[]): void {
110
+ for (const path of paths) {
111
+ if (!withinRoot(root, path)) throw new Error(`发布路径越出部署根目录:${path}`);
112
+ }
113
+ }
@@ -0,0 +1,76 @@
1
+ // core/doctor.ts —— 本机能力体检。不连接远端。
2
+ import { accessSync, constants } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { homedir } from "node:os";
5
+ import { delimiter, join } from "node:path";
6
+
7
+ function ok(path: string, mode: number): boolean {
8
+ try {
9
+ accessSync(path, mode);
10
+ return true;
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+
16
+ /**
17
+ * 按 PATH 找可执行文件,和 spawn 用裸命令名时的查找方式一致。
18
+ * 不能写死 /usr/bin:Homebrew、/usr/local/bin、NixOS 都不在那里,
19
+ * 写死会把实际可用的 ssh 报成不可用。
20
+ */
21
+ export function which(command: string, env: NodeJS.ProcessEnv = process.env): string | undefined {
22
+ const path = env.PATH ?? env.Path ?? "";
23
+ for (const dir of path.split(delimiter)) {
24
+ if (!dir) continue;
25
+ const candidate = join(dir, command);
26
+ if (ok(candidate, constants.X_OK)) return candidate;
27
+ }
28
+ return undefined;
29
+ }
30
+
31
+ /** openssh 传输依赖这三个:ssh 跑命令,scp 传文件,sftp 列目录和按行读。 */
32
+ function opensshLines(): string[] {
33
+ const found = ["ssh", "scp", "sftp"].map((name) => ({ name, path: which(name) }));
34
+ const missing = found.filter((item) => !item.path).map((item) => item.name);
35
+ if (missing.length === 0) {
36
+ return [`本机 openssh 可用(${found.map((item) => item.path).join("、")})`];
37
+ }
38
+ const present = found.filter((item) => item.path);
39
+ return [
40
+ `PATH 里缺 ${missing.join("、")},openssh 传输不可用${present.length > 0 ? `(只找到 ${present.map((item) => item.path).join("、")})` : ""}。` +
41
+ "需要 ProxyJump、证书或 ssh-agent 时请装上,否则把主机的 transport 设成 ssh2。",
42
+ ];
43
+ }
44
+
45
+ function keychainLine(): string {
46
+ if (process.platform === "linux") {
47
+ const tool = which("secret-tool");
48
+ return tool
49
+ ? `钥匙串可读写(${tool})`
50
+ : "没有 secret-tool,密码只进 0600 的 ssh-secrets.json";
51
+ }
52
+ if (process.platform === "darwin") {
53
+ const tool = which("security");
54
+ return tool
55
+ ? `钥匙串可读取已有项(${tool});新密码不进 security 的进程参数,写入 0600 的 ssh-secrets.json`
56
+ : "没有 security,密码只进 0600 的 ssh-secrets.json";
57
+ }
58
+ return "当前系统没有钥匙串,密码只进 0600 的 ssh-secrets.json";
59
+ }
60
+
61
+ export function doctorLines(): string[] {
62
+ const lines = [`node ${process.version}`];
63
+ try {
64
+ createRequire(import.meta.url)("ssh2");
65
+ lines.push("ssh2 可用");
66
+ } catch {
67
+ lines.push("ssh2 不可用");
68
+ }
69
+ lines.push(...opensshLines());
70
+ const known = join(homedir(), ".ssh", "known_hosts");
71
+ lines.push(ok(join(homedir(), ".ssh"), constants.W_OK) ? `known_hosts 目录可写(${known})` : "~/.ssh 不可写,首次连接无法记录主机密钥");
72
+ const auditDir = join(homedir(), ".pi", "agent");
73
+ lines.push(ok(auditDir, constants.W_OK) ? "审计目录可写" : "审计目录不可写,生产主机的破坏性操作会被拒绝");
74
+ lines.push(keychainLine());
75
+ return lines;
76
+ }
@@ -0,0 +1,139 @@
1
+ // core/guard.ts —— 看门狗脚本。通道 stdin 挂在 fd 3,命令自己的 stdin 是 /dev/null。
2
+
3
+ const SHELL_SINGLE_QUOTE = /'/g;
4
+
5
+ export function shellQuote(value: string): string {
6
+ return `'${value.replace(SHELL_SINGLE_QUOTE, `'"'"'`)}'`;
7
+ }
8
+
9
+ /**
10
+ * 把命令放进自己的进程组,返回脚本行。
11
+ *
12
+ * 不能靠 `set -m` 的退出码判断:dash 下 `set -m` 在没有 tty 时返回 0,
13
+ * 但 job control 并没开启(`$-` 里没有 `m`),进程组也建不起来,
14
+ * 于是 `kill -TERM -$pid` 变成 `kill: No such process`,超时清理形同虚设。
15
+ * 必须看 `$-` 里到底有没有 `m`。
16
+ *
17
+ * - 有 job control(bash):`( cmd ) &` 天然建新进程组,`kill -$pgid` 有效。
18
+ * - 没有 job control(dash/sh):用 `setsid` 单独开会话并成为组长,`kill -$pgid` 同样有效。
19
+ * 没有 setsid 时退回「超时只关通道」,并把降级事实写到 stderr。
20
+ */
21
+ function spawnInOwnGroup(command: string): string[] {
22
+ return [
23
+ "case \"$-\" in",
24
+ " *m*)",
25
+ ` ( ${command} ) &`,
26
+ " pid=$!",
27
+ " ;;",
28
+ " *)",
29
+ " if command -v setsid >/dev/null 2>&1; then",
30
+ ` setsid sh -c ${shellQuote(command)} &`,
31
+ " pid=$!",
32
+ " else",
33
+ " echo 'pi-ssh: 远端 shell 没有 job control 也没有 setsid,超时只能关掉通道,进程组不会被杀' >&2",
34
+ ` ( ${command} ) &`,
35
+ " pid=$!",
36
+ " PI_SSH_NO_GROUP=1",
37
+ " fi",
38
+ " ;;",
39
+ "esac",
40
+ ];
41
+ }
42
+
43
+ /**
44
+ * 包一层进程组看门狗。
45
+ * 先把通道复制到 fd 3,再把 fd 0 指到 /dev/null,然后才把命令放进后台。
46
+ * 命令继承 /dev/null,watcher 独占 fd 3。通道关闭就是 fd 3 的 EOF。
47
+ */
48
+ function jobControl(command: string, afterPid: string[]): string[] {
49
+ return [
50
+ "exec 3<&0",
51
+ "exec 0</dev/null",
52
+ ...spawnInOwnGroup(command),
53
+ ...afterPid,
54
+ ];
55
+ }
56
+
57
+ function watcher(): string[] {
58
+ return [
59
+ "(",
60
+ " while read -r _ <&3; do :; done",
61
+ " [ -n \"$PI_SSH_NO_GROUP\" ] && exit 0",
62
+ " kill -TERM -$pid 2>/dev/null",
63
+ " sleep 2",
64
+ " kill -KILL -$pid 2>/dev/null",
65
+ ") >/dev/null 2>&1 &",
66
+ "watcher=$!",
67
+ "wait $pid",
68
+ "status=$?",
69
+ "kill $watcher 2>/dev/null",
70
+ "wait $watcher 2>/dev/null",
71
+ ];
72
+ }
73
+
74
+ /**
75
+ * sudo 先从通道读走一行密码。
76
+ * 密码只通过不带引号的 heredoc 进 sudo 的 stdin,不进 printf 的参数,远端 ps 看不到。
77
+ * heredoc 必须挂在最外层那个调用(子 shell 或 setsid)上:
78
+ * 放进 `sh -c '...'` 的引号里,`$PI_SSH_PW` 就到不了内层 shell(没 export)。
79
+ */
80
+ export function wrapSudo(command: string): string {
81
+ const inner = `sudo -S -p '' -- ${command}`;
82
+ const feed = ["$PI_SSH_PW", "PI_SSH_PW_END"];
83
+ return [
84
+ "IFS= read -r PI_SSH_PW || exit 1",
85
+ "exec 3<&0",
86
+ "exec 0</dev/null",
87
+ "case \"$-\" in",
88
+ " *m*)",
89
+ ` ( ${inner} ) <<PI_SSH_PW_END &`,
90
+ ...feed,
91
+ " pid=$!",
92
+ " ;;",
93
+ " *)",
94
+ " if command -v setsid >/dev/null 2>&1; then",
95
+ ` setsid sh -c ${shellQuote(inner)} <<PI_SSH_PW_END &`,
96
+ ...feed,
97
+ " pid=$!",
98
+ " else",
99
+ " echo 'pi-ssh: 远端 shell 没有 job control 也没有 setsid,超时只能关掉通道,进程组不会被杀' >&2",
100
+ ` ( ${inner} ) <<PI_SSH_PW_END &`,
101
+ ...feed,
102
+ " pid=$!",
103
+ " PI_SSH_NO_GROUP=1",
104
+ " fi",
105
+ " ;;",
106
+ "esac",
107
+ ...watcher(),
108
+ "unset PI_SSH_PW",
109
+ "exit $status",
110
+ ].join("\n");
111
+ }
112
+
113
+ export function wrapWithWatchdog(command: string): string {
114
+ return [...jobControl(command, watcher()), "exit $status"].join("\n");
115
+ }
116
+
117
+ /** 在 deploy.root 内才允许。归一化后拒绝 `..` 逃逸和根目录本身以外的前缀巧合。 */
118
+ export function withinRoot(root: string, target: string): boolean {
119
+ const base = normalizePosix(root);
120
+ const path = normalizePosix(target);
121
+ if (base === "/" || path === base) return false;
122
+ return path.startsWith(`${base}/`);
123
+ }
124
+
125
+ export function normalizePosix(value: string): string {
126
+ const absolute = value.startsWith("/");
127
+ const parts: string[] = [];
128
+ for (const part of value.split("/")) {
129
+ if (part === "" || part === ".") continue;
130
+ if (part === "..") {
131
+ if (parts.length > 0 && parts[parts.length - 1] !== "..") parts.pop();
132
+ else if (!absolute) parts.push("..");
133
+ continue;
134
+ }
135
+ parts.push(part);
136
+ }
137
+ const joined = parts.join("/");
138
+ return absolute ? `/${joined}` : joined;
139
+ }
@@ -0,0 +1,39 @@
1
+ // core/hash.ts —— 本地与远端都用同一种 sha256。远端按命令依次降级。
2
+ import { createHash } from "node:crypto";
3
+ import { createReadStream } from "node:fs";
4
+ import { stat } from "node:fs/promises";
5
+ import { shellQuote } from "./guard.js";
6
+
7
+ /**
8
+ * 本地文件的 sha256。
9
+ * 目录必须先挡掉:`readableWebStream()` 对目录抛的 EISDIR 会逃成 unhandledRejection,
10
+ * 在长驻宿主里直接把进程打掉,`try/catch` 拦不住。用 createReadStream 的异步迭代器,
11
+ * 错误才会老老实实落到 await 上。
12
+ */
13
+ export async function sha256File(path: string): Promise<{ hash: string; bytes: number }> {
14
+ const info = await stat(path);
15
+ if (info.isDirectory()) {
16
+ throw new Error(`${path} 是目录。上传不接受目录:先在本地打成一个压缩包,再传包。`);
17
+ }
18
+ const hash = createHash("sha256");
19
+ for await (const chunk of createReadStream(path)) hash.update(chunk as Buffer);
20
+ return { hash: hash.digest("hex"), bytes: info.size };
21
+ }
22
+
23
+ export function remoteHashCommand(remotePath: string): string {
24
+ const quoted = shellQuote(remotePath);
25
+ return `sha256sum ${quoted} 2>/dev/null || shasum -a 256 ${quoted} 2>/dev/null || openssl dgst -sha256 ${quoted}`;
26
+ }
27
+
28
+ export function parseRemoteHash(stdout: string): string | undefined {
29
+ return stdout.match(/[a-f0-9]{64}/i)?.[0]?.toLowerCase();
30
+ }
31
+
32
+ /** 按字节截断,不把多字节字符从中间切开。 */
33
+ export function clipUtf8(value: string, maxBytes: number): string {
34
+ const bytes = Buffer.from(value);
35
+ if (bytes.length <= maxBytes) return value;
36
+ let end = Math.max(0, maxBytes);
37
+ while (end > 0 && (bytes[end] & 0b11000000) === 0b10000000) end -= 1;
38
+ return bytes.subarray(0, end).toString("utf8");
39
+ }
@@ -0,0 +1,87 @@
1
+ // core/known-hosts.ts —— 解析 OpenSSH known_hosts。证书行只解析、不作为信任依据。
2
+ import { appendFileSync, chmodSync, mkdirSync, readFileSync } from "node:fs";
3
+ import { createHash, createHmac, timingSafeEqual } from "node:crypto";
4
+ import { dirname } from "node:path";
5
+
6
+ export type HostKeyStatus = "match" | "unknown" | "changed" | "revoked";
7
+
8
+ interface KnownHostLine {
9
+ marker?: string;
10
+ patterns: string[];
11
+ keyType: string;
12
+ key: string;
13
+ }
14
+
15
+ /** OpenSSH 的 SHA256 指纹:密钥原文的 sha256,base64,去掉末尾等号。 */
16
+ export function hostKeyFingerprint(key: Buffer): string {
17
+ const digest = createHash("sha256").update(key).digest("base64").replace(/=+$/, "");
18
+ return `SHA256:${digest}`;
19
+ }
20
+
21
+ export function hostToken(host: string, port: number): string {
22
+ return port === 22 ? host : `[${host}]:${port}`;
23
+ }
24
+
25
+ export function appendKnownHost(file: string, host: string, port: number, keyType: string, key: string): void {
26
+ const dir = dirname(file);
27
+ mkdirSync(dir, { recursive: true });
28
+ appendFileSync(file, `${hostToken(host, port)} ${keyType} ${key}\n`, { mode: 0o600 });
29
+ chmodSync(file, 0o600);
30
+ }
31
+
32
+ function parseLine(line: string): KnownHostLine | null {
33
+ const trimmed = line.trim();
34
+ if (trimmed === "" || trimmed.startsWith("#")) return null;
35
+ const parts = trimmed.split(/\s+/);
36
+ let marker: string | undefined;
37
+ if (parts[0]?.startsWith("@")) {
38
+ marker = parts.shift();
39
+ }
40
+ if (!parts[0] || !parts[1] || !parts[2]) return null;
41
+ return { marker, patterns: parts[0].split(","), keyType: parts[1], key: parts[2] };
42
+ }
43
+
44
+ function hashedMatch(pattern: string, presented: string): boolean {
45
+ const match = /^\|1\|([^|]+)\|([^|]+)$/.exec(pattern);
46
+ if (!match) return false;
47
+ const salt = Buffer.from(match[1], "base64");
48
+ const expected = Buffer.from(match[2], "base64");
49
+ const actual = createHmac("sha1", salt).update(presented).digest();
50
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
51
+ }
52
+
53
+ function patternMatches(pattern: string, host: string, port: number): boolean {
54
+ if (pattern.startsWith("|1|")) return hashedMatch(pattern, hostToken(host, port));
55
+ return pattern === hostToken(host, port) || (port === 22 && pattern === host);
56
+ }
57
+
58
+ function lineMatches(line: KnownHostLine, host: string, port: number): boolean {
59
+ return line.patterns.some((pattern) => patternMatches(pattern, host, port));
60
+ }
61
+
62
+ export function checkHostKey(
63
+ file: string,
64
+ host: string,
65
+ port: number,
66
+ keyType: string,
67
+ key: string,
68
+ ): HostKeyStatus {
69
+ let text = "";
70
+ try {
71
+ text = readFileSync(file, "utf8");
72
+ } catch {
73
+ return "unknown";
74
+ }
75
+ const lines = text
76
+ .split("\n")
77
+ .map(parseLine)
78
+ .filter((line): line is KnownHostLine => line !== null)
79
+ .filter((line) => lineMatches(line, host, port));
80
+
81
+ const sameType = lines.filter((line) => line.keyType === keyType);
82
+ if (sameType.some((line) => line.marker === "@revoked" && line.key === key)) return "revoked";
83
+ const plain = sameType.filter((line) => line.marker !== "@revoked" && line.marker !== "@cert-authority");
84
+ if (plain.some((line) => line.key === key)) return "match";
85
+ if (plain.some((line) => line.key !== key)) return "changed";
86
+ return "unknown";
87
+ }