From 2abde464d9fc811832da82766d560e9e6c33fa00 Mon Sep 17 00:00:00 2001 From: arpandhakal Date: Mon, 4 Aug 2025 12:38:54 +0545 Subject: [PATCH] fix(OUT-2106): Autoresponder sending messages very late due to slow webhook invocation making it seem like autoresponder sending messages without being triggered by a client message. - created a hasTimeExceeded method which checks if the webhook's payload's createdAt timestamp is older than 60 seconds while auto responding. - If the webhook's payload's createdAt is older than 60 seconds, skipped the auto responding functionality. --- src/app/api/messages/webhook/route.ts | 5 +++++ src/constants/index.ts | 2 ++ src/utils/hasTimeExceeded.ts | 9 +++++++++ 3 files changed, 16 insertions(+) create mode 100644 src/utils/hasTimeExceeded.ts diff --git a/src/app/api/messages/webhook/route.ts b/src/app/api/messages/webhook/route.ts index a2e2986d..8db90100 100644 --- a/src/app/api/messages/webhook/route.ts +++ b/src/app/api/messages/webhook/route.ts @@ -4,6 +4,7 @@ import { MessageSchema } from '@/types/message'; import { MessageService } from '@/app/api/messages/services/message.service'; import appConfig from '@/config/app'; import { WebhookSchema } from '@/types/webhook'; +import { hasTimeExceeded } from '@/utils/hasTimeExceeded'; export async function POST(request: NextRequest) { const rawBody = await request.text(); @@ -48,6 +49,10 @@ export async function POST(request: NextRequest) { ); } } + if (hasTimeExceeded(payload.data.createdAt)) { + console.info('Autoresponse failed due to stale webhook timestamp. ', payload.data); + return NextResponse.json({}); + } const messageService = new MessageService(); await messageService.handleSendMessageWebhook(payload.data, { diff --git a/src/constants/index.ts b/src/constants/index.ts index fd4db506..7fa712e1 100644 --- a/src/constants/index.ts +++ b/src/constants/index.ts @@ -7,6 +7,8 @@ export enum AUTO_RESPONSE { OFF = 'off', } +export const AUTO_RESPONSE_TIME_THRESHOLD = 60; + export const AUTO_RESPONSE_OPTIONS: SelectOption<$Enums.SettingType>[] = [ { value: $Enums.SettingType.OUTSIDE_WORKING_HOURS, diff --git a/src/utils/hasTimeExceeded.ts b/src/utils/hasTimeExceeded.ts new file mode 100644 index 00000000..ce873997 --- /dev/null +++ b/src/utils/hasTimeExceeded.ts @@ -0,0 +1,9 @@ +import { AUTO_RESPONSE_TIME_THRESHOLD } from '@/constants'; + +export function hasTimeExceeded(createdAt: string): boolean { + const thresholdInSeconds = AUTO_RESPONSE_TIME_THRESHOLD || 60; + const createdTime = new Date(createdAt).getTime(); + const currentTime = Date.now(); + const diffInSeconds = Math.abs(currentTime - createdTime) / 1000; + return diffInSeconds > thresholdInSeconds; +}