import { CreateAuthChallengeTriggerEvent } from 'aws-lambda' ; import { randomDigits } from 'crypto-secure-random-digit' ; import { SES } from 'aws-sdk' ; import { verifyText , verifyHTML } from './email' ; export const createAuthChallengeHandler = async ( event ) => { try { const domain = process . env . DOMAIN ; const fromAddress = process . env . FROM_ADDRESS ; if ( typeof domain !== 'string' ) { throw new Error ( 'No DOMAIN defined in ENV' ) ; } if ( typeof fromAddress !== 'string' ) { throw new Error ( 'No FROM_ADDRESS defined in ENV' ) ; } let secretLoginCode ; if ( ! event . request . session || ! event . request . session . length ) { secretLoginCode = randomDigits ( 6 ) . join ( '' ) ; await sendEmail ( domain , event . request . userAttributes . email , secretLoginCode , fromAddress ) ; } else { const previousChallenge = event . request . session . slice ( - 1 ) [ 0 ] ; secretLoginCode = previousChallenge . challengeMetadata ! . match ( /CODE-(\d*)/ ) ! [ 1 ] ; } event . response . publicChallengeParameters = { email : event . request . userAttributes . email } ; event . response . privateChallengeParameters = { secretLoginCode } ; event . response . challengeMetadata = `CODE-${ secretLoginCode }` ; return event ; } catch ( error ) { console . error ( JSON . stringify ( { level : 'ERROR' , error : error . message + '\n' + error . stack } ) ) ; throw error ; } } ; async function sendEmail ( domain , emailAddress , secretLoginCode , fromAddress ) { const params = { Destination : { ToAddresses : [ emailAddress ] } , Message : { Body : { Html : { Charset : 'UTF-8' , Data : verifyHTML ( domain , secretLoginCode ) , } , Text : { Charset : 'UTF-8' , Data : verifyText ( secretLoginCode ) , } , } , Subject : { Charset : 'UTF-8' , Data : 'Office Booker - Verify' , } , } , Source : fromAddress , } ; console . log ( JSON . stringify ( params , null , 2 ) ) ; const ses = new SES ( ) ; await ses . sendEmail ( params ) . promise ( ) ; }