Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lambdas/account-scoped/src/customChannels/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,21 @@ export const getChannelStudioFlowSid = (
getSsmParameter(
`/${process.env.NODE_ENV}/twilio/${accountSid}/${channelName}_studio_flow_sid`,
);

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These SSM parameter names are all wrong, see https://github.com/techmatters/serverless/blob/master/.github/actions/custom-actions/aselo_development_custom/action.yml for examples of correct naming for these parameters

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6d0d0b1. The SSM paths now use the channel name as the service segment (e.g. /development/telegram/{accountSid}/bot_api_secret_token, /development/modica/{accountSid}/app_name, /development/line/{accountSid}/channel_secret) matching the pattern in the serverless action.yml.

export const getTelegramBotApiSecretToken = (accountSid: AccountSID): Promise<string> =>
getSsmParameter(`/${process.env.NODE_ENV}/telegram/${accountSid}/bot_api_secret_token`);

export const getTelegramFlexBotToken = (accountSid: AccountSID): Promise<string> =>
getSsmParameter(`/${process.env.NODE_ENV}/telegram/${accountSid}/flex_bot_token`);

export const getModicaAppName = (accountSid: AccountSID): Promise<string> =>
getSsmParameter(`/${process.env.NODE_ENV}/modica/${accountSid}/app_name`);

export const getModicaAppPassword = (accountSid: AccountSID): Promise<string> =>
getSsmParameter(`/${process.env.NODE_ENV}/modica/${accountSid}/app_password`);

export const getLineChannelSecret = (accountSid: AccountSID): Promise<string> =>
getSsmParameter(`/${process.env.NODE_ENV}/line/${accountSid}/channel_secret`);

export const getLineChannelAccessToken = (accountSid: AccountSID): Promise<string> =>
getSsmParameter(`/${process.env.NODE_ENV}/line/${accountSid}/channel_access_token`);
131 changes: 131 additions & 0 deletions lambdas/account-scoped/src/customChannels/line/flexToLine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* Copyright (C) 2021-2023 Technology Matters
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import crypto from 'crypto';
import {
ConversationWebhookEvent,
ExternalSendResult,
redirectConversationMessageToExternalChat,
RedirectResult,
TEST_SEND_URL,
} from '../flexToCustomChannel';
import { AccountScopedHandler, HttpError, HttpRequest } from '../../httpTypes';
import { isErr, newOk, Result } from '../../Result';
import { newMissingParameterResult } from '../../httpErrors';
import { getTwilioClient } from '@tech-matters/twilio-configuration';
import { getLineChannelAccessToken } from '../configuration';
import { AccountSID } from '@tech-matters/twilio-types';

const LINE_SEND_MESSAGE_URL = 'https://api.line.me/v2/bot/message/push';

export type Body = ConversationWebhookEvent & {
recipientId: string; // The Line id of the user that started the conversation. Provided as query parameter
};

const sendLineMessage =
(lineChannelAccessToken: string) =>
async (
recipientId: string,
messageText: string,
testSessionId?: string,
): Promise<ExternalSendResult> => {
const payload = {
to: recipientId,
messages: [
{
type: 'text',
text: messageText,
},
],
};

const headers = {
'Content-Type': 'application/json',
'X-Line-Retry-Key': crypto.randomUUID(),
Authorization: `Bearer ${lineChannelAccessToken}`,
...(testSessionId ? { 'x-webhook-receiver-session-id': testSessionId } : {}),
};

const sendUrl = testSessionId ? TEST_SEND_URL : LINE_SEND_MESSAGE_URL;
const response = await fetch(sendUrl, {
method: 'post',
body: JSON.stringify(payload),
headers,
});

return {
ok: response.ok,
resultCode: response.status,
body: await response.json(),
meta: Object.fromEntries(Object.entries(response.headers)),
};
};

const validateProperties = (
event: any,
requiredProperties: string[],
): Result<HttpError, true> => {
for (const prop of requiredProperties) {
if (event[prop] === undefined) {
return newMissingParameterResult(prop);
}
}
return newOk(true);
};

export const flexToLineHandler: AccountScopedHandler = async (
{ body: event, query: { recipientId } }: HttpRequest,
accountSid: AccountSID,
) => {
console.info('==== FlexToLine handler ====');
console.debug('FlexToLine: received event:', event);

if (!recipientId) {
return newMissingParameterResult('recipientId');
}

let result: RedirectResult;
const requiredProperties: (keyof ConversationWebhookEvent)[] = [
'ConversationSid',
'Body',
'Author',
'EventType',
'Source',
];
const validationResult = validateProperties(event, requiredProperties);
if (isErr(validationResult)) {
return validationResult;
}

const lineChannelAccessToken = await getLineChannelAccessToken(accountSid);
const client = await getTwilioClient(accountSid);
console.debug('FlexToLine: redirecting message to recipientId:', recipientId);
result = await redirectConversationMessageToExternalChat(client, {
event,
recipientId,
sendExternalMessage: sendLineMessage(lineChannelAccessToken),
});

console.debug('FlexToLine: result status:', result.status);
switch (result.status) {
case 'sent':
return newOk(result.response);
case 'ignored':
return newOk({ message: 'Ignored event' });
default:
throw new Error('Reached unexpected default case');
}
};
184 changes: 184 additions & 0 deletions lambdas/account-scoped/src/customChannels/line/lineToFlex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/**
* Copyright (C) 2021-2023 Technology Matters
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/

import crypto from 'crypto';
import { AccountSID } from '@tech-matters/twilio-types';
import {
AseloCustomChannel,
sendConversationMessageToFlex,
} from '../customChannelToFlex';
import { AccountScopedHandler, HttpRequest } from '../../httpTypes';
import { newErr, newOk } from '../../Result';
import { getChannelStudioFlowSid, getLineChannelSecret } from '../configuration';

export const LINE_SIGNATURE_HEADER = 'x-line-signature';

type LineMessage = {
type: 'text' | string;
id: string;
text: string;
};

type LineSource = {
type: 'user' | 'group' | 'room';
userId: string;
};

type LineEvent = {
type: 'message' | string;
message: LineMessage;
timestamp: number;
replyToken: string;
source: LineSource;
};

export type Body = {
destination: string;
events: LineEvent[];
testSessionId?: string; // Only used in Aselo integration tests, not sent from Line
};

// Line seems to have generated signatures using escaped unicode for emoji characters
// https://gist.github.com/jirawatee/366d6bef98b137131ab53dfa079bd0a4
const fixUnicodeForLine = (text: string): string =>
text.replace(/\p{Emoji_Presentation}/gu, emojiChars =>
emojiChars
.split('')
.map(c => `\\u${c.charCodeAt(0).toString(16).toUpperCase()}`)
.join(''),
);

/**
* Validates that the payload is signed with LINE_CHANNEL_SECRET so we know it's coming from Line
*/
const isValidLinePayload = (
body: Body,
xLineSignature: string | undefined,
lineChannelSecret: string,
): boolean => {
if (!xLineSignature) return false;

const payloadAsString = JSON.stringify(body);

const expectedSignature = crypto
.createHmac('sha256', lineChannelSecret)
.update(fixUnicodeForLine(payloadAsString))
.digest('base64');

try {
return crypto.timingSafeEqual(
Buffer.from(xLineSignature),
Buffer.from(expectedSignature),
);
} catch (e) {
console.warn('Unknown error validating signature (rejecting with 403):', e);
return false;
}
};

export const lineToFlexHandler: AccountScopedHandler = async (
{ body, headers }: HttpRequest,
accountSid: AccountSID,
) => {
console.info('==== LineToFlex handler ====');

const lineChannelSecret = await getLineChannelSecret(accountSid);
const xLineSignature = headers[LINE_SIGNATURE_HEADER];

if (!isValidLinePayload(body, xLineSignature, lineChannelSecret)) {
return newErr({
message: 'Forbidden',
error: { statusCode: 403 },
});
}

const event: Body = body;
console.debug('LineToFlex: validated event body:', event);
const { destination, events } = event;

const messageEvents = events.filter(e => e.type === 'message');
console.debug(
'LineToFlex: destination:',
destination,
'- message events count:',
messageEvents.length,
'/ total events:',
events.length,
);

if (messageEvents.length === 0) {
return newOk({ message: 'No messages to send' });
}

const studioFlowSid = await getChannelStudioFlowSid(
accountSid,
AseloCustomChannel.Line,
);
const responses: any[] = [];

for (const messageEvent of messageEvents) {
const messageText = messageEvent.message.text;
const channelType = AseloCustomChannel.Line;
const subscribedExternalId = destination; // AseloChat ID on Line
const senderExternalId = messageEvent.source.userId; // The child ID on Line
const chatFriendlyName = `${channelType}:${senderExternalId}`;
const uniqueUserName = `${channelType}:${senderExternalId}`;
const senderScreenName = 'child';
const onMessageSentWebhookUrl = `${process.env.WEBHOOK_BASE_URL}/lambda/twilio/account-scoped/${accountSid}/customChannels/line/flexToLine?recipientId=${senderExternalId}`;
console.debug(
'LineToFlex: sending message from',
uniqueUserName,
'to studio flow',
studioFlowSid,
);

// eslint-disable-next-line no-await-in-loop
const result = await sendConversationMessageToFlex(accountSid, {
studioFlowSid,
channelType,
uniqueUserName,
senderScreenName,
onMessageSentWebhookUrl,
messageText,
senderExternalId,
customSubscribedExternalId: subscribedExternalId,
conversationFriendlyName: chatFriendlyName,
testSessionId: event.testSessionId,
});

console.debug(
'LineToFlex: result status:',
result.status,
'for sender',
uniqueUserName,
);
switch (result.status) {
case 'sent':
responses.push(result.response);
break;
case 'ignored':
responses.push({ message: 'Ignored event.' });
break;
default:
return newErr({
message: 'Reached unexpected default case',
error: { statusCode: 500, error: new Error('Reached unexpected default case') },
});
}
}

return newOk(responses);
};
Loading
Loading