UNPKG

@soinlabs/secrets

Version:

Key management library for SOIN Labs

84 lines (76 loc) 2.02 kB
const { SimpleError: StandardError } = require('@soinlabs/errors') const crypto = require('crypto') class EnvProvider { constructor(configOptions) { this.secretManager = {} this.configureSecretManager(configOptions) } configureSecretManager(configOptions) { if ( configOptions && configOptions.encryptionKey && configOptions.encryptionVector ) { this.secretManager.encryptionKey = configOptions.encryptionKey this.secretManager.encryptionVector = configOptions.encryptionVector } else { throw new StandardError({ code: 500, message: 'EnvProvider missing required data' }) } } decryptSecrets(secretData) { try { const data = {} if (this.secretManager !== null) { for (const key in secretData) { data[key] = this.decrypt(secretData[key]) } } return data } catch (error) { throw new StandardError({ code: 500, message: error.message }) return false } } async getSecret(key) { return await this.decryptSecrets(key) } getSecretSync(key) { return this.decryptSecrets(key) } decrypt(data) { try { let chunk = '' const decryptionKey = this.base64Decoding( this.secretManager.encryptionKey ) const iv = this.base64Decoding(this.secretManager.encryptionVector) const decipher = crypto.createDecipheriv('aes-256-cbc', decryptionKey, iv) let decrypted = '' decipher.on('readable', () => { // eslint-disable-next-line while ((chunk = decipher.read()) !== null) { decrypted += chunk.toString('utf8') } }) decipher.write(data, 'base64') decipher.end() return decrypted } catch (error) { throw new StandardError({ code: 500, message: error.message }) return false } } base64Decoding(input) { return Buffer.from(input, 'base64') } } module.exports = EnvProvider