fix: make sure that directory of private/public ssh key exists before creating ssh key

This commit is contained in:
Levi Yan
2025-05-13 18:01:03 +08:00
parent eb41f5c8dc
commit 4152bd4be8

View File

@@ -191,16 +191,24 @@ export default class User {
const privateKeyStr = privateKey; const privateKeyStr = privateKey;
try { try {
await fs.writeFileSync(this.getUserPublicKeyPath(), publicKeyStr); // 确保公/私钥目录存在
await fs.writeFileSync(this.getUserPrivateKeyPath(), privateKeyStr); const publicKeyDir = path.dirname(this.getUserPublicKeyPath())
if (!fs.existsSync(publicKeyDir)) {
console.log(`Directory ${publicKeyDir} does not exist, creating it...`);
// 公钥与私钥的目录一样,所以只用创建一次
fs.mkdirSync(publicKeyDir, {recursive: true})
}
fs.writeFileSync(this.getUserPublicKeyPath(), publicKeyStr);
fs.writeFileSync(this.getUserPrivateKeyPath(), privateKeyStr);
// limit the permission of private key to prevent that the private key not works // limit the permission of private key to prevent that the private key not works
await fs.chmodSync(this.getUserPrivateKeyPath(), 0o600) fs.chmodSync(this.getUserPrivateKeyPath(), 0o600)
console.log(`User's ssh key has been created.`) console.log(`User's ssh key has been created.`)
// 更新local user private key path // 更新local user private key path
this.updateLocalUserPrivateKeyPath(this.getUserPrivateKeyPath()) this.updateLocalUserPrivateKeyPath(this.getUserPrivateKeyPath())
console.log(`Update local user private key path.`) console.log(`Update local user private key path.`)
} catch (error) { } catch (error) {
console.error("Failed to write public/private key into the default ssh public/key file: ", error); console.error(`Failed to write public/private key into the user(${this.username}) ssh public/key file: `, error);
} }
} }
} }