From 27a09a49abf8cc86762641f1b8802ee58271c324 Mon Sep 17 00:00:00 2001 From: Levi Yan Date: Tue, 12 Nov 2024 19:07:30 +0800 Subject: [PATCH] style: tab -> 2 spaces in all typescript files --- src/home.ts | 50 +++++----- src/remote-container.ts | 158 ++++++++++++++--------------- src/user.ts | 216 ++++++++++++++++++++-------------------- src/utils.ts | 158 ++++++++++++++--------------- 4 files changed, 291 insertions(+), 291 deletions(-) diff --git a/src/home.ts b/src/home.ts index b0df8e3..e84b17a 100644 --- a/src/home.ts +++ b/src/home.ts @@ -7,15 +7,15 @@ import * as utils from './utils' export default class DSHome { private context: vscode.ExtensionContext; private remoteContainer: RemoteContainer; - private user:User; - private devstarHomePageUrl:string; + private user: User; + private devstarHomePageUrl: string; constructor(context: vscode.ExtensionContext) { this.context = context; this.user = new User(context); this.remoteContainer = new RemoteContainer(this.user); - const devstarHomePageUrl:string|undefined = vscode.workspace.getConfiguration('devstar').get('devstarHomePage') + const devstarHomePageUrl: string | undefined = vscode.workspace.getConfiguration('devstar').get('devstarHomePage') if (undefined == devstarHomePageUrl || "" == devstarHomePageUrl) { this.devstarHomePageUrl = "https://devstar.cn/devstar-home" // this.devstarHomePageUrl = "http://localhost:3000/devstar-home" @@ -44,31 +44,31 @@ export default class DSHome { case 'getUserToken': const userToken = this.user.getUserTokenFromLocal() if (userToken === undefined) { - panel.webview.postMessage({ command: 'getUserToken', data: {userToken: ''}}) + panel.webview.postMessage({ command: 'getUserToken', data: { userToken: '' } }) break; } else { - panel.webview.postMessage({ command: 'getUserToken', data: {userToken: userToken}}) + panel.webview.postMessage({ command: 'getUserToken', data: { userToken: userToken } }) break; } case 'getUsername': const username = this.user.getUsernameFromLocal() if (username === undefined) { - panel.webview.postMessage({command: 'getUsername', data: {username: ''}}) + panel.webview.postMessage({ command: 'getUsername', data: { username: '' } }) break; } else { - panel.webview.postMessage({command: 'getUsername', data: {username: username}}) + panel.webview.postMessage({ command: 'getUsername', data: { username: username } }) break; } case 'firstOpenRemoteFolder': await this.remoteContainer.firstConnect(data.host, data.username, data.port) - .then((_res) => { - if (_res == 'success') { - // only success then open folder - this.remoteContainer.openRemoteFolder(data.host, data.username, data.port, data.path); - } - }).catch(error => { - console.error(`Failed to connect ${data.host}: `, error) - }) + .then((_res) => { + if (_res == 'success') { + // only success then open folder + this.remoteContainer.openRemoteFolder(data.host, data.username, data.port, data.path); + } + }).catch(error => { + console.error(`Failed to connect ${data.host}: `, error) + }) break; case 'openRemoteFolder': this.remoteContainer.openRemoteFolder(data.host, data.username, data.port, data.path); @@ -77,43 +77,43 @@ export default class DSHome { case 'setUserToken': this.user.setUserTokenToLocal(data.userToken) if (data.userToken === this.user.getUserTokenFromLocal()) { - panel.webview.postMessage({ command: 'setUserToken', data: {ok: true}}) + panel.webview.postMessage({ command: 'setUserToken', data: { ok: true } }) break; } else { - panel.webview.postMessage({ command: 'setUserToken', data: {ok: false}}) + panel.webview.postMessage({ command: 'setUserToken', data: { ok: false } }) break; } case 'setUsername': this.user.setUsernameToLocal(data.username); if (data.username === this.user.getUsernameFromLocal()) { - panel.webview.postMessage({command: 'setUsername', data: {ok: true}}); + panel.webview.postMessage({ command: 'setUsername', data: { ok: true } }); break; } else { - panel.webview.postMessage({command: 'setUsername', data: {ok: false}}); + panel.webview.postMessage({ command: 'setUsername', data: { ok: false } }); break; } case 'getUserPublicKey': var userPublicKey = ''; if (this.user.existUserPrivateKey()) { userPublicKey = this.user.getUserPublicKey(); - panel.webview.postMessage({command: 'getUserPublicKey', data: {userPublicKey: userPublicKey}}) + panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } }) break; } else { - panel.webview.postMessage({command: 'getUserPublicKey', data: {userPublicKey: userPublicKey}}) + panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } }) break; } case 'createUserPublicKey': await this.user.createUserSSHKey(); if (this.user.existUserPublicKey()) { - panel.webview.postMessage({command: 'createUserPublicKey', data: {ok: true}}) + panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: true } }) break; } else { - panel.webview.postMessage({command: 'createUserPublicKey', data: {ok: false}}) + panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: false } }) break; } case 'getMachineName': const machineName = os.hostname(); - panel.webview.postMessage({command: 'getMachineName', data: {machineName: machineName}}) + panel.webview.postMessage({ command: 'getMachineName', data: { machineName: machineName } }) case 'getDefaultPublicKey': var defaultPublicKey; if (utils.existDefaultPublicKey()) { @@ -123,7 +123,7 @@ export default class DSHome { utils.createSSHKey(); defaultPublicKey = utils.getDefaultPublicKey(); } - panel.webview.postMessage({ command: 'getDefaultPublicKey', data: {defaultPublicKey: defaultPublicKey}}) + panel.webview.postMessage({ command: 'getDefaultPublicKey', data: { defaultPublicKey: defaultPublicKey } }) } }, undefined, diff --git a/src/remote-container.ts b/src/remote-container.ts index 78e63ac..baf77ff 100644 --- a/src/remote-container.ts +++ b/src/remote-container.ts @@ -9,40 +9,40 @@ import * as utils from './utils'; import User from './user'; export default class RemoteContainer { - private user:User; + private user: User; - constructor(user:User) { + constructor(user: User) { this.user = user } async firstConnect(host: string, username: string, port: number): Promise; // connect with key // deprecated - async firstConnect(host: string, username: string, port: number, password: string): Promise; + async firstConnect(host: string, username: string, port: number, password: string): Promise; async firstConnect(host: string, username: string, port: number, password?: string): Promise { return new Promise(async (resolve, reject) => { const ssh = new NodeSSH(); vscode.window.withProgress({ - location: vscode.ProgressLocation.Notification, - title: "正在容器中安装vscode-server及devstar插件", - cancellable: false + location: vscode.ProgressLocation.Notification, + title: "正在容器中安装vscode-server及devstar插件", + cancellable: false }, async (progress) => { - try { + try { - if (password === undefined) { - // connect with key - await ssh.connect({ - host: host, - username: username, - port: port, - privateKeyPath: this.user.getUserPrivateKeyPath() - }); - progress.report({ message: "连接成功,开始安装" }); + if (password === undefined) { + // connect with key + await ssh.connect({ + host: host, + username: username, + port: port, + privateKeyPath: this.user.getUserPrivateKeyPath() + }); + progress.report({ message: "连接成功,开始安装" }); - // install vscode-server and devstar extension - const vscodeCommitId = await utils.getVsCodeCommitId(); - const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz` - const installVscodeServerScript = ` + // install vscode-server and devstar extension + const vscodeCommitId = await utils.getVsCodeCommitId(); + const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz` + const installVscodeServerScript = ` mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\ if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then ~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar @@ -55,25 +55,25 @@ export default class RemoteContainer { ~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar fi `; - await ssh.execCommand(installVscodeServerScript); - console.log("vscode-server and extension installed"); - vscode.window.showInformationMessage('安装完成!'); + await ssh.execCommand(installVscodeServerScript); + console.log("vscode-server and extension installed"); + vscode.window.showInformationMessage('安装完成!'); - await ssh.dispose(); - } else { - // connect with password (deprecate in future) - await ssh.connect({ - host: host, - username: username, - password: password, - port: port - }); - progress.report({ message: "连接成功,开始安装" }); + await ssh.dispose(); + } else { + // connect with password (deprecate in future) + await ssh.connect({ + host: host, + username: username, + password: password, + port: port + }); + progress.report({ message: "连接成功,开始安装" }); - // install vscode-server and devstar extension - const vscodeCommitId = await utils.getVsCodeCommitId(); - const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz` - const installVscodeServerScript = ` + // install vscode-server and devstar extension + const vscodeCommitId = await utils.getVsCodeCommitId(); + const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz` + const installVscodeServerScript = ` mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\ if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then ~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar @@ -86,63 +86,63 @@ export default class RemoteContainer { ~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar fi `; - await ssh.execCommand(installVscodeServerScript); - console.log("vscode-server and extension installed"); - vscode.window.showInformationMessage('安装完成!'); + await ssh.execCommand(installVscodeServerScript); + console.log("vscode-server and extension installed"); + vscode.window.showInformationMessage('安装完成!'); - // add the public key to the remote authorized_keys - if (!utils.existDefaultPublicKey() || !utils.existDefaultPrivateKey()) { - // if there is no public key, generate one - utils.createSSHKey() + // add the public key to the remote authorized_keys + if (!utils.existDefaultPublicKey() || !utils.existDefaultPrivateKey()) { + // if there is no public key, generate one + utils.createSSHKey() + } + + const publicKey = utils.getDefaultPublicKey(); + await ssh.execCommand(`mkdir -p ~/.ssh && echo '${publicKey}' >> ~/.ssh/authorized_keys`); + console.log('Public key added to remote authorized_keys'); + + await ssh.dispose(); } - const publicKey = utils.getDefaultPublicKey(); - await ssh.execCommand(`mkdir -p ~/.ssh && echo '${publicKey}' >> ~/.ssh/authorized_keys`); - console.log('Public key added to remote authorized_keys'); - + } catch (error) { + console.error('Failed to install vscode-server and extension: ', error); await ssh.dispose(); + reject(error); } - } catch (error) { - console.error('Failed to install vscode-server and extension: ', error); - await ssh.dispose(); - reject(error); - } + // only connect successfully then save the host info + const sshConfigPath = path.join(os.homedir(), '.ssh', 'config'); + // check if the host and related info exist in local ssh config file before saving + var canAppendSSHConfig = true + if (fs.existsSync(sshConfigPath)) { + var reader = rd.createInterface(fs.createReadStream(sshConfigPath)) - // only connect successfully then save the host info - const sshConfigPath = path.join(os.homedir(), '.ssh', 'config'); - // check if the host and related info exist in local ssh config file before saving - var canAppendSSHConfig = true - if (fs.existsSync(sshConfigPath)) { - var reader = rd.createInterface(fs.createReadStream(sshConfigPath)) - - for await (const line of reader) { - // host format: hostname:port - if (line.includes(`Host ${host}-${port}`)) { - // the container ssh info exists - canAppendSSHConfig = false - break; + for await (const line of reader) { + // host format: hostname:port + if (line.includes(`Host ${host}-${port}`)) { + // the container ssh info exists + canAppendSSHConfig = false + break; + } } } - } - if (canAppendSSHConfig) { - // save the host to the local ssh config file - const hostInConfig = `${host}-${port}` // host format: hostname-port - const privateKeyPath = this.user.getUserPrivateKeyPath(); - const newSShConfigContent = - `\nHost ${hostInConfig}\n HostName ${host}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `; - fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' }); - console.log('Host registered in local ssh config'); - } + if (canAppendSSHConfig) { + // save the host to the local ssh config file + const hostInConfig = `${host}-${port}` // host format: hostname-port + const privateKeyPath = this.user.getUserPrivateKeyPath(); + const newSShConfigContent = + `\nHost ${hostInConfig}\n HostName ${host}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `; + fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' }); + console.log('Host registered in local ssh config'); + } - resolve("success"); - }); + resolve("success"); + }); }); } - openRemoteFolder(host: string, username:string ,port:number, path: string): void { + openRemoteFolder(host: string, username: string, port: number, path: string): void { var host = `${host}-${port}` const command = `code --remote ssh-remote+${username}@${host} ${path} --reuse-window` let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`); diff --git a/src/user.ts b/src/user.ts index 298e45d..a7048d2 100644 --- a/src/user.ts +++ b/src/user.ts @@ -9,123 +9,123 @@ const { const sshpk = require('sshpk'); export default class User { - private context:vscode.ExtensionContext; - private username:string|undefined; - private userToken:string|undefined; - private usernameKey:string = 'devstarUsername' - private userTokenKey:string = 'devstarUserToken' + private context: vscode.ExtensionContext; + private username: string | undefined; + private userToken: string | undefined; + private usernameKey: string = 'devstarUsername' + private userTokenKey: string = 'devstarUserToken' - constructor(context: vscode.ExtensionContext) { - this.context = context; - this.username = this.context.globalState.get(this.usernameKey); - this.userToken = this.context.globalState.get(this.userTokenKey); + constructor(context: vscode.ExtensionContext) { + this.context = context; + this.username = this.context.globalState.get(this.usernameKey); + this.userToken = this.context.globalState.get(this.userTokenKey); + } + + private isLogged() { + var existUsername = false; + var existUserToken = false; + if (this.username != undefined && this.username != '') { + existUsername = true; + } + if (this.userToken != undefined && this.userToken != '') { + existUserToken = true; } - private isLogged() { - var existUsername = false; - var existUserToken = false; - if(this.username != undefined && this.username != '') { - existUsername = true; - } - if(this.userToken != undefined && this.userToken != '') { - existUserToken = true; - } + if (existUsername && existUserToken) { + return true; + } else { + return false; + } + } - if (existUsername && existUserToken) { - return true; - } else { - return false; - } + public getUsernameFromLocal(): string | undefined { + return this.username; + } + + public getUserTokenFromLocal(): string | undefined { + return this.userToken; + } + + public setUsernameToLocal(username: string) { + this.context.globalState.update(this.usernameKey, username); + this.username = username; + } + + public setUserTokenToLocal(userToken: string) { + this.context.globalState.update(this.userTokenKey, userToken) + this.userToken = userToken + } + + public getUserPrivateKeyPath(): string { + if (!this.isLogged) { + return ''; } - public getUsernameFromLocal(): string|undefined { - return this.username; + return path.join(os.homedir(), '.ssh', `id_rsa_${this.username}`) + } + + public getUserPublicKeyPath(): string { + if (!this.isLogged) { + return ''; } - public getUserTokenFromLocal(): string|undefined{ - return this.userToken; + return path.join(os.homedir(), '.ssh', `id_rsa_${this.username}.pub`) + } + + public existUserPublicKey(): boolean { + const userPublicKeyPath = this.getUserPublicKeyPath(); + return fs.existsSync(userPublicKeyPath) + } + + public existUserPrivateKey(): boolean { + const userPrivateKeyPath = this.getUserPrivateKeyPath(); + return fs.existsSync(userPrivateKeyPath) + } + + public getUserPublicKey(): string { + const userPublicKeyPath = this.getUserPublicKeyPath(); + const userPublicKey = fs.readFileSync(userPublicKeyPath, 'utf-8'); + // remove `\r` `\n` + const trimmedDefaultPublicKey = userPublicKey.replace(/[\r\n]/g, ""); + return trimmedDefaultPublicKey; + } + + public getUserPrivateKey(): string { + const userPrivateKey = this.getUserPrivateKeyPath(); + return fs.readFileSync(userPrivateKey, 'utf-8'); + } + + public async createUserSSHKey() { + if (this.existUserPublicKey() && this.existUserPrivateKey()) { + // if both public and private key exists, stop + return; } - public setUsernameToLocal(username:string) { - this.context.globalState.update(this.usernameKey, username); - this.username = username; - } - - public setUserTokenToLocal(userToken:string) { - this.context.globalState.update(this.userTokenKey, userToken) - this.userToken = userToken - } - - public getUserPrivateKeyPath() : string{ - if (!this.isLogged) { - return ''; - } - - return path.join(os.homedir(), '.ssh', `id_rsa_${this.username}`) - } - - public getUserPublicKeyPath() :string{ - if (!this.isLogged) { - return ''; - } - - return path.join(os.homedir(), '.ssh', `id_rsa_${this.username}.pub`) - } - - public existUserPublicKey() :boolean{ - const userPublicKeyPath = this.getUserPublicKeyPath(); - return fs.existsSync(userPublicKeyPath) - } - - public existUserPrivateKey() :boolean{ - const userPrivateKeyPath = this.getUserPrivateKeyPath(); - return fs.existsSync(userPrivateKeyPath) - } - - public getUserPublicKey(): string { - const userPublicKeyPath = this.getUserPublicKeyPath(); - const userPublicKey = fs.readFileSync(userPublicKeyPath, 'utf-8'); - // remove `\r` `\n` - const trimmedDefaultPublicKey = userPublicKey.replace(/[\r\n]/g, ""); - return trimmedDefaultPublicKey; - } - - public getUserPrivateKey(): string { - const userPrivateKey = this.getUserPrivateKeyPath(); - return fs.readFileSync(userPrivateKey, 'utf-8'); - } - - public async createUserSSHKey() { - if (this.existUserPublicKey() && this.existUserPrivateKey()) { - // if both public and private key exists, stop - return; - } - - const { - publicKey, - privateKey, - } = await generateKeyPairSync('rsa', { - modulusLength: 4096, - publicKeyEncoding: { - type: 'pkcs1', - format: 'pem', - }, - privateKeyEncoding: { - type: 'pkcs1', - format: 'pem', - }, - }); - const publicKeyFingerprint = sshpk.parseKey(publicKey, 'pem').toString('ssh'); - const publicKeyStr = publicKeyFingerprint; // public key is public key fingerprint - const privateKeyStr = privateKey; - - try { - await fs.writeFileSync(this.getUserPublicKeyPath(), publicKeyStr); - await 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) - } catch(error) { - console.error("Failed to write public/private key into the default ssh public/key file: ", error); - } + const { + publicKey, + privateKey, + } = await generateKeyPairSync('rsa', { + modulusLength: 4096, + publicKeyEncoding: { + type: 'pkcs1', + format: 'pem', + }, + privateKeyEncoding: { + type: 'pkcs1', + format: 'pem', + }, + }); + const publicKeyFingerprint = sshpk.parseKey(publicKey, 'pem').toString('ssh'); + const publicKeyStr = publicKeyFingerprint; // public key is public key fingerprint + const privateKeyStr = privateKey; + + try { + await fs.writeFileSync(this.getUserPublicKeyPath(), publicKeyStr); + await 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) + } catch (error) { + console.error("Failed to write public/private key into the default ssh public/key file: ", error); } + } } \ No newline at end of file diff --git a/src/utils.ts b/src/utils.ts index 2f96989..deb8b0c 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -10,114 +10,114 @@ const { } = require('node:crypto') export function fetch(url: string): Promise { - // determine the library to use (based on the url protocol) - const lib = url.startsWith('https://') ? https : http; + // determine the library to use (based on the url protocol) + const lib = url.startsWith('https://') ? https : http; - return new Promise((resolve, reject) => { - lib.get(url, (response) => { - // make sure the status code is 200 - if (response.statusCode !== 200) { - reject(new Error(`Failed to load page, status code: ${response.statusCode}`)); - return; - } + return new Promise((resolve, reject) => { + lib.get(url, (response) => { + // make sure the status code is 200 + if (response.statusCode !== 200) { + reject(new Error(`Failed to load page, status code: ${response.statusCode}`)); + return; + } - let data = ''; - response.on('data', (chunk) => { - data += chunk; - }); - response.on('end', () => { - resolve(data); - }); - }).on('error', (err) => { - reject(err); - }); + let data = ''; + response.on('data', (chunk) => { + data += chunk; + }); + response.on('end', () => { + resolve(data); + }); + }).on('error', (err) => { + reject(err); }); + }); } -export const Sleep = (ms:number)=> { - return new Promise(resolve=>setTimeout(resolve, ms)) +export const Sleep = (ms: number) => { + return new Promise(resolve => setTimeout(resolve, ms)) } export function getVsCodeCommitId(): Promise { return new Promise((resolve, reject) => { exec('code --version', (error, stdout, stderr) => { - if (error) { - reject('Error occurred:' + error.message); - return; - } - if (stderr) { - reject('Error output:' + stderr); - return; - } - const lines = stdout.trim().split('\n'); - if (lines.length > 1) { - const commitId = lines[1]; // 第二行是 commit ID - resolve(commitId); - } else { - reject('Unexpected output format:' + stdout); - } + if (error) { + reject('Error occurred:' + error.message); + return; + } + if (stderr) { + reject('Error output:' + stderr); + return; + } + const lines = stdout.trim().split('\n'); + if (lines.length > 1) { + const commitId = lines[1]; // 第二行是 commit ID + resolve(commitId); + } else { + reject('Unexpected output format:' + stdout); + } }); }) } -export function getDefaultPrivateKeyPath() : string{ - return path.join(os.homedir(), '.ssh', 'id_rsa') +export function getDefaultPrivateKeyPath(): string { + return path.join(os.homedir(), '.ssh', 'id_rsa') } -export function getDefaultPublicKeyPath() :string{ - return path.join(os.homedir(), '.ssh', 'id_rsa.pub') +export function getDefaultPublicKeyPath(): string { + return path.join(os.homedir(), '.ssh', 'id_rsa.pub') } -export function existDefaultPublicKey() :boolean{ - const defaultPublicKeyPath = getDefaultPublicKeyPath(); - return fs.existsSync(defaultPublicKeyPath) +export function existDefaultPublicKey(): boolean { + const defaultPublicKeyPath = getDefaultPublicKeyPath(); + return fs.existsSync(defaultPublicKeyPath) } -export function existDefaultPrivateKey() :boolean{ - const defaultPrivateKeyPath = getDefaultPrivateKeyPath(); - return fs.existsSync(defaultPrivateKeyPath) +export function existDefaultPrivateKey(): boolean { + const defaultPrivateKeyPath = getDefaultPrivateKeyPath(); + return fs.existsSync(defaultPrivateKeyPath) } export function getDefaultPublicKey(): string { - const defaultPublicKeyPath = getDefaultPublicKeyPath(); - const defaultPublicKey = fs.readFileSync(defaultPublicKeyPath, 'utf-8'); - // remove `\r` `\n` - const trimmedDefaultPublicKey = defaultPublicKey.replace(/[\r\n]/g, ""); - return trimmedDefaultPublicKey; + const defaultPublicKeyPath = getDefaultPublicKeyPath(); + const defaultPublicKey = fs.readFileSync(defaultPublicKeyPath, 'utf-8'); + // remove `\r` `\n` + const trimmedDefaultPublicKey = defaultPublicKey.replace(/[\r\n]/g, ""); + return trimmedDefaultPublicKey; } export function getDefaultPrivateKey(): string { - const defaultPrivateKey = getDefaultPrivateKeyPath(); - return fs.readFileSync(defaultPrivateKey, 'utf-8'); + const defaultPrivateKey = getDefaultPrivateKeyPath(); + return fs.readFileSync(defaultPrivateKey, 'utf-8'); } export function createSSHKey() { - if (existDefaultPublicKey() && existDefaultPrivateKey()) { - // if both public and private key exists, stop - return; - } + if (existDefaultPublicKey() && existDefaultPrivateKey()) { + // if both public and private key exists, stop + return; + } - const { - publicKey, - privateKey, - } = generateKeyPairSync('rsa', { - modulusLength: 4096, - publicKeyEncoding: { - type: 'spki', - format: 'pem', - }, - privateKeyEncoding: { - type: 'pkcs8', - format: 'pem', - cipher: 'aes-256-cbc', - passphrase: 'devstar' - }, - }); + const { + publicKey, + privateKey, + } = generateKeyPairSync('rsa', { + modulusLength: 4096, + publicKeyEncoding: { + type: 'spki', + format: 'pem', + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem', + cipher: 'aes-256-cbc', + passphrase: 'devstar' + }, + }); - try { - fs.writeFileSync(getDefaultPublicKeyPath(), publicKey); - fs.writeFileSync(getDefaultPrivateKeyPath(), privateKey); - } catch(error) { - console.error("Failed to write public/private key into the default ssh public/key file: ", error); - } + try { + fs.writeFileSync(getDefaultPublicKeyPath(), publicKey); + fs.writeFileSync(getDefaultPrivateKeyPath(), privateKey); + } catch (error) { + console.error("Failed to write public/private key into the default ssh public/key file: ", error); + } } \ No newline at end of file