All files / utils turnstile.js

100% Statements 35/35
100% Branches 22/22
100% Functions 3/3
100% Lines 30/30

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                2x   2x   2x   2x   2x   2x   2x         12x 11x 11x 10x 9x 9x 7x 7x                     19x 12x 12x 11x 3x 3x   8x           7x 7x 3x       3x   2x 2x           22x     2x  
// @implements UC-AUTH-009.1
/**
 * Cloudflare Turnstile, the CAPTCHA of a sign-up (docs/architecture/FLOW_SPACE.md,
 * "Abuse and costs"). The sign-up page sends the widget's token to
 * Cognito as validation data; the Pre Sign-up trigger checks it here, so a bot
 * calling Cognito's SignUp directly (the app client id is public) is refused
 * too, before any user exists, any MAU is counted or any email is sent.
 */
const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager')
 
const SITEVERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'
/** The widget's action on the sign-up page (flows-ui TurnstileWidget) */
const SIGNUP_ACTION = 'signup'
/** Cloudflare's own limit on a token */
const MAX_TOKEN_LENGTH = 2048
/** Cognito waits 5 seconds for the whole trigger */
const SITEVERIFY_TIMEOUT_MS = 3000
/** The value the secret is created with, until the real key is filled in */
const PLACEHOLDER_SECRET = 'REPLACE_WITH_TURNSTILE_SECRET_KEY'
 
const secretsClient = new SecretsManagerClient({})
let cachedSecretKey
 
/** The Turnstile secret key, read once per Lambda instance; undefined if not filled in */
async function secretKey() {
  if (cachedSecretKey) return cachedSecretKey
  const arn = process.env.TURNSTILE_SECRET_ARN
  if (!arn) return undefined
  const result = await secretsClient.send(new GetSecretValueCommand({ SecretId: arn }))
  const key = JSON.parse(result.SecretString || '{}').secretKey
  if (typeof key !== 'string' || !key || key === PLACEHOLDER_SECRET) return undefined
  cachedSecretKey = key
  return key
}
 
/**
 * Whether `token` is a valid, unused Turnstile token of the sign-up widget.
 * Fails closed: a missing secret or an unreachable Cloudflare refuses the
 * sign-up (the visitor can retry) rather than letting bots through.
 * @param {unknown} token
 * @returns {Promise<boolean>}
 */
async function verifyTurnstileToken(token) {
  if (typeof token !== 'string' || !token || token.length > MAX_TOKEN_LENGTH) return false
  try {
    const secret = await secretKey()
    if (!secret) {
      console.error('Turnstile secret key is not set: every sign-up is refused')
      return false
    }
    const response = await fetch(SITEVERIFY_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ secret, response: token }),
      signal: AbortSignal.timeout(SITEVERIFY_TIMEOUT_MS)
    })
    const result = await response.json()
    if (result.success === true && result.action === SIGNUP_ACTION) return true
    console.error('Turnstile token refused:', {
      errorCodes: result['error-codes'],
      action: result.action
    })
    return false
  } catch (error) {
    console.error('Turnstile verification failed:', error)
    return false
  }
}
 
/** For the tests: forget the secret read by a previous invocation */
function resetTurnstileCache() {
  cachedSecretKey = undefined
}
 
module.exports = { verifyTurnstileToken, resetTurnstileCache, SIGNUP_ACTION, PLACEHOLDER_SECRET }