Compare commits

...
Author SHA1 Message Date
陈奇 c379067977 feat(vault): export hosts as a standalone OpenSSH config 2026-12-04 09:45:02 +08:00
9 changed files with 190 additions and 14 deletions

No files matched your search

+5 -1
View File
@@ -1287,7 +1287,11 @@ Highlight the focused split pane:
'vault.hosts.newLocalShell': 'Local Shell (CMD)',
'vault.hosts.newGroup': 'New Group',
'vault.hosts.import': 'Import',
'vault.hosts.export': 'Export',
'vault.hosts.export': 'Export CSV',
'vault.hosts.export.sshConfig': 'Export SSH config',
'vault.hosts.export.sshEmpty': 'No SSH hosts with an exportable route',
'vault.hosts.export.sshSkipped': 'Skipped {count} hosts with unsupported protocols or routes',
'vault.hosts.export.sshFailed': 'Could not export SSH config',
'vault.hosts.export.toast.success': 'Exported {count} hosts to CSV',
'vault.hosts.export.toast.successWithSkipped': 'Exported {count} hosts to CSV ({skipped} unsupported hosts skipped)',
'vault.hosts.export.toast.passphrasesSkipped': '{count} saved key passphrases could not be read and were left blank',
+5 -1
View File
@@ -1287,7 +1287,11 @@ Resalta el panel dividido enfocado:
'vault.hosts.newLocalShell': 'Shell local (CMD)',
'vault.hosts.newGroup': 'Nuevo grupo',
'vault.hosts.import': 'Importar',
'vault.hosts.export': 'Exportar',
'vault.hosts.export': 'Exportar CSV',
'vault.hosts.export.sshConfig': 'Exportar configuración SSH',
'vault.hosts.export.sshEmpty': 'No hay hosts SSH con una ruta exportable',
'vault.hosts.export.sshSkipped': 'Se omitieron {count} hosts con protocolos o rutas incompatibles',
'vault.hosts.export.sshFailed': 'No se pudo exportar la configuración SSH',
'vault.hosts.export.toast.success': 'Se exportaron {count} hosts a CSV',
'vault.hosts.export.toast.successWithSkipped': 'Se exportaron {count} hosts a CSV (se omitieron {skipped} hosts no compatibles)',
'vault.hosts.export.toast.passphrasesSkipped': 'No se pudieron leer {count} frases de contraseña de claves guardadas y se dejaron en blanco',
+5 -1
View File
@@ -90,7 +90,11 @@ export const ruVaultMessages: Messages = {
'vault.hosts.newLocalShell': 'Локальная оболочка (CMD)',
'vault.hosts.newGroup': 'Новая группа',
'vault.hosts.import': 'Импорт',
'vault.hosts.export': 'Экспорт',
'vault.hosts.export': 'Экспорт CSV',
'vault.hosts.export.sshConfig': 'Экспорт конфигурации SSH',
'vault.hosts.export.sshEmpty': 'Нет SSH-хостов с доступным для экспорта маршрутом',
'vault.hosts.export.sshSkipped': 'Пропущено хостов с неподдерживаемым протоколом или маршрутом: {count}',
'vault.hosts.export.sshFailed': 'Не удалось экспортировать конфигурацию SSH',
'vault.hosts.export.toast.success': 'Экспортировано {count} хостов в CSV',
'vault.hosts.export.toast.successWithSkipped': 'Экспортировано {count} хостов в CSV ({skipped} неподдерживаемых хостов пропущено)',
'vault.hosts.export.toast.passphrasesSkipped': 'Не удалось прочитать {count} сохранённых парольных фраз ключей; они оставлены пустыми',
+5 -1
View File
@@ -840,7 +840,11 @@ Vaults 标签保持扁平,不使用这块背景。
'vault.hosts.newLocalShell': '本地终端 (CMD)',
'vault.hosts.newGroup': '新建分组',
'vault.hosts.import': '导入',
'vault.hosts.export': '导出',
'vault.hosts.export': '导出 CSV',
'vault.hosts.export.sshConfig': '导出 SSH 配置',
'vault.hosts.export.sshEmpty': '没有可导出连接配置的 SSH 主机',
'vault.hosts.export.sshSkipped': '已跳过 {count} 个协议或连接路径不受支持的主机',
'vault.hosts.export.sshFailed': '无法导出 SSH 配置',
'vault.hosts.export.toast.success': '已导出 {count} 个主机到 CSV',
'vault.hosts.export.toast.successWithSkipped': '已导出 {count} 个主机到 CSV(跳过 {skipped} 个不支持的主机)',
'vault.hosts.export.toast.passphrasesSkipped': '有 {count} 个已保存的密钥口令无法读取,导出时已留空',
+5 -1
View File
@@ -840,7 +840,11 @@ Vaults 分頁維持扁平,不使用這塊背景。
'vault.hosts.newLocalShell': '本地終端 (CMD)',
'vault.hosts.newGroup': '新增群組',
'vault.hosts.import': '匯入',
'vault.hosts.export': '匯出',
'vault.hosts.export': '匯出 CSV',
'vault.hosts.export.sshConfig': '匯出 SSH 設定',
'vault.hosts.export.sshEmpty': '沒有可匯出連線設定的 SSH 主機',
'vault.hosts.export.sshSkipped': '已略過 {count} 個通訊協定或連線路徑不受支援的主機',
'vault.hosts.export.sshFailed': '無法匯出 SSH 設定',
'vault.hosts.export.toast.success': '已匯出 {count} 個主機到 CSV',
'vault.hosts.export.toast.successWithSkipped': '已匯出 {count} 個主機到 CSV(跳過 {skipped} 個不支援的主機)',
'vault.hosts.export.toast.passphrasesSkipped': '有 {count} 個已儲存的金鑰密碼無法讀取,匯出時已留空',
+29 -9
View File
@@ -323,6 +323,18 @@ interface VaultViewProps {
};
}
function downloadHostExport(content: string, type: string, filename: string) {
const blob = new Blob([content], { type });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
const VaultViewInner: React.FC<VaultViewProps> = ({
hosts,
keys,
@@ -929,15 +941,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
return;
}
const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `hosts_export_${new Date().toISOString().slice(0, 10)}.csv`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
downloadHostExport(csv, "text/csv;charset=utf-8;", `hosts_export_${new Date().toISOString().slice(0, 10)}.csv`);
if (unreadablePassphraseCount > 0) {
toast.warning(
@@ -967,6 +971,21 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
}
}, [hosts, keys, proxyProfiles, identities, groupConfigs, t]);
const handleExportSshConfig = useCallback(async () => {
try {
const { exportVaultSshConfig } = await import("../domain/vaultSshConfigExport");
const { text, skippedCount } = exportVaultSshConfig(hosts, groupConfigs, identities, keys, proxyProfileIdSet);
if (!text) {
toast.warning(t("vault.hosts.export.sshEmpty"));
return;
}
downloadHostExport(text, "text/plain;charset=utf-8", "netcatty-ssh.conf");
if (skippedCount) toast.warning(t("vault.hosts.export.sshSkipped", { count: skippedCount }));
} catch (error) {
toast.error(error instanceof Error ? error.message : String(error), t("vault.hosts.export.sshFailed"));
}
}, [hosts, groupConfigs, identities, keys, proxyProfileIdSet, t]);
// Copy hostname/IP for cross-host paste without opening the editor
const handleCopyHostname = useCallback(
(host: Host) => {
@@ -1686,6 +1705,7 @@ const VaultViewInner: React.FC<VaultViewProps> = ({
handleEditHost,
handleEditTag,
handleExportHosts,
handleExportSshConfig,
handleHostConnect,
handleImportFileSelected,
handleNewHost,
+11
View File
@@ -319,6 +319,7 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
handleEditHost,
handleEditTag,
handleExportHosts,
handleExportSshConfig,
handleHostConnect,
handleImportFileSelected,
handleNewHost,
@@ -1173,6 +1174,16 @@ export function VaultViewLayout({ ctx }: { ctx: VaultViewLayoutContext }) {
</span>
{t("vault.hosts.export")}
</Button>
<Button
variant="ghost"
className="group justify-start gap-2.5"
onClick={handleExportSshConfig}
>
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md bg-sky-500/12 text-sky-500 group-hover:bg-current/15 group-hover:text-current">
<Download size={13} />
</span>
{t("vault.hosts.export.sshConfig")}
</Button>
</DropdownContent>
</Dropdown>
</div>
+52
View File
@@ -0,0 +1,52 @@
import assert from "node:assert/strict";
import test from "node:test";
import { getActiveGlobalDefaultProxyProfileId, publishActiveGlobalDefaultProxyProfileId } from "./globalDefaultProxy";
import type { Host, Identity, SSHKey } from "./models";
import { importVaultHostsFromText } from "./vaultImport";
import { exportVaultSshConfig } from "./vaultSshConfigExport";
const host = (id: string, fields: Partial<Host> = {}): Host => ({
id, label: id, hostname: id + ".test", username: "", tags: [], os: "linux", ...fields,
});
test("OpenSSH export resolves group credentials, preserves jump aliases, and round trips without secrets", () => {
const identity: Identity = { id: "admin", label: "Admin", username: "deploy", keyId: "k", authMethod: "key", created: 0 };
const key: SSHKey = { id: "k", label: "Key", type: "ED25519", category: "key", source: "reference",
filePath: "/keys/dev key", privateKey: "PRIVATE-DATA", passphrase: "KEY-SECRET", created: 0 };
const hosts = [host("a", { label: "Edge", password: "HOST-SECRET" }), host("b", { label: "E dge" }),
host("c", { label: "Edge-2" }), host("app", { group: "Work", hostChain: { hostIds: ["b"] }, useKeychain: true })];
const { text, skippedCount } = exportVaultSshConfig(hosts, [{ path: "Work", identityId: "admin", port: 2202 }], [identity], [key]);
assert.equal(skippedCount, 0);
assert.match(text, /Host Edge-3\n\s+HostName b\.test/);
assert.match(text, /ProxyJump Edge-3/);
assert.match(text, /^IgnoreUnknown UseKeychain/);
assert.doesNotMatch(text, /PRIVATE-DATA|KEY-SECRET|HOST-SECRET/);
const imported = importVaultHostsFromText("ssh_config", text);
const app = imported.hosts.find(entry => entry.hostname === "app.test");
assert.equal(app?.port, 2202);
assert.equal(app?.username, "deploy");
assert.deepEqual(app?.identityFilePaths, ["/keys/dev key"]);
assert.equal(imported.hosts.length, 4);
});
test("excludes non-SSH transports, unsupported routes and their dependants", () => {
const chain = (id: string, hop: string): Host => host(id, { hostChain: { hostIds: [hop] } });
const dual = host("dual", { protocol: "telnet", port: 23, protocols: [{ protocol: "ssh", enabled: true, port: 2266 }] });
const { text, skippedCount } = exportVaultSshConfig([host("serial", { protocol: "serial" }),
host("proxy", { proxyProfileId: "proxy" }), chain("via", "proxy"), chain("nested", "via"),
chain("loop", "loop"), chain("missing", "gone"), dual], [], [], []);
assert.equal(skippedCount, 6);
assert.equal(text, "Host dual\n HostName dual.test\n Port 2266\n");
assert.equal(exportVaultSshConfig([host("local", { protocol: "local" })], [], [], []).text, "");
});
test("a global proxy applies to exported routes, unless this host explicitly connects directly", (t) => {
const previous = getActiveGlobalDefaultProxyProfileId();
t.after(() => publishActiveGlobalDefaultProxyProfileId(previous));
publishActiveGlobalDefaultProxyProfileId("global");
const hosts = [host("routed"), host("direct", { directProxy: true })];
const { text, skippedCount } = exportVaultSshConfig(hosts, [], [], [], new Set(["global"]));
assert.equal(skippedCount, 1);
assert.match(text, /^Host direct$/m);
assert.doesNotMatch(text, /routed/);
});
+73
View File
@@ -0,0 +1,73 @@
import { applyGroupDefaults, resolveGroupDefaults } from "./groupConfig";
import type { GroupConfig, Host, Identity, SSHKey } from "./models";
import { getHostEnabledProtocols } from "./remoteDesktop";
import { resolveHostAuth } from "./sshAuth";
import { serializeHostsToSshConfig, toSafeSshHostAlias } from "./sshConfigSerializer";
import { canServeAsSshJumpHost } from "./terminalProtocol";
export function exportVaultSshConfig(
hosts: Host[],
groupConfigs: GroupConfig[],
identities: Identity[],
keys: SSHKey[],
validProxyProfileIds?: ReadonlySet<string>,
) {
const inheritance = { validProxyProfileIds };
const candidates = hosts.map(host => {
const defaults = host.group ? resolveGroupDefaults(host.group, groupConfigs, inheritance) : {};
return applyGroupDefaults(host, defaults, inheritance);
}).filter(host => getHostEnabledProtocols(host).includes("ssh") && !host.proxyConfig && !host.proxyProfileId);
// A missing or unrepresentable jump must not turn a routed connection into a direct one.
const byId = new Map(candidates.map(host => [host.id, host]));
const routeAvailable = new Map<string, boolean>();
function hasCompleteRoute(id: string): boolean {
if (routeAvailable.has(id)) return routeAvailable.get(id)!;
const host = byId.get(id);
routeAvailable.set(id, false); // Break cycles.
const available = !!host && (host.hostChain?.hostIds ?? []).every(hasCompleteRoute);
routeAvailable.set(id, available);
return available;
}
const exportable = candidates.filter(host => hasCompleteRoute(host.id));
// Some otherwise literal Host patterns (such as "server(prod)") cannot be used as ssh CLI arguments.
const labels = exportable.map(host => {
const label = host.label || host.hostname;
const alias = toSafeSshHostAlias(label, host.hostname);
return /^[\p{L}\p{N}._+-]+$/u.test(alias) ? label : alias.replace(/[^\p{L}\p{N}._+-]/gu, "_");
});
const reserved = new Set(labels.map(label => toSafeSshHostAlias(label, "").toLowerCase()));
const used = new Set<string>();
const entries = exportable.map((host, index) => {
let label = labels[index];
let alias = toSafeSshHostAlias(label, host.hostname).toLowerCase();
if (used.has(alias)) {
// OpenSSH uses the first matching Host block. Preserve literal aliases already in the vault.
let suffix = 2;
do {
label = `${labels[index]}-${suffix++}`;
alias = toSafeSshHostAlias(label, host.hostname).toLowerCase();
} while (reserved.has(alias) || used.has(alias));
}
used.add(alias);
const { username, identityFilePath, authMethod } = resolveHostAuth({ host, identities, keys });
return {
...host,
label,
username,
protocol: "ssh" as const,
port: canServeAsSshJumpHost(host)
? host.port
: host.protocols?.find(entry => entry.protocol === "ssh" && entry.enabled)?.port ?? 22,
identityFilePaths: authMethod === "password"
? undefined
: identityFilePath ? [identityFilePath] : host.identityFilePaths,
};
});
const preamble = entries.some(host => host.useKeychain !== undefined) ? "IgnoreUnknown UseKeychain\n\n" : "";
return {
text: entries.length ? preamble + serializeHostsToSshConfig(entries) : "",
skippedCount: hosts.length - entries.length,
};
}