-
Notifications
You must be signed in to change notification settings - Fork 10
Migrate Telegram, Modica, and Line custom channels to account-scoped lambda #3962
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
6
commits into
master
Choose a base branch
from
copilot/migrate-custom-channels-lambda
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4566f0e
Initial plan
Copilot 86b0af8
Migrate Telegram, Modica, and Line custom channels to account-scoped …
Copilot 3fc1425
Add extra debug logging to new custom channel handlers, change receiv…
Copilot 6d0d0b1
Fix SSM parameter paths for Telegram, Modica, and Line channels to ma…
Copilot 03aa1df
Fix prettier formatting in configuration.ts SSM parameter functions
Copilot 2c8a806
Add testSessionId support to Telegram, Modica, and Line channels
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
131 changes: 131 additions & 0 deletions
131
lambdas/account-scoped/src/customChannels/line/flexToLine.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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
184
lambdas/account-scoped/src/customChannels/line/lineToFlex.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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.