meta-cloud-api 0.2.29 → 0.2.30

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}from'./chunk-HEVRZRB4.js';import {a}from'./chunk-VW3LGHTJ.js';import*as l from'crypto';import l__default from'crypto';var S=(t=>(t.DELIVERED="delivered",t.READ="read",t.SENT="sent",t))(S||{});function H(s){return typeof s=="object"&&s!==null}function f(s){return typeof s=="string"}var q=["data_exchange","INIT","BACK"],F=["data_exchange","INIT"];function W(s){if(!("flow_token"in s&&f(s.flow_token)&&"action"in s))return false;let{action:e,version:o,screen:t,data:r}=s,a=o==="3.0",c=q.includes(e),g=typeof t>"u"||f(t)&&t!=="SUCCESS",p=e==="data_exchange"||H(r);return a&&c&&g&&p}function v(s){if(!("flow_token"in s&&f(s.flow_token)&&"action"in s))return false;let{action:e,screen:o,data:t}=s,r=F.includes(e),a=f(o),c=H(t)&&"error_key"in t&&f(t.error)&&"error_message"in t&&f(t.error_message);return r&&a&&c}function T(s){return "action"in s&&s.action==="ping"}var I="WEBHOOK_UTILS",d=new a(I,process.env.DEBUG==="true");function w(s,e){let o=s.query["hub.mode"],t=s.query["hub.verify_token"],r=s.query["hub.challenge"];return o!==void 0&&t!==void 0&&r!==void 0?o==="subscribe"&&t===e?(d.log("Webhook verified successfully"),{statusCode:200,body:r}):(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 k(s,e,o){let t=s.body,r=[];if(t.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";return d.log(a),{statusCode:404,body:{error:a}}}for(let a of t.entry)try{let c=a.changes;for(let g of c)g.field==="messages"&&await P(a.id,g.value,e,o);}catch(c){let g=`Error processing webhook: ${c}`;d.log(g),r.push(g);}return {statusCode:200,body:r.length>0?{errors:r}:void 0}}async function E(s,e,o,t){try{if(!N(s,e.WEBHOOK_VERIFICATION_TOKEN||""))return d.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let r=JSON.parse(s.rawBody||"{}"),{decryptedBody:a}=O(r,e),c=t.get("*");if(!c)return d.log(`No handler registered for flow action: ${a.action}`),{statusCode:404,body:{error:"Handler not found"}};if(T(a))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(v(a))return d.log(`Flow error: ${JSON.stringify(a)}`),{statusCode:200,body:{}};if(W(a)){let g=await c(o,a);return {statusCode:200,body:D(g,Buffer.from(r.aes_key,"base64"),Buffer.from(r.initial_vector,"base64"))}}return d.log(`Unknown flow request type: ${JSON.stringify(a)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(r){return d.log(`Error handling flow request: ${r}`),{statusCode:500,body:{error:"Internal server error"}}}}async function P(s,e,o,t){let r=e.metadata,a=e.contacts,c=s,g=r?.display_phone_number||"",p=r?.phone_number_id||"",y=a?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){let m=e.statuses;for(let n of m){let u={wabaId:c,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:p,displayPhoneNumber:g,profileName:y,statuses:e.statuses[0],originalData:n};await M(t.messageHandlers.get("statuses"),o,u,"statuses");}return}if(e.messages&&e.messages.length>0){let m=e.messages;for(let n of m){let u=n.type,i={wabaId:c,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:p,displayPhoneNumber:g,profileName:y,originalData:n};switch(u){case "text":i.text=n.text;break;case "image":i.image=n.image;break;case "video":i.video=n.video;break;case "audio":i.audio=n.audio;break;case "document":i.document=n.document;break;case "sticker":i.sticker=n.sticker;break;case "location":i.location=n.location;break;case "contacts":i.contacts=n.contacts;break;case "interactive":i.interactive=n.interactive;break;case "button":i.button=n.button;break;case "order":i.order=n.order;break;case "system":i.system=n.system;break;case "reaction":i.reaction=n.reaction;break;default:d.log(`Unknown message type: ${u}`);break}await M(t.preProcessHandler,o,i,"pre-process"),await M(t.messageHandlers.get(u),o,i,u),await M(t.postProcessHandler,o,i,"post-process");}}}async function M(s,e,o,t){if(s)try{await s(e,o);}catch(r){d.log(`Error in ${t} handler: ${r}`);}}function N(s,e){let o=s.headers["x-hub-signature-256"];if(!o||!s.rawBody)return false;let r=`sha256=${l__default.createHmac("sha256",e).update(s.rawBody,"utf8").digest("hex")}`;return l__default.timingSafeEqual(Buffer.from(o),Buffer.from(r))}function O(s,e){let{encrypted_aes_key:o,encrypted_flow_data:t,initial_vector:r}=s;if(!o||!t||!r)throw new Error("Missing required encryption properties");let a=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),c=e.FLOW_API_PASSPHRASE,g=l__default.createPrivateKey({key:a,passphrase:c}),p;try{p=l__default.privateDecrypt({key:g,padding:l__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 y=Buffer.from(t,"base64"),m=Buffer.from(r,"base64"),u=y.subarray(0,-16),i=y.subarray(-16),_=l__default.createDecipheriv("aes-128-gcm",p,m);_.setAuthTag(i);let C=Buffer.concat([_.update(u),_.final()]).toString("utf-8");return {decryptedBody:JSON.parse(C),aesKeyBuffer:p,initialVectorBuffer:m}}function D(s,e,o){let t=[];for(let r of Array.from(o.entries()))t.push(~r[1]);try{let r=l__default.createCipheriv("aes-128-gcm",e,Buffer.from(t));return Buffer.concat([r.update(JSON.stringify(s||{}),"utf-8"),r.final(),r.getAuthTag()]).toString("base64")}catch(r){throw d.log("Response encryption error:",r),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",h=new a(V,process.env.DEBUG==="true"),R=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$1(e),this.client=new b(e),h.log("WebhookHandler instantiated!");}handleVerification=e=>w(e,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async e=>k(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler});handleFlow=async e=>E(e,this.config,this.client,this.flowHandlers);onMessage(e,o){this.messageHandlers.set(e,o),h.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,h.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,h.log("Registered post-process handler");}onFlow(e,o){this.flowHandlers.set(e,o),h.log(`Registered flow handler for ${e}`);}};var oe=(s,e)=>l.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{S as a,w as b,k as c,E as d,R as e,oe as f};//# sourceMappingURL=chunk-TEJIY4ZS.js.map
3
+ //# sourceMappingURL=chunk-TEJIY4ZS.js.map
@@ -0,0 +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","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","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","W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AO,CACtCxB,CAAAA,CAAAA,CAAO,IAAI,CAAkCoE,+BAAAA,EAAAA,CAAI,EAAE,EACvD,CAKO,oBAAoB5C,CAA+B,CAAA,CACtD,IAAK,CAAA,iBAAA,CAAoBA,EACzBxB,CAAO,CAAA,GAAA,CAAI,gCAAgC,EAC/C,CAKO,qBAAqBwB,CAA+B,CAAA,CACvD,IAAK,CAAA,kBAAA,CAAqBA,EAC1BxB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,OAAOoE,CAAoB5C,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,aAAa,GAAI4C,CAAAA,CAAAA,CAAM5C,CAAO,CACnCxB,CAAAA,CAAAA,CAAO,IAAI,CAA+BoE,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ,EC1FO,IAAMC,GAAqB,CAAC3D,CAAAA,CAAc4D,IAC/BC,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUD,CAAS,CAAE,CAAA,MAAA,CAAO5D,EAAM,OAAO,CAAA,CAAE,OAAO,KAAK","file":"chunk-TEJIY4ZS.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 * Base message interface with common properties\n */\nexport interface BaseMessage {\n id: string;\n from: string;\n timestamp: string;\n type: MessageTypesEnum;\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 * 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/**\n * Text message interface\n */\nexport interface TextMessage extends BaseMessage {\n type: MessageTypesEnum.Text;\n text: {\n /**\n * The text content of the message\n */\n body: string;\n preview_url?: boolean;\n };\n}\n\n/**\n * Image message interface\n */\nexport interface ImageMessage extends BaseMessage {\n type: MessageTypesEnum.Image;\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/**\n * Video message interface\n */\nexport interface VideoMessage extends BaseMessage {\n type: MessageTypesEnum.Video;\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/**\n * Audio message interface\n */\nexport interface AudioMessage extends BaseMessage {\n type: MessageTypesEnum.Audio;\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/**\n * Document message interface\n */\nexport interface DocumentMessage extends BaseMessage {\n type: MessageTypesEnum.Document;\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/**\n * Sticker message interface\n */\nexport interface StickerMessage extends BaseMessage {\n type: MessageTypesEnum.Sticker;\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/**\n * Reaction message interface\n */\nexport interface ReactionMessage extends BaseMessage {\n type: MessageTypesEnum.Reaction;\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/**\n * Contacts message interface\n */\nexport interface ContactsMessage extends BaseMessage {\n type: MessageTypesEnum.Contacts;\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/**\n * Location message interface\n */\nexport interface LocationMessage extends BaseMessage {\n type: MessageTypesEnum.Location;\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/**\n * Interactive message interface\n */\nexport interface InteractiveMessage extends BaseMessage {\n type: MessageTypesEnum.Interactive;\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 * 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/**\n * System message interface\n */\nexport interface SystemMessage extends BaseMessage {\n type: MessageTypesEnum.System;\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/**\n * Order message interface\n */\nexport interface OrderMessage extends BaseMessage {\n type: MessageTypesEnum.Order;\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/**\n * Button message interface\n */\nexport interface ButtonMessage extends BaseMessage {\n type: MessageTypesEnum.Button;\n button: {\n /**\n * The payload for the button\n */\n payload: string;\n /**\n * Button text\n */\n text: string;\n };\n}\n\n/**\n * Union type for all message types\n */\nexport type WhatsAppMessage =\n | TextMessage\n | ImageMessage\n | VideoMessage\n | AudioMessage\n | DocumentMessage\n | StickerMessage\n | ReactionMessage\n | ContactsMessage\n | LocationMessage\n | InteractiveMessage\n | SystemMessage\n | OrderMessage\n | ButtonMessage;\n\nexport interface WebhookMessageValue {\n /**\n * The messaging product\n */\n messaging_product: string;\n /**\n * The metadata\n */\n metadata: {\n /**\n * The display phone number of the whatsapp business account\n */\n display_phone_number: string;\n /**\n * The phone number ID of the whatsapp business account\n */\n phone_number_id: string;\n };\n contacts?: Array<{\n profile: {\n /**\n * The display name of the whatsapp user\n */\n name: string;\n };\n /**\n * The whatsapp ID of the user\n */\n wa_id: string;\n }>;\n messages: Array<WhatsAppMessage>;\n\n statuses?: Array<{\n /**\n * The ID of the message\n */\n id: string;\n /**\n * The status of the message\n */\n status: MessageStatus;\n /**\n * The timestamp of the message\n */\n timestamp: string;\n /**\n * The recipient ID ( phone number of the user )\n */\n recipient_id: string;\n }>;\n\n errors?: Array<{\n /**\n * The error code\n */\n code: number;\n /**\n * The error title\n */\n title: string;\n /**\n * The error data\n */\n error_data?: {\n /**\n * The error details\n */\n details: string;\n };\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 WhatsApp Business Account ID\n */\n wabaId: string;\n\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 text?: TextMessage['text'];\n image?: ImageMessage['image'];\n video?: VideoMessage['video'];\n audio?: AudioMessage['audio'];\n document?: DocumentMessage['document'];\n sticker?: StickerMessage['sticker'];\n location?: LocationMessage['location'];\n contacts?: ContactsMessage['contacts'];\n interactive?: InteractiveMessage['interactive'];\n button?: ButtonMessage['button'];\n order?: OrderMessage['order'];\n system?: SystemMessage['system'];\n reaction?: ReactionMessage['reaction'];\n\n statuses?: {\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, WebhookMessageValue } 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(entry.id, 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 waba_id: string,\n value: WebhookMessageValue,\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 contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\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: value.statuses[0],\n originalData: status,\n };\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 (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\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 switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.log(`Unknown message type: ${messageType}`);\n break;\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\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"]}
@@ -520,25 +520,7 @@ interface WebhookMessageValue {
520
520
  */
521
521
  wa_id: string;
522
522
  }>;
523
- messages: Array<{
524
- from: string;
525
- id: string;
526
- timestamp: string;
527
- type: MessageTypesEnum;
528
- text?: TextMessage;
529
- image?: ImageMessage;
530
- video?: VideoMessage;
531
- audio?: AudioMessage;
532
- document?: DocumentMessage;
533
- sticker?: StickerMessage;
534
- location?: LocationMessage;
535
- contacts?: ContactsMessage;
536
- interactive?: InteractiveMessage;
537
- button?: ButtonMessage;
538
- order?: OrderMessage;
539
- system?: SystemMessage;
540
- reaction?: ReactionMessage;
541
- }>;
523
+ messages: Array<WhatsAppMessage>;
542
524
  statuses?: Array<{
543
525
  /**
544
526
  * The ID of the message
@@ -614,18 +596,19 @@ interface WebhookMessage {
614
596
  * The profile name of the sender
615
597
  */
616
598
  profileName: string;
617
- text?: TextMessage;
618
- image?: ImageMessage;
619
- video?: VideoMessage;
620
- audio?: AudioMessage;
621
- document?: DocumentMessage;
622
- sticker?: StickerMessage;
623
- location?: LocationMessage;
624
- contacts?: ContactsMessage;
625
- interactive?: InteractiveMessage;
626
- button?: ButtonMessage;
627
- order?: OrderMessage;
628
- system?: SystemMessage;
599
+ text?: TextMessage['text'];
600
+ image?: ImageMessage['image'];
601
+ video?: VideoMessage['video'];
602
+ audio?: AudioMessage['audio'];
603
+ document?: DocumentMessage['document'];
604
+ sticker?: StickerMessage['sticker'];
605
+ location?: LocationMessage['location'];
606
+ contacts?: ContactsMessage['contacts'];
607
+ interactive?: InteractiveMessage['interactive'];
608
+ button?: ButtonMessage['button'];
609
+ order?: OrderMessage['order'];
610
+ system?: SystemMessage['system'];
611
+ reaction?: ReactionMessage['reaction'];
629
612
  statuses?: {
630
613
  /**
631
614
  * Arbitrary string included in sent message
@@ -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-NTQYJXAZ.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
1
+ export{a as MessageStatus,e as WebhookHandler,f as generateXHub256Sig,d as processFlowRequest,c as processWebhookMessages,b as verifyWebhook}from'../../chunk-TEJIY4ZS.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-NTQYJXAZ.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
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-TEJIY4ZS.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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meta-cloud-api",
3
- "version": "0.2.29",
3
+ "version": "0.2.30",
4
4
  "description": "TypeScript wrapper for Meta's Cloud API",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,3 +0,0 @@
1
- import {a as a$1,b}from'./chunk-HEVRZRB4.js';import {a}from'./chunk-VW3LGHTJ.js';import*as p from'crypto';import p__default from'crypto';var S=(t=>(t.DELIVERED="delivered",t.READ="read",t.SENT="sent",t))(S||{});function H(s){return typeof s=="object"&&s!==null}function m(s){return typeof s=="string"}var q=["data_exchange","INIT","BACK"],F=["data_exchange","INIT"];function v(s){if(!("flow_token"in s&&m(s.flow_token)&&"action"in s))return false;let{action:e,version:o,screen:t,data:r}=s,a=o==="3.0",i=q.includes(e),g=typeof t>"u"||m(t)&&t!=="SUCCESS",d=e==="data_exchange"||H(r);return a&&i&&g&&d}function W(s){if(!("flow_token"in s&&m(s.flow_token)&&"action"in s))return false;let{action:e,screen:o,data:t}=s,r=F.includes(e),a=m(o),i=H(t)&&"error_key"in t&&m(t.error)&&"error_message"in t&&m(t.error_message);return r&&a&&i}function T(s){return "action"in s&&s.action==="ping"}var I="WEBHOOK_UTILS",c=new a(I,process.env.DEBUG==="true");function w(s,e){let o=s.query["hub.mode"],t=s.query["hub.verify_token"],r=s.query["hub.challenge"];return o!==void 0&&t!==void 0&&r!==void 0?o==="subscribe"&&t===e?(c.log("Webhook verified successfully"),{statusCode:200,body:r}):(c.log("Webhook verification failed"),{statusCode:403}):(c.log("Not a webhook verification request - missing required parameters"),{statusCode:400,body:{error:"Invalid webhook verification request"}})}async function E(s,e,o){let t=s.body,r=[];if(t.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";return c.log(a),{statusCode:404,body:{error:a}}}for(let a of t.entry)try{let i=a.changes;for(let g of i)g.field==="messages"&&await P(a.id,g.value,e,o);}catch(i){let g=`Error processing webhook: ${i}`;c.log(g),r.push(g);}return {statusCode:200,body:r.length>0?{errors:r}:void 0}}async function k(s,e,o,t){try{if(!N(s,e.WEBHOOK_VERIFICATION_TOKEN||""))return c.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let r=JSON.parse(s.rawBody||"{}"),{decryptedBody:a}=O(r,e),i=t.get("*");if(!i)return c.log(`No handler registered for flow action: ${a.action}`),{statusCode:404,body:{error:"Handler not found"}};if(T(a))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(W(a))return c.log(`Flow error: ${JSON.stringify(a)}`),{statusCode:200,body:{}};if(v(a)){let g=await i(o,a);return {statusCode:200,body:D(g,Buffer.from(r.aes_key,"base64"),Buffer.from(r.initial_vector,"base64"))}}return c.log(`Unknown flow request type: ${JSON.stringify(a)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(r){return c.log(`Error handling flow request: ${r}`),{statusCode:500,body:{error:"Internal server error"}}}}async function P(s,e,o,t){let r=e.metadata,a=e.contacts,i=s,g=r?.display_phone_number||"",d=r?.phone_number_id||"",f=a?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){let u=e.statuses;for(let n of u){let l={wabaId:i,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:d,displayPhoneNumber:g,profileName:f,statuses:e.statuses[0],originalData:n};await M(t.messageHandlers.get("statuses"),o,l,"statuses");}return}if(e.messages&&e.messages.length>0){let u=e.messages;for(let n of u){let l=n.type,y={wabaId:i,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:d,displayPhoneNumber:g,profileName:f,text:n.text,image:n.image,video:n.video,audio:n.audio,document:n.document,sticker:n.sticker,location:n.location,contacts:n.contacts,interactive:n.interactive,button:n.button,order:n.order,system:n.system,originalData:n};await M(t.preProcessHandler,o,y,"pre-process"),await M(t.messageHandlers.get(l),o,y,l),await M(t.postProcessHandler,o,y,"post-process");}}}async function M(s,e,o,t){if(s)try{await s(e,o);}catch(r){c.log(`Error in ${t} handler: ${r}`);}}function N(s,e){let o=s.headers["x-hub-signature-256"];if(!o||!s.rawBody)return false;let r=`sha256=${p__default.createHmac("sha256",e).update(s.rawBody,"utf8").digest("hex")}`;return p__default.timingSafeEqual(Buffer.from(o),Buffer.from(r))}function O(s,e){let{encrypted_aes_key:o,encrypted_flow_data:t,initial_vector:r}=s;if(!o||!t||!r)throw new Error("Missing required encryption properties");let a=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
- `),i=e.FLOW_API_PASSPHRASE,g=p__default.createPrivateKey({key:a,passphrase:i}),d;try{d=p__default.privateDecrypt({key:g,padding:p__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 f=Buffer.from(t,"base64"),u=Buffer.from(r,"base64"),l=f.subarray(0,-16),y=f.subarray(-16),_=p__default.createDecipheriv("aes-128-gcm",d,u);_.setAuthTag(y);let C=Buffer.concat([_.update(l),_.final()]).toString("utf-8");return {decryptedBody:JSON.parse(C),aesKeyBuffer:d,initialVectorBuffer:u}}function D(s,e,o){let t=[];for(let r of Array.from(o.entries()))t.push(~r[1]);try{let r=p__default.createCipheriv("aes-128-gcm",e,Buffer.from(t));return Buffer.concat([r.update(JSON.stringify(s||{}),"utf-8"),r.final(),r.getAuthTag()]).toString("base64")}catch(r){throw c.log("Response encryption error:",r),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",h=new a(V,process.env.DEBUG==="true"),R=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$1(e),this.client=new b(e),h.log("WebhookHandler instantiated!");}handleVerification=e=>w(e,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async e=>E(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler});handleFlow=async e=>k(e,this.config,this.client,this.flowHandlers);onMessage(e,o){this.messageHandlers.set(e,o),h.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,h.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,h.log("Registered post-process handler");}onFlow(e,o){this.flowHandlers.set(e,o),h.log(`Registered flow handler for ${e}`);}};var oe=(s,e)=>p.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{S as a,w as b,E as c,k as d,R as e,oe as f};//# sourceMappingURL=chunk-NTQYJXAZ.js.map
3
- //# sourceMappingURL=chunk-NTQYJXAZ.js.map
@@ -1 +0,0 @@
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","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","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","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,CAAA,kBAAA,CAAoB,KAAK,kBAC7B,CAAC,CAME,CAAA,UAAA,CAAa,MAAOA,CAChB8B,EAAAA,CAAAA,CAAmB9B,EAAS,IAAK,CAAA,MAAA,CAAQ,KAAK,MAAQ,CAAA,IAAA,CAAK,YAAY,CAAA,CAM3E,UAAUgF,CAAwB5C,CAAAA,CAAAA,CAA+B,CACpE,IAAK,CAAA,eAAA,CAAgB,IAAI4C,CAAM5C,CAAAA,CAAO,CACtCxB,CAAAA,CAAAA,CAAO,IAAI,CAAkCoE,+BAAAA,EAAAA,CAAI,EAAE,EACvD,CAKO,oBAAoB5C,CAA+B,CAAA,CACtD,IAAK,CAAA,iBAAA,CAAoBA,EACzBxB,CAAO,CAAA,GAAA,CAAI,gCAAgC,EAC/C,CAKO,qBAAqBwB,CAA+B,CAAA,CACvD,IAAK,CAAA,kBAAA,CAAqBA,EAC1BxB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,OAAOoE,CAAoB5C,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,aAAa,GAAI4C,CAAAA,CAAAA,CAAM5C,CAAO,CACnCxB,CAAAA,CAAAA,CAAO,IAAI,CAA+BoE,4BAAAA,EAAAA,CAAI,CAAE,CAAA,EACpD,CACJ,EC1FO,IAAMC,GAAqB,CAAC3D,CAAAA,CAAc4D,IAC/BC,CAAW,CAAA,UAAA,CAAA,QAAA,CAAUD,CAAS,CAAE,CAAA,MAAA,CAAO5D,EAAM,OAAO,CAAA,CAAE,OAAO,KAAK","file":"chunk-NTQYJXAZ.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 * Base message interface with common properties\n */\nexport interface BaseMessage {\n id: string;\n from: string;\n timestamp: string;\n type: MessageTypesEnum;\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 * 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/**\n * Text message interface\n */\nexport interface TextMessage extends BaseMessage {\n type: MessageTypesEnum.Text;\n text: {\n /**\n * The text content of the message\n */\n body: string;\n preview_url?: boolean;\n };\n}\n\n/**\n * Image message interface\n */\nexport interface ImageMessage extends BaseMessage {\n type: MessageTypesEnum.Image;\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/**\n * Video message interface\n */\nexport interface VideoMessage extends BaseMessage {\n type: MessageTypesEnum.Video;\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/**\n * Audio message interface\n */\nexport interface AudioMessage extends BaseMessage {\n type: MessageTypesEnum.Audio;\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/**\n * Document message interface\n */\nexport interface DocumentMessage extends BaseMessage {\n type: MessageTypesEnum.Document;\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/**\n * Sticker message interface\n */\nexport interface StickerMessage extends BaseMessage {\n type: MessageTypesEnum.Sticker;\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/**\n * Reaction message interface\n */\nexport interface ReactionMessage extends BaseMessage {\n type: MessageTypesEnum.Reaction;\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/**\n * Contacts message interface\n */\nexport interface ContactsMessage extends BaseMessage {\n type: MessageTypesEnum.Contacts;\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/**\n * Location message interface\n */\nexport interface LocationMessage extends BaseMessage {\n type: MessageTypesEnum.Location;\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/**\n * Interactive message interface\n */\nexport interface InteractiveMessage extends BaseMessage {\n type: MessageTypesEnum.Interactive;\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 * 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/**\n * System message interface\n */\nexport interface SystemMessage extends BaseMessage {\n type: MessageTypesEnum.System;\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/**\n * Order message interface\n */\nexport interface OrderMessage extends BaseMessage {\n type: MessageTypesEnum.Order;\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/**\n * Button message interface\n */\nexport interface ButtonMessage extends BaseMessage {\n type: MessageTypesEnum.Button;\n button: {\n /**\n * The payload for the button\n */\n payload: string;\n /**\n * Button text\n */\n text: string;\n };\n}\n\n/**\n * Union type for all message types\n */\nexport type WhatsAppMessage =\n | TextMessage\n | ImageMessage\n | VideoMessage\n | AudioMessage\n | DocumentMessage\n | StickerMessage\n | ReactionMessage\n | ContactsMessage\n | LocationMessage\n | InteractiveMessage\n | SystemMessage\n | OrderMessage\n | ButtonMessage;\n\nexport interface WebhookMessageValue {\n /**\n * The messaging product\n */\n messaging_product: string;\n /**\n * The metadata\n */\n metadata: {\n /**\n * The display phone number of the whatsapp business account\n */\n display_phone_number: string;\n /**\n * The phone number ID of the whatsapp business account\n */\n phone_number_id: string;\n };\n contacts?: Array<{\n profile: {\n /**\n * The display name of the whatsapp user\n */\n name: string;\n };\n /**\n * The whatsapp ID of the user\n */\n wa_id: string;\n }>;\n messages: Array<{\n from: string;\n id: string;\n timestamp: string;\n type: MessageTypesEnum;\n text?: TextMessage;\n image?: ImageMessage;\n video?: VideoMessage;\n audio?: AudioMessage;\n document?: DocumentMessage;\n sticker?: StickerMessage;\n location?: LocationMessage;\n contacts?: ContactsMessage;\n interactive?: InteractiveMessage;\n button?: ButtonMessage;\n order?: OrderMessage;\n system?: SystemMessage;\n reaction?: ReactionMessage;\n }>;\n\n statuses?: Array<{\n /**\n * The ID of the message\n */\n id: string;\n /**\n * The status of the message\n */\n status: MessageStatus;\n /**\n * The timestamp of the message\n */\n timestamp: string;\n /**\n * The recipient ID ( phone number of the user )\n */\n recipient_id: string;\n }>;\n\n errors?: Array<{\n /**\n * The error code\n */\n code: number;\n /**\n * The error title\n */\n title: string;\n /**\n * The error data\n */\n error_data?: {\n /**\n * The error details\n */\n details: string;\n };\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 WhatsApp Business Account ID\n */\n wabaId: string;\n\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 text?: TextMessage;\n image?: ImageMessage;\n video?: VideoMessage;\n audio?: AudioMessage;\n document?: DocumentMessage;\n sticker?: StickerMessage;\n location?: LocationMessage;\n contacts?: ContactsMessage;\n interactive?: InteractiveMessage;\n button?: ButtonMessage;\n order?: OrderMessage;\n system?: SystemMessage;\n\n statuses?: {\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, WebhookMessageValue } 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(entry.id, 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 waba_id: string,\n value: WebhookMessageValue,\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 contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\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: value.statuses[0],\n originalData: status,\n };\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 (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\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 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\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"]}