tapbundle/ts_node/classes.tapnodetools.ts

66 lines
1.7 KiB
TypeScript

import * as plugins from './plugins.js';
import { createSign } from 'crypto';
class TapNodeTools {
private smartshellInstance: plugins.smartshell.Smartshell;
constructor() {}
public async runCommand(commandArg: string): Promise<any> {
if (!this.smartshellInstance) {
this.smartshellInstance = new plugins.smartshell.Smartshell({
executor: 'bash',
});
}
const result = await this.smartshellInstance.exec(commandArg);
return result;
}
public async createHttpsCert(
commonName: string = 'localhost'
): Promise<{ key: string; cert: string }> {
// Generate RSA key pair
const { publicKey, privateKey } = plugins.crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicExponent: 65537,
});
// Create a self-signed certificate
const cert = this.generateSelfSignedCert(publicKey, privateKey, commonName);
// Export the private key and return the cert and key
const keyContent = privateKey.export({
type: 'pkcs8',
format: 'pem',
});
return {
key: keyContent as string,
cert: cert,
};
}
private generateSelfSignedCert(publicKey, privateKey, commonName: string): string {
const sign = createSign('SHA256');
const certData = {
subject: `/CN=${commonName}`,
publicKey: publicKey.export({ type: 'spki', format: 'pem' }),
};
sign.update(JSON.stringify(certData));
sign.end();
const signature = sign.sign(privateKey, 'base64');
return (
'-----BEGIN CERTIFICATE-----\n' +
Buffer.from(certData.publicKey).toString('base64') +
'\n' +
signature +
'\n-----END CERTIFICATE-----\n'
);
}
}
export const tapNodeTools = new TapNodeTools();