All files / resources/api/v2 _twilio.ts

100% Statements 44/44
88.88% Branches 8/9
100% Functions 1/1
100% Lines 44/44

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  1x           1x   1x   1x 17x 17x 17x     17x 17x 17x   17x 17x 17x     17x 17x 15x 15x 15x 15x 15x 15x 17x 3x 3x 3x 3x 3x 3x     14x 14x   2x 2x   17x 1x 1x 1x 1x 1x 1x   13x 13x 13x 13x 13x  
import { APIGatewayProxyEvent } from 'aws-lambda';
import * as twilio from 'twilio';
 
import {
  PhoneNumberConfig, TwilioConfig
} from '@/deprecated/utils/general';
import { CreateTextApi } from '@/types/api/twilio';
import { getLogger } from '@/utils/common/logger';
 
const logger = getLogger('_twilio');
 
export function validateTwilioRequest(
  event: APIGatewayProxyEvent,
  query: CreateTextApi['query'],
  bodyObj: {
    [key: string]: unknown;
  },
  phoneNumberConf: PhoneNumberConfig,
  twilioConf: TwilioConfig
): [ boolean, boolean ] {
  // Get the information needed out of the request
  const signature = event.headers['X-Twilio-Signature'];
  const url = `${event.headers['X-Forwarded-Proto']}://${event.headers['X-Forwarded-Host']}${event.path}`;
  const isTest = typeof signature === 'undefined';
 
  // Validate a production request
  if (
    !isTest &&
    !twilio.validateRequest(
      twilioConf[`authToken${phoneNumberConf.account || ''}`],
      signature || '',
      url,
      bodyObj
    )
  ) {
    logger.error('Not Verified');
    return [
      false,
      isTest,
    ];
  }
 
  // Validate a test request
  if (
    isTest &&
    (
      typeof query.code === 'undefined' ||
      query.code !== twilioConf.apiCode
    )
  ) {
    logger.error('Not verified - test mode');
    return [
      false,
      isTest,
    ];
  }
 
  return [
    true,
    isTest,
  ];
}