From 4152bd4be819f53abd7bf87755eb9e517dc77ef9 Mon Sep 17 00:00:00 2001 From: Levi Yan Date: Tue, 13 May 2025 18:01:03 +0800 Subject: [PATCH] fix: make sure that directory of private/public ssh key exists before creating ssh key --- src/user.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/user.ts b/src/user.ts index 7a7fbd2..530fbca 100644 --- a/src/user.ts +++ b/src/user.ts @@ -191,16 +191,24 @@ export default class User { const privateKeyStr = privateKey; 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 - await fs.chmodSync(this.getUserPrivateKeyPath(), 0o600) + fs.chmodSync(this.getUserPrivateKeyPath(), 0o600) console.log(`User's ssh key has been created.`) // 更新local user private key path this.updateLocalUserPrivateKeyPath(this.getUserPrivateKeyPath()) console.log(`Update local user private key path.`) } 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); } } } \ No newline at end of file