feat: generate both RSA and Ed25519 host keys

This commit is contained in:
2026-07-13 17:00:39 +07:00
parent 927a953d43
commit 3c3531d1f7
+28 -16
View File
@@ -3,25 +3,37 @@ import path from "path";
import crypto from "crypto"; import crypto from "crypto";
import sshpk from "sshpk"; import sshpk from "sshpk";
export function ensureHostKeys(configDir: string): void { function generateAndSave(keyPath: string, type: "rsa" | "ed25519"): void {
const keyPath = path.join(configDir, "id_rsa"); console.log(`Generating ${type} host key...`);
if (fs.existsSync(keyPath)) return;
console.log("Generating host keys..."); const { privateKey } =
const key = crypto.generateKeyPairSync("rsa", { type === "rsa"
? crypto.generateKeyPairSync("rsa", {
modulusLength: 4096, modulusLength: 4096,
publicKeyEncoding: { publicKeyEncoding: { type: "pkcs1", format: "pem" },
type: "pkcs1", privateKeyEncoding: { type: "pkcs8", format: "pem" },
format: "pem", })
}, : crypto.generateKeyPairSync("ed25519", {
privateKeyEncoding: { publicKeyEncoding: { type: "spki", format: "pem" },
type: "pkcs8", privateKeyEncoding: { type: "pkcs8", format: "pem" },
format: "pem",
},
}); });
const keyPem = sshpk.parsePrivateKey(key.privateKey, "pem"); const parsed = sshpk.parsePrivateKey(privateKey, "pem");
const keyParsed = sshpk.parsePrivateKey(keyPem.toString("pem")); fs.writeFileSync(keyPath, parsed.toString("openssh"), { mode: 0o600 });
fs.chmodSync(keyPath, 0o600);
}
fs.writeFileSync(keyPath, keyParsed.toString("openssh")); export function ensureHostKeys(configDir: string): Buffer[] {
const keys: Array<{ file: string; type: "rsa" | "ed25519" }> = [
{ file: "id_rsa", type: "rsa" },
{ file: "id_ed25519", type: "ed25519" },
];
return keys.map(({ file, type }) => {
const keyPath = path.join(configDir, file);
if (!fs.existsSync(keyPath)) {
generateAndSave(keyPath, type);
}
return fs.readFileSync(keyPath);
});
} }