meta-cloud-api 0.2.41 → 0.2.43

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.
@@ -280,7 +280,9 @@ type SimpleTextObject = {
280
280
  text: string;
281
281
  };
282
282
  type TextParametersObject = ParametersObject<ParametersTypesEnum.Text> & SimpleTextObject;
283
- type CouponCodeParametersObject = ParametersObject<ParametersTypesEnum.CouponCode> & SimpleTextObject;
283
+ type CouponCodeParametersObject = ParametersObject<ParametersTypesEnum.CouponCode> & {
284
+ coupon_code: string;
285
+ };
284
286
  type CurrencyObject = {
285
287
  fallback_value: string;
286
288
  code: CurrencyCodesEnum;
@@ -1,7 +1,7 @@
1
+ import { g as FlowEndpointRequest, n as FlowTypeEnum } from './FlowApi-CASVC-Al.js';
1
2
  import { WabaConfigType, WhatsAppConfig } from './shared/types/config.js';
2
3
  import { M as MessageTypesEnum } from './enums-DvwSJq9w.js';
3
- import { g as FlowEndpointRequest, n as FlowTypeEnum } from './FlowApi-CASVC-Al.js';
4
- import { W as WhatsApp } from './index-BPgH1nT-.js';
4
+ import { W as WhatsApp } from './index-DiCI1vEz.js';
5
5
 
6
6
  interface WebhookContact {
7
7
  /**
@@ -658,39 +658,23 @@ declare enum MessageStatus {
658
658
  SENT = "sent"
659
659
  }
660
660
 
661
- interface WebhookRequest {
662
- method: string;
663
- query: Record<string, any>;
664
- body: any;
665
- headers: Record<string, string | string[] | undefined>;
666
- rawBody?: string;
667
- }
668
- interface WebhookResponse {
669
- statusCode: number;
670
- body?: any;
671
- headers?: Record<string, string>;
672
- }
673
661
  type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;
674
662
  type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;
675
663
  /**
676
- * Pure function to handle webhook verification
677
- */
678
- declare function verifyWebhook(request: Pick<WebhookRequest, 'query'>, verificationToken: string): WebhookResponse;
679
- /**
680
- * Pure function to process webhook messages
664
+ * Process webhook messages
681
665
  */
682
- declare function processWebhookMessages(request: WebhookRequest, whatsapp: WhatsApp, handlers: {
666
+ declare function processWebhookMessages(request: Request, whatsapp: WhatsApp, handlers: {
683
667
  messageHandlers: Map<MessageTypesEnum, MessageHandler>;
684
668
  preProcessHandler?: MessageHandler;
685
669
  postProcessHandler?: MessageHandler;
686
- }): Promise<WebhookResponse>;
670
+ }): Promise<Response>;
687
671
  /**
688
- * Pure function to handle flow requests
672
+ * Handle flow requests
689
673
  */
690
- declare function processFlowRequest(request: WebhookRequest, config: WabaConfigType, whatsapp: WhatsApp, flowHandlers: Map<FlowTypeEnum, FlowHandler>): Promise<WebhookResponse>;
674
+ declare function processFlowRequest(request: Request, config: WabaConfigType, whatsapp: WhatsApp, flowHandlers: Map<FlowTypeEnum, FlowHandler>): Promise<Response>;
691
675
 
692
676
  /**
693
- * Framework-agnostic WebhookHandler using pure functions
677
+ * WebhookHandler based on Web Standard API
694
678
  */
695
679
  declare class WebhookHandler {
696
680
  private config;
@@ -701,17 +685,17 @@ declare class WebhookHandler {
701
685
  private flowHandlers;
702
686
  constructor(config: WhatsAppConfig);
703
687
  /**
704
- * Handle webhook verification (framework-agnostic)
688
+ * Handle webhook requests using Web Standard API
705
689
  */
706
- handleVerification: (request: Pick<WebhookRequest, "query">) => WebhookResponse;
690
+ handleWebhook(request: Request): Promise<Response>;
707
691
  /**
708
- * Handle webhook messages (framework-agnostic)
692
+ * Handle flow requests
709
693
  */
710
- handleWebhook: (request: WebhookRequest) => Promise<WebhookResponse>;
694
+ handleFlow(request: Request): Promise<Response>;
711
695
  /**
712
- * Handle flow requests (framework-agnostic)
696
+ * Verify webhook signature
713
697
  */
714
- handleFlow: (request: WebhookRequest) => Promise<WebhookResponse>;
698
+ private verifySignature;
715
699
  /**
716
700
  * Register a message handler for a specific message type
717
701
  */
@@ -730,4 +714,4 @@ declare class WebhookHandler {
730
714
  onFlow(type: FlowTypeEnum, handler: FlowHandler): void;
731
715
  }
732
716
 
733
- export { type FlowHandler as F, MessageStatus as M, type WebhookContact as W, type WebhookEvent as a, type WebhookMessage as b, WebhookHandler as c, processWebhookMessages as d, type WebhookRequest as e, type WebhookResponse as f, processFlowRequest as p, verifyWebhook as v };
717
+ export { type FlowHandler as F, MessageStatus as M, type WebhookContact as W, type WebhookEvent as a, type WebhookMessage as b, WebhookHandler as c, type MessageHandler as d, processFlowRequest as e, processWebhookMessages as p };
@@ -0,0 +1,3 @@
1
+ import {a as a$1,b}from'./chunk-5O5GLWIE.js';import {a}from'./chunk-VW3LGHTJ.js';import*as m from'crypto';import m__default from'crypto';function k(s){return typeof s=="object"&&s!==null}function h(s){return typeof s=="string"}var v=["data_exchange","INIT","BACK"],B=["data_exchange","INIT"];function A(s){if(!("flow_token"in s&&h(s.flow_token)&&"action"in s))return false;let{action:e,version:r,screen:t,data:o}=s,c=r==="3.0",p=v.includes(e),a=typeof t>"u"||h(t)&&t!=="SUCCESS",l=e==="data_exchange"||k(o);return c&&p&&a&&l}function S(s){if(!("flow_token"in s&&h(s.flow_token)&&"action"in s))return false;let{action:e,screen:r,data:t}=s,o=B.includes(e),c=h(r),p=k(t)&&"error_key"in t&&h(t.error)&&"error_message"in t&&h(t.error_message);return o&&c&&p}function M(s){return "action"in s&&s.action==="ping"}var W="WEBHOOK_UTILS",f=new a(W,process.env.DEBUG==="true");async function O(s,e,r){try{let t=await s.json();if(t.object!=="whatsapp_business_account"){let c="Received webhook for non-WhatsApp event";return f.log(c),new Response(JSON.stringify({error:c}),{status:404})}let o=[];for(let c of t.entry)try{let p=c.changes;for(let a of p)a.field==="messages"&&await I(c.id,a.value,e,r);}catch(p){let a=`Error processing webhook: ${p}`;f.log(a),o.push(a);}return new Response(o.length>0?JSON.stringify({errors:o}):null,{status:200})}catch(t){return f.log(`Error processing webhook: ${t}`),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}async function P(s,e,r,t){try{let o=await s.text(),c=s.headers.get("x-hub-signature-256");if(!C(o,c,e.WEBHOOK_VERIFICATION_TOKEN||""))return f.log("Invalid request signature"),new Response(JSON.stringify({error:"Unauthorized"}),{status:401});let p=JSON.parse(o),{decryptedBody:a}=x(p,e),l=t.get("*");if(!l)return f.log(`No handler registered for flow action: ${a.action}`),new Response(JSON.stringify({error:"Handler not found"}),{status:404});if(M(a))return new Response(JSON.stringify({version:"3.0",data:{status:"active"}}),{status:200});if(S(a))return f.log(`Flow error: ${JSON.stringify(a)}`),new Response(null,{status:200});if(A(a)){let d=await l(r,a),u=q(d,Buffer.from(p.aes_key,"base64"),Buffer.from(p.initial_vector,"base64"));return new Response(JSON.stringify(u),{status:200})}return f.log(`Unknown flow request type: ${JSON.stringify(a)}`),new Response(JSON.stringify({error:"Unknown request type"}),{status:400})}catch(o){return f.log(`Error handling flow request: ${o}`),new Response(JSON.stringify({error:"Internal server error"}),{status:500})}}function C(s,e,r){if(!e)return false;let t=m__default.createHmac("sha256",r).update(s).digest("hex");return m__default.timingSafeEqual(Buffer.from(e.replace("sha256=","")),Buffer.from(t))}async function I(s,e,r,t){let o=e.metadata,c=e.contacts,p=s,a=o?.display_phone_number||"",l=o?.phone_number_id||"",d=c?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){let u=e.statuses;for(let n of u){let g={wabaId:p,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:l,displayPhoneNumber:a,profileName:d,statuses:e.statuses[0],originalData:n};await R(t.messageHandlers.get("statuses"),r,g,"statuses");}return}if(e.messages&&e.messages.length>0){let u=e.messages;for(let n of u){let g=n.type,i={wabaId:p,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:l,displayPhoneNumber:a,profileName:d,originalData:n};switch(g){case "text":i.text=n.text;break;case "image":i.image=n.image;break;case "video":i.video=n.video;break;case "audio":i.audio=n.audio;break;case "document":i.document=n.document;break;case "sticker":i.sticker=n.sticker;break;case "location":i.location=n.location;break;case "contacts":i.contacts=n.contacts;break;case "interactive":i.interactive=n.interactive;break;case "button":i.button=n.button;break;case "order":i.order=n.order;break;case "system":i.system=n.system;break;case "reaction":i.reaction=n.reaction;break;default:f.log(`Unknown message type: ${g}`);break}await R(t.preProcessHandler,r,i,"pre-process"),await R(t.messageHandlers.get(g),r,i,g),await R(t.postProcessHandler,r,i,"post-process");}}}async function R(s,e,r,t){if(s)try{await s(e,r);}catch(o){f.log(`Error in ${t} handler: ${o}`);}}function x(s,e){let{encrypted_aes_key:r,encrypted_flow_data:t,initial_vector:o}=s;if(!r||!t||!o)throw new Error("Missing required encryption properties");let c=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),p=e.FLOW_API_PASSPHRASE,a=m__default.createPrivateKey({key:c,passphrase:p}),l;try{l=m__default.privateDecrypt({key:a,padding:m__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let d=Buffer.from(t,"base64"),u=Buffer.from(o,"base64"),g=d.subarray(0,-16),i=d.subarray(-16),b=m__default.createDecipheriv("aes-128-gcm",l,u);b.setAuthTag(i);let T=Buffer.concat([b.update(g),b.final()]).toString("utf-8");return {decryptedBody:JSON.parse(T),aesKeyBuffer:l,initialVectorBuffer:u}}function q(s,e,r){let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=m__default.createCipheriv("aes-128-gcm",e,Buffer.from(t));return Buffer.concat([o.update(JSON.stringify(s||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64")}catch(o){throw f.log("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var D="WEBHOOK",y=new a(D,process.env.DEBUG==="true"),E=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),y.log("WebhookHandler instantiated!");}async handleWebhook(e){try{if(e.method==="GET"){let r=new URL(e.url),t=r.searchParams.get("hub.mode"),o=r.searchParams.get("hub.verify_token"),c=r.searchParams.get("hub.challenge");return t==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?new Response(c,{status:200}):new Response(null,{status:403})}return e.method==="POST"?O(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}):new Response(null,{status:405})}catch(r){return y.log(`Error handling webhook: ${r}`),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}async handleFlow(e){try{return P(e,this.config,this.client,this.flowHandlers)}catch(r){return y.log(`Error handling flow: ${r}`),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}verifySignature(e,r){if(!r)return false;let t=m__default.createHmac("sha256",this.config.WEBHOOK_VERIFICATION_TOKEN).update(e).digest("hex");return m__default.timingSafeEqual(Buffer.from(r.replace("sha256=","")),Buffer.from(t))}onMessage(e,r){this.messageHandlers.set(e,r),y.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,y.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,y.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),y.log(`Registered flow handler for ${e}`);}};var ae=(s,e)=>m.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{A as a,S as b,M as c,O as d,P as e,E as f,ae as g};//# sourceMappingURL=chunk-WR6KABCQ.js.map
3
+ //# sourceMappingURL=chunk-WR6KABCQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","processWebhookMessages","whatsapp","handlers","body","errorMsg","errors","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","signature","verifySignature","decryptedBody","decryptFlowRequest","handler","result","encryptedResponse","encryptFlowResponse","verificationToken","expectedSignature","crypto","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","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","url","mode","token","challenge","type","generateXHub256Sig","appSecret","F"],"mappings":"yIAaA,SAASA,CAAAA,CAASC,EAAkD,CAChE,OAAO,OAAOA,CAAAA,EAAU,QAAYA,EAAAA,CAAAA,GAAU,IAClD,CAOA,SAASC,CAASD,CAAAA,CAAAA,CAAiC,CAC/C,OAAO,OAAOA,CAAU,EAAA,QAC5B,CAGA,IAAME,CAAwB,CAAA,CAAA,eAAA,CAAA,MAAA,CAAA,MAAuE,EAG/FC,CAAgB,CAAA,CAAA,eAAA,CAAA,MAAkD,CASjE,CAAA,SAASC,CAA0BC,CAAAA,CAAAA,CAKxC,CAEE,GAAI,EAAE,YAAgBA,GAAAA,CAAAA,EAAWJ,CAASI,CAAAA,CAAAA,CAAQ,UAAU,CAAK,EAAA,QAAA,GAAYA,CACzE,CAAA,CAAA,OAAO,MAGX,CAAA,GAAM,CAAE,MAAAC,CAAAA,CAAAA,CAAQ,OAAAC,CAAAA,CAAAA,CAAS,MAAAC,CAAAA,CAAAA,CAAQ,KAAAC,CAAK,CAAA,CAAIJ,CAGpCK,CAAAA,CAAAA,CAAkBH,CAAY,GAAA,KAAA,CAG9BI,EAAiBT,CAAsB,CAAA,QAAA,CAASI,CAAa,CAAA,CAG7DM,CAAiB,CAAA,OAAOJ,EAAW,GAAgBP,EAAAA,CAAAA,CAASO,CAAM,CAAA,EAAKA,CAAW,GAAA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AAA,CAAIiD,CAAMjD,CAAAA,CAAO,CACnCpB,CAAAA,CAAAA,CAAO,GAAI,CAAA,CAAA,4BAAA,EAA+BqE,CAAI,CAAA,CAAE,EACpD,CACJ,ECtHaC,IAAAA,EAAAA,CAAqB,CAACjE,CAAAA,CAAckE,CAC/B,GAAAC,CAAA,CAAA,UAAA,CAAW,QAAUD,CAAAA,CAAS,CAAE,CAAA,MAAA,CAAOlE,CAAM,CAAA,OAAO,CAAE,CAAA,MAAA,CAAO,KAAK","file":"chunk-WR6KABCQ.js","sourcesContent":["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 type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n const body = await request.json();\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 new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\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 new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, 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 new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) return false;\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.log(`Unknown message type: ${messageType}`);\n break;\n }\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction 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 crypto from 'crypto';\nimport { WhatsApp } from '../whatsapp';\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WebhookHandler based on Web Standard API\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 requests using Web Standard API\n */\n public async handleWebhook(request: Request): Promise<Response> {\n try {\n // Handle GET request (verification)\n if (request.method === 'GET') {\n const url = new URL(request.url);\n const mode = url.searchParams.get('hub.mode');\n const token = url.searchParams.get('hub.verify_token');\n const challenge = url.searchParams.get('hub.challenge');\n\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return new Response(challenge, { status: 200 });\n }\n return new Response(null, { status: 403 });\n }\n\n // Handle POST request (webhook)\n if (request.method === 'POST') {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n }\n\n return new Response(null, { status: 405 });\n } catch (error) {\n LOGGER.log(`Error handling webhook: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n }\n\n /**\n * Handle flow requests\n */\n public async handleFlow(request: Request): Promise<Response> {\n try {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n } catch (error) {\n LOGGER.log(`Error handling flow: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n }\n\n /**\n * Verify webhook signature\n */\n private verifySignature(body: string, signature: string | null): boolean {\n if (!signature) return false;\n\n const expectedSignature = crypto\n .createHmac('sha256', this.config.WEBHOOK_VERIFICATION_TOKEN)\n .update(body)\n .digest('hex');\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n }\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"]}
@@ -1,12 +1,12 @@
1
- export { F as FlowHandler, M as MessageStatus, W as WebhookContact, a as WebhookEvent, c as WebhookHandler, b as WebhookMessage, e as WebhookRequest, f as WebhookResponse, p as processFlowRequest, d as processWebhookMessages, v as verifyWebhook } from '../../WebhookHandler-DG3M9c7f.js';
2
- import '../../shared/types/config.js';
3
- import '../../enums-DvwSJq9w.js';
1
+ export { F as FlowHandler, d as MessageHandler, M as MessageStatus, W as WebhookContact, a as WebhookEvent, c as WebhookHandler, b as WebhookMessage, e as processFlowRequest, p as processWebhookMessages } from '../../WebhookHandler-Bxxi6SdT.js';
4
2
  import '../../FlowApi-CASVC-Al.js';
5
3
  import '../../base-BhCbbsxB.js';
6
- import '../../index-BPgH1nT-.js';
4
+ import '../../shared/types/config.js';
5
+ import '../../enums-DvwSJq9w.js';
6
+ import '../../index-DiCI1vEz.js';
7
7
  import '../../EncryptionApi-PHxeI2G_.js';
8
8
  import '../../MediaApi-B2vtjiCm.js';
9
- import '../../MessageApi-Bzor7Swo.js';
9
+ import '../../MessageApi-ptFlWg3O.js';
10
10
  import '../../PhoneNumberApi-DMb_G3uw.js';
11
11
  import '../../BusinessProfileApi-DE7Nnuy_.js';
12
12
  import '../../QrCodeApi-D3rVKuxV.js';
@@ -1,2 +1,2 @@
1
- export{g as WebhookHandler,h as generateXHub256Sig,f as processFlowRequest,e as processWebhookMessages,d as verifyWebhook}from'../../chunk-Y5L5GUKB.js';import'../../chunk-5O5GLWIE.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-LGLRGXCE.js';import'../../chunk-GIQLIMOD.js';import'../../chunk-BZ5QDXNR.js';import'../../chunk-VW3LGHTJ.js';import'../../chunk-4O3T25CT.js';import'../../chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
1
+ export{f as WebhookHandler,g as generateXHub256Sig,e as processFlowRequest,d as processWebhookMessages}from'../../chunk-WR6KABCQ.js';import'../../chunk-5O5GLWIE.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-LGLRGXCE.js';import'../../chunk-GIQLIMOD.js';import'../../chunk-BZ5QDXNR.js';import'../../chunk-VW3LGHTJ.js';import'../../chunk-4O3T25CT.js';import'../../chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,11 +1,11 @@
1
- export { W as WhatsApp, d as WhatsAppClass } from '../../index-BPgH1nT-.js';
1
+ export { W as WhatsApp, d as WhatsAppClass } from '../../index-DiCI1vEz.js';
2
2
  import '../../EncryptionApi-PHxeI2G_.js';
3
3
  import '../../base-BhCbbsxB.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-DvwSJq9w.js';
6
6
  import '../../FlowApi-CASVC-Al.js';
7
7
  import '../../MediaApi-B2vtjiCm.js';
8
- import '../../MessageApi-Bzor7Swo.js';
8
+ import '../../MessageApi-ptFlWg3O.js';
9
9
  import '../../PhoneNumberApi-DMb_G3uw.js';
10
10
  import '../../BusinessProfileApi-DE7Nnuy_.js';
11
11
  import '../../QrCodeApi-D3rVKuxV.js';
@@ -1,5 +1,5 @@
1
- import { M as MessagesApi } from '../../MessageApi-Bzor7Swo.js';
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, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, f as TextObject, V as VideoMediaObject } from '../../MessageApi-Bzor7Swo.js';
1
+ import { M as MessagesApi } from '../../MessageApi-ptFlWg3O.js';
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, c as MessagesResponse, R as ReactionParams, S as StatusParams, e as StickerMediaObject, T as TextMessageParams, f as TextObject, V as VideoMediaObject } from '../../MessageApi-ptFlWg3O.js';
3
3
  import '../../base-BhCbbsxB.js';
4
4
  import '../../shared/types/config.js';
5
5
  import '../../enums-DvwSJq9w.js';
@@ -2,7 +2,7 @@ import { E as EncryptionApi } from './EncryptionApi-PHxeI2G_.js';
2
2
  import { F as FlowApi } from './FlowApi-CASVC-Al.js';
3
3
  import { WhatsAppConfig, WabaConfigType } from './shared/types/config.js';
4
4
  import { M as MediaApi } from './MediaApi-B2vtjiCm.js';
5
- import { M as MessagesApi } from './MessageApi-Bzor7Swo.js';
5
+ import { M as MessagesApi } from './MessageApi-ptFlWg3O.js';
6
6
  import { P as PhoneNumberApi } from './PhoneNumberApi-DMb_G3uw.js';
7
7
  import { B as BusinessProfileApi } from './BusinessProfileApi-DE7Nnuy_.js';
8
8
  import { Q as QrCodeApi } from './QrCodeApi-D3rVKuxV.js';
package/dist/index.d.ts CHANGED
@@ -1,13 +1,13 @@
1
- export { W as WebhookContact, a as WebhookEvent, c as WebhookHandler, b as WebhookMessage } from './WebhookHandler-DG3M9c7f.js';
1
+ export { W as WebhookContact, a as WebhookEvent, c as WebhookHandler, b as WebhookMessage } from './WebhookHandler-Bxxi6SdT.js';
2
2
  import { g as FlowEndpointRequest, o as FlowDataExchangeRequest, c as FlowActionEnum, p as FlowErrorNotificationRequest, q as FlowHealthCheckRequest } from './FlowApi-CASVC-Al.js';
3
3
  export { a as Flow, F as FlowApi, f as FlowClass, h as FlowEndpointResponse, b as FlowType, n as FlowTypeEnum } from './FlowApi-CASVC-Al.js';
4
4
  export { B as BaseAPI, d as BaseClass, e as GeneralHeaderInterface, G as GeneralRequestBody, P as Paging, a as RequesterClass, f as RequesterResponseInterface, c as ResponseData, b as ResponsePagination, R as ResponseSuccess } from './base-BhCbbsxB.js';
5
5
  export { WabaConfigType, WhatsAppConfig } from './shared/types/config.js';
6
- export { H as HttpsClientClass, a as HttpsClientResponseClass, b as ResponseHeaderValue, R as ResponseHeaders, c as ResponseJSONBody, W as WhatsApp } from './index-BPgH1nT-.js';
6
+ export { H as HttpsClientClass, a as HttpsClientResponseClass, b as ResponseHeaderValue, R as ResponseHeaders, c as ResponseJSONBody, W as WhatsApp } from './index-DiCI1vEz.js';
7
7
  export { A as AudioMediaTypesEnum, B as BusinessVerticalEnum, b as ButtonPositionEnum, a as CategoryEnum, c as ComponentTypesEnum, d as ConversationTypesEnum, C as CurrencyCodesEnum, D as DataLocalizationRegionEnum, h as DocumentMediaTypesEnum, H as HttpMethodsEnum, g as ImageMediaTypesEnum, I as InteractiveTypesEnum, L as LanguagesEnum, M as MessageTypesEnum, P as ParametersTypesEnum, R as ReferralSourceTypesEnum, k as RequestCodeMethodsEnum, e as StatusEnum, f as StickerMediaTypesEnum, S as SubTypeEnum, j as SystemChangeTypesEnum, T as TemplateStatusEnum, V as VideoMediaTypesEnum, W as WabaConfigEnum, i as WebhookTypesEnum } from './enums-DvwSJq9w.js';
8
8
  export { E as EncryptionApi } from './EncryptionApi-PHxeI2G_.js';
9
9
  export { a as MediaClass, b as MediaResponse, c as MediasResponse, U as UploadMediaResponse } from './MediaApi-B2vtjiCm.js';
10
- 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-Bzor7Swo.js';
10
+ 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-ptFlWg3O.js';
11
11
  export { P as PhoneNumberApi, c as PhoneNumberClass, d as PhoneNumberResponse } from './PhoneNumberApi-DMb_G3uw.js';
12
12
  export { B as BusinessProfileApi, a as BusinessProfileClass, e as BusinessProfileResponse } from './BusinessProfileApi-DE7Nnuy_.js';
13
13
  export { Q as QrCodeApi, a as QrCodeClass, b as QrCodeResponse } from './QrCodeApi-D3rVKuxV.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import'./chunk-CNGQISKS.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';export{g as WebhookHandler,a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'./chunk-Y5L5GUKB.js';export{b as WhatsApp}from'./chunk-5O5GLWIE.js';export{a as isMetaError}from'./chunk-3MO3BTBC.js';export{a as TemplateApi}from'./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';export{a as buildFieldsQueryString}from'./chunk-7GL74SXM.js';export{c as FlowApi}from'./chunk-LGLRGXCE.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';export{a as objectToQueryString}from'./chunk-BZ5QDXNR.js';export{b as BaseAPI,a as Logger}from'./chunk-VW3LGHTJ.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,g as ButtonPositionEnum,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,h as SubTypeEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'./chunk-4O3T25CT.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
1
+ import'./chunk-CNGQISKS.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';export{f as WebhookHandler,a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'./chunk-WR6KABCQ.js';export{b as WhatsApp}from'./chunk-5O5GLWIE.js';export{a as isMetaError}from'./chunk-3MO3BTBC.js';export{a as TemplateApi}from'./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';export{a as buildFieldsQueryString}from'./chunk-7GL74SXM.js';export{c as FlowApi}from'./chunk-LGLRGXCE.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';export{a as objectToQueryString}from'./chunk-BZ5QDXNR.js';export{b as BaseAPI,a as Logger}from'./chunk-VW3LGHTJ.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,g as ButtonPositionEnum,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,h as SubTypeEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'./chunk-4O3T25CT.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meta-cloud-api",
3
- "version": "0.2.41",
3
+ "version": "0.2.43",
4
4
  "description": "TypeScript wrapper for Meta's Cloud API",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,3 +0,0 @@
1
- import {a as a$1,b}from'./chunk-5O5GLWIE.js';import {a}from'./chunk-VW3LGHTJ.js';import*as l from'crypto';import l__default from'crypto';function C(s){return typeof s=="object"&&s!==null}function y(s){return typeof s=="string"}var v=["data_exchange","INIT","BACK"],T=["data_exchange","INIT"];function M(s){if(!("flow_token"in s&&y(s.flow_token)&&"action"in s))return false;let{action:e,version:r,screen:t,data:o}=s,a=r==="3.0",c=v.includes(e),p=typeof t>"u"||y(t)&&t!=="SUCCESS",u=e==="data_exchange"||C(o);return a&&c&&p&&u}function q(s){if(!("flow_token"in s&&y(s.flow_token)&&"action"in s))return false;let{action:e,screen:r,data:t}=s,o=T.includes(e),a=y(r),c=C(t)&&"error_key"in t&&y(t.error)&&"error_message"in t&&y(t.error_message);return o&&a&&c}function F(s){return "action"in s&&s.action==="ping"}var B="WEBHOOK_UTILS",d=new a(B,process.env.DEBUG==="true");function R(s,e){let r=s.query["hub.mode"],t=s.query["hub.verify_token"],o=s.query["hub.challenge"];return r!==void 0&&t!==void 0&&o!==void 0?r==="subscribe"&&t===e?(d.log("Webhook verified successfully"),{statusCode:200,body:o}):(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(s,e,r){let t=s.body,o=[];if(t.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";return d.log(a),{statusCode:404,body:{error:a}}}for(let a of t.entry)try{let c=a.changes;for(let p of c)p.field==="messages"&&await I(a.id,p.value,e,r);}catch(c){let p=`Error processing webhook: ${c}`;d.log(p),o.push(p);}return {statusCode:200,body:o.length>0?{errors:o}:void 0}}async function H(s,e,r,t){try{if(!x(s,e.WEBHOOK_VERIFICATION_TOKEN||""))return d.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let o=JSON.parse(s.rawBody||"{}"),{decryptedBody:a}=N(o,e),c=t.get("*");if(!c)return d.log(`No handler registered for flow action: ${a.action}`),{statusCode:404,body:{error:"Handler not found"}};if(F(a))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(q(a))return d.log(`Flow error: ${JSON.stringify(a)}`),{statusCode:200,body:{}};if(M(a)){let p=await c(r,a);return {statusCode:200,body:O(p,Buffer.from(o.aes_key,"base64"),Buffer.from(o.initial_vector,"base64"))}}return d.log(`Unknown flow request type: ${JSON.stringify(a)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(o){return d.log(`Error handling flow request: ${o}`),{statusCode:500,body:{error:"Internal server error"}}}}async function I(s,e,r,t){let o=e.metadata,a=e.contacts,c=s,p=o?.display_phone_number||"",u=o?.phone_number_id||"",h=a?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){let g=e.statuses;for(let n of g){let f={wabaId:c,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:u,displayPhoneNumber:p,profileName:h,statuses:e.statuses[0],originalData:n};await w(t.messageHandlers.get("statuses"),r,f,"statuses");}return}if(e.messages&&e.messages.length>0){let g=e.messages;for(let n of g){let f=n.type,i={wabaId:c,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:u,displayPhoneNumber:p,profileName:h,originalData:n};switch(f){case "text":i.text=n.text;break;case "image":i.image=n.image;break;case "video":i.video=n.video;break;case "audio":i.audio=n.audio;break;case "document":i.document=n.document;break;case "sticker":i.sticker=n.sticker;break;case "location":i.location=n.location;break;case "contacts":i.contacts=n.contacts;break;case "interactive":i.interactive=n.interactive;break;case "button":i.button=n.button;break;case "order":i.order=n.order;break;case "system":i.system=n.system;break;case "reaction":i.reaction=n.reaction;break;default:d.log(`Unknown message type: ${f}`);break}await w(t.preProcessHandler,r,i,"pre-process"),await w(t.messageHandlers.get(f),r,i,f),await w(t.postProcessHandler,r,i,"post-process");}}}async function w(s,e,r,t){if(s)try{await s(e,r);}catch(o){d.log(`Error in ${t} handler: ${o}`);}}function x(s,e){let r=s.headers["x-hub-signature-256"];if(!r||!s.rawBody)return false;let o=`sha256=${l__default.createHmac("sha256",e).update(s.rawBody,"utf8").digest("hex")}`;return l__default.timingSafeEqual(Buffer.from(r),Buffer.from(o))}function N(s,e){let{encrypted_aes_key:r,encrypted_flow_data:t,initial_vector:o}=s;if(!r||!t||!o)throw new Error("Missing required encryption properties");let a=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
- `),c=e.FLOW_API_PASSPHRASE,p=l__default.createPrivateKey({key:a,passphrase:c}),u;try{u=l__default.privateDecrypt({key:p,padding:l__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let h=Buffer.from(t,"base64"),g=Buffer.from(o,"base64"),f=h.subarray(0,-16),i=h.subarray(-16),k=l__default.createDecipheriv("aes-128-gcm",u,g);k.setAuthTag(i);let S=Buffer.concat([k.update(f),k.final()]).toString("utf-8");return {decryptedBody:JSON.parse(S),aesKeyBuffer:u,initialVectorBuffer:g}}function O(s,e,r){let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=l__default.createCipheriv("aes-128-gcm",e,Buffer.from(t));return Buffer.concat([o.update(JSON.stringify(s||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64")}catch(o){throw d.log("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",m=new a(V,process.env.DEBUG==="true"),W=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),m.log("WebhookHandler instantiated!");}handleVerification=e=>R(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=>H(e,this.config,this.client,this.flowHandlers);onMessage(e,r){this.messageHandlers.set(e,r),m.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,m.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,m.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),m.log(`Registered flow handler for ${e}`);}};var ie=(s,e)=>l.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{M as a,q as b,F as c,R as d,E as e,H as f,W as g,ie as h};//# sourceMappingURL=chunk-Y5L5GUKB.js.map
3
- //# sourceMappingURL=chunk-Y5L5GUKB.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["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","P"],"mappings":"yIAaA,SAASA,CAAAA,CAASC,EAAkD,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,EAASD,CAAiC,CAAA,CAC/C,OAAO,OAAOA,CAAU,EAAA,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAuE,eAAA,CAAA,MAAA,CAAA,MAAA,CAAA,CAG/FC,CAAgB,CAAA,CAAA,eAAA,CAAA,MAAkD,EASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAgBA,GAAAA,CAAAA,EAAWJ,CAASI,CAAAA,CAAAA,CAAQ,UAAU,CAAA,EAAK,WAAYA,CACzE,CAAA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\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport interface WebhookRequest {\n method: string;\n query: Record<string, any>;\n body: any;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: string;\n}\n\nexport interface WebhookResponse {\n statusCode: number;\n body?: any;\n headers?: Record<string, string>;\n}\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Pure function to handle webhook verification\n */\nexport function verifyWebhook(request: Pick<WebhookRequest, 'query'>, verificationToken: string): WebhookResponse {\n const mode = request.query['hub.mode'];\n const token = request.query['hub.verify_token'];\n const challenge = request.query['hub.challenge'];\n\n // Check if this is actually a webhook verification request\n const isWebhookVerificationRequest = mode !== undefined && token !== undefined && challenge !== undefined;\n\n if (!isWebhookVerificationRequest) {\n LOGGER.log('Not a webhook verification request - missing required parameters');\n return {\n statusCode: 400,\n body: { error: 'Invalid webhook verification request' },\n };\n }\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === verificationToken;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n return {\n statusCode: 200,\n body: challenge,\n };\n } else {\n LOGGER.log('Webhook verification failed');\n return {\n statusCode: 403,\n };\n }\n}\n\n/**\n * Pure function to process webhook messages\n */\nexport async function processWebhookMessages(\n request: WebhookRequest,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<WebhookResponse> {\n const body = request.body;\n const errors: string[] = [];\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return {\n statusCode: 404,\n body: { error: errorMsg },\n };\n }\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return {\n statusCode: 200,\n body: errors.length > 0 ? { errors } : undefined,\n };\n}\n\n/**\n * Pure function to handle flow requests\n */\nexport async function processFlowRequest(\n request: WebhookRequest,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<WebhookResponse> {\n try {\n // Validate request signature\n if (!isRequestSignatureValid(request, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return {\n statusCode: 401,\n body: { error: 'Unauthorized' },\n };\n }\n\n const body = JSON.parse(request.rawBody || '{}');\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(body, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return {\n statusCode: 404,\n body: { error: 'Handler not found' },\n };\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return {\n statusCode: 200,\n body: {\n version: '3.0',\n data: { status: 'active' },\n },\n };\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 200,\n body: {},\n };\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n return {\n statusCode: 200,\n body: encryptedResponse,\n };\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return {\n statusCode: 400,\n body: { error: 'Unknown request type' },\n };\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return {\n statusCode: 500,\n body: { error: 'Internal server error' },\n };\n }\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.log(`Unknown message type: ${messageType}`);\n break;\n }\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction isRequestSignatureValid(request: WebhookRequest, verificationToken: string): boolean {\n const signature = request.headers['x-hub-signature-256'] as string;\n if (!signature || !request.rawBody) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', verificationToken)\n .update(request.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\n\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\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"]}