meta-cloud-api 0.2.27 → 0.2.29
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.
- package/dist/chunk-NTQYJXAZ.js +3 -0
- package/dist/chunk-NTQYJXAZ.js.map +1 -0
- package/dist/core/webhook/index.d.ts +274 -126
- package/dist/core/webhook/index.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-575ICT3Y.js +0 -3
- package/dist/chunk-575ICT3Y.js.map +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
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
|
|
@@ -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","WebhookHandler","importConfig","WhatsApp","type","generateXHub256Sig","appSecret","B"],"mappings":"yIAoyBYA,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,ICvxBZ,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,CAAA,UAAU,GAAK,QAAYA,GAAAA,CAAAA,CAAAA,CACzE,OAAO,MAGX,CAAA,GAAM,CAAE,MAAAC,CAAAA,CAAAA,CAAQ,OAAAC,CAAAA,CAAAA,CAAS,MAAAC,CAAAA,CAAAA,CAAQ,KAAAC,CAAK,CAAA,CAAIJ,EAGpCK,CAAkBH,CAAAA,CAAAA,GAAY,MAG9BI,CAAiBT,CAAAA,CAAAA,CAAsB,QAASI,CAAAA,CAAa,CAG7DM,CAAAA,CAAAA,CAAiB,OAAOJ,CAAW,CAAA,GAAA,EAAgBP,EAASO,CAAM,CAAA,EAAKA,IAAW,SAGlFK,CAAAA,CAAAA,CAAeP,CAAW,GAAA,eAAA,EAAgCP,CAASU,CAAAA,CAAI,EAG7E,OAAOC,CAAAA,EAAmBC,GAAkBC,CAAkBC,EA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AS,CAAA,IAAA,CAAK,OAAQ,CAChD,eAAA,CAAiB,KAAK,eACtB,CAAA,iBAAA,CAAmB,KAAK,iBACxB,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"]}
|
|
@@ -35,51 +35,97 @@ interface WebhookContact {
|
|
|
35
35
|
};
|
|
36
36
|
}
|
|
37
37
|
/**
|
|
38
|
-
*
|
|
39
|
-
* Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#messages-object
|
|
38
|
+
* Base message interface with common properties
|
|
40
39
|
*/
|
|
41
|
-
interface
|
|
42
|
-
/**
|
|
43
|
-
* The message ID
|
|
44
|
-
*/
|
|
40
|
+
interface BaseMessage {
|
|
45
41
|
id: string;
|
|
46
|
-
/**
|
|
47
|
-
* The sender's phone number
|
|
48
|
-
*/
|
|
49
42
|
from: string;
|
|
50
|
-
/**
|
|
51
|
-
* The timestamp of the message
|
|
52
|
-
*/
|
|
53
43
|
timestamp: string;
|
|
54
|
-
/**
|
|
55
|
-
* The type of message (text, image, etc.)
|
|
56
|
-
*/
|
|
57
44
|
type: MessageTypesEnum;
|
|
58
45
|
/**
|
|
59
|
-
*
|
|
60
|
-
*/
|
|
61
|
-
phoneNumberId: string;
|
|
62
|
-
/**
|
|
63
|
-
* The display phone number that received the message
|
|
64
|
-
*/
|
|
65
|
-
displayPhoneNumber: string;
|
|
66
|
-
/**
|
|
67
|
-
* The profile name of the sender
|
|
46
|
+
* Context object, included when a user replies or interacts
|
|
68
47
|
*/
|
|
69
|
-
|
|
48
|
+
context?: {
|
|
49
|
+
/**
|
|
50
|
+
* ID of the message
|
|
51
|
+
*/
|
|
52
|
+
id?: string;
|
|
53
|
+
/**
|
|
54
|
+
* ID of the sender
|
|
55
|
+
*/
|
|
56
|
+
from?: string;
|
|
57
|
+
/**
|
|
58
|
+
* ID of the message being replied to or interacted with
|
|
59
|
+
*/
|
|
60
|
+
message_id: string;
|
|
61
|
+
/**
|
|
62
|
+
* ID of the forwarded message, if applicable
|
|
63
|
+
*/
|
|
64
|
+
forwarded?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Frequently forwarded status
|
|
67
|
+
*/
|
|
68
|
+
frequently_forwarded?: boolean;
|
|
69
|
+
/**
|
|
70
|
+
* Original message information if the message was referred
|
|
71
|
+
*/
|
|
72
|
+
referred_product?: {
|
|
73
|
+
/**
|
|
74
|
+
* Catalog ID
|
|
75
|
+
*/
|
|
76
|
+
catalog_id: string;
|
|
77
|
+
/**
|
|
78
|
+
* Product ID
|
|
79
|
+
*/
|
|
80
|
+
product_retailer_id: string;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
70
83
|
/**
|
|
71
|
-
*
|
|
84
|
+
* Errors array, if the message had errors
|
|
72
85
|
*/
|
|
73
|
-
|
|
86
|
+
errors?: Array<{
|
|
87
|
+
/**
|
|
88
|
+
* Error code
|
|
89
|
+
*/
|
|
90
|
+
code: number;
|
|
91
|
+
/**
|
|
92
|
+
* Error title
|
|
93
|
+
*/
|
|
94
|
+
title: string;
|
|
95
|
+
/**
|
|
96
|
+
* Error message
|
|
97
|
+
*/
|
|
98
|
+
message: string;
|
|
99
|
+
/**
|
|
100
|
+
* Error details object
|
|
101
|
+
*/
|
|
102
|
+
error_data?: {
|
|
103
|
+
/**
|
|
104
|
+
* Describes the error details
|
|
105
|
+
*/
|
|
106
|
+
details: string;
|
|
107
|
+
};
|
|
108
|
+
}>;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Text message interface
|
|
112
|
+
*/
|
|
113
|
+
interface TextMessage extends BaseMessage {
|
|
114
|
+
type: MessageTypesEnum.Text;
|
|
115
|
+
text: {
|
|
74
116
|
/**
|
|
75
117
|
* The text content of the message
|
|
76
118
|
*/
|
|
77
119
|
body: string;
|
|
120
|
+
preview_url?: boolean;
|
|
78
121
|
};
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Image message interface
|
|
125
|
+
*/
|
|
126
|
+
interface ImageMessage extends BaseMessage {
|
|
127
|
+
type: MessageTypesEnum.Image;
|
|
128
|
+
image: {
|
|
83
129
|
/**
|
|
84
130
|
* The image caption (if provided)
|
|
85
131
|
*/
|
|
@@ -97,10 +143,13 @@ interface WebhookMessage {
|
|
|
97
143
|
*/
|
|
98
144
|
mime_type: string;
|
|
99
145
|
};
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Video message interface
|
|
149
|
+
*/
|
|
150
|
+
interface VideoMessage extends BaseMessage {
|
|
151
|
+
type: MessageTypesEnum.Video;
|
|
152
|
+
video: {
|
|
104
153
|
/**
|
|
105
154
|
* The video caption (if provided)
|
|
106
155
|
*/
|
|
@@ -118,10 +167,13 @@ interface WebhookMessage {
|
|
|
118
167
|
*/
|
|
119
168
|
mime_type: string;
|
|
120
169
|
};
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Audio message interface
|
|
173
|
+
*/
|
|
174
|
+
interface AudioMessage extends BaseMessage {
|
|
175
|
+
type: MessageTypesEnum.Audio;
|
|
176
|
+
audio: {
|
|
125
177
|
/**
|
|
126
178
|
* The ID for the audio file
|
|
127
179
|
*/
|
|
@@ -135,10 +187,13 @@ interface WebhookMessage {
|
|
|
135
187
|
*/
|
|
136
188
|
voice?: boolean;
|
|
137
189
|
};
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Document message interface
|
|
193
|
+
*/
|
|
194
|
+
interface DocumentMessage extends BaseMessage {
|
|
195
|
+
type: MessageTypesEnum.Document;
|
|
196
|
+
document: {
|
|
142
197
|
/**
|
|
143
198
|
* The document caption (if provided)
|
|
144
199
|
*/
|
|
@@ -160,10 +215,13 @@ interface WebhookMessage {
|
|
|
160
215
|
*/
|
|
161
216
|
mime_type: string;
|
|
162
217
|
};
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Sticker message interface
|
|
221
|
+
*/
|
|
222
|
+
interface StickerMessage extends BaseMessage {
|
|
223
|
+
type: MessageTypesEnum.Sticker;
|
|
224
|
+
sticker: {
|
|
167
225
|
/**
|
|
168
226
|
* The ID for the sticker
|
|
169
227
|
*/
|
|
@@ -177,10 +235,13 @@ interface WebhookMessage {
|
|
|
177
235
|
*/
|
|
178
236
|
mime_type: string;
|
|
179
237
|
};
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Reaction message interface
|
|
241
|
+
*/
|
|
242
|
+
interface ReactionMessage extends BaseMessage {
|
|
243
|
+
type: MessageTypesEnum.Reaction;
|
|
244
|
+
reaction: {
|
|
184
245
|
/**
|
|
185
246
|
* The ID of the message being reacted to
|
|
186
247
|
*/
|
|
@@ -190,10 +251,13 @@ interface WebhookMessage {
|
|
|
190
251
|
*/
|
|
191
252
|
emoji: string;
|
|
192
253
|
};
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Contacts message interface
|
|
257
|
+
*/
|
|
258
|
+
interface ContactsMessage extends BaseMessage {
|
|
259
|
+
type: MessageTypesEnum.Contacts;
|
|
260
|
+
contacts: Array<{
|
|
197
261
|
/**
|
|
198
262
|
* The contact's name
|
|
199
263
|
*/
|
|
@@ -270,10 +334,13 @@ interface WebhookMessage {
|
|
|
270
334
|
*/
|
|
271
335
|
birthday?: string;
|
|
272
336
|
}>;
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Location message interface
|
|
340
|
+
*/
|
|
341
|
+
interface LocationMessage extends BaseMessage {
|
|
342
|
+
type: MessageTypesEnum.Location;
|
|
343
|
+
location: {
|
|
277
344
|
/**
|
|
278
345
|
* Latitude of the location
|
|
279
346
|
*/
|
|
@@ -291,10 +358,13 @@ interface WebhookMessage {
|
|
|
291
358
|
*/
|
|
292
359
|
address?: string;
|
|
293
360
|
};
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
361
|
+
}
|
|
362
|
+
/**
|
|
363
|
+
* Interactive message interface
|
|
364
|
+
*/
|
|
365
|
+
interface InteractiveMessage extends BaseMessage {
|
|
366
|
+
type: MessageTypesEnum.Interactive;
|
|
367
|
+
interactive: {
|
|
298
368
|
/**
|
|
299
369
|
* Type of the interactive message
|
|
300
370
|
* Can be: button_reply, list_reply, flow, nfm_reply, etc.
|
|
@@ -333,10 +403,13 @@ interface WebhookMessage {
|
|
|
333
403
|
name: string;
|
|
334
404
|
};
|
|
335
405
|
};
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* System message interface
|
|
409
|
+
*/
|
|
410
|
+
interface SystemMessage extends BaseMessage {
|
|
411
|
+
type: MessageTypesEnum.System;
|
|
412
|
+
system: {
|
|
340
413
|
/**
|
|
341
414
|
* The type of system update
|
|
342
415
|
*/
|
|
@@ -359,10 +432,13 @@ interface WebhookMessage {
|
|
|
359
432
|
wa_id: string;
|
|
360
433
|
};
|
|
361
434
|
};
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Order message interface
|
|
438
|
+
*/
|
|
439
|
+
interface OrderMessage extends BaseMessage {
|
|
440
|
+
type: MessageTypesEnum.Order;
|
|
441
|
+
order: {
|
|
366
442
|
/**
|
|
367
443
|
* Catalog ID
|
|
368
444
|
*/
|
|
@@ -393,92 +469,164 @@ interface WebhookMessage {
|
|
|
393
469
|
*/
|
|
394
470
|
text?: string;
|
|
395
471
|
};
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Button message interface
|
|
475
|
+
*/
|
|
476
|
+
interface ButtonMessage extends BaseMessage {
|
|
477
|
+
type: MessageTypesEnum.Button;
|
|
478
|
+
button: {
|
|
479
|
+
/**
|
|
480
|
+
* The payload for the button
|
|
481
|
+
*/
|
|
482
|
+
payload: string;
|
|
483
|
+
/**
|
|
484
|
+
* Button text
|
|
485
|
+
*/
|
|
486
|
+
text: string;
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Union type for all message types
|
|
491
|
+
*/
|
|
492
|
+
type WhatsAppMessage = TextMessage | ImageMessage | VideoMessage | AudioMessage | DocumentMessage | StickerMessage | ReactionMessage | ContactsMessage | LocationMessage | InteractiveMessage | SystemMessage | OrderMessage | ButtonMessage;
|
|
493
|
+
interface WebhookMessageValue {
|
|
396
494
|
/**
|
|
397
|
-
*
|
|
495
|
+
* The messaging product
|
|
398
496
|
*/
|
|
399
|
-
|
|
497
|
+
messaging_product: string;
|
|
498
|
+
/**
|
|
499
|
+
* The metadata
|
|
500
|
+
*/
|
|
501
|
+
metadata: {
|
|
400
502
|
/**
|
|
401
|
-
*
|
|
503
|
+
* The display phone number of the whatsapp business account
|
|
402
504
|
*/
|
|
403
|
-
|
|
505
|
+
display_phone_number: string;
|
|
404
506
|
/**
|
|
405
|
-
* ID of the
|
|
507
|
+
* The phone number ID of the whatsapp business account
|
|
406
508
|
*/
|
|
407
|
-
|
|
509
|
+
phone_number_id: string;
|
|
510
|
+
};
|
|
511
|
+
contacts?: Array<{
|
|
512
|
+
profile: {
|
|
513
|
+
/**
|
|
514
|
+
* The display name of the whatsapp user
|
|
515
|
+
*/
|
|
516
|
+
name: string;
|
|
517
|
+
};
|
|
408
518
|
/**
|
|
409
|
-
* ID of the
|
|
519
|
+
* The whatsapp ID of the user
|
|
410
520
|
*/
|
|
411
|
-
|
|
521
|
+
wa_id: string;
|
|
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
|
+
}>;
|
|
542
|
+
statuses?: Array<{
|
|
412
543
|
/**
|
|
413
|
-
* ID of the
|
|
544
|
+
* The ID of the message
|
|
414
545
|
*/
|
|
415
|
-
|
|
546
|
+
id: string;
|
|
416
547
|
/**
|
|
417
|
-
*
|
|
548
|
+
* The status of the message
|
|
418
549
|
*/
|
|
419
|
-
|
|
550
|
+
status: MessageStatus;
|
|
420
551
|
/**
|
|
421
|
-
*
|
|
552
|
+
* The timestamp of the message
|
|
422
553
|
*/
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
* Product ID
|
|
430
|
-
*/
|
|
431
|
-
product_retailer_id: string;
|
|
432
|
-
};
|
|
433
|
-
};
|
|
434
|
-
/**
|
|
435
|
-
* Errors array, if the message had errors
|
|
436
|
-
*/
|
|
554
|
+
timestamp: string;
|
|
555
|
+
/**
|
|
556
|
+
* The recipient ID ( phone number of the user )
|
|
557
|
+
*/
|
|
558
|
+
recipient_id: string;
|
|
559
|
+
}>;
|
|
437
560
|
errors?: Array<{
|
|
438
561
|
/**
|
|
439
|
-
*
|
|
562
|
+
* The error code
|
|
440
563
|
*/
|
|
441
564
|
code: number;
|
|
442
565
|
/**
|
|
443
|
-
*
|
|
566
|
+
* The error title
|
|
444
567
|
*/
|
|
445
568
|
title: string;
|
|
446
569
|
/**
|
|
447
|
-
*
|
|
448
|
-
*/
|
|
449
|
-
message: string;
|
|
450
|
-
/**
|
|
451
|
-
* Error details object
|
|
570
|
+
* The error data
|
|
452
571
|
*/
|
|
453
572
|
error_data?: {
|
|
454
573
|
/**
|
|
455
|
-
*
|
|
574
|
+
* The error details
|
|
456
575
|
*/
|
|
457
576
|
details: string;
|
|
458
577
|
};
|
|
459
578
|
}>;
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Represents a message received through the webhook
|
|
582
|
+
* Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#messages-object
|
|
583
|
+
*/
|
|
584
|
+
interface WebhookMessage {
|
|
460
585
|
/**
|
|
461
|
-
*
|
|
586
|
+
* The WhatsApp Business Account ID
|
|
462
587
|
*/
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
588
|
+
wabaId: string;
|
|
589
|
+
/**
|
|
590
|
+
* The message ID
|
|
591
|
+
*/
|
|
592
|
+
id: string;
|
|
593
|
+
/**
|
|
594
|
+
* The sender's phone number
|
|
595
|
+
*/
|
|
596
|
+
from: string;
|
|
597
|
+
/**
|
|
598
|
+
* The timestamp of the message
|
|
599
|
+
*/
|
|
600
|
+
timestamp: string;
|
|
601
|
+
/**
|
|
602
|
+
* The type of message (text, image, etc.)
|
|
603
|
+
*/
|
|
604
|
+
type: MessageTypesEnum;
|
|
605
|
+
/**
|
|
606
|
+
* The phone number ID that received the message
|
|
607
|
+
*/
|
|
608
|
+
phoneNumberId: string;
|
|
609
|
+
/**
|
|
610
|
+
* The display phone number that received the message
|
|
611
|
+
*/
|
|
612
|
+
displayPhoneNumber: string;
|
|
613
|
+
/**
|
|
614
|
+
* The profile name of the sender
|
|
615
|
+
*/
|
|
616
|
+
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;
|
|
473
629
|
statuses?: {
|
|
474
|
-
/**
|
|
475
|
-
* The phone number ID that received the status update
|
|
476
|
-
*/
|
|
477
|
-
phoneNumberId: string;
|
|
478
|
-
/**
|
|
479
|
-
* The display phone number that received the status update
|
|
480
|
-
*/
|
|
481
|
-
displayPhoneNumber: string;
|
|
482
630
|
/**
|
|
483
631
|
* Arbitrary string included in sent message
|
|
484
632
|
*/
|
|
@@ -686,4 +834,4 @@ declare class WebhookHandler {
|
|
|
686
834
|
|
|
687
835
|
declare const generateXHub256Sig: (body: string, appSecret: string) => string;
|
|
688
836
|
|
|
689
|
-
export { type FlowHandler, type MessageHandler, MessageStatus, type WebhookContact, type WebhookEvent, WebhookHandler, type WebhookMessage, type WebhookRequest, type WebhookResponse, generateXHub256Sig, processFlowRequest, processWebhookMessages, verifyWebhook };
|
|
837
|
+
export { type AudioMessage, type BaseMessage, type ButtonMessage, type ContactsMessage, type DocumentMessage, type FlowHandler, type ImageMessage, type InteractiveMessage, type LocationMessage, type MessageHandler, MessageStatus, type OrderMessage, type ReactionMessage, type StickerMessage, type SystemMessage, type TextMessage, type VideoMessage, type WebhookContact, type WebhookEvent, WebhookHandler, type WebhookMessage, type WebhookMessageValue, type WebhookRequest, type WebhookResponse, type WhatsAppMessage, generateXHub256Sig, processFlowRequest, processWebhookMessages, verifyWebhook };
|
|
@@ -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-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
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { FlowHandler, MessageHandler, MessageStatus, WebhookContact, WebhookEvent, WebhookHandler, WebhookMessage, WebhookRequest, WebhookResponse, generateXHub256Sig, processFlowRequest, processWebhookMessages, verifyWebhook } from './core/webhook/index.js';
|
|
1
|
+
export { AudioMessage, BaseMessage, ButtonMessage, ContactsMessage, DocumentMessage, FlowHandler, ImageMessage, InteractiveMessage, LocationMessage, MessageHandler, MessageStatus, OrderMessage, ReactionMessage, StickerMessage, SystemMessage, TextMessage, VideoMessage, WebhookContact, WebhookEvent, WebhookHandler, WebhookMessage, WebhookMessageValue, WebhookRequest, WebhookResponse, WhatsAppMessage, generateXHub256Sig, processFlowRequest, processWebhookMessages, verifyWebhook } from './core/webhook/index.js';
|
|
2
2
|
export { A as AudioMediaObject, C as ContactObject, D as DocumentMediaObject, I as ImageMediaObject, a as InteractiveObject, L as LocationObject, b as MessageRequestParams, d as MessageTemplateObject, M as MessagesApi, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, f as TextObject, V as VideoMediaObject } from './MessageApi-vNrieuce.js';
|
|
3
3
|
export { WabaConfigType, WhatsAppConfig } from './shared/types/config.js';
|
|
4
4
|
export { A as AudioMediaTypesEnum, k as BusinessVerticalEnum, a as ButtonPositionEnum, B as ButtonTypesEnum, C as CategoryEnum, b as ComponentTypesEnum, c as ConversationTypesEnum, i as CurrencyCodesEnum, j as DataLocalizationRegionEnum, D as DocumentMediaTypesEnum, H as HttpMethodsEnum, e as ImageMediaTypesEnum, I as InteractiveTypesEnum, L as LanguagesEnum, M as MessageTypesEnum, P as ParametersTypesEnum, R as ReferralSourceTypesEnum, h as RequestCodeMethodsEnum, S as StatusEnum, d as StickerMediaTypesEnum, g as SystemChangeTypesEnum, T as TemplateStatusEnum, V as VideoMediaTypesEnum, W as WabaConfigEnum, f as WebhookTypesEnum } from './enums-iedeomKw.js';
|
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-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
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
package/dist/chunk-575ICT3Y.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 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 +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","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,CAA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A,CAAmB9B,EAAS,IAAK,CAAA,MAAA,CAAQ,KAAK,MAAQ,CAAA,IAAA,CAAK,YAAY,CAAA,CAM3E,UAAU4E,CAAwBxC,CAAAA,CAAAA,CAA+B,CACpE,IAAK,CAAA,eAAA,CAAgB,IAAIwC,CAAMxC,CAAAA,CAAO,CACtCxB,CAAAA,CAAAA,CAAO,IAAI,CAAkCgE,+BAAAA,EAAAA,CAAI,EAAE,EACvD,CAKO,oBAAoBxC,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,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"]}
|