All files / resources/api/v2 twilioBase.ts

96.72% Statements 177/183
92.1% Branches 35/38
100% Functions 2/2
96.72% Lines 177/183

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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 2341x         1x       1x   1x     1x       1x     1x     1x 1x 1x   1x   1x 1x   10x 10x 10x 10x 10x 6x 4x 10x 10x 10x 10x 10x 10x 10x                   1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 10x     10x 10x   10x 10x 10x 10x 10x 45x 45x 10x 10x 10x 10x 10x 10x 10x 10x 10x 9x 10x 1x 1x 1x     9x 9x 9x 9x 10x 10x 10x 10x 10x 9x 10x           9x 9x 10x 1x 1x 1x 8x 10x           8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 10x 1x 1x     7x 7x 7x 7x 7x 7x 10x 1x 1x 6x 6x 4x 4x 1x 10x 1x 1x     5x 5x 5x 4x 10x 1x 1x 1x 1x 1x 10x 1x 1x 1x 1x 1x     3x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x   1x 1x   1x 1x 1x  
import {
  SQSClient,
  SendMessageCommand
} from '@aws-sdk/client-sqs';
 
import {
  LambdaApiFunction,
  handleResourceApi
} from './_base';
import { validateTwilioRequest } from './_twilio';
 
import {
  getTwilioSecret, twilioPhoneNumbers
} from '@/deprecated/utils/general';
import {
  CreateTextApi, createTextBodyValidator, createTextQueryValidator
} from '@/types/api/twilio';
import { FullUserObject } from '@/types/api/users';
import { departmentConfig } from '@/types/backend/department';
import { TypedUpdateInput } from '@/types/backend/dynamo';
import { TwilioTextQueueItem } from '@/types/backend/queue';
import {
  TABLE_USER, typedGet, typedUpdate
} from '@/utils/backend/dynamoTyped';
import { validateObject } from '@/utils/backend/validation';
import { getLogger } from '@/utils/common/logger';
import { getUserPermissions } from '@/utils/common/user';
 
const logger = getLogger('twilioBase');
 
const sqs = new SQSClient();
const queueUrl = process.env.SQS_QUEUE;
 
function buildTwilioResponse(
  statusCode: keyof CreateTextApi['responses'],
  message?: string
): [ keyof CreateTextApi['responses'], string, null, string ] {
  const msgString = message
    ? `<Message>${message}</Message>`
    : '';
  return [
    statusCode,
    `<Response>${msgString}</Response>`,
    null,
    'application/xml',
  ];
}
 
interface TextCommand {
  response: string;
  update: Pick<
    TypedUpdateInput<FullUserObject>,
    'ExpressionAttributeNames' | 'ExpressionAttributeValues' | 'UpdateExpression'
  >;
}
 
const textCommands: {
  [key: string]: TextCommand;
} = {
  '!startTest': {
    response: 'Testing mode enabled',
    update: {
      ExpressionAttributeNames: {
        '#isTest': 'isTest',
      },
      ExpressionAttributeValues: {
        ':isTest': true,
      },
      UpdateExpression: 'SET #isTest = :isTest',
    },
  },
  '!endTest': {
    response: 'Testing mode disabled',
    update: {
      ExpressionAttributeNames: {
        '#isTest': 'isTest',
      },
      UpdateExpression: 'REMOVE #isTest',
    },
  },
};
 
const POST: LambdaApiFunction<CreateTextApi> = async function (event) {
  logger.trace('POST');
 
  // Get and validate the body
  const urlParamsBody = new URLSearchParams(event.body || '');
  const bodyObj: {
    [key: string]: unknown;
  } = {};
  for (const [
    key,
    value,
  ] of urlParamsBody.entries()) {
    bodyObj[key] = value;
  }
  const [
    body,
    bodyErrors,
  ] = validateObject<CreateTextApi['body']>(
    bodyObj,
    createTextBodyValidator
  );
  if (
    body === null ||
    bodyErrors.length > 0
  ) {
    logger.error('Invalid Request - body', bodyErrors, bodyObj);
    return buildTwilioResponse(400, 'There was an issue processing your request');
  }
 
  // Get and validate the query params
  const [
    query,
    queryErrors,
  ] = validateObject(
    event.queryStringParameters || {},
    createTextQueryValidator
  );
  if (
    query === null ||
    queryErrors.length > 0
  ) {
    logger.error('Invalid Request - query', queryErrors, event.queryStringParameters);
    return buildTwilioResponse(400, 'There was an issue processing your request');
  }
 
  // Get the phone number configurations
  const phoneNumberConfigs = await twilioPhoneNumbers();
  const twilioConf = await getTwilioSecret();
  if (typeof phoneNumberConfigs[body.To] === 'undefined') {
    logger.error(`Invalid phone number - ${body.To}`, body);
    return buildTwilioResponse(200);
  }
  const phoneNumberConf = phoneNumberConfigs[body.To];
  if (typeof twilioConf[`authToken${phoneNumberConf.account || ''}`] === 'undefined') {
    logger.error(`Invalid phone number account - ${phoneNumberConf.account || 'undef'}`, body, phoneNumberConf);
    return buildTwilioResponse(200);
  }
 
  // Validate the signature
  const [
    isValid,
    isTest,
  ] = validateTwilioRequest(
    event,
    query,
    bodyObj,
    phoneNumberConf,
    twilioConf
  );
  if (!isValid) {
    return buildTwilioResponse(200);
  }
 
  // Check for a user
  const sender = await typedGet<FullUserObject>({
    TableName: TABLE_USER,
    Key: {
      phone: Number(body.From.slice(2)),
    },
  });
  if (!sender.Item) {
    return buildTwilioResponse(200);
  }
  if (
    phoneNumberConf.type === 'page' &&
    typeof phoneNumberConf.department !== 'undefined' &&
    !getUserPermissions(sender.Item).adminDepartments.includes(phoneNumberConf.department) &&
    departmentConfig[phoneNumberConf.department].type === 'page'
  ) {
    return buildTwilioResponse(200, 'This department is not using the group text feature of this system');
  }
 
  // Validate that the user can send a message to this number
  const sendingUser = sender.Item;
  if (
    typeof phoneNumberConf.department === 'undefined' ||
    phoneNumberConf.type === 'alert'
  ) {
    return buildTwilioResponse(
      200,
      'This number is not able to receive messages'
    );
  }
  if (!sendingUser[phoneNumberConf.department]?.active) {
    return buildTwilioResponse(
      200,
      `You are not an active member of the ${phoneNumberConf.department} department`
    );
  }
 
  // Check for messages that are text commands
  const isTextCommand = typeof textCommands[body.Body] !== 'undefined';
  if (isTextCommand) {
    await typedUpdate<FullUserObject>({
      TableName: TABLE_USER,
      Key: {
        phone: sendingUser.phone,
      },
      ...textCommands[body.Body].update,
    });
    return buildTwilioResponse(
      200,
      textCommands[body.Body].response
    );
  } else if (body.Body.startsWith('!')) {
    return buildTwilioResponse(
      200,
      'Messages that begin with an exclamation mark are reserved for testing purposes'
    );
  }
 
  // Send the message into the queue
  const queueMessage: TwilioTextQueueItem = {
    action: 'twilio-text',
    body,
    user: {
      ...sendingUser,
      isTest: sendingUser.isTest || isTest,
    },
  };
  await sqs.send(new SendMessageCommand({
    MessageBody: JSON.stringify(queueMessage),
    QueueUrl: queueUrl,
  }));
 
  return buildTwilioResponse(200);
};
 
export const main = handleResourceApi.bind(null, {
  POST,
});