import { logError } from "../utils" ; export class KMSService { public async decrypt ( ciphertext ) { try { const kms = require ( "aws-sdk/clients/kms" ) ; const kmsClient = new kms ( ) ; const buffer = Buffer . from ( ciphertext , "base64" ) ; let result ; try { result = await kmsClient . decrypt ( { CiphertextBlob : buffer } ) . promise ( ) ; } catch { const encryptionContext = { LambdaFunctionName : process . env . AWS_LAMBDA_FUNCTION_NAME ?? "" } ; result = await kmsClient . decrypt ( { CiphertextBlob : buffer , EncryptionContext : encryptionContext } ) . promise ( ) ; } if ( result . Plaintext === undefined ) { throw Error ( ) ; } return result . Plaintext . toString ( "ascii" ) ; } catch ( err ) { if ( ( err as any ) . code === "MODULE_NOT_FOUND" ) { const errorMsg = "optional dependency aws-sdk not installed. KMS key decryption will not work" ; logError ( errorMsg ) ; throw Error ( errorMsg ) ; } throw Error ( "Couldn't decrypt ciphertext" ) ; } } }