2020-04-11 17:29:20 +03:00
|
|
|
const { join } = require('path');
|
2023-01-02 23:06:33 +03:00
|
|
|
const { execSync } = require('child_process');
|
|
|
|
const { writeToFile } = require('./helpers');
|
|
|
|
|
|
|
|
const KNOWN_HOSTS = 'known_hosts';
|
|
|
|
const getPrivateKeyPath = (filename = '') => {
|
|
|
|
const { HOME } = process.env;
|
|
|
|
const dir = join(HOME || '~', '.ssh');
|
|
|
|
const knownHostsPath = join(dir, KNOWN_HOSTS);
|
|
|
|
return {
|
|
|
|
dir,
|
|
|
|
filename,
|
|
|
|
path: join(dir, filename),
|
|
|
|
knownHostsPath
|
|
|
|
};
|
|
|
|
};
|
2020-04-11 17:29:20 +03:00
|
|
|
|
2023-01-02 23:06:33 +03:00
|
|
|
const addSshKey = (content, deployKeyName) => {
|
|
|
|
const { dir, filename } = getPrivateKeyPath(deployKeyName);
|
|
|
|
writeToFile({ dir, filename: KNOWN_HOSTS, content: '' });
|
|
|
|
console.log('✅ [SSH] known_hosts file ensured', dir);
|
|
|
|
writeToFile({ dir, filename, content, isRequired: true, mode: '0400' });
|
|
|
|
console.log('✅ [SSH] key added to `.ssh` dir ', dir, filename);
|
|
|
|
};
|
2020-04-11 17:29:20 +03:00
|
|
|
|
2023-01-02 23:06:33 +03:00
|
|
|
const updateKnownHosts = (host) => {
|
|
|
|
const { knownHostsPath } = getPrivateKeyPath();
|
|
|
|
console.log('[SSH] Adding host to `known_hosts` ....', host, knownHostsPath);
|
2020-04-11 17:29:20 +03:00
|
|
|
try {
|
2023-01-02 23:06:33 +03:00
|
|
|
execSync(`ssh-keyscan -H ${host} >> ${knownHostsPath}`, {
|
|
|
|
stdio: 'inherit'
|
2020-04-11 17:29:20 +03:00
|
|
|
});
|
2023-01-02 23:06:33 +03:00
|
|
|
} catch (error) {
|
|
|
|
console.error('❌ [SSH] Adding host to `known_hosts` ERROR', host, error.message);
|
2020-04-11 17:29:20 +03:00
|
|
|
}
|
2023-01-02 23:06:33 +03:00
|
|
|
console.log('✅ [SSH] Adding host to `known_hosts` DONE', host, knownHostsPath);
|
2020-04-11 17:29:20 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = {
|
2023-01-02 23:06:33 +03:00
|
|
|
getPrivateKeyPath,
|
|
|
|
updateKnownHosts,
|
2020-04-11 17:29:20 +03:00
|
|
|
addSshKey
|
2023-01-02 23:06:33 +03:00
|
|
|
};
|