@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,181 @@
1
+ // core/policy.ts —— 命令危险度分级。纯函数,只看命令文本。
2
+ // decide 只用于 ssh_exec / ssh_sudo。上传覆盖和隧道确认不走这里。
3
+
4
+ export type Danger = "read" | "write" | "destructive";
5
+ export type Decision = "run" | "confirm" | "deny";
6
+ export type ConfirmLevel = "destructive" | "write" | "always";
7
+
8
+ export interface Verdict {
9
+ danger: Danger;
10
+ /** 给人看的「这条命令会做什么」 */
11
+ summary: string;
12
+ }
13
+
14
+ export interface Policy {
15
+ readonly: boolean;
16
+ confirm: ConfirmLevel;
17
+ }
18
+
19
+ export interface PolicyHost {
20
+ id: string;
21
+ tags?: string[];
22
+ }
23
+
24
+ /** 非生产主机的会话级 write 授权。生产主机不得授予,调用方也不应传入。 */
25
+ export interface SessionGrant {
26
+ hostId: string;
27
+ untilMs: number;
28
+ }
29
+
30
+ interface Rule {
31
+ danger: Exclude<Danger, "read">;
32
+ summary: string;
33
+ test: (command: string) => boolean;
34
+ }
35
+
36
+ const DESTRUCTIVE: Rule[] = [
37
+ { danger: "destructive", summary: "fork 炸弹", test: (c) => /:\(\)\{/.test(c.replace(/\s/g, "")) },
38
+ {
39
+ danger: "destructive",
40
+ summary: "把解码后的内容交给 shell 执行",
41
+ test: (c) => /\bbase64\b[\s\S]*(?:-d\b|--decode\b)[\s\S]*\|\s*(?:sh|bash|zsh|dash)\b/.test(c),
42
+ },
43
+ {
44
+ danger: "destructive",
45
+ summary: "清理 Docker 资源",
46
+ test: (c) => /\bdocker\s+(?:system|image|container|volume|builder)\s+prune\b/.test(c),
47
+ },
48
+ {
49
+ danger: "destructive",
50
+ summary: "删除容器或镜像",
51
+ test: (c) => /\bdocker\s+(?:rm|rmi)\b/.test(c),
52
+ },
53
+ {
54
+ danger: "destructive",
55
+ summary: "删除文件或目录",
56
+ test: (c) => /\brm\b/.test(c) && !/^\s*rm\s+--(?:help|version)\s*$/.test(c),
57
+ },
58
+ {
59
+ danger: "destructive",
60
+ summary: "find 删除匹配文件",
61
+ test: (c) => /\bfind\b/.test(c) && (/\s-delete\b/.test(c) || /\s-exec\s+rm\b/.test(c)),
62
+ },
63
+ {
64
+ danger: "destructive",
65
+ summary: "停止、禁用或屏蔽服务",
66
+ test: (c) => /\bsystemctl\s+(?:stop|disable|mask)\b/.test(c),
67
+ },
68
+ { danger: "destructive", summary: "格式化磁盘", test: (c) => /\bmkfs(?:\.\w+)?\b/.test(c) },
69
+ { danger: "destructive", summary: "dd 写入设备或文件", test: (c) => /\bdd\b[\s\S]*\bof=/.test(c) },
70
+ {
71
+ danger: "destructive",
72
+ summary: "覆盖 /etc 或 /boot 下的文件",
73
+ test: (c) => fileRedirectTarget(c, "/etc", "/boot") !== null,
74
+ },
75
+ { danger: "destructive", summary: "丢弃未提交的本地修改", test: (c) => /\bgit\s+reset\b[\s\S]*--hard\b/.test(c) },
76
+ {
77
+ danger: "destructive",
78
+ summary: "删除未跟踪文件",
79
+ test: (c) => /\bgit\s+clean\b/.test(c) && /\s-[A-Za-z]*[fd]/.test(c),
80
+ },
81
+ {
82
+ danger: "destructive",
83
+ summary: "强制杀死进程",
84
+ test: (c) => /\bkill\b[\s\S]*\s-(?:9|KILL|SIGKILL)\b/.test(c),
85
+ },
86
+ {
87
+ danger: "destructive",
88
+ summary: "关闭或重启机器",
89
+ test: (c) => /(?:^|[\s;&|`(])(?:reboot|shutdown|halt|poweroff)\b/.test(c),
90
+ },
91
+ { danger: "destructive", summary: "删除用户或用户组", test: (c) => /\b(?:userdel|groupdel)\b/.test(c) },
92
+ {
93
+ danger: "destructive",
94
+ summary: "清空防火墙规则",
95
+ test: (c) => /\b(?:iptables|ip6tables)\b/.test(c) && /(?:\s-F\b|--flush\b)/.test(c),
96
+ },
97
+ {
98
+ danger: "destructive",
99
+ summary: "递归放开全部权限",
100
+ test: (c) => /\bchmod\b/.test(c) && /\s-R\b/.test(c) && /\b0*777\b/.test(c),
101
+ },
102
+ ];
103
+
104
+ const WRITE: Rule[] = [
105
+ { danger: "write", summary: "原地修改文件", test: (c) => /\bsed\b/.test(c) && /(?:\s-i\b|--in-place\b)/.test(c) },
106
+ {
107
+ danger: "write",
108
+ summary: "重启或设置服务开机启动",
109
+ test: (c) => /\bsystemctl\s+(?:restart|reload|enable)\b/.test(c),
110
+ },
111
+ {
112
+ danger: "write",
113
+ summary: "变更 compose 项目",
114
+ test: (c) => /\bdocker(?:\s+|-)compose\b[\s\S]*\b(?:up|down)\b/.test(c),
115
+ },
116
+ {
117
+ danger: "write",
118
+ summary: "启动、停止或重启容器",
119
+ test: (c) => /\bdocker\s+(?:run|stop|restart)\b/.test(c),
120
+ },
121
+ {
122
+ danger: "write",
123
+ summary: "安装或卸载软件包",
124
+ test: (c) =>
125
+ /\b(?:apt-get|apt|yum|dnf|apk|pacman|zypper|brew|npm|pnpm|yarn|pip3|pip)\b/.test(c) &&
126
+ /\b(?:install|remove|uninstall|purge|erase|add|del)\b/.test(c),
127
+ },
128
+ {
129
+ danger: "write",
130
+ summary: "移动、复制或修改文件",
131
+ test: (c) => /\b(?:mv|cp|install|chmod|chown|tee|truncate)\b/.test(c),
132
+ },
133
+ { danger: "write", summary: "把输出写入文件", test: (c) => fileRedirectTarget(c) !== null },
134
+ { danger: "write", summary: "执行动态拼接的命令,无法静态确认", test: (c) => /\beval\b/.test(c) },
135
+ ];
136
+
137
+ /** 文件重定向的目标。`2>&1` 和 `>/dev/null` 不算写文件。指定 prefixes 时只返回命中的目标。 */
138
+ function fileRedirectTarget(command: string, ...prefixes: string[]): string | null {
139
+ // 前一个字符是 `-` 或 `=` 时是 `->` / `=>`,不是重定向。`>=` 由 `(?!=)` 排掉。
140
+ const re = /(^|[^>])>{1,2}(?!=)\s*([^\s;&|]+)/g;
141
+ for (const match of command.matchAll(re)) {
142
+ const prev = match[1];
143
+ const target = match[2];
144
+ if (prev === "-" || prev === "=") continue;
145
+ if (target.startsWith("&") || target === "/dev/null") continue;
146
+ if (prefixes.length === 0 || prefixes.some((p) => target === p || target.startsWith(p + "/"))) return target;
147
+ }
148
+ return null;
149
+ }
150
+
151
+ export function classify(command: string): Verdict {
152
+ const commandText = command.trim();
153
+ for (const rule of [...DESTRUCTIVE, ...WRITE]) {
154
+ if (rule.test(commandText)) return { danger: rule.danger, summary: rule.summary };
155
+ }
156
+ return { danger: "read", summary: "只读命令" };
157
+ }
158
+
159
+ export function isProdHost(host: PolicyHost): boolean {
160
+ return host.tags?.includes("prod") === true;
161
+ }
162
+
163
+ function grantCovers(grant: SessionGrant | null | undefined, host: PolicyHost, nowMs: number): boolean {
164
+ return !!grant && grant.hostId === host.id && grant.untilMs > nowMs && !isProdHost(host);
165
+ }
166
+
167
+ export function decide(
168
+ verdict: Verdict,
169
+ policy: Policy,
170
+ host: PolicyHost,
171
+ grant?: SessionGrant | null,
172
+ nowMs: number = Date.now(),
173
+ ): Decision {
174
+ if (verdict.danger === "read") return policy.confirm === "always" ? "confirm" : "run";
175
+ if (policy.readonly) return "deny";
176
+ if (verdict.danger === "destructive") return "confirm";
177
+ if (isProdHost(host)) return "confirm";
178
+ if (grantCovers(grant, host, nowMs)) return "run";
179
+ if (policy.confirm === "destructive") return "run";
180
+ return "confirm";
181
+ }
@@ -0,0 +1,110 @@
1
+ // core/secrets.ts —— 凭据只进 0600 文件。钥匙串只负责读取已有项。
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+
6
+ interface SecretFile {
7
+ hosts: Record<string, string>;
8
+ }
9
+
10
+ function load(file: string): SecretFile {
11
+ if (!existsSync(file)) return { hosts: {} };
12
+ let parsed: Partial<SecretFile>;
13
+ try {
14
+ parsed = JSON.parse(readFileSync(file, "utf8")) as Partial<SecretFile>;
15
+ } catch (error) {
16
+ const message = error instanceof Error ? error.message : String(error);
17
+ throw new Error(`凭据文件损坏,拒绝覆盖 ${file}:${message}`);
18
+ }
19
+ if (!parsed.hosts || typeof parsed.hosts !== "object") {
20
+ throw new Error(`凭据文件缺少 hosts,拒绝覆盖 ${file}`);
21
+ }
22
+ return { hosts: parsed.hosts };
23
+ }
24
+
25
+ function save(file: string, data: SecretFile): void {
26
+ const next = JSON.stringify(data, null, 2) + "\n";
27
+ mkdirSync(dirname(file), { recursive: true });
28
+ const tmp = `${file}.${process.pid}.tmp`;
29
+ writeFileSync(tmp, next, { mode: 0o600 });
30
+ chmodSync(tmp, 0o600);
31
+ renameSync(tmp, file);
32
+ chmodSync(file, 0o600);
33
+ }
34
+
35
+ export function defaultSecretsPath(): string {
36
+ return join(homedir(), ".pi", "agent", "ssh-secrets.json");
37
+ }
38
+
39
+ export function putSecret(file: string, host: string, secret: string): void {
40
+ const data = load(file);
41
+ data.hosts[host] = secret;
42
+ save(file, data);
43
+ }
44
+
45
+ export function getSecret(file: string, host: string): string | undefined {
46
+ return load(file).hosts[host];
47
+ }
48
+
49
+ export function deleteSecret(file: string, host: string): void {
50
+ const data = load(file);
51
+ delete data.hosts[host];
52
+ save(file, data);
53
+ }
54
+
55
+ export interface Keychain {
56
+ get(service: string, account: string): Promise<string | undefined>;
57
+ set(service: string, account: string, secret: string): Promise<void>;
58
+ }
59
+
60
+ export function linuxKeychain(): Keychain {
61
+ return {
62
+ async get(service, account) {
63
+ const { spawn } = await import("node:child_process");
64
+ return new Promise((resolve) => {
65
+ const child = spawn("secret-tool", ["lookup", "service", service, "account", account], { stdio: ["ignore", "pipe", "ignore"] });
66
+ let out = "";
67
+ child.stdout.on("data", (chunk: Buffer) => {
68
+ out += chunk.toString("utf8");
69
+ });
70
+ child.on("close", (code) => resolve(code === 0 ? out.trim() : undefined));
71
+ child.on("error", () => resolve(undefined));
72
+ });
73
+ },
74
+ async set(service, account, secret) {
75
+ const { spawn } = await import("node:child_process");
76
+ await new Promise<void>((resolve, reject) => {
77
+ const child = spawn("secret-tool", ["store", "--label", "pi-ssh", "service", service, "account", account], { stdio: ["pipe", "ignore", "ignore"] });
78
+ child.stdin.end(secret);
79
+ child.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`secret-tool 退出码 ${code}`))));
80
+ child.on("error", reject);
81
+ });
82
+ },
83
+ };
84
+ }
85
+
86
+ export function macKeychain(): Keychain {
87
+ return {
88
+ async get(service, account) {
89
+ const { spawn } = await import("node:child_process");
90
+ return new Promise((resolve) => {
91
+ const child = spawn("security", ["find-generic-password", "-s", service, "-a", account, "-w"], { stdio: ["ignore", "pipe", "ignore"] });
92
+ let out = "";
93
+ child.stdout.on("data", (chunk: Buffer) => {
94
+ out += chunk.toString("utf8");
95
+ });
96
+ child.on("close", (code) => resolve(code === 0 ? out.trim() : undefined));
97
+ child.on("error", () => resolve(undefined));
98
+ });
99
+ },
100
+ async set(_service, _account, _secret) {
101
+ throw new Error("macOS 的 security 不能从 stdin 收密码,-w 会把密码留在进程参数里。密码改写入 0600 的 ssh-secrets.json。");
102
+ },
103
+ };
104
+ }
105
+
106
+ export function platformKeychain(): Keychain {
107
+ if (process.platform === "linux") return linuxKeychain();
108
+ if (process.platform === "darwin") return macKeychain();
109
+ throw new Error("当前系统没有钥匙串。密码只写入 0600 的 ssh-secrets.json。");
110
+ }
@@ -0,0 +1,69 @@
1
+ // core/types.ts —— 主机、传输结果与错误类型。零 pi 依赖。
2
+
3
+ export type TransportKind = "ssh2" | "openssh" | "ftp" | "ftps";
4
+ export type AuthKind = "key" | "password" | "agent";
5
+
6
+ export interface HostAuth {
7
+ kind: AuthKind;
8
+ secretRef?: string;
9
+ privateKeyPath?: string;
10
+ passphraseRef?: string;
11
+ /** 只活在这次连接的内存里,不写回配置。 */
12
+ password?: string;
13
+ /** 只活在这次连接的内存里,不写回配置。 */
14
+ passphrase?: string;
15
+ }
16
+
17
+ export interface DeployLayout {
18
+ root: string;
19
+ releasesDir?: string;
20
+ currentLink?: string;
21
+ sharedDir?: string;
22
+ restartCmd?: string;
23
+ healthCmd?: string;
24
+ keepReleases?: number;
25
+ }
26
+
27
+ export interface HostProfile {
28
+ id: string;
29
+ name: string;
30
+ transport: TransportKind | "auto";
31
+ host: string;
32
+ port?: number;
33
+ user: string;
34
+ auth: HostAuth;
35
+ strictHostKey?: boolean;
36
+ secure?: "explicit" | "implicit";
37
+ active?: boolean;
38
+ insecure?: boolean;
39
+ tags?: string[];
40
+ defaults?: { cwd?: string; timeoutSec?: number };
41
+ deploy?: DeployLayout;
42
+ createdAt: string;
43
+ lastUsedAt?: string;
44
+ }
45
+
46
+ export interface HostFile {
47
+ hosts: Record<string, HostProfile>;
48
+ activeHost?: string;
49
+ policy?: { readonly: boolean; confirm: "destructive" | "write" | "always" };
50
+ }
51
+
52
+ export const EMPTY_HOST_FILE: HostFile = { hosts: {} };
53
+
54
+ export class SshError extends Error {
55
+ constructor(message: string) {
56
+ super(message);
57
+ this.name = new.target.name;
58
+ }
59
+ }
60
+
61
+ export class HostKeyUnknownError extends SshError {}
62
+ export class HostKeyChangedError extends SshError {}
63
+ export class AuthFailedError extends SshError {}
64
+ export class UnsupportedError extends SshError {}
65
+ export class PolicyDeniedError extends SshError {}
66
+ export class ConfirmRejectedError extends SshError {}
67
+ export class BoundsError extends SshError {}
68
+ export class TransferMismatchError extends SshError {}
69
+ export class AuditUnavailableError extends SshError {}
@@ -0,0 +1,29 @@
1
+ // core/wait.ts —— 把等待收成远端一条循环,避免本地反复探活。
2
+ import { shellQuote } from "./guard.js";
3
+
4
+ export interface WaitFor {
5
+ port?: number;
6
+ http?: string;
7
+ file?: string;
8
+ timeoutSec: number;
9
+ }
10
+
11
+ export function waitCommand(wait: WaitFor): string {
12
+ const ticks = Math.max(1, Math.floor(wait.timeoutSec));
13
+ const port = Number(wait.port);
14
+ if (wait.port !== undefined && Number.isInteger(port) && port > 0 && port < 65536) {
15
+ const body = `for i in $(seq 1 ${ticks}); do (echo >/dev/tcp/127.0.0.1/${port}) >/dev/null 2>&1 && exit 0; command -v nc >/dev/null 2>&1 && nc -z 127.0.0.1 ${port} && exit 0; sleep 1; done; exit 1`;
16
+ return `bash -c ${shellQuote(body)}`;
17
+ }
18
+ if (wait.http) {
19
+ const url = shellQuote(wait.http);
20
+ const body = `for i in $(seq 1 ${ticks}); do curl -fsS -m 2 ${url} >/dev/null 2>&1 && exit 0; command -v wget >/dev/null 2>&1 && wget -q -T 2 -O /dev/null ${url} && exit 0; sleep 1; done; exit 1`;
21
+ return `bash -c ${shellQuote(body)}`;
22
+ }
23
+ if (wait.file) {
24
+ const file = shellQuote(wait.file);
25
+ const body = `for i in $(seq 1 ${ticks}); do test -e ${file} && exit 0; sleep 1; done; exit 1`;
26
+ return `bash -c ${shellQuote(body)}`;
27
+ }
28
+ throw new Error("waitFor 需要 port、http 或 file 其中一个");
29
+ }
package/src/prompt.ts ADDED
@@ -0,0 +1,15 @@
1
+ // prompt.ts —— 注入系统提示的主机摘要。超过 20 台只保留活动主机。
2
+ import type { HostFile } from "./core/types.js";
3
+
4
+ export function describeHosts(file: HostFile): string {
5
+ const hosts = Object.values(file.hosts);
6
+ if (hosts.length === 0) return "[SSH 主机]\n还没有主机。用 /ssh add 添加。";
7
+ const visible = hosts.length > 20 ? hosts.filter((item) => item.name === file.activeHost) : hosts;
8
+ const lines = visible.map((item) => {
9
+ const prod = item.tags?.includes("prod") ? " [prod]" : "";
10
+ return `- ${item.name}${prod} ${item.user}@${item.host}`;
11
+ });
12
+ const extra = hosts.length > 20 ? `\n共 ${hosts.length} 台,其余用 ssh_hosts 的 list 查看。` : "";
13
+ const rule = hosts.length >= 2 ? "已配置多台,调用必须传 host。" : "只有一台,host 可以省略。";
14
+ return `[SSH 主机]\n${lines.join("\n")}${extra}\n${rule}`;
15
+ }