Files
szci/ts/mod_ssh/index.ts
2025-12-14 01:42:14 +00:00

98 lines
2.6 KiB
TypeScript

import { logger } from '../szci.logging.ts';
import * as plugins from './mod.plugins.ts';
let sshInstance: plugins.smartssh.SshInstance;
/**
* Interface for CLI arguments
*/
interface ICliArgs {
_: string[];
[key: string]: unknown;
}
/**
* Handle SSH CLI commands
*/
export const handleCli = async (argvArg: ICliArgs): Promise<void> => {
if (argvArg._.length >= 2) {
const action = argvArg._[1];
switch (action) {
case 'prepare':
await prepare();
break;
default:
logger.log('error', `action >>${action}<< not supported`);
Deno.exit(1);
}
} else {
logger.log('error', `>>szci ssh ...<< please specify an action!`);
Deno.exit(1);
}
};
/**
* Checks if a string value is defined and not a placeholder
*/
const isValidValue = (value: string | undefined): boolean => {
return Boolean(value && value !== 'undefined' && value !== '##');
};
/**
* Checks for ENV vars in form of SZCI_SSHKEY_* and deploys any found ones
*/
export const prepare = async (): Promise<void> => {
sshInstance = new plugins.smartssh.SshInstance();
// Get all env vars and filter for SSH keys
const envVars = Deno.env.toObject();
const sshKeyEnvVars = Object.entries(envVars).filter(([key]) =>
key.startsWith('SZCI_SSHKEY_')
);
// Process each SSH key env var
for (const [key, value] of sshKeyEnvVars) {
logger.log('info', `Processing SSH key from ${key}`);
addSshKeyFromEnvVar(value);
}
// Only write to disk if not in test mode
if (!Deno.env.get('SZCI_TEST')) {
try {
sshInstance.writeToDisk();
logger.log('ok', 'SSH keys written to disk');
} catch (error) {
logger.log('error', `Failed to write SSH keys: ${(error as Error).message}`);
throw error;
}
} else {
logger.log('info', 'In test mode, so not storing SSH keys to disk!');
}
};
/**
* Parses an SSH key env var and adds it to the SSH instance
* Format: host|privKeyBase64|pubKeyBase64
*/
const addSshKeyFromEnvVar = (sshkeyEnvVarArg: string): void => {
const [host, privKeyBase64, pubKeyBase64] = sshkeyEnvVarArg.split('|');
const sshKey = new plugins.smartssh.SshKey();
logger.log('info', `Found SSH identity for ${host || 'unknown host'}`);
if (isValidValue(host)) {
logger.log('info', '---> host defined!');
sshKey.host = host;
}
if (isValidValue(privKeyBase64)) {
logger.log('info', '---> privKey defined!');
sshKey.privKeyBase64 = privKeyBase64;
}
if (isValidValue(pubKeyBase64)) {
logger.log('info', '---> pubKey defined!');
sshKey.pubKeyBase64 = pubKeyBase64;
}
sshInstance.addKey(sshKey);
};