meta-cloud-api 0.2.26 → 0.2.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {a as a$1,b as b$1}from'./chunk-HEVRZRB4.js';import {a}from'./chunk-VW3LGHTJ.js';import*as g from'crypto';import g__default from'crypto';var F=(o=>(o.DELIVERED="delivered",o.READ="read",o.SENT="sent",o))(F||{});function W(e){return typeof e=="object"&&e!==null}function l(e){return typeof e=="string"}var T=["data_exchange","INIT","BACK"],S=["data_exchange","INIT"];function v(e){if(!("flow_token"in e&&l(e.flow_token)&&"action"in e))return false;let{action:t,version:n,screen:o,data:s}=e,i=n==="3.0",a=T.includes(t),c=typeof o>"u"||l(o)&&o!=="SUCCESS",r=t==="data_exchange"||W(s);return i&&a&&c&&r}function A(e){if(!("flow_token"in e&&l(e.flow_token)&&"action"in e))return false;let{action:t,screen:n,data:o}=e,s=S.includes(t),i=l(n),a=W(o)&&"error_key"in o&&l(o.error)&&"error_message"in o&&l(o.error_message);return s&&i&&a}function M(e){return "action"in e&&e.action==="ping"}var N="WEBHOOK_UTILS",d=new a(N,process.env.DEBUG==="true");function b(e,t){let n=e.query["hub.mode"],o=e.query["hub.verify_token"],s=e.query["hub.challenge"];return n!==void 0&&o!==void 0&&s!==void 0?n==="subscribe"&&o===t?(d.log("Webhook verified successfully"),{statusCode:200,body:s}):(d.log("Webhook verification failed"),{statusCode:403}):(d.log("Not a webhook verification request - missing required parameters"),{statusCode:400,body:{error:"Invalid webhook verification request"}})}async function _(e,t,n){let o=e.body,s=[];if(o.object!=="whatsapp_business_account"){let i="Received webhook for non-WhatsApp event";return d.log(i),{statusCode:404,body:{error:i}}}for(let i of o.entry)try{let a=i.changes;for(let c of a)c.field==="messages"&&await B(c.value,t,n);}catch(a){let c=`Error processing webhook: ${a}`;d.log(c),s.push(c);}return {statusCode:200,body:s.length>0?{errors:s}:void 0}}async function w(e,t,n,o){try{if(!I(e,t.WEBHOOK_VERIFICATION_TOKEN||""))return d.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let s=JSON.parse(e.rawBody||"{}"),{decryptedBody:i}=O(s,t),a=o.get("*");if(!a)return d.log(`No handler registered for flow action: ${i.action}`),{statusCode:404,body:{error:"Handler not found"}};if(M(i))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(A(i))return d.log(`Flow error: ${JSON.stringify(i)}`),{statusCode:200,body:{}};if(v(i)){let c=await a(n,i);return {statusCode:200,body:D(c,Buffer.from(s.aes_key,"base64"),Buffer.from(s.initial_vector,"base64"))}}return d.log(`Unknown flow request type: ${JSON.stringify(i)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(s){return d.log(`Error handling flow request: ${s}`),{statusCode:500,body:{error:"Internal server error"}}}}async function B(e,t,n){let o=e.metadata,s=o.display_phone_number,i=o.phone_number_id,a=e.contacts[0]?.profile?.name||"",c=e.messages;if(e.statuses&&e.statuses.length>0){for(let r of e.statuses){let p={id:r.id,from:r.recipient_id,timestamp:r.timestamp,type:"statuses",phoneNumberId:i,displayPhoneNumber:s,profileName:a,statuses:{phoneNumberId:i,displayPhoneNumber:s,...r},originalData:r};r.context&&(p.context=r.context),r.errors&&(p.errors=r.errors),await y(n.messageHandlers.get("statuses"),t,p,"statuses");}return}if(c&&c.length>0)for(let r of c){let p=r.type,u={id:r.id,from:r.from,timestamp:r.timestamp,type:r.type,phoneNumberId:i,displayPhoneNumber:s,profileName:a,text:r.text,image:r.image,video:r.video,audio:r.audio,document:r.document,sticker:r.sticker,location:r.location,contacts:r.contacts,interactive:r.interactive,button:r.button,order:r.order,system:r.system,errors:r.errors,context:r.context,originalData:r};await y(n.preProcessHandler,t,u,"pre-process"),await y(n.messageHandlers.get(p),t,u,p),await y(n.postProcessHandler,t,u,"post-process");}}async function y(e,t,n,o){if(e)try{await e(t,n);}catch(s){d.log(`Error in ${o} handler: ${s}`);}}function I(e,t){let n=e.headers["x-hub-signature-256"];if(!n||!e.rawBody)return false;let s=`sha256=${g__default.createHmac("sha256",t).update(e.rawBody,"utf8").digest("hex")}`;return g__default.timingSafeEqual(Buffer.from(n),Buffer.from(s))}function O(e,t){let{encrypted_aes_key:n,encrypted_flow_data:o,initial_vector:s}=e;if(!n||!o||!s)throw new Error("Missing required encryption properties");let i=t.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
|
|
2
|
+
`),a=t.FLOW_API_PASSPHRASE,c=g__default.createPrivateKey({key:i,passphrase:a}),r;try{r=g__default.privateDecrypt({key:c,padding:g__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(n,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let p=Buffer.from(o,"base64"),u=Buffer.from(s,"base64"),P=p.subarray(0,-16),C=p.subarray(-16),h=g__default.createDecipheriv("aes-128-gcm",r,u);h.setAuthTag(C);let q=Buffer.concat([h.update(P),h.final()]).toString("utf-8");return {decryptedBody:JSON.parse(q),aesKeyBuffer:r,initialVectorBuffer:u}}function D(e,t,n){let o=[];for(let s of Array.from(n.entries()))o.push(~s[1]);try{let s=g__default.createCipheriv("aes-128-gcm",t,Buffer.from(o));return Buffer.concat([s.update(JSON.stringify(e||{}),"utf-8"),s.final(),s.getAuthTag()]).toString("base64")}catch(s){throw d.log("Response encryption error:",s),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",f=new a(V,process.env.DEBUG==="true"),k=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(t){this.config=a$1(t),this.client=new b$1(t),f.log("WebhookHandler instantiated!");}handleVerification=t=>b(t,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async t=>_(t,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler});handleFlow=async t=>w(t,this.config,this.client,this.flowHandlers);onMessage(t,n){this.messageHandlers.set(t,n),f.log(`Registered message handler for ${t}`);}onMessagePreProcess(t){this.preProcessHandler=t,f.log("Registered pre-process handler");}onMessagePostProcess(t){this.postProcessHandler=t,f.log("Registered post-process handler");}onFlow(t,n){this.flowHandlers.set(t,n),f.log(`Registered flow handler for ${t}`);}};var oe=(e,t)=>g.createHmac("sha256",t).update(e,"utf-8").digest("hex");export{F as a,b,_ as c,w as d,k as e,oe as f};//# sourceMappingURL=chunk-575ICT3Y.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-575ICT3Y.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/webhook/types.ts","../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["MessageStatus","isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","verifyWebhook","verificationToken","mode","token","challenge","processWebhookMessages","whatsapp","handlers","body","errors","errorMsg","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","isRequestSignatureValid","decryptedBody","decryptFlowRequest","handler","result","encryptFlowResponse","metadata","displayPhoneNumber","phoneNumberId","profileName","messages","status","processedStatus","getMessageTypeData","executeHandler","message","messageType","processedMessage","typeData","handlerType","signature","formattedExpectedSignature","crypto","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","type","generateXHub256Sig","appSecret","P"],"mappings":"gJAioBYA,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACRA,EAAA,SAAY,CAAA,WAAA,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AAgC,EAC/C,CAKO,qBAAqBwB,CAA+B,CAAA,CACvD,IAAK,CAAA,kBAAA,CAAqBA,EAC1BxB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,OAAOkE,CAAoB1C,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,aAAa,GAAI0C,CAAAA,CAAAA,CAAM1C,CAAO,CACnCxB,CAAAA,CAAAA,CAAO,IAAI,CAA+BkE,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ,EC1FO,IAAMC,GAAqB,CAACzD,CAAAA,CAAc0D,IAC/BC,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUD,CAAS,CAAE,CAAA,MAAA,CAAO1D,EAAM,OAAO,CAAA,CAAE,OAAO,KAAK","file":"chunk-QMNPAR5X.js","sourcesContent":["import { MessageTypesEnum } from '@shared/types/enums';\n\nexport interface WebhookContact {\n /**\n * WhatsApp ID of the contact. Business can respond to this contact using this ID.\n */\n wa_id: string;\n /**\n * Additional unique, alphanumeric identifier for a WhatsApp user\n */\n user_id?: string;\n /**\n * Profile of Whatsapp user\n */\n profile: {\n /**\n * The display name of the contact\n */\n name: string;\n };\n}\n\n/**\n * Represents a message received through the webhook\n * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#messages-object\n */\nexport interface WebhookMessage {\n /**\n * The message ID\n */\n id: string;\n\n /**\n * The sender's phone number\n */\n from: string;\n\n /**\n * The timestamp of the message\n */\n timestamp: string;\n\n /**\n * The type of message (text, image, etc.)\n */\n type: MessageTypesEnum;\n\n /**\n * The phone number ID that received the message\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the message\n */\n displayPhoneNumber: string;\n\n /**\n * The profile name of the sender\n */\n profileName: string;\n\n /**\n * Text object for text messages\n */\n text?: {\n /**\n * The text content of the message\n */\n body: string;\n };\n\n /**\n * Image object for image messages\n */\n image?: {\n /**\n * The image caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the image\n */\n sha256?: string;\n /**\n * The ID for the image\n */\n id: string;\n /**\n * The MIME type of the image\n */\n mime_type: string;\n };\n\n /**\n * Video object for video messages\n */\n video?: {\n /**\n * The video caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the video\n */\n sha256?: string;\n /**\n * The ID for the video\n */\n id: string;\n /**\n * The MIME type of the video\n */\n mime_type: string;\n };\n\n /**\n * Audio object for audio messages\n */\n audio?: {\n /**\n * The ID for the audio file\n */\n id: string;\n /**\n * The MIME type of the audio file\n */\n mime_type: string;\n /**\n * Whether the audio is a voice message\n */\n voice?: boolean;\n };\n\n /**\n * Document object for document messages\n */\n document?: {\n /**\n * The document caption (if provided)\n */\n caption?: string;\n /**\n * The document filename\n */\n filename: string;\n /**\n * The SHA256 hash of the document\n */\n sha256?: string;\n /**\n * The ID for the document\n */\n id: string;\n /**\n * The MIME type of the document\n */\n mime_type: string;\n };\n\n /**\n * Sticker object for sticker messages\n */\n sticker?: {\n /**\n * The ID for the sticker\n */\n id: string;\n /**\n * Whether this is an animated sticker\n */\n animated: boolean;\n /**\n * The MIME type of the sticker\n */\n mime_type: string;\n };\n\n /**\n * Reaction object for reaction messages\n */\n reaction?: {\n /**\n * The ID of the message being reacted to\n */\n message_id: string;\n /**\n * Emoji used for the reaction\n */\n emoji: string;\n };\n\n /**\n * Contacts object for contact messages\n */\n contacts?: Array<{\n /**\n * The contact's name\n */\n name: {\n /**\n * The formatted name\n */\n formatted_name: string;\n /**\n * The first name\n */\n first_name?: string;\n /**\n * The last name\n */\n last_name?: string;\n /**\n * The middle name\n */\n middle_name?: string;\n /**\n * The suffix\n */\n suffix?: string;\n /**\n * The prefix\n */\n prefix?: string;\n };\n /**\n * The contact's phone numbers\n */\n phones?: Array<{\n phone: string;\n type?: string;\n wa_id?: string;\n }>;\n /**\n * The contact's emails\n */\n emails?: Array<{\n email: string;\n type?: string;\n }>;\n /**\n * The contact's addresses\n */\n addresses?: Array<{\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n country?: string;\n country_code?: string;\n type?: string;\n }>;\n /**\n * The contact's organizations\n */\n org?: {\n company?: string;\n department?: string;\n title?: string;\n };\n /**\n * The contact's URLs\n */\n urls?: Array<{\n url: string;\n type?: string;\n }>;\n /**\n * The contact's birthday (YYYY-MM-DD format)\n */\n birthday?: string;\n }>;\n\n /**\n * Location object for location messages\n */\n location?: {\n /**\n * Latitude of the location\n */\n latitude: number;\n /**\n * Longitude of the location\n */\n longitude: number;\n /**\n * Name of the location\n */\n name?: string;\n /**\n * Address of the location\n */\n address?: string;\n };\n\n /**\n * Interactive object for interactive messages\n */\n interactive?: {\n /**\n * Type of the interactive message\n * Can be: button_reply, list_reply, flow, nfm_reply, etc.\n */\n type: string;\n /**\n * ID for the button that was clicked\n */\n button_reply?: {\n id: string;\n title: string;\n };\n /**\n * ID for the list item that was selected\n */\n list_reply?: {\n id: string;\n title: string;\n description?: string;\n };\n\n /**\n * NFM (No-Code Flow Message) reply data\n */\n nfm_reply?: {\n /**\n * Response data in JSON format\n */\n response_json: string;\n /**\n * Body text of the reply\n */\n body: string;\n /**\n * Name of the flow\n */\n name: string;\n };\n };\n\n /**\n * System object for system messages (like user phone number changes)\n */\n system?: {\n /**\n * The type of system update\n */\n type: string;\n /**\n * User's identity if the update is a customer identity change\n */\n identity?: string;\n /**\n * Old and new phone numbers if the update is a phone number change\n */\n customer?: {\n /**\n * The previous phone number\n */\n previous_wa_id: string;\n /**\n * The new phone number\n */\n wa_id: string;\n };\n };\n\n /**\n * Order object for order messages\n */\n order?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product items in the order\n */\n product_items: Array<{\n /**\n * Product ID\n */\n product_retailer_id: string;\n /**\n * Quantity of the product\n */\n quantity: number;\n /**\n * Item price\n */\n item_price: number;\n /**\n * Currency code\n */\n currency: string;\n }>;\n /**\n * Text message included with the order\n */\n text?: string;\n };\n\n /**\n * Context object, included when a user replies or interacts\n */\n context?: {\n /**\n * ID of the message\n */\n id?: string;\n /**\n * ID of the sender\n */\n from?: string;\n /**\n * ID of the message being replied to or interacted with\n */\n message_id: string;\n /**\n * ID of the forwarded message, if applicable\n */\n forwarded?: boolean;\n /**\n * Frequently forwarded status\n */\n frequently_forwarded?: boolean;\n /**\n * Original message information if the message was referred\n */\n referred_product?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product ID\n */\n product_retailer_id: string;\n };\n };\n\n /**\n * Errors array, if the message had errors\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error title\n */\n title: string;\n /**\n * Error message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * Button object for button messages\n */\n button?: {\n /**\n * The payload for the button\n */\n payload: string;\n /**\n * Button text\n */\n text: string;\n };\n\n statuses?: {\n /**\n * The phone number ID that received the status update\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the status update\n */\n displayPhoneNumber: string;\n\n /**\n * Arbitrary string included in sent message\n */\n biz_opaque_callback_data?: string;\n\n /**\n * Information about the conversation\n */\n conversation?: {\n /**\n * Represents the ID of the conversation the given status notification belongs to\n */\n id: string;\n /**\n * Describes conversation category\n */\n origin: {\n /**\n * Indicates conversation category. This can also be referred to as a conversation entry point\n * - authentication: Conversation opened by business sending template categorized as AUTHENTICATION\n * - marketing: Conversation opened by business sending template categorized as MARKETING\n * - utility: Conversation opened by business sending template categorized as UTILITY\n * - service: Conversation opened by business replying to customer within service window\n * - referral_conversion: Free entry point conversation\n */\n type: 'authentication' | 'marketing' | 'utility' | 'service' | 'referral_conversion';\n };\n /**\n * Date when the conversation expires. Only present for messages with status 'sent'\n */\n expiration_timestamp?: string;\n };\n\n /**\n * Array of error objects describing the error\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error code title\n */\n title: string;\n /**\n * Error code message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * The ID for the message that the business sent to a customer\n */\n id: string;\n\n /**\n * Pricing information for the message/conversation\n */\n pricing?: {\n /**\n * Indicates if the given message or conversation is billable\n * @deprecated This field is deprecated. Visit the WhatsApp Changelog for more information.\n */\n billable?: boolean;\n /**\n * Indicates the conversation category:\n * - authentication: Authentication conversation\n * - authentication_international: Authentication-international conversation\n * - marketing: Marketing conversation\n * - utility: Utility conversation\n * - service: Service conversation\n * - referral_conversion: Free entry point conversation\n */\n category:\n | 'authentication'\n | 'authentication_international'\n | 'marketing'\n | 'utility'\n | 'service'\n | 'referral_conversion';\n /**\n * Type of pricing model used by the business. Current supported value is CBP\n */\n pricing_model: 'CBP';\n };\n\n /**\n * The customer's WhatsApp ID. Business can respond to customer using this ID.\n * This ID may not match the customer's phone number.\n */\n recipient_id: string;\n\n /**\n * Status of the message:\n * - delivered: Message has been delivered\n * - read: Message has been read by the customer\n * - sent: Message has been sent to the customer\n */\n status: 'delivered' | 'read' | 'sent';\n\n /**\n * Unix timestamp for the status message\n */\n timestamp: string;\n };\n /**\n * The original message data as received from the webhook\n */\n originalData: any;\n}\n\n/**\n * Webhook event received from WhatsApp\n */\nexport interface WebhookEvent {\n /**\n * The field type of the event\n */\n field: string;\n\n /**\n * The event data\n */\n value: any;\n\n /**\n * The timestamp when the event was received\n */\n timestamp: number;\n}\n\n/**\n * Message handler function type\n */\nexport type MessageHandler = (message: WebhookMessage) => void | Promise<void>;\n\n/**\n * Message status enum\n */\nexport enum MessageStatus {\n DELIVERED = 'delivered',\n READ = 'read',\n SENT = 'sent',\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport interface WebhookRequest {\n method: string;\n query: Record<string, any>;\n body: any;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: string;\n}\n\nexport interface WebhookResponse {\n statusCode: number;\n body?: any;\n headers?: Record<string, string>;\n}\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Pure function to handle webhook verification\n */\nexport function verifyWebhook(request: Pick<WebhookRequest, 'query'>, verificationToken: string): WebhookResponse {\n const mode = request.query['hub.mode'];\n const token = request.query['hub.verify_token'];\n const challenge = request.query['hub.challenge'];\n\n // Check if this is actually a webhook verification request\n const isWebhookVerificationRequest = mode !== undefined && token !== undefined && challenge !== undefined;\n\n if (!isWebhookVerificationRequest) {\n LOGGER.log('Not a webhook verification request - missing required parameters');\n return {\n statusCode: 400,\n body: { error: 'Invalid webhook verification request' },\n };\n }\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === verificationToken;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n return {\n statusCode: 200,\n body: challenge,\n };\n } else {\n LOGGER.log('Webhook verification failed');\n return {\n statusCode: 403,\n };\n }\n}\n\n/**\n * Pure function to process webhook messages\n */\nexport async function processWebhookMessages(\n request: WebhookRequest,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<WebhookResponse> {\n const body = request.body;\n const errors: string[] = [];\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return {\n statusCode: 404,\n body: { error: errorMsg },\n };\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n await processMessages(change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return {\n statusCode: 200,\n body: errors.length > 0 ? { errors } : undefined,\n };\n}\n\n/**\n * Pure function to handle flow requests\n */\nexport async function processFlowRequest(\n request: WebhookRequest,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<WebhookResponse> {\n try {\n // Validate request signature\n if (!isRequestSignatureValid(request, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return {\n statusCode: 401,\n body: { error: 'Unauthorized' },\n };\n }\n\n const body = JSON.parse(request.rawBody || '{}');\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(body, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return {\n statusCode: 404,\n body: { error: 'Handler not found' },\n };\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return {\n statusCode: 200,\n body: {\n version: '3.0',\n data: { status: 'active' },\n },\n };\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 200,\n body: {},\n };\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n return {\n statusCode: 200,\n body: encryptedResponse,\n };\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 400,\n body: { error: 'Unknown request type' },\n };\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return {\n statusCode: 500,\n body: { error: 'Internal server error' },\n };\n }\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n value: any,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n const profileName = value.contacts[0]?.profile?.name || '';\n const messages = value.messages as WebhookMessage[];\n\n if (value.statuses && value.statuses.length > 0) {\n for (const status of value.statuses) {\n const processedStatus: WebhookMessage = {\n id: status.id,\n from: status.from,\n timestamp: status.timestamp,\n type: status.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: status,\n };\n\n // Add type-specific data\n Object.assign(processedStatus, getMessageTypeData(status));\n\n // Add context and errors if available\n if (status.context) processedStatus.context = status.context;\n if (status.errors) processedStatus.errors = status.errors;\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n }\n\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nfunction getMessageTypeData(message: any): Partial<WebhookMessage> {\n const typeData: Partial<WebhookMessage> = {};\n\n switch (message.type) {\n case MessageTypesEnum.Text:\n typeData.text = message.text;\n break;\n case MessageTypesEnum.Image:\n typeData.image = message.image;\n break;\n case MessageTypesEnum.Video:\n typeData.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n typeData.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n typeData.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n typeData.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n typeData.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n typeData.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n typeData.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n typeData.button = message.button;\n break;\n case MessageTypesEnum.Order:\n typeData.order = message.order;\n break;\n case MessageTypesEnum.System:\n typeData.system = message.system;\n break;\n case MessageTypesEnum.Statuses:\n typeData.statuses = message.statuses;\n break;\n }\n\n return typeData;\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction isRequestSignatureValid(request: WebhookRequest, verificationToken: string): boolean {\n const signature = request.headers['x-hub-signature-256'] as string;\n if (!signature || !request.rawBody) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', verificationToken)\n .update(request.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport Logger from '@shared/utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport {\n FlowHandler,\n MessageHandler,\n processFlowRequest,\n processWebhookMessages,\n verifyWebhook,\n WebhookRequest,\n WebhookResponse,\n} from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Framework-agnostic WebhookHandler using pure functions\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook verification (framework-agnostic)\n */\n public handleVerification = (request: Pick<WebhookRequest, 'query'>): WebhookResponse => {\n return verifyWebhook(request, this.config.WEBHOOK_VERIFICATION_TOKEN || '');\n };\n\n /**\n * Handle webhook messages (framework-agnostic)\n */\n public handleWebhook = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n };\n\n /**\n * Handle flow requests (framework-agnostic)\n */\n public handleFlow = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n };\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/webhook/types.ts","../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["MessageStatus","isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","verifyWebhook","verificationToken","mode","token","challenge","processWebhookMessages","whatsapp","handlers","body","errors","errorMsg","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","isRequestSignatureValid","decryptedBody","decryptFlowRequest","handler","result","encryptFlowResponse","metadata","displayPhoneNumber","phoneNumberId","profileName","messages","status","processedStatus","executeHandler","message","messageType","processedMessage","handlerType","signature","formattedExpectedSignature","crypto","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","type","generateXHub256Sig","appSecret","x"],"mappings":"gJAioBYA,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACRA,EAAA,SAAY,CAAA,WAAA,CACZA,EAAA,IAAO,CAAA,MAAA,CACPA,CAAA,CAAA,IAAA,CAAO,MAHCA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,ICpnBZ,SAASC,CAAAA,CAASC,EAAkD,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,EAASD,CAAiC,CAAA,CAC/C,OAAO,OAAOA,CAAAA,EAAU,QAC5B,CAGA,IAAME,CAAwB,CAAA,CAAA,eAAA,CAAA,MAAA,CAAA,MAAuE,CAG/FC,CAAAA,CAAAA,CAAgB,uBAAkD,CASjE,CAAA,SAASC,EAA0BC,CAKxC,CAAA,CAEE,GAAI,EAAE,YAAA,GAAgBA,CAAWJ,EAAAA,CAAAA,CAASI,CAAQ,CA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A,EAC1BxB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,OAAOgE,CAAoBxC,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,aAAa,GAAIwC,CAAAA,CAAAA,CAAMxC,CAAO,CACnCxB,CAAAA,CAAAA,CAAO,IAAI,CAA+BgE,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ,EC1FO,IAAMC,GAAqB,CAACvD,CAAAA,CAAcwD,IAC/BC,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUD,CAAS,CAAE,CAAA,MAAA,CAAOxD,EAAM,OAAO,CAAA,CAAE,OAAO,KAAK","file":"chunk-575ICT3Y.js","sourcesContent":["import { MessageTypesEnum } from '@shared/types/enums';\n\nexport interface WebhookContact {\n /**\n * WhatsApp ID of the contact. Business can respond to this contact using this ID.\n */\n wa_id: string;\n /**\n * Additional unique, alphanumeric identifier for a WhatsApp user\n */\n user_id?: string;\n /**\n * Profile of Whatsapp user\n */\n profile: {\n /**\n * The display name of the contact\n */\n name: string;\n };\n}\n\n/**\n * Represents a message received through the webhook\n * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#messages-object\n */\nexport interface WebhookMessage {\n /**\n * The message ID\n */\n id: string;\n\n /**\n * The sender's phone number\n */\n from: string;\n\n /**\n * The timestamp of the message\n */\n timestamp: string;\n\n /**\n * The type of message (text, image, etc.)\n */\n type: MessageTypesEnum;\n\n /**\n * The phone number ID that received the message\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the message\n */\n displayPhoneNumber: string;\n\n /**\n * The profile name of the sender\n */\n profileName: string;\n\n /**\n * Text object for text messages\n */\n text?: {\n /**\n * The text content of the message\n */\n body: string;\n };\n\n /**\n * Image object for image messages\n */\n image?: {\n /**\n * The image caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the image\n */\n sha256?: string;\n /**\n * The ID for the image\n */\n id: string;\n /**\n * The MIME type of the image\n */\n mime_type: string;\n };\n\n /**\n * Video object for video messages\n */\n video?: {\n /**\n * The video caption (if provided)\n */\n caption?: string;\n /**\n * The SHA256 hash of the video\n */\n sha256?: string;\n /**\n * The ID for the video\n */\n id: string;\n /**\n * The MIME type of the video\n */\n mime_type: string;\n };\n\n /**\n * Audio object for audio messages\n */\n audio?: {\n /**\n * The ID for the audio file\n */\n id: string;\n /**\n * The MIME type of the audio file\n */\n mime_type: string;\n /**\n * Whether the audio is a voice message\n */\n voice?: boolean;\n };\n\n /**\n * Document object for document messages\n */\n document?: {\n /**\n * The document caption (if provided)\n */\n caption?: string;\n /**\n * The document filename\n */\n filename: string;\n /**\n * The SHA256 hash of the document\n */\n sha256?: string;\n /**\n * The ID for the document\n */\n id: string;\n /**\n * The MIME type of the document\n */\n mime_type: string;\n };\n\n /**\n * Sticker object for sticker messages\n */\n sticker?: {\n /**\n * The ID for the sticker\n */\n id: string;\n /**\n * Whether this is an animated sticker\n */\n animated: boolean;\n /**\n * The MIME type of the sticker\n */\n mime_type: string;\n };\n\n /**\n * Reaction object for reaction messages\n */\n reaction?: {\n /**\n * The ID of the message being reacted to\n */\n message_id: string;\n /**\n * Emoji used for the reaction\n */\n emoji: string;\n };\n\n /**\n * Contacts object for contact messages\n */\n contacts?: Array<{\n /**\n * The contact's name\n */\n name: {\n /**\n * The formatted name\n */\n formatted_name: string;\n /**\n * The first name\n */\n first_name?: string;\n /**\n * The last name\n */\n last_name?: string;\n /**\n * The middle name\n */\n middle_name?: string;\n /**\n * The suffix\n */\n suffix?: string;\n /**\n * The prefix\n */\n prefix?: string;\n };\n /**\n * The contact's phone numbers\n */\n phones?: Array<{\n phone: string;\n type?: string;\n wa_id?: string;\n }>;\n /**\n * The contact's emails\n */\n emails?: Array<{\n email: string;\n type?: string;\n }>;\n /**\n * The contact's addresses\n */\n addresses?: Array<{\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n country?: string;\n country_code?: string;\n type?: string;\n }>;\n /**\n * The contact's organizations\n */\n org?: {\n company?: string;\n department?: string;\n title?: string;\n };\n /**\n * The contact's URLs\n */\n urls?: Array<{\n url: string;\n type?: string;\n }>;\n /**\n * The contact's birthday (YYYY-MM-DD format)\n */\n birthday?: string;\n }>;\n\n /**\n * Location object for location messages\n */\n location?: {\n /**\n * Latitude of the location\n */\n latitude: number;\n /**\n * Longitude of the location\n */\n longitude: number;\n /**\n * Name of the location\n */\n name?: string;\n /**\n * Address of the location\n */\n address?: string;\n };\n\n /**\n * Interactive object for interactive messages\n */\n interactive?: {\n /**\n * Type of the interactive message\n * Can be: button_reply, list_reply, flow, nfm_reply, etc.\n */\n type: string;\n /**\n * ID for the button that was clicked\n */\n button_reply?: {\n id: string;\n title: string;\n };\n /**\n * ID for the list item that was selected\n */\n list_reply?: {\n id: string;\n title: string;\n description?: string;\n };\n\n /**\n * NFM (No-Code Flow Message) reply data\n */\n nfm_reply?: {\n /**\n * Response data in JSON format\n */\n response_json: string;\n /**\n * Body text of the reply\n */\n body: string;\n /**\n * Name of the flow\n */\n name: string;\n };\n };\n\n /**\n * System object for system messages (like user phone number changes)\n */\n system?: {\n /**\n * The type of system update\n */\n type: string;\n /**\n * User's identity if the update is a customer identity change\n */\n identity?: string;\n /**\n * Old and new phone numbers if the update is a phone number change\n */\n customer?: {\n /**\n * The previous phone number\n */\n previous_wa_id: string;\n /**\n * The new phone number\n */\n wa_id: string;\n };\n };\n\n /**\n * Order object for order messages\n */\n order?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product items in the order\n */\n product_items: Array<{\n /**\n * Product ID\n */\n product_retailer_id: string;\n /**\n * Quantity of the product\n */\n quantity: number;\n /**\n * Item price\n */\n item_price: number;\n /**\n * Currency code\n */\n currency: string;\n }>;\n /**\n * Text message included with the order\n */\n text?: string;\n };\n\n /**\n * Context object, included when a user replies or interacts\n */\n context?: {\n /**\n * ID of the message\n */\n id?: string;\n /**\n * ID of the sender\n */\n from?: string;\n /**\n * ID of the message being replied to or interacted with\n */\n message_id: string;\n /**\n * ID of the forwarded message, if applicable\n */\n forwarded?: boolean;\n /**\n * Frequently forwarded status\n */\n frequently_forwarded?: boolean;\n /**\n * Original message information if the message was referred\n */\n referred_product?: {\n /**\n * Catalog ID\n */\n catalog_id: string;\n /**\n * Product ID\n */\n product_retailer_id: string;\n };\n };\n\n /**\n * Errors array, if the message had errors\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error title\n */\n title: string;\n /**\n * Error message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * Button object for button messages\n */\n button?: {\n /**\n * The payload for the button\n */\n payload: string;\n /**\n * Button text\n */\n text: string;\n };\n\n statuses?: {\n /**\n * The phone number ID that received the status update\n */\n phoneNumberId: string;\n\n /**\n * The display phone number that received the status update\n */\n displayPhoneNumber: string;\n\n /**\n * Arbitrary string included in sent message\n */\n biz_opaque_callback_data?: string;\n\n /**\n * Information about the conversation\n */\n conversation?: {\n /**\n * Represents the ID of the conversation the given status notification belongs to\n */\n id: string;\n /**\n * Describes conversation category\n */\n origin: {\n /**\n * Indicates conversation category. This can also be referred to as a conversation entry point\n * - authentication: Conversation opened by business sending template categorized as AUTHENTICATION\n * - marketing: Conversation opened by business sending template categorized as MARKETING\n * - utility: Conversation opened by business sending template categorized as UTILITY\n * - service: Conversation opened by business replying to customer within service window\n * - referral_conversion: Free entry point conversation\n */\n type: 'authentication' | 'marketing' | 'utility' | 'service' | 'referral_conversion';\n };\n /**\n * Date when the conversation expires. Only present for messages with status 'sent'\n */\n expiration_timestamp?: string;\n };\n\n /**\n * Array of error objects describing the error\n */\n errors?: Array<{\n /**\n * Error code\n */\n code: number;\n /**\n * Error code title\n */\n title: string;\n /**\n * Error code message\n */\n message: string;\n /**\n * Error details object\n */\n error_data?: {\n /**\n * Describes the error details\n */\n details: string;\n };\n }>;\n\n /**\n * The ID for the message that the business sent to a customer\n */\n id: string;\n\n /**\n * Pricing information for the message/conversation\n */\n pricing?: {\n /**\n * Indicates if the given message or conversation is billable\n * @deprecated This field is deprecated. Visit the WhatsApp Changelog for more information.\n */\n billable?: boolean;\n /**\n * Indicates the conversation category:\n * - authentication: Authentication conversation\n * - authentication_international: Authentication-international conversation\n * - marketing: Marketing conversation\n * - utility: Utility conversation\n * - service: Service conversation\n * - referral_conversion: Free entry point conversation\n */\n category:\n | 'authentication'\n | 'authentication_international'\n | 'marketing'\n | 'utility'\n | 'service'\n | 'referral_conversion';\n /**\n * Type of pricing model used by the business. Current supported value is CBP\n */\n pricing_model: 'CBP';\n };\n\n /**\n * The customer's WhatsApp ID. Business can respond to customer using this ID.\n * This ID may not match the customer's phone number.\n */\n recipient_id: string;\n\n /**\n * Status of the message:\n * - delivered: Message has been delivered\n * - read: Message has been read by the customer\n * - sent: Message has been sent to the customer\n */\n status: 'delivered' | 'read' | 'sent';\n\n /**\n * Unix timestamp for the status message\n */\n timestamp: string;\n };\n /**\n * The original message data as received from the webhook\n */\n originalData: any;\n}\n\n/**\n * Webhook event received from WhatsApp\n */\nexport interface WebhookEvent {\n /**\n * The field type of the event\n */\n field: string;\n\n /**\n * The event data\n */\n value: any;\n\n /**\n * The timestamp when the event was received\n */\n timestamp: number;\n}\n\n/**\n * Message handler function type\n */\nexport type MessageHandler = (message: WebhookMessage) => void | Promise<void>;\n\n/**\n * Message status enum\n */\nexport enum MessageStatus {\n DELIVERED = 'delivered',\n READ = 'read',\n SENT = 'sent',\n}\n","import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport interface WebhookRequest {\n method: string;\n query: Record<string, any>;\n body: any;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: string;\n}\n\nexport interface WebhookResponse {\n statusCode: number;\n body?: any;\n headers?: Record<string, string>;\n}\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Pure function to handle webhook verification\n */\nexport function verifyWebhook(request: Pick<WebhookRequest, 'query'>, verificationToken: string): WebhookResponse {\n const mode = request.query['hub.mode'];\n const token = request.query['hub.verify_token'];\n const challenge = request.query['hub.challenge'];\n\n // Check if this is actually a webhook verification request\n const isWebhookVerificationRequest = mode !== undefined && token !== undefined && challenge !== undefined;\n\n if (!isWebhookVerificationRequest) {\n LOGGER.log('Not a webhook verification request - missing required parameters');\n return {\n statusCode: 400,\n body: { error: 'Invalid webhook verification request' },\n };\n }\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === verificationToken;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n return {\n statusCode: 200,\n body: challenge,\n };\n } else {\n LOGGER.log('Webhook verification failed');\n return {\n statusCode: 403,\n };\n }\n}\n\n/**\n * Pure function to process webhook messages\n */\nexport async function processWebhookMessages(\n request: WebhookRequest,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<WebhookResponse> {\n const body = request.body;\n const errors: string[] = [];\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return {\n statusCode: 404,\n body: { error: errorMsg },\n };\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n await processMessages(change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return {\n statusCode: 200,\n body: errors.length > 0 ? { errors } : undefined,\n };\n}\n\n/**\n * Pure function to handle flow requests\n */\nexport async function processFlowRequest(\n request: WebhookRequest,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<WebhookResponse> {\n try {\n // Validate request signature\n if (!isRequestSignatureValid(request, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return {\n statusCode: 401,\n body: { error: 'Unauthorized' },\n };\n }\n\n const body = JSON.parse(request.rawBody || '{}');\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(body, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return {\n statusCode: 404,\n body: { error: 'Handler not found' },\n };\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return {\n statusCode: 200,\n body: {\n version: '3.0',\n data: { status: 'active' },\n },\n };\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 200,\n body: {},\n };\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n return {\n statusCode: 200,\n body: encryptedResponse,\n };\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 400,\n body: { error: 'Unknown request type' },\n };\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return {\n statusCode: 500,\n body: { error: 'Internal server error' },\n };\n }\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n value: any,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const displayPhoneNumber = metadata.display_phone_number;\n const phoneNumberId = metadata.phone_number_id;\n const profileName = value.contacts[0]?.profile?.name || '';\n const messages = value.messages as WebhookMessage[];\n\n if (value.statuses && value.statuses.length > 0) {\n for (const status of value.statuses) {\n const processedStatus: WebhookMessage = {\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: {\n phoneNumberId,\n displayPhoneNumber,\n ...status, // Include all status fields\n },\n originalData: status,\n };\n\n // Add context and errors if available\n if (status.context) processedStatus.context = status.context;\n if (status.errors) processedStatus.errors = status.errors;\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n text: message.text,\n image: message.image,\n video: message.video,\n audio: message.audio,\n document: message.document,\n sticker: message.sticker,\n location: message.location,\n contacts: message.contacts,\n interactive: message.interactive,\n button: message.button,\n order: message.order,\n system: message.system,\n errors: message.errors,\n context: message.context,\n originalData: message,\n };\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nfunction getMessageTypeData(message: any): Partial<WebhookMessage> {\n const typeData: Partial<WebhookMessage> = {};\n\n switch (message.type) {\n case MessageTypesEnum.Text:\n typeData.text = message.text;\n break;\n case MessageTypesEnum.Image:\n typeData.image = message.image;\n break;\n case MessageTypesEnum.Video:\n typeData.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n typeData.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n typeData.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n typeData.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n typeData.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n typeData.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n typeData.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n typeData.button = message.button;\n break;\n case MessageTypesEnum.Order:\n typeData.order = message.order;\n break;\n case MessageTypesEnum.System:\n typeData.system = message.system;\n break;\n case MessageTypesEnum.Statuses:\n typeData.statuses = message.statuses;\n break;\n }\n\n return typeData;\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction isRequestSignatureValid(request: WebhookRequest, verificationToken: string): boolean {\n const signature = request.headers['x-hub-signature-256'] as string;\n if (!signature || !request.rawBody) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', verificationToken)\n .update(request.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport Logger from '@shared/utils/logger';\nimport { WhatsApp } from '../whatsapp';\nimport {\n FlowHandler,\n MessageHandler,\n processFlowRequest,\n processWebhookMessages,\n verifyWebhook,\n WebhookRequest,\n WebhookResponse,\n} from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * Framework-agnostic WebhookHandler using pure functions\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook verification (framework-agnostic)\n */\n public handleVerification = (request: Pick<WebhookRequest, 'query'>): WebhookResponse => {\n return verifyWebhook(request, this.config.WEBHOOK_VERIFICATION_TOKEN || '');\n };\n\n /**\n * Handle webhook messages (framework-agnostic)\n */\n public handleWebhook = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n };\n\n /**\n * Handle flow requests (framework-agnostic)\n */\n public handleFlow = async (request: WebhookRequest): Promise<WebhookResponse> => {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n };\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as MessageStatus,e as WebhookHandler,f as generateXHub256Sig,d as processFlowRequest,c as processWebhookMessages,b as verifyWebhook}from'../../chunk-
|
|
1
|
+
export{a as MessageStatus,e as WebhookHandler,f as generateXHub256Sig,d as processFlowRequest,c as processWebhookMessages,b as verifyWebhook}from'../../chunk-575ICT3Y.js';import'../../chunk-HEVRZRB4.js';import'../../chunk-3MO3BTBC.js';import'../../chunk-R36L2XYO.js';import'../../chunk-GT3XQN7Y.js';import'../../chunk-O2OTHNWM.js';import'../../chunk-7NQLQPLH.js';import'../../chunk-UQPD6GIF.js';import'../../chunk-5JGM556C.js';import'../../chunk-2NJVBJUN.js';import'../../chunk-XPPDOFBN.js';import'../../chunk-KFPOVYEJ.js';import'../../chunk-7GL74SXM.js';import'../../chunk-A264MT4Q.js';import'../../chunk-GIQLIMOD.js';import'../../chunk-BZ5QDXNR.js';import'../../chunk-VW3LGHTJ.js';import'../../chunk-SMHCU5MN.js';import'../../chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{a as TemplateApi}from'./chunk-H55VIWDI.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';import'./chunk-W2U7MN7M.js';export{a as MessageStatus,e as WebhookHandler,f as generateXHub256Sig,d as processFlowRequest,c as processWebhookMessages,b as verifyWebhook}from'./chunk-
|
|
1
|
+
export{a as TemplateApi}from'./chunk-H55VIWDI.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';import'./chunk-W2U7MN7M.js';export{a as MessageStatus,e as WebhookHandler,f as generateXHub256Sig,d as processFlowRequest,c as processWebhookMessages,b as verifyWebhook}from'./chunk-575ICT3Y.js';import {b}from'./chunk-HEVRZRB4.js';import'./chunk-3MO3BTBC.js';import'./chunk-R36L2XYO.js';import'./chunk-GT3XQN7Y.js';export{b as RegistrationApi}from'./chunk-O2OTHNWM.js';export{b as EncryptionApi}from'./chunk-7NQLQPLH.js';export{b as TwoStepVerificationApi}from'./chunk-UQPD6GIF.js';export{b as WabaApi}from'./chunk-5JGM556C.js';export{b as MessagesApi}from'./chunk-2NJVBJUN.js';import'./chunk-XPPDOFBN.js';export{b as BusinessProfileApi}from'./chunk-KFPOVYEJ.js';import'./chunk-7GL74SXM.js';export{b as FlowApi}from'./chunk-A264MT4Q.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';import'./chunk-BZ5QDXNR.js';import'./chunk-VW3LGHTJ.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,h as ButtonPositionEnum,g as ButtonTypesEnum,a as CategoryEnum,i as ComponentTypesEnum,k as ConversationTypesEnum,w as CurrencyCodesEnum,x as DataLocalizationRegionEnum,p as DocumentMediaTypesEnum,c as HttpMethodsEnum,o as ImageMediaTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum,t as ReferralSourceTypesEnum,u as RequestCodeMethodsEnum,l as StatusEnum,n as StickerMediaTypesEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'./chunk-SMHCU5MN.js';import'./chunk-4C666HHU.js';var se=b;export{se as default};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
package/dist/chunk-QMNPAR5X.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import {a as a$1,b as b$1}from'./chunk-HEVRZRB4.js';import {a}from'./chunk-VW3LGHTJ.js';import*as g from'crypto';import g__default from'crypto';var x=(s=>(s.DELIVERED="delivered",s.READ="read",s.SENT="sent",s))(x||{});function W(e){return typeof e=="object"&&e!==null}function l(e){return typeof e=="string"}var T=["data_exchange","INIT","BACK"],S=["data_exchange","INIT"];function A(e){if(!("flow_token"in e&&l(e.flow_token)&&"action"in e))return false;let{action:r,version:o,screen:s,data:t}=e,i=o==="3.0",a=T.includes(r),c=typeof s>"u"||l(s)&&s!=="SUCCESS",n=r==="data_exchange"||W(t);return i&&a&&c&&n}function v(e){if(!("flow_token"in e&&l(e.flow_token)&&"action"in e))return false;let{action:r,screen:o,data:s}=e,t=S.includes(r),i=l(o),a=W(s)&&"error_key"in s&&l(s.error)&&"error_message"in s&&l(s.error_message);return t&&i&&a}function M(e){return "action"in e&&e.action==="ping"}var N="WEBHOOK_UTILS",d=new a(N,process.env.DEBUG==="true");function b(e,r){let o=e.query["hub.mode"],s=e.query["hub.verify_token"],t=e.query["hub.challenge"];return o!==void 0&&s!==void 0&&t!==void 0?o==="subscribe"&&s===r?(d.log("Webhook verified successfully"),{statusCode:200,body:t}):(d.log("Webhook verification failed"),{statusCode:403}):(d.log("Not a webhook verification request - missing required parameters"),{statusCode:400,body:{error:"Invalid webhook verification request"}})}async function _(e,r,o){let s=e.body,t=[];if(s.object!=="whatsapp_business_account"){let i="Received webhook for non-WhatsApp event";return d.log(i),{statusCode:404,body:{error:i}}}for(let i of s.entry)try{let a=i.changes;for(let c of a)c.field==="messages"&&await B(c.value,r,o);}catch(a){let c=`Error processing webhook: ${a}`;d.log(c),t.push(c);}return {statusCode:200,body:t.length>0?{errors:t}:void 0}}async function w(e,r,o,s){try{if(!O(e,r.WEBHOOK_VERIFICATION_TOKEN||""))return d.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let t=JSON.parse(e.rawBody||"{}"),{decryptedBody:i}=D(t,r),a=s.get("*");if(!a)return d.log(`No handler registered for flow action: ${i.action}`),{statusCode:404,body:{error:"Handler not found"}};if(M(i))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(v(i))return d.log(`Flow error: ${JSON.stringify(i)}`),{statusCode:200,body:{}};if(A(i)){let c=await a(o,i);return {statusCode:200,body:V(c,Buffer.from(t.aes_key,"base64"),Buffer.from(t.initial_vector,"base64"))}}return d.log(`Unknown flow request type: ${JSON.stringify(i)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(t){return d.log(`Error handling flow request: ${t}`),{statusCode:500,body:{error:"Internal server error"}}}}async function B(e,r,o){let s=e.metadata,t=s.display_phone_number,i=s.phone_number_id,a=e.contacts[0]?.profile?.name||"",c=e.messages;if(e.statuses&&e.statuses.length>0)for(let n of e.statuses){let p={id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:i,displayPhoneNumber:t,profileName:a,originalData:n};Object.assign(p,I(n)),n.context&&(p.context=n.context),n.errors&&(p.errors=n.errors),await y(o.messageHandlers.get("statuses"),r,p,"statuses");}if(c&&c.length>0)for(let n of c){let p=n.type,u={id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:i,displayPhoneNumber:t,profileName:a,originalData:n};await y(o.preProcessHandler,r,u,"pre-process"),await y(o.messageHandlers.get(p),r,u,p),await y(o.postProcessHandler,r,u,"post-process");}}function I(e){let r={};switch(e.type){case "text":r.text=e.text;break;case "image":r.image=e.image;break;case "video":r.video=e.video;break;case "audio":r.audio=e.audio;break;case "document":r.document=e.document;break;case "sticker":r.sticker=e.sticker;break;case "location":r.location=e.location;break;case "contacts":r.contacts=e.contacts;break;case "interactive":r.interactive=e.interactive;break;case "button":r.button=e.button;break;case "order":r.order=e.order;break;case "system":r.system=e.system;break;case "statuses":r.statuses=e.statuses;break}return r}async function y(e,r,o,s){if(e)try{await e(r,o);}catch(t){d.log(`Error in ${s} handler: ${t}`);}}function O(e,r){let o=e.headers["x-hub-signature-256"];if(!o||!e.rawBody)return false;let t=`sha256=${g__default.createHmac("sha256",r).update(e.rawBody,"utf8").digest("hex")}`;return g__default.timingSafeEqual(Buffer.from(o),Buffer.from(t))}function D(e,r){let{encrypted_aes_key:o,encrypted_flow_data:s,initial_vector:t}=e;if(!o||!s||!t)throw new Error("Missing required encryption properties");let i=r.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
|
|
2
|
-
`),a=r.FLOW_API_PASSPHRASE,c=g__default.createPrivateKey({key:i,passphrase:a}),n;try{n=g__default.privateDecrypt({key:c,padding:g__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(o,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let p=Buffer.from(s,"base64"),u=Buffer.from(t,"base64"),C=p.subarray(0,-16),q=p.subarray(-16),h=g__default.createDecipheriv("aes-128-gcm",n,u);h.setAuthTag(q);let F=Buffer.concat([h.update(C),h.final()]).toString("utf-8");return {decryptedBody:JSON.parse(F),aesKeyBuffer:n,initialVectorBuffer:u}}function V(e,r,o){let s=[];for(let t of Array.from(o.entries()))s.push(~t[1]);try{let t=g__default.createCipheriv("aes-128-gcm",r,Buffer.from(s));return Buffer.concat([t.update(JSON.stringify(e||{}),"utf-8"),t.final(),t.getAuthTag()]).toString("base64")}catch(t){throw d.log("Response encryption error:",t),new Error("Failed to encrypt response. Internal server error.")}}var G="WEBHOOK",f=new a(G,process.env.DEBUG==="true"),k=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(r){this.config=a$1(r),this.client=new b$1(r),f.log("WebhookHandler instantiated!");}handleVerification=r=>b(r,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async r=>_(r,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler});handleFlow=async r=>w(r,this.config,this.client,this.flowHandlers);onMessage(r,o){this.messageHandlers.set(r,o),f.log(`Registered message handler for ${r}`);}onMessagePreProcess(r){this.preProcessHandler=r,f.log("Registered pre-process handler");}onMessagePostProcess(r){this.postProcessHandler=r,f.log("Registered post-process handler");}onFlow(r,o){this.flowHandlers.set(r,o),f.log(`Registered flow handler for ${r}`);}};var ne=(e,r)=>g.createHmac("sha256",r).update(e,"utf-8").digest("hex");export{x as a,b,_ as c,w as d,k as e,ne as f};//# sourceMappingURL=chunk-QMNPAR5X.js.map
|
|
3
|
-
//# sourceMappingURL=chunk-QMNPAR5X.js.map
|