All files / auth custom-message.js

100% Statements 28/28
100% Branches 17/17
100% Functions 2/2
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                          1x 1x 1x 1x 1x   1x   1x       9x 7x     6x 5x     5x 2x     1x 10x 9x 9x 9x 9x 8x 8x 8x   1x   9x    
// @implements UC-SPACE-008.1
/**
 * Cognito Custom Message trigger: the sign-up verification email, sent again
 * with the same look when the code is resent. A sign-up started from a join
 * page passes the flow's slug and the UI language in its client metadata
 * (flows-ui stores/auth.ts); the email then shows the flow while its space is
 * published. See docs/architecture/FLOW_SPACE.md "Emails in the flow's colours".
 *
 * Every other message (forgotten password, attribute change) keeps the user
 * pool's own. This trigger must never fail a sign-up: on any error, the event
 * goes back unchanged and Cognito sends the pool's default verification email.
 */
 
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb')
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb')
const { EMAIL_LANGUAGES } = require('../utils/email')
const { SLUG_REGEX } = require('../utils/spaceJoin')
const { renderVerificationEmail } = require('../utils/emailTemplates/verificationCode')
 
const docClient = DynamoDBDocumentClient.from(new DynamoDBClient({}))
 
const VERIFICATION_TRIGGERS = ['CustomMessage_SignUp', 'CustomMessage_ResendCode']
 
/** The flow whose published space the sign-up started from, or null */
async function loadJoinFlow(slug) {
  if (typeof slug !== 'string' || !SLUG_REGEX.test(slug)) return null
  const { Item: slugItem } = await docClient.send(
    new GetCommand({ TableName: process.env.FLOW_SLUGS_TABLE_NAME, Key: { slug } })
  )
  if (!slugItem?.flowId) return null
  const { Item: flow } = await docClient.send(
    new GetCommand({ TableName: process.env.FLOWS_TABLE_NAME, Key: { id: slugItem.flowId } })
  )
  if (!flow || flow.status !== 'active' || flow.space?.enabled !== true) return null
  return flow
}
 
exports.handler = async (event) => {
  if (!VERIFICATION_TRIGGERS.includes(event.triggerSource)) return event
  try {
    const metadata = event.request?.clientMetadata || {}
    const lang = EMAIL_LANGUAGES.includes(metadata.lang) ? metadata.lang : 'en'
    const flow = await loadJoinFlow(metadata.joinSlug)
    const { subject, html } = renderVerificationEmail({ lang, flow })
    event.response.emailSubject = subject
    event.response.emailMessage = html
  } catch (error) {
    console.error('Custom message failed, the default verification email is sent:', error)
  }
  return event
}