@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.
- package/LICENSE +21 -0
- package/README.md +10 -2
- package/index.ts +573 -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 +107 -0
- package/src/core/doctor.ts +45 -0
- package/src/core/guard.ts +106 -0
- package/src/core/hash.ts +35 -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 +585 -0
- package/src/scan/auto.ts +12 -0
- package/src/scan/project.ts +36 -0
- package/src/scan/save.ts +50 -0
- package/src/scan/ssh-config.ts +67 -0
- package/src/transports/ftp.ts +101 -0
- package/src/transports/openssh.ts +109 -0
- package/src/transports/ssh2.ts +534 -0
|
@@ -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,107 @@
|
|
|
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
|
+
export function rejectArchiveMembers(members: string[], destination: string): string[] {
|
|
81
|
+
return members.filter((member) => {
|
|
82
|
+
const value = member.trim();
|
|
83
|
+
if (value === "" || value.startsWith("/") || value.includes("\\")) return true;
|
|
84
|
+
return !withinRoot(destination, `${destination}/${value}`) && normalizeMember(value) !== "";
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function normalizeMember(value: string): string {
|
|
89
|
+
return value
|
|
90
|
+
.split("/")
|
|
91
|
+
.filter((part) => part !== "" && part !== ".")
|
|
92
|
+
.join("/");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function releaseIdNow(date = new Date()): string {
|
|
96
|
+
return date.toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function checkReleaseId(releaseId: string): void {
|
|
100
|
+
if (!/^[A-Za-z0-9._-]{1,80}$/.test(releaseId)) throw new Error(`发布号只能包含字母、数字、点、下划线和横线:${releaseId}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function assertInside(root: string, paths: string[]): void {
|
|
104
|
+
for (const path of paths) {
|
|
105
|
+
if (!withinRoot(root, path)) throw new Error(`发布路径越出部署根目录:${path}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
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 { 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
|
+
function keychainLine(): string {
|
|
17
|
+
if (process.platform === "linux") {
|
|
18
|
+
return ok("/usr/bin/secret-tool", constants.X_OK)
|
|
19
|
+
? "钥匙串 secret-tool 可读写"
|
|
20
|
+
: "没有 secret-tool,密码只进 0600 的 ssh-secrets.json";
|
|
21
|
+
}
|
|
22
|
+
if (process.platform === "darwin") {
|
|
23
|
+
return ok("/usr/bin/security", constants.X_OK)
|
|
24
|
+
? "钥匙串可读取已有项;新密码不进 security 的进程参数,写入 0600 的 ssh-secrets.json"
|
|
25
|
+
: "没有 security,密码只进 0600 的 ssh-secrets.json";
|
|
26
|
+
}
|
|
27
|
+
return "当前系统没有钥匙串,密码只进 0600 的 ssh-secrets.json";
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function doctorLines(): string[] {
|
|
31
|
+
const lines = [`node ${process.version}`];
|
|
32
|
+
try {
|
|
33
|
+
createRequire(import.meta.url)("ssh2");
|
|
34
|
+
lines.push("ssh2 可用");
|
|
35
|
+
} catch {
|
|
36
|
+
lines.push("ssh2 不可用");
|
|
37
|
+
}
|
|
38
|
+
lines.push(ok("/usr/bin/ssh", constants.X_OK) ? "本机 ssh 可用" : "本机没有 /usr/bin/ssh,openssh 传输不可用");
|
|
39
|
+
const known = join(homedir(), ".ssh", "known_hosts");
|
|
40
|
+
lines.push(ok(join(homedir(), ".ssh"), constants.W_OK) ? `known_hosts 目录可写(${known})` : "~/.ssh 不可写,首次连接无法记录主机密钥");
|
|
41
|
+
const auditDir = join(homedir(), ".pi", "agent");
|
|
42
|
+
lines.push(ok(auditDir, constants.W_OK) ? "审计目录可写" : "审计目录不可写,生产主机的破坏性操作会被拒绝");
|
|
43
|
+
lines.push(keychainLine());
|
|
44
|
+
return lines;
|
|
45
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
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
|
+
* 先把通道复制到 fd 3,再把 fd 0 指到 /dev/null,然后才把命令放进后台。
|
|
12
|
+
* 命令继承 /dev/null,watcher 独占 fd 3。通道关闭就是 fd 3 的 EOF。
|
|
13
|
+
*/
|
|
14
|
+
function jobControl(command: string, afterPid: string[]): string[] {
|
|
15
|
+
return [
|
|
16
|
+
"if ! set -m 2>/dev/null; then",
|
|
17
|
+
" echo 'pi-ssh: 远端 shell 不支持 set -m,超时只会关掉通道' >&2",
|
|
18
|
+
" exec 3<&0",
|
|
19
|
+
" exec 0</dev/null",
|
|
20
|
+
` ${command}`,
|
|
21
|
+
" exit $?",
|
|
22
|
+
"fi",
|
|
23
|
+
"exec 3<&0",
|
|
24
|
+
"exec 0</dev/null",
|
|
25
|
+
`( ${command} ) &`,
|
|
26
|
+
"pid=$!",
|
|
27
|
+
"set +m",
|
|
28
|
+
...afterPid,
|
|
29
|
+
];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function watcher(): string[] {
|
|
33
|
+
return [
|
|
34
|
+
"(",
|
|
35
|
+
" while read -r _ <&3; do :; done",
|
|
36
|
+
" kill -TERM -$pid 2>/dev/null",
|
|
37
|
+
" sleep 2",
|
|
38
|
+
" kill -KILL -$pid 2>/dev/null",
|
|
39
|
+
") >/dev/null 2>&1 &",
|
|
40
|
+
"watcher=$!",
|
|
41
|
+
"wait $pid",
|
|
42
|
+
"status=$?",
|
|
43
|
+
"kill $watcher 2>/dev/null",
|
|
44
|
+
"wait $watcher 2>/dev/null",
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* sudo 先从通道读走一行密码。
|
|
50
|
+
* 密码只通过不带引号的 heredoc 进 sudo 的 stdin,不进 printf 的参数,远端 ps 看不到。
|
|
51
|
+
*/
|
|
52
|
+
export function wrapSudo(command: string): string {
|
|
53
|
+
const feed = [
|
|
54
|
+
`sudo -S -p '' -- ${command} <<PI_SSH_PW_END`,
|
|
55
|
+
"$PI_SSH_PW",
|
|
56
|
+
"PI_SSH_PW_END",
|
|
57
|
+
];
|
|
58
|
+
return [
|
|
59
|
+
"IFS= read -r PI_SSH_PW || exit 1",
|
|
60
|
+
"if ! set -m 2>/dev/null; then",
|
|
61
|
+
" echo 'pi-ssh: 远端 shell 不支持 set -m,超时只会关掉通道' >&2",
|
|
62
|
+
" exec 3<&0",
|
|
63
|
+
" exec 0</dev/null",
|
|
64
|
+
...feed,
|
|
65
|
+
" exit $?",
|
|
66
|
+
"fi",
|
|
67
|
+
"exec 3<&0",
|
|
68
|
+
"exec 0</dev/null",
|
|
69
|
+
"(",
|
|
70
|
+
...feed,
|
|
71
|
+
") &",
|
|
72
|
+
"pid=$!",
|
|
73
|
+
"set +m",
|
|
74
|
+
...watcher(),
|
|
75
|
+
"unset PI_SSH_PW",
|
|
76
|
+
"exit $status",
|
|
77
|
+
].join("\n");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function wrapWithWatchdog(command: string): string {
|
|
81
|
+
return [...jobControl(command, watcher()), "exit $status"].join("\n");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 在 deploy.root 内才允许。归一化后拒绝 `..` 逃逸和根目录本身以外的前缀巧合。 */
|
|
85
|
+
export function withinRoot(root: string, target: string): boolean {
|
|
86
|
+
const base = normalizePosix(root);
|
|
87
|
+
const path = normalizePosix(target);
|
|
88
|
+
if (base === "/" || path === base) return false;
|
|
89
|
+
return path.startsWith(`${base}/`);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function normalizePosix(value: string): string {
|
|
93
|
+
const absolute = value.startsWith("/");
|
|
94
|
+
const parts: string[] = [];
|
|
95
|
+
for (const part of value.split("/")) {
|
|
96
|
+
if (part === "" || part === ".") continue;
|
|
97
|
+
if (part === "..") {
|
|
98
|
+
if (parts.length > 0 && parts[parts.length - 1] !== "..") parts.pop();
|
|
99
|
+
else if (!absolute) parts.push("..");
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
parts.push(part);
|
|
103
|
+
}
|
|
104
|
+
const joined = parts.join("/");
|
|
105
|
+
return absolute ? `/${joined}` : joined;
|
|
106
|
+
}
|
package/src/core/hash.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// core/hash.ts —— 本地与远端都用同一种 sha256。远端按命令依次降级。
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { constants } from "node:fs";
|
|
4
|
+
import { open, stat } from "node:fs/promises";
|
|
5
|
+
import { shellQuote } from "./guard.js";
|
|
6
|
+
|
|
7
|
+
export async function sha256File(path: string): Promise<{ hash: string; bytes: number }> {
|
|
8
|
+
const info = await stat(path);
|
|
9
|
+
const handle = await open(path, constants.O_RDONLY);
|
|
10
|
+
const hash = createHash("sha256");
|
|
11
|
+
try {
|
|
12
|
+
for await (const chunk of handle.readableWebStream() as AsyncIterable<Uint8Array>) hash.update(chunk);
|
|
13
|
+
} finally {
|
|
14
|
+
await handle.close();
|
|
15
|
+
}
|
|
16
|
+
return { hash: hash.digest("hex"), bytes: info.size };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function remoteHashCommand(remotePath: string): string {
|
|
20
|
+
const quoted = shellQuote(remotePath);
|
|
21
|
+
return `sha256sum ${quoted} 2>/dev/null || shasum -a 256 ${quoted} 2>/dev/null || openssl dgst -sha256 ${quoted}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function parseRemoteHash(stdout: string): string | undefined {
|
|
25
|
+
return stdout.match(/[a-f0-9]{64}/i)?.[0]?.toLowerCase();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 按字节截断,不把多字节字符从中间切开。 */
|
|
29
|
+
export function clipUtf8(value: string, maxBytes: number): string {
|
|
30
|
+
const bytes = Buffer.from(value);
|
|
31
|
+
if (bytes.length <= maxBytes) return value;
|
|
32
|
+
let end = Math.max(0, maxBytes);
|
|
33
|
+
while (end > 0 && (bytes[end] & 0b11000000) === 0b10000000) end -= 1;
|
|
34
|
+
return bytes.subarray(0, end).toString("utf8");
|
|
35
|
+
}
|
|
@@ -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
|
+
}
|