UNPKG

@soinlabs/secrets

Version:

Key management library for SOIN Labs

79 lines (70 loc) 2.17 kB
const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager') const { fromNodeProviderChain } = require('@aws-sdk/credential-providers') const { SimpleError: StandardError } = require('@soinlabs/errors') const sp = require('synchronized-promise') class AmazonProvider { constructor(configOptions) { this.secretManager = null this.configureSecretManager(configOptions) } configureSecretManager(configOptions) { if (configOptions && configOptions.region) { this.secretManager = new SecretsManagerClient({ region: configOptions.region }) this.validateFile().catch((err) => { console.error( 'Error during initial AWS credential validation:', err.message ) throw new StandardError({ code: 500, message: `Initialization failed: ${err.message}` }) }) } else { throw new StandardError({ code: 500, message: 'AmazonProvider at AWS.SecretManager: not region provided' }) } } // Validates AWS credentials using the v3 credential provider chain. async validateFile() { try { // Attempt to load credentials using the default Node.js provider chain. // If no credentials can be found, this will throw an error. await fromNodeProviderChain() } catch (err) { // Catch any error from fromNodeProviderChain and re-throw it as a StandardError. throw new StandardError({ code: 500, message: `AWS credentials not loaded: ${err.message}` }) } } async getSecretById(SecretId) { if (this.secretManager !== null) { try { const command = new GetSecretValueCommand({ SecretId }) const data = await this.secretManager.send(command) if ('SecretString' in data) { return JSON.parse(data.SecretString) } } catch (err) { throw err } } } async getSecret(key) { return await this.getSecretById(key) } getSecretSync(key) { let getSecret = sp(this.getSecretById.bind(this)) return getSecret(key) } } module.exports = AmazonProvider