pi-ssh-manager 0.0.0-stage → 0.2.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/CHANGELOG.md +19 -0
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/package.json +52 -4
- package/src/config-reader.ts +824 -0
- package/src/index.ts +209 -0
- package/src/manager.ts +371 -0
- package/src/model.ts +144 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, truncateHead, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { JsonObject } from "@earendil-works/pi-ai";
|
|
3
|
+
import { Type } from "typebox";
|
|
4
|
+
import { SshManager, type SshManagerOptions } from "./manager.ts";
|
|
5
|
+
import type { SshHostPatch } from "./model.ts";
|
|
6
|
+
|
|
7
|
+
export { readSshConfig, resolveSshHost, type ResolvedSshHost, type SshConfigReadOptions, type SshConfigSnapshot, type SshConfigSource, type SshHostSummary } from "./config-reader.ts";
|
|
8
|
+
export { SshManager, type SshManagerOptions } from "./manager.ts";
|
|
9
|
+
export { getSshPaths, normalizeHost, normalizeOptions, quoteSshPath, renderSshConfig, validateAlias, type SshHostPatch, type SshHostRecord, type SshPaths, type SshStore } from "./model.ts";
|
|
10
|
+
|
|
11
|
+
function stringEnum<T extends readonly string[]>(
|
|
12
|
+
values: T,
|
|
13
|
+
options?: { description?: string; default?: T[number] },
|
|
14
|
+
) {
|
|
15
|
+
return Type.Unsafe<T[number]>({
|
|
16
|
+
type: "string",
|
|
17
|
+
enum: [...values],
|
|
18
|
+
...(options?.description && { description: options.description }),
|
|
19
|
+
...(options?.default && { default: options.default }),
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const parameters = Type.Object({
|
|
24
|
+
action: Type.Optional(stringEnum(["list", "get", "upsert", "delete", "import"] as const, { description: "默认 list。get 查询连接信息;upsert 添加或更新主机;delete 删除受管理的主机;import 导入外部 SSH 配置和引用的密钥。" })),
|
|
25
|
+
host: Type.Optional(Type.String({ description: "get/upsert/delete 使用的主机别名。", minLength: 1, maxLength: 255 })),
|
|
26
|
+
query: Type.Optional(Type.String({ description: "list 的搜索词,可匹配别名及受管理主机的地址、用户和备注。", maxLength: 255 })),
|
|
27
|
+
offset: Type.Optional(Type.Integer({ description: "list 的分页起点,默认 0。", minimum: 0 })),
|
|
28
|
+
limit: Type.Optional(Type.Integer({ description: "list 的每页数量,默认 50,最大 100。", minimum: 1, maximum: 100 })),
|
|
29
|
+
hostname: Type.Optional(Type.String({ description: "主机名或 IP;新增主机时必填。", minLength: 1, maxLength: 255 })),
|
|
30
|
+
port: Type.Optional(Type.Integer({ description: "SSH 端口,新增时默认 22。", minimum: 1, maximum: 65535 })),
|
|
31
|
+
user: Type.Optional(Type.String({ description: "SSH 用户名;空字符串清除显式用户名。", maxLength: 255 })),
|
|
32
|
+
identityFiles: Type.Optional(Type.Array(Type.String({ minLength: 1, maxLength: 2048 }), { description: "密钥文件的绝对路径或 ~/ 路径;空数组清除显式密钥。", maxItems: 8 })),
|
|
33
|
+
description: Type.Optional(Type.String({ description: "主机备注;空字符串清除备注。", maxLength: 1000 })),
|
|
34
|
+
options: Type.Optional(Type.Record(Type.String(), Type.Union([Type.String({ maxLength: 2048 }), Type.Array(Type.String({ maxLength: 2048 }), { minItems: 1, maxItems: 16 })]), { description: "其他 OpenSSH 选项,值使用 SSH 配置语法;数组表示重复指令。提供时替换该主机原有的其他选项。" })),
|
|
35
|
+
source: Type.Optional(Type.String({ description: "import 的来源目录或 config 文件路径。目录中引用的密钥和 known_hosts 会复制到 pi-ssh-manager 数据目录。", minLength: 1, maxLength: 2048 })),
|
|
36
|
+
overwrite: Type.Optional(Type.Boolean({ description: "import 时是否覆盖同名受管理主机,默认 false,保留现有记录。" })),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
function result(data: Record<string, unknown>) {
|
|
40
|
+
const serialized = JSON.stringify(data, null, 2);
|
|
41
|
+
const truncated = truncateHead(serialized, { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES });
|
|
42
|
+
const value = truncated.truncated ? {
|
|
43
|
+
outputTruncated: true,
|
|
44
|
+
message: "结果超过输出上限,请缩小 query 或 limit 后重新查询。",
|
|
45
|
+
action: data.action,
|
|
46
|
+
sshAlias: data.sshAlias,
|
|
47
|
+
hostCount: data.hostCount,
|
|
48
|
+
matchingHostCount: data.matchingHostCount,
|
|
49
|
+
sshArguments: data.sshArguments,
|
|
50
|
+
configPath: data.configPath,
|
|
51
|
+
commandArgumentSafe: data.commandArgumentSafe,
|
|
52
|
+
hiddenOptions: (data.host as Record<string, unknown> | undefined)?.hiddenOptions,
|
|
53
|
+
unsupportedOptions: (data.host as Record<string, unknown> | undefined)?.unsupportedOptions,
|
|
54
|
+
warnings: ((data.host as Record<string, unknown> | undefined)?.warnings as string[] | undefined)?.slice(0, 12).map((warning) => warning.slice(0, 512)),
|
|
55
|
+
} : data;
|
|
56
|
+
const structuredContent: JsonObject = JSON.parse(JSON.stringify(value));
|
|
57
|
+
return { content: [{ type: "text" as const, text: JSON.stringify(structuredContent, null, 2) }], details: structuredContent, structuredContent };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function required(value: string | undefined, field: string): string {
|
|
61
|
+
if (!value?.trim()) throw new Error(`[REQUIRED] 缺少 ${field}。`);
|
|
62
|
+
return value.trim();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function editHost(manager: SshManager, ctx: ExtensionContext, alias?: string) {
|
|
66
|
+
const details = alias ? await manager.get(alias) : undefined;
|
|
67
|
+
const host = alias ?? await ctx.ui.input("主机别名");
|
|
68
|
+
if (!host) return;
|
|
69
|
+
const hostname = await ctx.ui.input("主机名或 IP", details ? String(details.hostname) : "");
|
|
70
|
+
if (hostname === undefined) return;
|
|
71
|
+
const user = await ctx.ui.input("SSH 用户名", details?.user ? String(details.user) : "");
|
|
72
|
+
if (user === undefined) return;
|
|
73
|
+
const port = await ctx.ui.input("SSH 端口", String(details?.port ?? 22));
|
|
74
|
+
if (port === undefined) return;
|
|
75
|
+
const identities = await ctx.ui.editor("密钥路径,每行一个", details?.identityFiles.map((identity) => identity.path).join("\n") ?? "");
|
|
76
|
+
if (identities === undefined) return;
|
|
77
|
+
const description = await ctx.ui.input("备注", details?.description ?? "");
|
|
78
|
+
if (description === undefined) return;
|
|
79
|
+
const saved = await manager.upsert({ host, hostname, user, port: Number(port), identityFiles: identities.split(/\r?\n/).map((line) => line.trim()).filter(Boolean), description });
|
|
80
|
+
ctx.ui.notify(`已${saved.created ? "添加" : "更新"}主机 ${host}。`, "info");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function describeHost(details: Awaited<ReturnType<SshManager["get"]>>): string {
|
|
84
|
+
const lines = [details.sshAlias, `${details.user ? `${details.user}@` : ""}${details.hostname}:${details.port}`];
|
|
85
|
+
if (details.description) lines.push(details.description);
|
|
86
|
+
for (const identity of details.identityFiles) lines.push(`密钥:${identity.path}${identity.exists === false ? "(文件不存在)" : ""}`);
|
|
87
|
+
if (details.host.hiddenOptions.length) lines.push(`附加选项:${details.host.hiddenOptions.join("、")}`);
|
|
88
|
+
lines.push(`连接:${details.command}`);
|
|
89
|
+
for (const warning of details.host.warnings) lines.push(warning);
|
|
90
|
+
return lines.join("\n");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function manageHost(manager: SshManager, ctx: ExtensionContext) {
|
|
94
|
+
let offset = 0;
|
|
95
|
+
while (true) {
|
|
96
|
+
const page = await manager.list("", offset, 50);
|
|
97
|
+
if (!page.hostCount) { ctx.ui.notify("还没有 SSH 主机。", "info"); return; }
|
|
98
|
+
const labels = page.hosts.map((host) => `${host.alias}${host.description ? ` — ${host.description}` : ""}${host.managed ? "" : "(已有配置)"}`);
|
|
99
|
+
const navigation = [...(offset > 0 ? ["上一页"] : []), ...(page.hasMore ? ["下一页"] : [])];
|
|
100
|
+
const selected = await ctx.ui.select("选择 SSH 主机", [...labels, ...navigation]);
|
|
101
|
+
if (!selected) return;
|
|
102
|
+
if (selected === "上一页") { offset -= 50; continue; }
|
|
103
|
+
if (selected === "下一页") { offset += 50; continue; }
|
|
104
|
+
const host = page.hosts[labels.indexOf(selected)];
|
|
105
|
+
if (!host) return;
|
|
106
|
+
const details = await manager.get(host.alias);
|
|
107
|
+
ctx.ui.notify(describeHost(details), "info");
|
|
108
|
+
const action = await ctx.ui.select(host.alias, host.managed ? ["编辑主机", "删除主机", "复制连接命令到输入框", "返回"] : ["复制连接命令到输入框", "返回"]);
|
|
109
|
+
if (action === "编辑主机") await editHost(manager, ctx, host.alias);
|
|
110
|
+
if (action === "删除主机" && await ctx.ui.confirm("删除主机", `删除 ${host.alias} 的 pi-ssh-manager 配置?`)) {
|
|
111
|
+
await manager.delete(host.alias);
|
|
112
|
+
ctx.ui.notify(`已删除主机 ${host.alias}。`, "info");
|
|
113
|
+
}
|
|
114
|
+
if (action === "复制连接命令到输入框") { ctx.ui.setEditorText(details.command); return; }
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function registerSshManager(pi: ExtensionAPI, options: SshManagerOptions = {}): void {
|
|
120
|
+
const manager = new SshManager(options);
|
|
121
|
+
pi.registerTool({
|
|
122
|
+
name: "ssh_manager",
|
|
123
|
+
label: "ssh_manager",
|
|
124
|
+
description: "查询与维护本机 SSH 主机。支持列表、搜索、连接参数查询、主机添加/更新/删除,以及从 OpenSSH 配置导入主机、引用的密钥和 known_hosts。配置写入 ~/.ssh/pi-ssh-manager 并通过 Include 接入 ~/.ssh/config;已有配置也可查询。修改前自动备份;删除仅移除受管理的主机记录。工具不建立连接,查询不读取密钥内容,导入和写入均不执行 SSH 配置中的命令。",
|
|
125
|
+
promptSnippet: "查询 SSH 主机与连接参数,添加、更新、删除和导入 SSH 配置",
|
|
126
|
+
promptGuidelines: [
|
|
127
|
+
"需要 SSH 信息时使用 ssh_manager;可用 list 搜索别名,再用 get 取得连接信息与 sshArguments。",
|
|
128
|
+
"执行 SSH 前检查 get 返回的 hiddenOptions、unsupportedOptions、warnings 和 commandArgumentSafe;通过参数数组传递 sshArguments,避免将主机名拼接到 shell。",
|
|
129
|
+
"只在用户要求修改 SSH 配置时使用 upsert/delete/import。更新未提供的字段会保留原值,options 提供时整体替换。",
|
|
130
|
+
"ssh_manager 的 get 只静态解析用户 SSH 配置,不求值 Match exec 或展开其他动态条件;含相关警告时先核对配置。",
|
|
131
|
+
],
|
|
132
|
+
parameters,
|
|
133
|
+
outputSchema: Type.Record(Type.String(), Type.Unknown()),
|
|
134
|
+
executionMode: "sequential",
|
|
135
|
+
async execute(_id, params, signal) {
|
|
136
|
+
signal?.throwIfAborted();
|
|
137
|
+
switch (params.action ?? "list") {
|
|
138
|
+
case "list": return result(await manager.list(params.query, params.offset, params.limit, signal));
|
|
139
|
+
case "get": return result(await manager.get(required(params.host, "host"), signal));
|
|
140
|
+
case "upsert": return result(await manager.upsert({ ...params, host: required(params.host, "host") } as SshHostPatch, signal));
|
|
141
|
+
case "delete": return result(await manager.delete(required(params.host, "host"), signal));
|
|
142
|
+
case "import": return result(await manager.import(required(params.source, "source"), params.overwrite, signal));
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
pi.registerCommand("ssh", {
|
|
148
|
+
description: "管理 SSH 主机;支持 list、get <别名>、import <路径>",
|
|
149
|
+
async getArgumentCompletions(prefix) {
|
|
150
|
+
const trimmed = prefix.trimStart();
|
|
151
|
+
if (!trimmed.includes(" ")) {
|
|
152
|
+
const needle = trimmed.toLowerCase();
|
|
153
|
+
const subcommands = [
|
|
154
|
+
{ value: "list", label: "list", description: "列出本机 SSH 主机" },
|
|
155
|
+
{ value: "get ", label: "get <别名>", description: "查询主机连接信息" },
|
|
156
|
+
{ value: "import ", label: "import <路径>", description: "导入外部 SSH 配置与凭据" },
|
|
157
|
+
];
|
|
158
|
+
const matches = subcommands.filter((item) => item.value.startsWith(needle));
|
|
159
|
+
return matches.length ? matches : null;
|
|
160
|
+
}
|
|
161
|
+
const spaceIndex = trimmed.indexOf(" ");
|
|
162
|
+
const subcommand = trimmed.slice(0, spaceIndex).toLowerCase();
|
|
163
|
+
if (subcommand !== "get") return null;
|
|
164
|
+
const hostPrefix = trimmed.slice(spaceIndex + 1).trimStart();
|
|
165
|
+
try {
|
|
166
|
+
const page = await manager.list(hostPrefix, 0, 20);
|
|
167
|
+
const matches = page.hosts.map((host) => ({
|
|
168
|
+
value: `get ${host.alias}`,
|
|
169
|
+
label: host.alias,
|
|
170
|
+
...(host.description ? { description: host.description } : host.hostname ? { description: `${host.hostname}:${host.port}` } : {}),
|
|
171
|
+
}));
|
|
172
|
+
return matches.length ? matches : null;
|
|
173
|
+
} catch {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
async handler(args, ctx) {
|
|
178
|
+
try {
|
|
179
|
+
if (!ctx.hasUI) throw new Error("当前模式请使用 ssh_manager 工具。");
|
|
180
|
+
const command = args.trim();
|
|
181
|
+
if (command === "list") {
|
|
182
|
+
const page = await manager.list();
|
|
183
|
+
ctx.ui.notify(page.hosts.length ? page.hosts.map((host) => `${host.alias}${host.hostname ? ` ${host.hostname}:${host.port}` : ""}`).join("\n") + (page.hasMore ? "\n还有更多主机,可在管理菜单中翻页查看。" : "") : "还没有 SSH 主机。", "info");
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (command.startsWith("get ")) { ctx.ui.notify(describeHost(await manager.get(required(command.slice(4), "主机别名"))), "info"); return; }
|
|
187
|
+
if (command.startsWith("import ")) {
|
|
188
|
+
const imported = await manager.import(required(command.slice(7), "来源路径"));
|
|
189
|
+
ctx.ui.notify(`已导入 ${imported.imported.length} 个主机,保留 ${imported.skipped.length} 个同名主机。`, "info");
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (command) throw new Error("用法:/ssh、/ssh list、/ssh get <别名>、/ssh import <路径>。");
|
|
193
|
+
const action = await ctx.ui.select("Pi SSH Manager", ["查看和编辑主机", "添加主机", "导入 SSH 配置"]);
|
|
194
|
+
if (action === "查看和编辑主机") await manageHost(manager, ctx);
|
|
195
|
+
if (action === "添加主机") await editHost(manager, ctx);
|
|
196
|
+
if (action === "导入 SSH 配置") {
|
|
197
|
+
const source = await ctx.ui.input("SSH 配置文件或目录路径");
|
|
198
|
+
if (!source) return;
|
|
199
|
+
const conflict = await ctx.ui.select("遇到同名主机时", ["保留现有主机", "覆盖现有主机"]);
|
|
200
|
+
if (!conflict) return;
|
|
201
|
+
const imported = await manager.import(source, conflict === "覆盖现有主机");
|
|
202
|
+
ctx.ui.notify(`已导入 ${imported.imported.length} 个主机,保留 ${imported.skipped.length} 个同名主机。`, "info");
|
|
203
|
+
}
|
|
204
|
+
} catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); }
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export default function sshManager(pi: ExtensionAPI): void { registerSshManager(pi); }
|
package/src/manager.ts
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import type { Stats } from "node:fs";
|
|
3
|
+
import { chmod, lstat, mkdir, open, rename, rm, stat } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { readSshConfig, resolveSshHost, type SshConfigSnapshot } from "./config-reader.ts";
|
|
8
|
+
import { getSshPaths, normalizeHost, quoteSshPath, renderSshConfig, validateAlias, type SshHostPatch, type SshHostRecord, type SshPaths, type SshStore } from "./model.ts";
|
|
9
|
+
|
|
10
|
+
const MAX_FILE_BYTES = 4 * 1024 * 1024;
|
|
11
|
+
const MAX_STATE_BYTES = 16 * 1024 * 1024;
|
|
12
|
+
const MAX_HOSTS = 500;
|
|
13
|
+
const BEGIN = "# >>> pi-ssh-manager >>>";
|
|
14
|
+
const END = "# <<< pi-ssh-manager <<<";
|
|
15
|
+
|
|
16
|
+
type Asset = { content: Buffer; privateKey: boolean };
|
|
17
|
+
export interface SshManagerOptions { homeDir?: string }
|
|
18
|
+
|
|
19
|
+
function missing(error: unknown): boolean {
|
|
20
|
+
return (error as NodeJS.ErrnoException)?.code === "ENOENT";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function isHomeRelativePath(value: string): boolean {
|
|
24
|
+
return value.startsWith("~/") || (process.platform === "win32" && value.startsWith("~\\"));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function expandHomePath(value: string, home: string): string {
|
|
28
|
+
return isHomeRelativePath(value) ? path.join(home, value.slice(2)) : value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function readOptional(file: string, maximum = MAX_FILE_BYTES, rejectLinks = false): Promise<Buffer | undefined> {
|
|
32
|
+
let info: Stats;
|
|
33
|
+
try { info = await lstat(file); } catch (error) { if (missing(error)) return undefined; throw error; }
|
|
34
|
+
if (rejectLinks && info.isSymbolicLink()) throw new Error(`[SYMLINK_REJECTED] 写入目标不能是符号链接:${file}`);
|
|
35
|
+
if (!info.isFile() && !info.isSymbolicLink()) throw new Error(`[NOT_A_FILE] 需要普通文件:${file}`);
|
|
36
|
+
// 文件句柄复核尺寸,避免链接目标和读取期间的变化绕过大小限制。
|
|
37
|
+
const handle = await open(file, "r");
|
|
38
|
+
try {
|
|
39
|
+
const actual = await handle.stat();
|
|
40
|
+
if (!actual.isFile() || actual.size > maximum) throw new Error(`[FILE_TOO_LARGE] 文件不是普通文件或超过 ${maximum} 字节:${file}`);
|
|
41
|
+
const buffer = Buffer.alloc(actual.size + 1);
|
|
42
|
+
let offset = 0;
|
|
43
|
+
while (offset < buffer.length) {
|
|
44
|
+
const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
|
|
45
|
+
if (!bytesRead) break;
|
|
46
|
+
offset += bytesRead;
|
|
47
|
+
}
|
|
48
|
+
if (offset > maximum || offset > actual.size) throw new Error(`[FILE_CHANGED] 读取期间文件大小发生变化:${file}`);
|
|
49
|
+
return buffer.subarray(0, offset);
|
|
50
|
+
} finally { await handle.close(); }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function privateDirectory(directory: string): Promise<void> {
|
|
54
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
55
|
+
const info = await lstat(directory);
|
|
56
|
+
if (!info.isDirectory() || info.isSymbolicLink()) throw new Error(`[INVALID_DIRECTORY] 配置目录须为真实目录:${directory}`);
|
|
57
|
+
if (process.platform !== "win32") await chmod(directory, 0o700);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function atomicWrite(file: string, content: string | Buffer): Promise<void> {
|
|
61
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
62
|
+
try {
|
|
63
|
+
const handle = await open(temporary, "wx", 0o600);
|
|
64
|
+
try { await handle.writeFile(content); await handle.sync(); } finally { await handle.close(); }
|
|
65
|
+
await rename(temporary, file);
|
|
66
|
+
} finally { await rm(temporary, { force: true }); }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function shellQuote(value: string): string {
|
|
70
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function integrateConfig(original: string, managedConfig: string): string {
|
|
74
|
+
let text = original.replace(/^\uFEFF/, "");
|
|
75
|
+
const start = text.indexOf(BEGIN);
|
|
76
|
+
if (start >= 0) {
|
|
77
|
+
const end = text.indexOf(END, start);
|
|
78
|
+
if (end < 0 || text.indexOf(BEGIN, start + BEGIN.length) >= 0) throw new Error("[INVALID_INCLUDE_BLOCK] ~/.ssh/config 中的 pi-ssh-manager 配置标记不完整或重复。");
|
|
79
|
+
text = text.slice(0, start) + text.slice(end + END.length).replace(/^\r?\n/, "");
|
|
80
|
+
}
|
|
81
|
+
const block = `${BEGIN}\nInclude ${quoteSshPath(managedConfig)}\nHost *\n${END}\n`;
|
|
82
|
+
return block + text;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export class SshManager {
|
|
86
|
+
readonly paths: SshPaths;
|
|
87
|
+
constructor(options: SshManagerOptions = {}) { this.paths = getSshPaths(options.homeDir ?? homedir()); }
|
|
88
|
+
|
|
89
|
+
private async load(): Promise<SshStore> {
|
|
90
|
+
const content = await readOptional(this.paths.state, MAX_STATE_BYTES, true);
|
|
91
|
+
if (!content) return { version: 1, hosts: [] };
|
|
92
|
+
let data: SshStore;
|
|
93
|
+
try { data = JSON.parse(content.toString("utf8")); } catch { throw new Error("[INVALID_STORE] pi-ssh-manager 主机文件不是有效 JSON,请检查或从备份恢复。"); }
|
|
94
|
+
if (data?.version !== 1 || !Array.isArray(data.hosts) || data.hosts.length > MAX_HOSTS) throw new Error("[INVALID_STORE] pi-ssh-manager 主机文件格式或版本无效。");
|
|
95
|
+
const aliases = new Set<string>();
|
|
96
|
+
const hosts = data.hosts.map((record) => {
|
|
97
|
+
if (!record || typeof record !== "object") throw new Error("[INVALID_STORE] 主机记录无效。");
|
|
98
|
+
const host = normalizeHost({ ...record, host: record.alias });
|
|
99
|
+
if (aliases.has(host.alias)) throw new Error(`[INVALID_STORE] 主机别名重复:${host.alias}`);
|
|
100
|
+
aliases.add(host.alias);
|
|
101
|
+
return host;
|
|
102
|
+
});
|
|
103
|
+
return { version: 1, hosts };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private async snapshot(signal?: AbortSignal): Promise<SshConfigSnapshot> {
|
|
107
|
+
return readSshConfig({ homeDir: this.paths.home, configPath: this.paths.nativeConfig, signal });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async list(query = "", offset = 0, limit = 50, signal?: AbortSignal) {
|
|
111
|
+
if (!Number.isInteger(offset) || offset < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new Error("[INVALID_PAGE] offset 须为非负整数,limit 须为 1~100。");
|
|
112
|
+
return withFileMutationQueue(this.paths.nativeConfig, async () => {
|
|
113
|
+
signal?.throwIfAborted();
|
|
114
|
+
const store = await this.load();
|
|
115
|
+
const snapshot = await this.snapshot(signal);
|
|
116
|
+
const managed = new Map(store.hosts.map((host) => [host.alias, host]));
|
|
117
|
+
const aliases = [...new Set([...snapshot.hosts.map((host) => host.alias), ...managed.keys()])].sort((a, b) => a.localeCompare(b, "en"));
|
|
118
|
+
const filter = query.trim().toLowerCase();
|
|
119
|
+
const matching = aliases.filter((alias) => {
|
|
120
|
+
const record = managed.get(alias);
|
|
121
|
+
return !filter || [alias, record?.hostname, record?.user, record?.description].some((value) => value?.toLowerCase().includes(filter));
|
|
122
|
+
});
|
|
123
|
+
const selected = matching.slice(offset, offset + limit);
|
|
124
|
+
return {
|
|
125
|
+
configPath: this.paths.nativeConfig,
|
|
126
|
+
managedDirectory: this.paths.directory,
|
|
127
|
+
hostCount: aliases.length,
|
|
128
|
+
managedHostCount: managed.size,
|
|
129
|
+
matchingHostCount: matching.length,
|
|
130
|
+
offset,
|
|
131
|
+
limit,
|
|
132
|
+
hasMore: offset + selected.length < matching.length,
|
|
133
|
+
hosts: selected.map((alias) => {
|
|
134
|
+
const record = managed.get(alias);
|
|
135
|
+
return { alias, managed: Boolean(record), ...(record ? { hostname: record.hostname, port: record.port, user: record.user, description: record.description } : {}) };
|
|
136
|
+
}),
|
|
137
|
+
warnings: snapshot.warnings.slice(0, 12).map((warning) => warning.length > 512 ? `${warning.slice(0, 512)}…` : warning),
|
|
138
|
+
warningCount: snapshot.warnings.length,
|
|
139
|
+
warningsTruncated: snapshot.warnings.length > 12,
|
|
140
|
+
warningCategories: snapshot.warningCategories,
|
|
141
|
+
};
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async get(alias: string, signal?: AbortSignal) {
|
|
146
|
+
return withFileMutationQueue(this.paths.nativeConfig, async () => {
|
|
147
|
+
signal?.throwIfAborted();
|
|
148
|
+
const store = await this.load();
|
|
149
|
+
const record = store.hosts.find((host) => host.alias === alias);
|
|
150
|
+
let snapshot = await this.snapshot(signal);
|
|
151
|
+
let configPath = this.paths.nativeConfig;
|
|
152
|
+
if (record && !snapshot.hosts.some((host) => host.alias === alias)) {
|
|
153
|
+
configPath = this.paths.config;
|
|
154
|
+
snapshot = await readSshConfig({ homeDir: this.paths.home, configPath, signal });
|
|
155
|
+
}
|
|
156
|
+
const resolved = resolveSshHost(snapshot, alias);
|
|
157
|
+
const sshArguments = ["-F", configPath, "--", alias];
|
|
158
|
+
const identities = Array.isArray(resolved.options.identityfile) ? resolved.options.identityfile : [];
|
|
159
|
+
const identityFiles = await Promise.all(identities.map(async (file) => {
|
|
160
|
+
if (file === "none" || /%(?!%)/.test(file) || file.includes("${")) return { path: file, exists: null };
|
|
161
|
+
const expanded = expandHomePath(file, this.paths.home);
|
|
162
|
+
if (!path.isAbsolute(expanded)) return { path: file, exists: null };
|
|
163
|
+
try { const info = await stat(expanded); return { path: file, exists: info.isFile() }; }
|
|
164
|
+
catch (error) { if (missing(error)) return { path: file, exists: false }; return { path: file, exists: null }; }
|
|
165
|
+
}));
|
|
166
|
+
signal?.throwIfAborted();
|
|
167
|
+
return {
|
|
168
|
+
sshAlias: alias,
|
|
169
|
+
managed: Boolean(record),
|
|
170
|
+
description: record?.description,
|
|
171
|
+
configPath,
|
|
172
|
+
hostname: resolved.options.hostname ?? alias,
|
|
173
|
+
port: resolved.options.port ? Number(resolved.options.port) : 22,
|
|
174
|
+
user: resolved.options.user,
|
|
175
|
+
sshArguments,
|
|
176
|
+
command: ["ssh", ...sshArguments].map(shellQuote).join(" "),
|
|
177
|
+
commandArgumentSafe: /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(alias),
|
|
178
|
+
identityFiles,
|
|
179
|
+
host: resolved,
|
|
180
|
+
};
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async upsert(patch: SshHostPatch, signal?: AbortSignal) {
|
|
185
|
+
return withFileMutationQueue(this.paths.nativeConfig, async () => {
|
|
186
|
+
signal?.throwIfAborted();
|
|
187
|
+
const store = await this.load();
|
|
188
|
+
const index = store.hosts.findIndex((host) => host.alias === patch.host);
|
|
189
|
+
const normalized = { ...patch };
|
|
190
|
+
if (patch.identityFiles) normalized.identityFiles = patch.identityFiles.map((file) => {
|
|
191
|
+
if (file === "none" || isHomeRelativePath(file) || path.isAbsolute(file)) return file;
|
|
192
|
+
throw new Error("[INVALID_IDENTITY] 密钥路径须为绝对路径、~/ 开头的路径或 none。");
|
|
193
|
+
});
|
|
194
|
+
const host = normalizeHost(normalized, index >= 0 ? store.hosts[index] : undefined);
|
|
195
|
+
if (index >= 0) store.hosts[index] = host;
|
|
196
|
+
else store.hosts.push(host);
|
|
197
|
+
const backupPath = await this.commit(store, new Map(), undefined, signal);
|
|
198
|
+
return { action: "upsert", sshAlias: host.alias, created: index < 0, hostCount: store.hosts.length, configPath: this.paths.config, backupPath };
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async delete(alias: string, signal?: AbortSignal) {
|
|
203
|
+
validateAlias(alias);
|
|
204
|
+
return withFileMutationQueue(this.paths.nativeConfig, async () => {
|
|
205
|
+
signal?.throwIfAborted();
|
|
206
|
+
const store = await this.load();
|
|
207
|
+
const index = store.hosts.findIndex((host) => host.alias === alias);
|
|
208
|
+
if (index < 0) throw new Error(`[HOST_NOT_MANAGED] pi-ssh-manager 没有管理该别名:${alias}`);
|
|
209
|
+
store.hosts.splice(index, 1);
|
|
210
|
+
const backupPath = await this.commit(store, new Map(), undefined, signal);
|
|
211
|
+
return { action: "delete", sshAlias: alias, hostCount: store.hosts.length, backupPath };
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async import(source: string, overwrite = false, signal?: AbortSignal) {
|
|
216
|
+
return withFileMutationQueue(this.paths.nativeConfig, async () => {
|
|
217
|
+
signal?.throwIfAborted();
|
|
218
|
+
const sourcePath = isHomeRelativePath(source) ? expandHomePath(source, this.paths.home) : path.resolve(source);
|
|
219
|
+
const sourceInfo = await lstat(sourcePath);
|
|
220
|
+
const configPath = sourceInfo.isDirectory() ? path.join(sourcePath, "config") : sourcePath;
|
|
221
|
+
const sourceDirectory = path.dirname(configPath);
|
|
222
|
+
if (path.resolve(configPath) === this.paths.nativeConfig || configPath.startsWith(`${this.paths.directory}${path.sep}`)) throw new Error("[SELF_IMPORT] 请使用外部 SSH 配置作为导入来源。");
|
|
223
|
+
const snapshot = await readSshConfig({ configPath, homeDir: path.dirname(sourceDirectory), signal });
|
|
224
|
+
if (!snapshot.found) throw new Error(`[CONFIG_NOT_FOUND] 未找到 SSH 配置:${configPath}`);
|
|
225
|
+
if (snapshot.warnings.length) throw new Error(`[IMPORT_INCOMPLETE] 配置无法完整解析:${snapshot.warnings.join(";")}`);
|
|
226
|
+
if (!snapshot.hosts.length) throw new Error("[NO_HOSTS] 配置中没有具体的 Host 别名。");
|
|
227
|
+
const store = await this.load();
|
|
228
|
+
const assets = new Map<string, Asset>();
|
|
229
|
+
const existing = new Map(store.hosts.map((host) => [host.alias, host]));
|
|
230
|
+
const imported: string[] = [];
|
|
231
|
+
const skipped: string[] = [];
|
|
232
|
+
const knownHostContents: string[] = [];
|
|
233
|
+
const defaultKnownHosts = await readOptional(path.join(sourceDirectory, "known_hosts"));
|
|
234
|
+
if (defaultKnownHosts) knownHostContents.push(defaultKnownHosts.toString("utf8"));
|
|
235
|
+
|
|
236
|
+
const sourceFile = (raw: string, host: { alias: string; hostname: string; user?: string; port: number }): string => {
|
|
237
|
+
let value = raw.replaceAll("%%", "\u0000").replaceAll("%d", path.dirname(sourceDirectory)).replaceAll("%h", host.hostname).replaceAll("%n", host.alias).replaceAll("%p", String(host.port));
|
|
238
|
+
if (host.user) value = value.replaceAll("%r", host.user);
|
|
239
|
+
if (/%[A-Za-z]|\$\{/.test(value)) throw new Error(`[DYNAMIC_PATH] 无法解析 ${host.alias} 的文件路径:${raw}`);
|
|
240
|
+
value = value.replaceAll("\u0000", "%");
|
|
241
|
+
if (/^~[\\/]\.ssh[\\/]/.test(value)) return path.join(sourceDirectory, value.slice(7));
|
|
242
|
+
if (/^~[\\/]/.test(value)) return path.join(path.dirname(sourceDirectory), value.slice(2));
|
|
243
|
+
if (/^[A-Za-z]:[\\/]/.test(value)) {
|
|
244
|
+
const normalized = value.replaceAll("\\", "/");
|
|
245
|
+
const sshSegment = normalized.toLowerCase().lastIndexOf("/.ssh/");
|
|
246
|
+
if (sshSegment < 0) throw new Error(`[WINDOWS_PATH] Windows 路径须位于来源 .ssh 目录:${raw}`);
|
|
247
|
+
return path.join(sourceDirectory, normalized.slice(sshSegment + 6));
|
|
248
|
+
}
|
|
249
|
+
return path.isAbsolute(value) ? value : path.resolve(sourceDirectory, value);
|
|
250
|
+
};
|
|
251
|
+
const keyAsset = async (file: string, privateKey: boolean): Promise<string> => {
|
|
252
|
+
signal?.throwIfAborted();
|
|
253
|
+
const content = await readOptional(file);
|
|
254
|
+
if (!content) throw new Error(`[IDENTITY_NOT_FOUND] 来源配置引用的文件不存在:${file}`);
|
|
255
|
+
const digest = createHash("sha256").update(content).digest("hex").slice(0, 16);
|
|
256
|
+
const basename = path.basename(file).replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 100);
|
|
257
|
+
const target = path.join(this.paths.keys, `${basename}-${digest}`);
|
|
258
|
+
assets.set(target, { content, privateKey });
|
|
259
|
+
if (privateKey) {
|
|
260
|
+
const publicContent = await readOptional(`${file}.pub`);
|
|
261
|
+
if (publicContent) assets.set(`${target}.pub`, { content: publicContent, privateKey: false });
|
|
262
|
+
}
|
|
263
|
+
return target;
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
for (const summary of snapshot.hosts) {
|
|
267
|
+
signal?.throwIfAborted();
|
|
268
|
+
const alias = validateAlias(summary.alias);
|
|
269
|
+
if (existing.has(alias) && !overwrite) { skipped.push(alias); continue; }
|
|
270
|
+
const resolved = resolveSshHost(snapshot, alias);
|
|
271
|
+
if (resolved.warnings.length || resolved.hiddenOptions.length || resolved.unsupportedOptions.length) {
|
|
272
|
+
throw new Error(`[IMPORT_UNSUPPORTED] ${alias} 包含暂不支持导入的条件或选项:${[...resolved.warnings, ...resolved.hiddenOptions, ...resolved.unsupportedOptions].join(";")}`);
|
|
273
|
+
}
|
|
274
|
+
const { hostname, port, user, identityfile, certificatefile, userknownhostsfile, globalknownhostsfile, ...options } = resolved.options;
|
|
275
|
+
const host = normalizeHost({ host: alias, hostname: typeof hostname === "string" ? hostname : alias, port: port ? Number(port) : 22, user: typeof user === "string" ? user : undefined, options });
|
|
276
|
+
for (const file of Array.isArray(identityfile) ? identityfile : []) {
|
|
277
|
+
host.identityFiles.push(file === "none" ? file : await keyAsset(sourceFile(file, host), true));
|
|
278
|
+
}
|
|
279
|
+
if (Array.isArray(certificatefile)) {
|
|
280
|
+
host.options.certificatefile = [];
|
|
281
|
+
for (const file of certificatefile) (host.options.certificatefile as string[]).push(quoteSshPath(await keyAsset(sourceFile(file, host), false)));
|
|
282
|
+
}
|
|
283
|
+
for (const [name, value] of [["userknownhostsfile", userknownhostsfile], ["globalknownhostsfile", globalknownhostsfile]] as const) {
|
|
284
|
+
if (!value) continue;
|
|
285
|
+
const files = Array.isArray(value) ? value : [value];
|
|
286
|
+
const targetFiles: string[] = [];
|
|
287
|
+
for (const file of files) {
|
|
288
|
+
if (file === "none") { targetFiles.push("none"); continue; }
|
|
289
|
+
targetFiles.push(quoteSshPath(await keyAsset(sourceFile(file, host), false)));
|
|
290
|
+
}
|
|
291
|
+
host.options[name] = targetFiles.join(" ");
|
|
292
|
+
}
|
|
293
|
+
if (!userknownhostsfile && defaultKnownHosts) host.options.userknownhostsfile = `${quoteSshPath(this.paths.knownHosts)} ${quoteSshPath(path.join(this.paths.sshDirectory, "known_hosts"))}`;
|
|
294
|
+
existing.set(alias, host);
|
|
295
|
+
imported.push(alias);
|
|
296
|
+
}
|
|
297
|
+
if (!imported.length) return { action: "import", source: configPath, imported, skipped, hostCount: store.hosts.length, copiedKeyCount: 0 };
|
|
298
|
+
store.hosts = [...existing.values()];
|
|
299
|
+
const previousKnownHosts = await readOptional(this.paths.knownHosts, MAX_FILE_BYTES, true);
|
|
300
|
+
if (previousKnownHosts) knownHostContents.unshift(previousKnownHosts.toString("utf8"));
|
|
301
|
+
const lines = [...new Set(knownHostContents.flatMap((text) => text.split(/\r?\n/)).filter((line) => line.trim()))];
|
|
302
|
+
const knownHosts = lines.length ? `${lines.join("\n")}\n` : undefined;
|
|
303
|
+
const backupPath = await this.commit(store, assets, knownHosts, signal);
|
|
304
|
+
return { action: "import", source: configPath, imported, skipped, hostCount: store.hosts.length, copiedKeyCount: [...assets.values()].filter((asset) => asset.privateKey).length, copiedFileCount: assets.size, knownHostCount: lines.filter((line) => !line.startsWith("#")).length, configPath: this.paths.config, backupPath };
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private async commit(store: SshStore, assets: Map<string, Asset>, knownHosts?: string, signal?: AbortSignal): Promise<string | undefined> {
|
|
309
|
+
signal?.throwIfAborted();
|
|
310
|
+
if (store.hosts.length > MAX_HOSTS) throw new Error(`[HOST_LIMIT] 主机数量超过上限 ${MAX_HOSTS}。`);
|
|
311
|
+
await privateDirectory(this.paths.sshDirectory);
|
|
312
|
+
await privateDirectory(this.paths.directory);
|
|
313
|
+
await privateDirectory(this.paths.keys);
|
|
314
|
+
const state = `${JSON.stringify(store, null, 2)}\n`;
|
|
315
|
+
if (Buffer.byteLength(state) > MAX_STATE_BYTES) throw new Error("[STORE_TOO_LARGE] 主机配置文件超过大小上限。");
|
|
316
|
+
const config = renderSshConfig(store.hosts);
|
|
317
|
+
if (Buffer.byteLength(config) > 1024 * 1024 || config.split("\n").length > 4900) throw new Error("[CONFIG_TOO_LARGE] 生成的 SSH 配置超过解析大小或指令数量上限。");
|
|
318
|
+
const previousNative = await readOptional(this.paths.nativeConfig, MAX_FILE_BYTES, true);
|
|
319
|
+
const updates = new Map<string, string>([
|
|
320
|
+
[this.paths.state, state],
|
|
321
|
+
[this.paths.config, config],
|
|
322
|
+
[this.paths.nativeConfig, integrateConfig(previousNative?.toString("utf8") ?? "", this.paths.config)],
|
|
323
|
+
]);
|
|
324
|
+
if (knownHosts !== undefined) {
|
|
325
|
+
if (Buffer.byteLength(knownHosts) > MAX_FILE_BYTES) throw new Error("[KNOWN_HOSTS_TOO_LARGE] 合并后的主机指纹文件超过大小上限。");
|
|
326
|
+
updates.set(this.paths.knownHosts, knownHosts);
|
|
327
|
+
}
|
|
328
|
+
const previous = new Map<string, Buffer | undefined>();
|
|
329
|
+
for (const file of updates.keys()) previous.set(file, await readOptional(file, file === this.paths.state ? MAX_STATE_BYTES : MAX_FILE_BYTES, true));
|
|
330
|
+
const changing = [...updates].filter(([file, content]) => previous.get(file)?.toString("utf8") !== content);
|
|
331
|
+
let backupPath: string | undefined;
|
|
332
|
+
if (changing.some(([file]) => previous.get(file) !== undefined)) {
|
|
333
|
+
await privateDirectory(this.paths.backups);
|
|
334
|
+
backupPath = path.join(this.paths.backups, `${new Date().toISOString().replaceAll(":", "-")}-${randomUUID().slice(0, 8)}`);
|
|
335
|
+
await privateDirectory(backupPath);
|
|
336
|
+
for (const [file] of changing) {
|
|
337
|
+
const old = previous.get(file);
|
|
338
|
+
if (old) await atomicWrite(path.join(backupPath, file === this.paths.nativeConfig ? "ssh-config" : path.basename(file)), old);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
signal?.throwIfAborted();
|
|
342
|
+
// 先复制全部凭据再提交配置,配置始终引用已经存在的文件。
|
|
343
|
+
for (const [file, asset] of assets) {
|
|
344
|
+
signal?.throwIfAborted();
|
|
345
|
+
const previousAsset = await readOptional(file, MAX_FILE_BYTES, true);
|
|
346
|
+
if (previousAsset && !previousAsset.equals(asset.content)) throw new Error(`[ASSET_CONFLICT] 已存在不同内容的凭据文件:${file}`);
|
|
347
|
+
if (!previousAsset) await atomicWrite(file, asset.content);
|
|
348
|
+
else if (process.platform !== "win32") await chmod(file, 0o600);
|
|
349
|
+
}
|
|
350
|
+
const changed: string[] = [];
|
|
351
|
+
try {
|
|
352
|
+
for (const [file, content] of changing) {
|
|
353
|
+
signal?.throwIfAborted();
|
|
354
|
+
await atomicWrite(file, content);
|
|
355
|
+
changed.push(file);
|
|
356
|
+
}
|
|
357
|
+
} catch (error) {
|
|
358
|
+
const rollbackErrors: string[] = [];
|
|
359
|
+
for (const file of changed.reverse()) {
|
|
360
|
+
try {
|
|
361
|
+
const content = previous.get(file);
|
|
362
|
+
if (content) await atomicWrite(file, content);
|
|
363
|
+
else await rm(file, { force: true });
|
|
364
|
+
} catch { rollbackErrors.push(file); }
|
|
365
|
+
}
|
|
366
|
+
if (rollbackErrors.length) throw new Error(`[ROLLBACK_FAILED] 写入失败且部分文件恢复失败:${rollbackErrors.join("、")};备份:${backupPath ?? "无"}`, { cause: error });
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
return backupPath;
|
|
370
|
+
}
|
|
371
|
+
}
|