meta-cloud-api 0.2.24 → 0.2.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ import {a as a$1,b as b$2}from'./chunk-XQDM2WBV.js';import {a}from'./chunk-VW3LGHTJ.js';import {b as b$1,d as d$1,c}from'./chunk-M2GC5VFJ.js';import*as h from'crypto';import h__default from'crypto';import {createParamDecorator,Injectable}from'@nestjs/common';import {map}from'rxjs/operators';var X=(s=>(s.DELIVERED="delivered",s.READ="read",s.SENT="sent",s))(X||{}),z=(a=>(a.MESSAGES="messages",a.STATUSES="statuses",a.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",a.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",a.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",a.UNKNOWN="unknown",a))(z||{});function j(e){return typeof e=="object"&&e!==null}function g(e){return typeof e=="string"}var Q=["data_exchange","INIT","BACK"],Y=["data_exchange","INIT"];function D(e){if(!("flow_token"in e&&g(e.flow_token)&&"action"in e))return false;let{action:t,version:o,screen:s,data:r}=e,n=o==="3.0",a=Q.includes(t),i=typeof s>"u"||g(s)&&s!=="SUCCESS",u=t==="data_exchange"||j(r);return n&&a&&i&&u}function J(e){if(!("flow_token"in e&&g(e.flow_token)&&"action"in e))return false;let{action:t,screen:o,data:s}=e,r=Y.includes(t),n=g(o),a=j(s)&&"error_key"in s&&g(s.error)&&"error_message"in s&&g(s.error_message);return r&&n&&a}function V(e){return "action"in e&&e.action==="ping"}var Z="WEBHOOK_UTILS",d=new a(Z,process.env.DEBUG==="true");function S(e,t){let o=e.query["hub.mode"],s=e.query["hub.verify_token"],r=e.query["hub.challenge"];return o==="subscribe"&&s===t?(d.log("Webhook verified successfully"),{statusCode:200,body:r}):(d.log("Webhook verification failed"),{statusCode:403})}async function A(e,t,o){let s=e.body,r=[];if(s.object!=="whatsapp_business_account"){let n="Received webhook for non-WhatsApp event";return d.log(n),{statusCode:404,body:{error:n}}}for(let n of s.entry)try{let a=n.changes;for(let i of a)i.field==="messages"?(await ee(i.value,t,o),i.value.statuses&&o.statusHandlers&&await te(i.value.statuses,i.value.metadata,t,o.statusHandlers)):await se(i.field,i.value,o.eventHandlers);}catch(a){let i=`Error processing webhook: ${a}`;d.log(i),r.push(i);}return {statusCode:200,body:r.length>0?{errors:r}:void 0}}async function P(e,t,o,s){try{if(!re(e,t.WEBHOOK_VERIFICATION_TOKEN||""))return d.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let r=JSON.parse(e.rawBody||"{}"),{decryptedBody:n}=ne(r,t),a=s.get("*");if(!a)return d.log(`No handler registered for flow action: ${n.action}`),{statusCode:404,body:{error:"Handler not found"}};if(V(n))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(J(n))return d.log(`Flow error: ${JSON.stringify(n)}`),{statusCode:200,body:{}};if(D(n)){let i=await a(o,n);return {statusCode:200,body:ae(i,Buffer.from(r.aes_key,"base64"),Buffer.from(r.initial_vector,"base64"))}}return d.log(`Unknown flow request type: ${JSON.stringify(n)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(r){return d.log(`Error handling flow request: ${r}`),{statusCode:500,body:{error:"Internal server error"}}}}async function ee(e,t,o){let s=e.metadata,r=s.display_phone_number,n=s.phone_number_id,a=e.contacts[0]?.profile?.name||"",i=e.messages;if(i&&i.length>0)for(let u of i){let p=u.type,c={id:u.id,from:u.from,timestamp:u.timestamp,type:u.type,phoneNumberId:n,displayPhoneNumber:r,profileName:a,originalData:u};Object.assign(c,oe(u)),u.context&&(c.context=u.context),u.errors&&(c.errors=u.errors),await x(o.preProcessHandler,t,c,"pre-process"),await x(o.messageHandlers.get(p),t,c,p),await x(o.postProcessHandler,t,c,"post-process");}}async function te(e,t,o,s){if(e&&e.length>0)for(let r of e){let n={phoneNumberId:t.phone_number_id,displayPhoneNumber:t.display_phone_number,id:r.id,status:r.status,timestamp:r.timestamp,recipient_id:r.recipient_id,conversation:r.conversation,pricing:r.pricing,biz_opaque_callback_data:r.biz_opaque_callback_data,errors:r.errors,originalData:r},a=s.get(r.status);if(a)try{await a(o,n);}catch(i){d.log(`Error in status handler for ${r.status}: ${i}`);}}}function oe(e){let t={};switch(e.type){case "text":t.text=e.text;break;case "image":t.image=e.image;break;case "video":t.video=e.video;break;case "audio":t.audio=e.audio;break;case "document":t.document=e.document;break;case "sticker":t.sticker=e.sticker;break;case "location":t.location=e.location;break;case "contacts":t.contacts=e.contacts;break;case "interactive":t.interactive=e.interactive;break;case "button":t.button=e.button;break;case "order":t.order=e.order;break;case "system":t.system=e.system;break}return t}async function x(e,t,o,s){if(e)try{await e(t,o);}catch(r){d.log(`Error in ${s} handler: ${r}`);}}async function se(e,t,o){let s={field:e,value:t,timestamp:Date.now()},r=o.get(e);if(r)try{await r(s);}catch(n){d.log(`Error in event handler for ${e}: ${n}`);}}function re(e,t){let o=e.headers["x-hub-signature-256"];if(!o||!e.rawBody)return false;let r=`sha256=${h__default.createHmac("sha256",t).update(e.rawBody,"utf8").digest("hex")}`;return h__default.timingSafeEqual(Buffer.from(o),Buffer.from(r))}function ne(e,t){let{encrypted_aes_key:o,encrypted_flow_data:s,initial_vector:r}=e;if(!o||!s||!r)throw new Error("Missing required encryption properties");let n=t.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),a=t.FLOW_API_PASSPHRASE,i=h__default.createPrivateKey({key:n,passphrase:a}),u;try{u=h__default.privateDecrypt({key:i,padding:h__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(o,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let p=Buffer.from(s,"base64"),c=Buffer.from(r,"base64"),L=p.subarray(0,-16),$=p.subarray(-16),H=h__default.createDecipheriv("aes-128-gcm",u,c);H.setAuthTag($);let K=Buffer.concat([H.update(L),H.final()]).toString("utf-8");return {decryptedBody:JSON.parse(K),aesKeyBuffer:u,initialVectorBuffer:c}}function ae(e,t,o){let s=[];for(let r of Array.from(o.entries()))s.push(~r[1]);try{let r=h__default.createCipheriv("aes-128-gcm",t,Buffer.from(s));return Buffer.concat([r.update(JSON.stringify(e||{}),"utf-8"),r.final(),r.getAuthTag()]).toString("base64")}catch(r){throw d.log("Response encryption error:",r),new Error("Failed to encrypt response. Internal server error.")}}var ie="WEBHOOK",y=new a(ie,process.env.DEBUG==="true"),N=class{config;client;messageHandlers=new Map;statusHandlers=new Map;eventHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(t){this.config=a$1(t),this.client=new b$2(t),y.log("WebhookHandler instantiated!");}handleVerification=t=>S(t,this.config.WEBHOOK_VERIFICATION_TOKEN||"");handleWebhook=async t=>A(t,this.client,{messageHandlers:this.messageHandlers,eventHandlers:this.eventHandlers,statusHandlers:this.statusHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler});handleFlow=async t=>P(t,this.config,this.client,this.flowHandlers);onMessage(t,o){this.messageHandlers.set(t,o),y.log(`Registered message handler for ${t}`);}onStatus(t,o){this.statusHandlers.set(t,o),y.log("Registered status handler");}onEvent(t,o){this.eventHandlers.set(t,o),y.log(`Registered event handler for ${t}`);}onMessagePreProcess(t){this.preProcessHandler=t,y.log("Registered pre-process handler");}onMessagePostProcess(t){this.postProcessHandler=t,y.log("Registered post-process handler");}onFlow(t,o){this.flowHandlers.set(t,o),y.log(`Registered flow handler for ${t}`);}getClient(){return this.client}getConfig(){return this.config}};var Ce=(e,t)=>h.createHmac("sha256",t).update(e,"utf-8").digest("hex");function v(e){return {method:e.method,query:e.query,body:e.body,headers:e.headers,rawBody:e.rawBody||JSON.stringify(e.body)}}function m(e,t){t.status(e.statusCode),e.headers&&Object.entries(e.headers).forEach(([o,s])=>{t.set(o,s);}),e.body!==void 0?typeof e.body=="string"?t.send(e.body):t.json(e.body):t.end();}function ue(){return {handleVerification:e=>(t,o)=>{let s=v(t),r=e(s);m(r,o);},handleWebhook:e=>async(t,o)=>{try{let s=v(t),r=await e(s);m(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleFlow:e=>async(t,o)=>{try{let s=v(t),r=await e(s);m(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleRequest:e=>async(t,o)=>{try{let s=v(t);if(t.method==="GET"){let r=e.verification(s);m(r,o);}else if(t.method==="POST"){let r=await e.webhook(s);m(r,o);}else o.status(405).json({error:"Method not allowed"});}catch{o.status(500).json({error:"Internal server error"});}}}}function _(e){return {method:e.method,query:e.query,body:e.body,headers:e.headers,rawBody:e.rawBody||JSON.stringify(e.body)}}async function R(e,t){return t.status(e.statusCode),e.headers&&Object.entries(e.headers).forEach(([o,s])=>{t.header(o,s);}),e.body!==void 0?t.send(e.body):t.send()}function ce(){return {handleVerification:e=>async(t,o)=>{let s=_(t),r=e(s);return R(r,o)},handleWebhook:e=>async(t,o)=>{try{let s=_(t),r=await e(s);return R(r,o)}catch{return o.status(500).send({error:"Internal server error"})}},handleFlow:e=>async(t,o)=>{try{let s=_(t),r=await e(s);return R(r,o)}catch{return o.status(500).send({error:"Internal server error"})}},handleRequest:e=>async(t,o)=>{try{let s=_(t);if(t.method==="GET"){let r=e.verification(s);return R(r,o)}else if(t.method==="POST"){let r=await e.webhook(s);return R(r,o)}else return o.status(405).send({error:"Method not allowed"})}catch{return o.status(500).send({error:"Internal server error"})}}}}function f(e){return {method:e.method,query:e.query,body:e.body,headers:e.headers,rawBody:e.rawBody||JSON.stringify(e.body)}}function l(e,t){t.status(e.statusCode),e.headers&&Object.entries(e.headers).forEach(([o,s])=>{t.set(o,s);}),e.body!==void 0?typeof e.body=="string"?t.send(e.body):t.json(e.body):t.end();}var he=createParamDecorator((e,t)=>{let o=t.switchToHttp().getRequest();return f(o)}),U,T;U=[Injectable()];var b=class{intercept(t,o){let s=t.switchToHttp().getResponse();return o.handle().pipe(map(r=>{l(r,s);}))}};T=b$1(null),b=d$1(T,0,"WebhookResponseInterceptor",U,b),c(T,1,b);function ye(){return {handleVerification:e=>(t,o)=>{let s=f(t),r=e(s);l(r,o);},handleWebhook:e=>async(t,o)=>{try{let s=f(t),r=await e(s);l(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleFlow:e=>async(t,o)=>{try{let s=f(t),r=await e(s);l(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleRequest:e=>async(t,o)=>{try{let s=f(t);if(t.method==="GET"){let r=e.verification(s);l(r,o);}else if(t.method==="POST"){let r=await e.webhook(s);l(r,o);}else o.status(405).json({error:"Method not allowed"});}catch{o.status(500).json({error:"Internal server error"});}},createVerificationHandler:e=>(t,o,s)=>{let r=s.value;s.value=function(...n){let a=n.find(i=>i&&i.switchToHttp);if(a){let i=a.switchToHttp().getRequest(),u=a.switchToHttp().getResponse(),p=f(i),c=e(p);l(c,u);return}return r.apply(this,n)};},createWebhookHandler:e=>(t,o,s)=>{let r=s.value;s.value=async function(...n){let a=n.find(i=>i&&i.switchToHttp);if(a)try{let i=a.switchToHttp().getRequest(),u=a.switchToHttp().getResponse(),p=f(i),c=await e(p);l(c,u);return}catch{a.switchToHttp().getResponse().status(500).json({error:"Internal server error"});return}return r.apply(this,n)};}}}function E(e){return {method:e.method||"GET",query:e.query,body:e.body,headers:e.headers,rawBody:e.rawBody||JSON.stringify(e.body)}}function k(e,t){t.status(e.statusCode),e.headers&&Object.entries(e.headers).forEach(([o,s])=>{t.setHeader(o,s);}),e.body!==void 0?typeof e.body=="string"?t.send(e.body):t.json(e.body):t.end();}function fe(){return {handleVerification:e=>(t,o)=>{let s=E(t),r=e(s);k(r,o);},handleWebhook:e=>async(t,o)=>{try{let s=E(t),r=await e(s);k(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleFlow:e=>async(t,o)=>{try{let s=E(t),r=await e(s);k(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleRequest:e=>async(t,o)=>{try{let s=E(t);if(t.method==="GET"){let r=e.verification(s);k(r,o);}else if(t.method==="POST"){let r=await e.webhook(s);k(r,o);}else o.status(405).json({error:"Method not allowed"});}catch{o.status(500).json({error:"Internal server error"});}}}}function w(e,t){return {method:e.method||"GET",query:t?Object.fromEntries(t.entries()):{},body:void 0,headers:Object.fromEntries(e.headers.entries()),rawBody:void 0}}function W(e){let t=new Headers;return e.headers&&Object.entries(e.headers).forEach(([o,s])=>{t.set(o,s);}),e.body!==void 0?typeof e.body=="string"?new Response(e.body,{status:e.statusCode,headers:t}):(t.set("Content-Type","application/json"),new Response(JSON.stringify(e.body),{status:e.statusCode,headers:t})):new Response(null,{status:e.statusCode,headers:t})}function ge(){return {handleVerification:e=>t=>{let o=t.nextUrl.searchParams,s=w(t,o),r=e(s);return W(r)},handleWebhook:e=>async t=>{try{let o=w(t);if(t.method==="POST")if((t.headers.get("content-type")||"").includes("application/json"))o.body=await t.json(),o.rawBody=JSON.stringify(o.body);else {let n=await t.text();o.rawBody=n,o.body=n;}let s=await e(o);return W(s)}catch{return new Response(JSON.stringify({error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}},handleFlow:e=>async t=>{try{let o=w(t);if(t.method==="POST")if((t.headers.get("content-type")||"").includes("application/json"))o.body=await t.json(),o.rawBody=JSON.stringify(o.body);else {let n=await t.text();o.rawBody=n,o.body=n;}let s=await e(o);return W(s)}catch{return new Response(JSON.stringify({error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}},createHandlers:e=>({GET:t=>{let o=t.nextUrl.searchParams,s=w(t,o),r=e.verification(s);return W(r)},POST:async t=>{try{let o=w(t);if((t.headers.get("content-type")||"").includes("application/json"))o.body=await t.json(),o.rawBody=JSON.stringify(o.body);else {let n=await t.text();o.rawBody=n,o.body=n;}let r=await e.webhook(o);return W(r)}catch{return new Response(JSON.stringify({error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}}})}}export{X as a,z as b,S as c,A as d,P as e,N as f,Ce as g,ue as h,ce as i,he as j,b as k,ye as l,fe as m,ge as n};//# sourceMappingURL=chunk-ZJV5NIQ7.js.map
3
+ //# sourceMappingURL=chunk-ZJV5NIQ7.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","../src/core/webhook/adapters/expressAdapter.ts","../src/core/webhook/adapters/fastifyAdapter.ts","../src/core/webhook/adapters/nestjsAdapter.ts","../src/core/webhook/adapters/nextjsApiRouteAdapter.ts","../src/core/webhook/adapters/nextjsRouteHandlerAdapter.ts"],"names":["MessageStatus","EventField","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","processStatuses","processEvent","error","processFlowRequest","config","flowHandlers","isRequestSignatureValid","decryptedBody","decryptFlowRequest","handler","result","encryptFlowResponse","metadata","displayPhoneNumber","phoneNumberId","profileName","messages","message","messageType","processedMessage","getMessageTypeData","executeHandler","statuses","statusHandlers","status","processedStatus","typeData","handlerType","field","eventHandlers","event","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","G","fromExpressRequest","req","toExpressResponse","webhookResponse","res","key","createExpressAdapter","webhookRequest","fromFastifyRequest","toFastifyReply","reply","createFastifyAdapter","fromNestJSRequest","toNestJSResponse","WebhookReq","createParamDecorator","ctx","_WebhookResponseInterceptor_decorators","_init","Injectable","WebhookResponseInterceptor","context","next","map","__decoratorStart","__decorateElement","__runInitializers","createNestJSAdapter","target","propertyName","descriptor","method","args","arg","fromNextJSRequest","toNextJSResponse","createNextJSAdapter","fromRouteHandlerRequest","searchParams","toRouteHandlerResponse","headers","createNextJSRouteHandlerAdapter","text"],"mappings":"oSAqpBYA,IAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACRA,CAAA,CAAA,SAAA,CAAY,WACZA,CAAAA,CAAAA,CAAA,IAAO,CAAA,MAAA,CACPA,CAAA,CAAA,IAAA,CAAO,MAHCA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EASAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACRA,EAAA,QAAW,CAAA,UAAA,CACXA,CAAA,CAAA,QAAA,CAAW,UACXA,CAAAA,CAAAA,CAAA,8BAAiC,CAAA,gCAAA,CACjCA,CAAA,CAAA,2BAAA,CAA8B,6BAC9BA,CAAAA,CAAAA,CAAA,wBAA2B,CAAA,0BAAA,CAC3BA,EAAA,OAAU,CAAA,SAAA,CANFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,ECjpBZ,SAASC,CAAAA,CAASC,CAAkD,CAAA,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,CAASD,CAAAA,CAAAA,CAAiC,CAC/C,OAAO,OAAOA,CAAAA,EAAU,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAuE,eAAA,CAAA,MAAA,CAAA,MAAA,CAAA,CAG/FC,CAAgB,CAAA,CAAA,eAAA,CAAA,MAAkD,EASjE,SAASC,CAAAA,CAA0BC,CAKxC,CAAA,CAEE,GAAI,EAAE,YAAgBA,GAAAA,CAAAA,EAAWJ,CAASI,CAAAA,CAAAA,CAAQ,UAAU,CAAA,EAAK,QAAYA,GAAAA,CAAAA,CAAAA,CACzE,OAAO,MAAA,CAGX,GAAM,CAAE,MAAAC,CAAAA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,CAAS,CAAE,cAAA,CAAgB,kBAAmB,CAClD,CAAC,CACL,CACJ,CACJ,EAER,CACJ","file":"chunk-ZJV5NIQ7.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 /**\n * The original message data as received from the webhook\n */\n originalData: any;\n}\n\n/**\n * Represents a message status update received through the webhook\n * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#statuses-object\n */\nexport interface WebhookMessageStatus {\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 status 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 * Event handler function type\n */\nexport type EventHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * Status handler function type\n */\nexport type StatusHandler = (statuses: WebhookMessageStatus[]) => void | Promise<void>;\n\n/**\n * Message status enum\n */\nexport enum MessageStatus {\n DELIVERED = 'delivered',\n READ = 'read',\n SENT = 'sent',\n}\n\n/**\n * Event field enum for webhook events\n */\nexport enum EventField {\n MESSAGES = 'messages',\n STATUSES = 'statuses',\n MESSAGE_TEMPLATE_STATUS_UPDATE = 'message_template_status_update',\n PHONE_NUMBER_QUALITY_UPDATE = 'phone_number_quality_update',\n PHONE_NUMBER_NAME_UPDATE = 'phone_number_name_update',\n UNKNOWN = 'unknown',\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 { EventField, MessageStatus, WebhookEvent, WebhookMessage, WebhookMessageStatus } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n// Framework-agnostic request/response types\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 EventHandler = (event: WebhookEvent) => void | Promise<void>;\nexport type StatusHandler = (whatsapp: WhatsApp, statuses: WebhookMessageStatus) => 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: WebhookRequest, 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 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 eventHandlers: Map<string, EventHandler>;\n statusHandlers?: Map<MessageStatus, StatusHandler>;\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 === EventField.MESSAGES) {\n await processMessages(change.value, whatsapp, handlers);\n\n // Process statuses if they exist\n if (change.value.statuses && handlers.statusHandlers) {\n await processStatuses(\n change.value.statuses,\n change.value.metadata,\n whatsapp,\n handlers.statusHandlers,\n );\n }\n } else {\n await processEvent(change.field, change.value, handlers.eventHandlers);\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 (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n // Add type-specific data\n Object.assign(processedMessage, getMessageTypeData(message));\n\n // Add context and errors if available\n if (message.context) processedMessage.context = message.context;\n if (message.errors) processedMessage.errors = message.errors;\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 processStatuses(\n statuses: any[],\n metadata: any,\n whatsapp: WhatsApp,\n statusHandlers: Map<MessageStatus, StatusHandler>,\n): Promise<void> {\n if (statuses && statuses.length > 0) {\n for (const status of statuses) {\n const processedStatus: WebhookMessageStatus = {\n phoneNumberId: metadata.phone_number_id,\n displayPhoneNumber: metadata.display_phone_number,\n id: status.id,\n status: status.status,\n timestamp: status.timestamp,\n recipient_id: status.recipient_id,\n conversation: status.conversation,\n pricing: status.pricing,\n biz_opaque_callback_data: status.biz_opaque_callback_data,\n errors: status.errors,\n originalData: status,\n };\n\n const handler = statusHandlers.get(status.status as MessageStatus);\n if (handler) {\n try {\n await handler(whatsapp, processedStatus);\n } catch (error) {\n LOGGER.log(`Error in status handler for ${status.status}: ${error}`);\n }\n }\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 }\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\nasync function processEvent(field: string, value: any, eventHandlers: Map<string, EventHandler>): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n timestamp: Date.now(),\n };\n\n const handler = eventHandlers.get(field);\n if (handler) {\n try {\n await handler(event);\n } catch (error) {\n LOGGER.log(`Error in event handler for ${field}: ${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 EventHandler,\n FlowHandler,\n MessageHandler,\n processFlowRequest,\n processWebhookMessages,\n StatusHandler,\n verifyWebhook,\n WebhookRequest,\n WebhookResponse,\n} from './utils/webhookUtils';\nimport { MessageStatus } from './types';\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 statusHandlers: Map<MessageStatus, StatusHandler> = new Map();\n private eventHandlers: Map<string, EventHandler> = 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: WebhookRequest): 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 eventHandlers: this.eventHandlers,\n statusHandlers: this.statusHandlers,\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 status handler for a specific status type\n */\n public onStatus(type: MessageStatus, handler: StatusHandler): void {\n this.statusHandlers.set(type, handler);\n LOGGER.log(`Registered status handler`);\n }\n\n /**\n * Register an event handler for a specific field\n */\n public onEvent(field: string, handler: EventHandler): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered event handler for ${field}`);\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 /**\n * Get the WhatsApp client instance\n */\n public getClient(): WhatsApp {\n return this.client;\n }\n\n /**\n * Get the configuration\n */\n public getConfig(): WabaConfigType {\n return this.config;\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","import { Request, Response } from 'express';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Express request to framework-agnostic request\n */\nfunction fromExpressRequest(req: Request): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Express response\n */\nfunction toExpressResponse(webhookResponse: WebhookResponse, res: Response): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Create Express.js adapter for webhook handlers\n */\nexport function createExpressAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: Request, res: Response) => {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { FastifyReply, FastifyRequest } from 'fastify';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Fastify request to framework-agnostic request\n */\nfunction fromFastifyRequest(req: FastifyRequest): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Fastify reply\n */\nasync function toFastifyReply(webhookResponse: WebhookResponse, reply: FastifyReply): Promise<void> {\n reply.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n reply.header(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n return reply.send(webhookResponse.body);\n } else {\n return reply.send();\n }\n}\n\n/**\n * Create Fastify adapter for webhook handlers\n */\nexport function createFastifyAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = await handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = await handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } else {\n return reply.status(405).send({ error: 'Method not allowed' });\n }\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { CallHandler, createParamDecorator, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert NestJS request to framework-agnostic request\n */\nfunction fromNestJSRequest(req: Request): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to NestJS response\n */\nfunction toNestJSResponse(webhookResponse: WebhookResponse, res: Response): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Custom parameter decorator to inject WebhookRequest\n */\nexport const WebhookReq = createParamDecorator((data: unknown, ctx: ExecutionContext): WebhookRequest => {\n const request = ctx.switchToHttp().getRequest<Request>();\n return fromNestJSRequest(request);\n});\n\n/**\n * Interceptor to handle WebhookResponse conversion\n */\n@Injectable()\nexport class WebhookResponseInterceptor implements NestInterceptor<WebhookResponse, void> {\n intercept(context: ExecutionContext, next: CallHandler<WebhookResponse>): Observable<void> {\n const response = context.switchToHttp().getResponse<Response>();\n\n return next.handle().pipe(\n map((webhookResponse: WebhookResponse) => {\n toNestJSResponse(webhookResponse, response);\n return;\n }),\n );\n }\n}\n\n/**\n * Create NestJS adapter for webhook handlers\n */\nexport function createNestJSAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: Request, res: Response) => {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Create controller method decorator for webhook verification\n */\n createVerificationHandler: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (target: any, propertyName: string, descriptor: PropertyDescriptor) => {\n const method = descriptor.value;\n descriptor.value = function (...args: any[]) {\n const context = args.find((arg) => arg && arg.switchToHttp) as ExecutionContext;\n if (context) {\n const request = context.switchToHttp().getRequest<Request>();\n const response = context.switchToHttp().getResponse<Response>();\n const webhookRequest = fromNestJSRequest(request);\n const webhookResponse = handler(webhookRequest);\n toNestJSResponse(webhookResponse, response);\n return;\n }\n return method.apply(this, args);\n };\n };\n },\n\n /**\n * Create controller method decorator for webhook POST handling\n */\n createWebhookHandler: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return (target: any, propertyName: string, descriptor: PropertyDescriptor) => {\n const method = descriptor.value;\n descriptor.value = async function (...args: any[]) {\n const context = args.find((arg) => arg && arg.switchToHttp) as ExecutionContext;\n if (context) {\n try {\n const request = context.switchToHttp().getRequest<Request>();\n const response = context.switchToHttp().getResponse<Response>();\n const webhookRequest = fromNestJSRequest(request);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, response);\n return;\n } catch (error) {\n const response = context.switchToHttp().getResponse<Response>();\n response.status(500).json({ error: 'Internal server error' });\n return;\n }\n }\n return method.apply(this, args);\n };\n };\n },\n };\n}\n","import { NextApiRequest, NextApiResponse } from 'next';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Next.js request to framework-agnostic request\n */\nfunction fromNextJSRequest(req: NextApiRequest): WebhookRequest {\n return {\n method: req.method || 'GET',\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Next.js response\n */\nfunction toNextJSResponse(webhookResponse: WebhookResponse, res: NextApiResponse): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Create Next.js Pages Router adapter for webhook handlers\n * For App Router, use createNextJSRouteHandlerAdapter instead\n */\nexport function createNextJSAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: NextApiRequest, res: NextApiResponse) => {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { NextRequest } from 'next/server';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Route Handler request to framework-agnostic request\n */\nfunction fromRouteHandlerRequest(req: Request, searchParams?: URLSearchParams): WebhookRequest {\n return {\n method: req.method || 'GET',\n query: searchParams ? Object.fromEntries(searchParams.entries()) : {},\n body: undefined, // Will be populated when body is read\n headers: Object.fromEntries(req.headers.entries()),\n rawBody: undefined, // Will be populated when body is read\n };\n}\n\n/**\n * Apply framework-agnostic response to Route Handler response\n */\nfunction toRouteHandlerResponse(webhookResponse: WebhookResponse): Response {\n const headers = new Headers();\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n return new Response(webhookResponse.body, {\n status: webhookResponse.statusCode,\n headers,\n });\n } else {\n headers.set('Content-Type', 'application/json');\n return new Response(JSON.stringify(webhookResponse.body), {\n status: webhookResponse.statusCode,\n headers,\n });\n }\n } else {\n return new Response(null, {\n status: webhookResponse.statusCode,\n headers,\n });\n }\n}\n\n/**\n * Create Next.js Route Handler adapter for webhook handlers\n */\nexport function createNextJSRouteHandlerAdapter() {\n return {\n /**\n * Handle webhook verification requests (GET)\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: NextRequest) => {\n const searchParams = req.nextUrl.searchParams;\n const webhookRequest = fromRouteHandlerRequest(req, searchParams);\n const webhookResponse = handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n if (req.method === 'POST') {\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n }\n\n const webhookResponse = await handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n if (req.method === 'POST') {\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n }\n\n const webhookResponse = await handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n },\n\n /**\n * Universal handler that creates separate GET and POST handlers\n * Usage: export const { GET, POST } = adapter.createHandlers({ verification, webhook })\n */\n createHandlers: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return {\n GET: (req: NextRequest) => {\n const searchParams = req.nextUrl.searchParams;\n const webhookRequest = fromRouteHandlerRequest(req, searchParams);\n const webhookResponse = handlers.verification(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n },\n\n POST: async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n\n const webhookResponse = await handlers.webhook(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n };\n },\n };\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { M as MessageTypesEnum } from '../../enums-CI7vzKhn.js';
2
- import { WhatsAppConfig, WabaConfigType } from '../../shared/types/config.js';
3
- import { IncomingMessage } from 'http';
4
2
  import { c as FlowEndpointRequest, m as FlowTypeEnum } from '../../FlowApi-BhpWbli2.js';
3
+ import { WabaConfigType, WhatsAppConfig } from '../../shared/types/config.js';
5
4
  import { WhatsApp } from '../whatsapp/index.js';
6
5
  import { Request as Request$1, Response as Response$1 } from 'express';
7
6
  import { FastifyRequest, FastifyReply } from 'fastify';
@@ -482,6 +481,125 @@ interface WebhookMessage {
482
481
  */
483
482
  originalData: any;
484
483
  }
484
+ /**
485
+ * Represents a message status update received through the webhook
486
+ * Based on Meta's documentation: https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components#statuses-object
487
+ */
488
+ interface WebhookMessageStatus {
489
+ /**
490
+ * The phone number ID that received the status update
491
+ */
492
+ phoneNumberId: string;
493
+ /**
494
+ * The display phone number that received the status update
495
+ */
496
+ displayPhoneNumber: string;
497
+ /**
498
+ * Arbitrary string included in sent message
499
+ */
500
+ biz_opaque_callback_data?: string;
501
+ /**
502
+ * Information about the conversation
503
+ */
504
+ conversation?: {
505
+ /**
506
+ * Represents the ID of the conversation the given status notification belongs to
507
+ */
508
+ id: string;
509
+ /**
510
+ * Describes conversation category
511
+ */
512
+ origin: {
513
+ /**
514
+ * Indicates conversation category. This can also be referred to as a conversation entry point
515
+ * - authentication: Conversation opened by business sending template categorized as AUTHENTICATION
516
+ * - marketing: Conversation opened by business sending template categorized as MARKETING
517
+ * - utility: Conversation opened by business sending template categorized as UTILITY
518
+ * - service: Conversation opened by business replying to customer within service window
519
+ * - referral_conversion: Free entry point conversation
520
+ */
521
+ type: 'authentication' | 'marketing' | 'utility' | 'service' | 'referral_conversion';
522
+ };
523
+ /**
524
+ * Date when the conversation expires. Only present for messages with status 'sent'
525
+ */
526
+ expiration_timestamp?: string;
527
+ };
528
+ /**
529
+ * Array of error objects describing the error
530
+ */
531
+ errors?: Array<{
532
+ /**
533
+ * Error code
534
+ */
535
+ code: number;
536
+ /**
537
+ * Error code title
538
+ */
539
+ title: string;
540
+ /**
541
+ * Error code message
542
+ */
543
+ message: string;
544
+ /**
545
+ * Error details object
546
+ */
547
+ error_data?: {
548
+ /**
549
+ * Describes the error details
550
+ */
551
+ details: string;
552
+ };
553
+ }>;
554
+ /**
555
+ * The ID for the message that the business sent to a customer
556
+ */
557
+ id: string;
558
+ /**
559
+ * Pricing information for the message/conversation
560
+ */
561
+ pricing?: {
562
+ /**
563
+ * Indicates if the given message or conversation is billable
564
+ * @deprecated This field is deprecated. Visit the WhatsApp Changelog for more information.
565
+ */
566
+ billable?: boolean;
567
+ /**
568
+ * Indicates the conversation category:
569
+ * - authentication: Authentication conversation
570
+ * - authentication_international: Authentication-international conversation
571
+ * - marketing: Marketing conversation
572
+ * - utility: Utility conversation
573
+ * - service: Service conversation
574
+ * - referral_conversion: Free entry point conversation
575
+ */
576
+ category: 'authentication' | 'authentication_international' | 'marketing' | 'utility' | 'service' | 'referral_conversion';
577
+ /**
578
+ * Type of pricing model used by the business. Current supported value is CBP
579
+ */
580
+ pricing_model: 'CBP';
581
+ };
582
+ /**
583
+ * The customer's WhatsApp ID. Business can respond to customer using this ID.
584
+ * This ID may not match the customer's phone number.
585
+ */
586
+ recipient_id: string;
587
+ /**
588
+ * Status of the message:
589
+ * - delivered: Message has been delivered
590
+ * - read: Message has been read by the customer
591
+ * - sent: Message has been sent to the customer
592
+ */
593
+ status: 'delivered' | 'read' | 'sent';
594
+ /**
595
+ * Unix timestamp for the status message
596
+ */
597
+ timestamp: string;
598
+ /**
599
+ * The original status data as received from the webhook
600
+ */
601
+ originalData: any;
602
+ }
485
603
  /**
486
604
  * Webhook event received from WhatsApp
487
605
  */
@@ -519,147 +637,102 @@ declare enum EventField {
519
637
  UNKNOWN = "unknown"
520
638
  }
521
639
 
522
- interface IRequest extends IncomingMessage {
523
- body: any;
640
+ interface WebhookRequest {
641
+ method: string;
524
642
  query: Record<string, any>;
525
- method?: string;
643
+ body: any;
644
+ headers: Record<string, string | string[] | undefined>;
645
+ rawBody?: string;
526
646
  }
527
- interface IResponse {
528
- status: (code: number) => IResponse;
529
- send: (body: any) => IResponse | void;
530
- json: (body: any) => IResponse | void;
531
- end: () => void;
647
+ interface WebhookResponse {
648
+ statusCode: number;
649
+ body?: any;
650
+ headers?: Record<string, string>;
532
651
  }
652
+ type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;
653
+ type EventHandler = (event: WebhookEvent) => void | Promise<void>;
654
+ type StatusHandler = (whatsapp: WhatsApp, statuses: WebhookMessageStatus) => void | Promise<void>;
655
+ type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;
533
656
  /**
534
- * Webhook handler for WhatsApp Cloud API
657
+ * Pure function to handle webhook verification
658
+ */
659
+ declare function verifyWebhook(request: WebhookRequest, verificationToken: string): WebhookResponse;
660
+ /**
661
+ * Pure function to process webhook messages
662
+ */
663
+ declare function processWebhookMessages(request: WebhookRequest, whatsapp: WhatsApp, handlers: {
664
+ messageHandlers: Map<MessageTypesEnum, MessageHandler>;
665
+ eventHandlers: Map<string, EventHandler>;
666
+ statusHandlers?: Map<MessageStatus, StatusHandler>;
667
+ preProcessHandler?: MessageHandler;
668
+ postProcessHandler?: MessageHandler;
669
+ }): Promise<WebhookResponse>;
670
+ /**
671
+ * Pure function to handle flow requests
672
+ */
673
+ declare function processFlowRequest(request: WebhookRequest, config: WabaConfigType, whatsapp: WhatsApp, flowHandlers: Map<FlowTypeEnum, FlowHandler>): Promise<WebhookResponse>;
674
+
675
+ /**
676
+ * Framework-agnostic WebhookHandler using pure functions
535
677
  */
536
678
  declare class WebhookHandler {
537
679
  private config;
538
680
  private client;
539
681
  private messageHandlers;
682
+ private statusHandlers;
540
683
  private eventHandlers;
541
684
  private preProcessHandler;
542
685
  private postProcessHandler;
543
686
  private flowHandlers;
544
- /**
545
- * Create a new WebhookHandler
546
- * @param config The WhatsApp configuration
547
- */
548
687
  constructor(config: WhatsAppConfig);
549
688
  /**
550
- * Handle a GET request for webhook verification
689
+ * Handle webhook verification (framework-agnostic)
551
690
  */
552
- handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void;
553
- handleVerificationRequest<Req extends IRequest>(req: Req): string;
691
+ handleVerification: (request: WebhookRequest) => WebhookResponse;
554
692
  /**
555
- * Handle a POST request for webhook events
693
+ * Handle webhook messages (framework-agnostic)
556
694
  */
557
- handleWebhookRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): Promise<void>;
558
- handleWebhookRequest<Req extends IRequest>(req: Req): Promise<{
559
- success: boolean;
560
- errors?: string[];
561
- }>;
695
+ handleWebhook: (request: WebhookRequest) => Promise<WebhookResponse>;
562
696
  /**
563
- * Handle webhook requests (both verification and events)
697
+ * Handle flow requests (framework-agnostic)
564
698
  */
565
- handleRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void | Promise<void>;
566
- handleRequest<Req extends IRequest>(req: Req): string | Promise<{
567
- success: boolean;
568
- errors?: string[];
569
- }>;
699
+ handleFlow: (request: WebhookRequest) => Promise<WebhookResponse>;
570
700
  /**
571
- * Process incoming messages
701
+ * Register a message handler for a specific message type
572
702
  */
573
- private processMessages;
703
+ onMessage(type: MessageTypesEnum, handler: MessageHandler): void;
574
704
  /**
575
- * Process other webhook events
705
+ * Register a status handler for a specific status type
576
706
  */
577
- private processEvent;
578
- /**
579
- * Register a message handler for a specific message type
580
- */
581
- onMessage(type: MessageTypesEnum, handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void;
707
+ onStatus(type: MessageStatus, handler: StatusHandler): void;
582
708
  /**
583
709
  * Register an event handler for a specific field
584
710
  */
585
- onEvent(field: string, handler: (event: WebhookEvent) => void | Promise<void>): void;
711
+ onEvent(field: string, handler: EventHandler): void;
586
712
  /**
587
713
  * Register a pre-process handler that runs before all message handlers
588
714
  */
589
- onMessagePreProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void;
715
+ onMessagePreProcess(handler: MessageHandler): void;
590
716
  /**
591
717
  * Register a post-process handler that runs after all message handlers
592
718
  */
593
- onMessagePostProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void;
594
- handleFlowRequest<Req extends IRequest & {
595
- rawBody: string;
596
- }, Res extends IResponse>(req: Req, res: Res): Promise<void>;
597
- handleFlowRequest<Req extends IRequest & {
598
- rawBody: string;
599
- }>(req: Req): Promise<{
600
- statusCode: number;
601
- body: any;
602
- headers?: Record<string, string>;
603
- }>;
604
- /**
605
- * Validate the request signature
606
- */
607
- isRequestSignatureValid(req: IRequest & {
608
- rawBody: string;
609
- }): boolean;
719
+ onMessagePostProcess(handler: MessageHandler): void;
610
720
  /**
611
- * Decrypt a flow request
721
+ * Register a flow handler for a specific flow type
612
722
  */
613
- decryptRequest(body: any): {
614
- decryptedBody: FlowEndpointRequest;
615
- aesKeyBuffer: Buffer;
616
- initialVectorBuffer: Buffer;
617
- };
723
+ onFlow(type: FlowTypeEnum, handler: FlowHandler): void;
618
724
  /**
619
- * Encrypt a flow response
725
+ * Get the WhatsApp client instance
620
726
  */
621
- private encryptResponse;
727
+ getClient(): WhatsApp;
622
728
  /**
623
- * Register a flow handler for a specific flow type
729
+ * Get the configuration
624
730
  */
625
- onFlow(type: FlowTypeEnum, handler: (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>): void;
731
+ getConfig(): WabaConfigType;
626
732
  }
627
733
 
628
734
  declare const generateXHub256Sig: (body: string, appSecret: string) => string;
629
735
 
630
- interface WebhookRequest {
631
- method: string;
632
- query: Record<string, any>;
633
- body: any;
634
- headers: Record<string, string | string[] | undefined>;
635
- rawBody?: string;
636
- }
637
- interface WebhookResponse {
638
- statusCode: number;
639
- body?: any;
640
- headers?: Record<string, string>;
641
- }
642
- type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;
643
- type EventHandler = (event: WebhookEvent) => void | Promise<void>;
644
- type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;
645
- /**
646
- * Pure function to handle webhook verification
647
- */
648
- declare function verifyWebhook(request: WebhookRequest, verificationToken: string): WebhookResponse;
649
- /**
650
- * Pure function to process webhook messages
651
- */
652
- declare function processWebhookMessages(request: WebhookRequest, whatsapp: WhatsApp, handlers: {
653
- messageHandlers: Map<MessageTypesEnum, MessageHandler>;
654
- eventHandlers: Map<string, EventHandler>;
655
- preProcessHandler?: MessageHandler;
656
- postProcessHandler?: MessageHandler;
657
- }): Promise<WebhookResponse>;
658
- /**
659
- * Pure function to handle flow requests
660
- */
661
- declare function processFlowRequest(request: WebhookRequest, config: WabaConfigType, whatsapp: WhatsApp, flowHandlers: Map<FlowTypeEnum, FlowHandler>): Promise<WebhookResponse>;
662
-
663
736
  /**
664
737
  * Create Express.js adapter for webhook handlers
665
738
  */
@@ -808,4 +881,4 @@ declare function createNextJSRouteHandlerAdapter(): {
808
881
  };
809
882
  };
810
883
 
811
- export { EventField, type EventHandler, type FlowHandler, type IRequest, type IResponse, type MessageHandler, MessageStatus, type WebhookContact, type WebhookEvent, WebhookHandler, type WebhookMessage, WebhookReq, type WebhookRequest, type WebhookResponse, WebhookResponseInterceptor, createExpressAdapter, createFastifyAdapter, createNestJSAdapter, createNextJSAdapter, createNextJSRouteHandlerAdapter, generateXHub256Sig, processFlowRequest, processWebhookMessages, verifyWebhook };
884
+ export { EventField, type EventHandler, type FlowHandler, type MessageHandler, MessageStatus, type StatusHandler, type WebhookContact, type WebhookEvent, WebhookHandler, type WebhookMessage, type WebhookMessageStatus, WebhookReq, type WebhookRequest, type WebhookResponse, WebhookResponseInterceptor, createExpressAdapter, createFastifyAdapter, createNestJSAdapter, createNextJSAdapter, createNextJSRouteHandlerAdapter, generateXHub256Sig, processFlowRequest, processWebhookMessages, verifyWebhook };
@@ -1,2 +1,2 @@
1
- export{b as EventField,a as MessageStatus,c as WebhookHandler,j as WebhookReq,k as WebhookResponseInterceptor,h as createExpressAdapter,i as createFastifyAdapter,l as createNestJSAdapter,m as createNextJSAdapter,n as createNextJSRouteHandlerAdapter,d as generateXHub256Sig,g as processFlowRequest,f as processWebhookMessages,e as verifyWebhook}from'../../chunk-FYHBS7Q5.js';import'../../chunk-XQDM2WBV.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-2NCV35XS.js';import'../../chunk-M2GC5VFJ.js';//# sourceMappingURL=index.js.map
1
+ export{b as EventField,a as MessageStatus,f as WebhookHandler,j as WebhookReq,k as WebhookResponseInterceptor,h as createExpressAdapter,i as createFastifyAdapter,l as createNestJSAdapter,m as createNextJSAdapter,n as createNextJSRouteHandlerAdapter,g as generateXHub256Sig,e as processFlowRequest,d as processWebhookMessages,c as verifyWebhook}from'../../chunk-ZJV5NIQ7.js';import'../../chunk-XQDM2WBV.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-2NCV35XS.js';import'../../chunk-M2GC5VFJ.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { EventField, EventHandler, FlowHandler, IRequest, IResponse, MessageHandler, MessageStatus, WebhookContact, WebhookEvent, WebhookHandler, WebhookMessage, WebhookReq, WebhookRequest, WebhookResponse, WebhookResponseInterceptor, createExpressAdapter, createFastifyAdapter, createNestJSAdapter, createNextJSAdapter, createNextJSRouteHandlerAdapter, generateXHub256Sig, processFlowRequest, processWebhookMessages, verifyWebhook } from './core/webhook/index.js';
1
+ export { EventField, EventHandler, FlowHandler, MessageHandler, MessageStatus, StatusHandler, WebhookContact, WebhookEvent, WebhookHandler, WebhookMessage, WebhookMessageStatus, WebhookReq, WebhookRequest, WebhookResponse, WebhookResponseInterceptor, createExpressAdapter, createFastifyAdapter, createNestJSAdapter, createNextJSAdapter, createNextJSRouteHandlerAdapter, 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-Cr3Q6qg4.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-CI7vzKhn.js';
@@ -13,7 +13,6 @@ export { Q as QrCodeApi, a as QrCodeClass, b as QrCodeResponse } from './QrCodeA
13
13
  export { T as TwoStepVerificationApi } from './TwoStepVerificationApi-nJ12648J.js';
14
14
  export { b as WABAClass, a as WabaAccount, W as WabaApi } from './WabaApi-BIP6G4pB.js';
15
15
  import { WhatsApp } from './core/whatsapp/index.js';
16
- import 'http';
17
16
  import 'express';
18
17
  import 'fastify';
19
18
  import '@nestjs/common';
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{b as EventField,a as MessageStatus,c as WebhookHandler,j as WebhookReq,k as WebhookResponseInterceptor,h as createExpressAdapter,i as createFastifyAdapter,l as createNestJSAdapter,m as createNextJSAdapter,n as createNextJSRouteHandlerAdapter,d as generateXHub256Sig,g as processFlowRequest,f as processWebhookMessages,e as verifyWebhook}from'./chunk-FYHBS7Q5.js';import {b}from'./chunk-XQDM2WBV.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-2NCV35XS.js';import'./chunk-M2GC5VFJ.js';var le=b;export{le as default};//# sourceMappingURL=index.js.map
1
+ export{a as TemplateApi}from'./chunk-H55VIWDI.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';import'./chunk-W2U7MN7M.js';export{b as EventField,a as MessageStatus,f as WebhookHandler,j as WebhookReq,k as WebhookResponseInterceptor,h as createExpressAdapter,i as createFastifyAdapter,l as createNestJSAdapter,m as createNextJSAdapter,n as createNextJSRouteHandlerAdapter,g as generateXHub256Sig,e as processFlowRequest,d as processWebhookMessages,c as verifyWebhook}from'./chunk-ZJV5NIQ7.js';import {b}from'./chunk-XQDM2WBV.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-2NCV35XS.js';import'./chunk-M2GC5VFJ.js';var le=b;export{le as default};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meta-cloud-api",
3
- "version": "0.2.24",
3
+ "version": "0.2.25",
4
4
  "description": "TypeScript wrapper for Meta's Cloud API",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,4 +0,0 @@
1
- import {a as a$1,b as b$1}from'./chunk-XQDM2WBV.js';import {a}from'./chunk-VW3LGHTJ.js';import {b,d as d$1,c}from'./chunk-M2GC5VFJ.js';import*as g from'crypto';import g__default from'crypto';import {createParamDecorator,Injectable}from'@nestjs/common';import {map}from'rxjs/operators';var K=(s=>(s.DELIVERED="delivered",s.READ="read",s.SENT="sent",s))(K||{}),X=(i=>(i.MESSAGES="messages",i.STATUSES="statuses",i.MESSAGE_TEMPLATE_STATUS_UPDATE="message_template_status_update",i.PHONE_NUMBER_QUALITY_UPDATE="phone_number_quality_update",i.PHONE_NUMBER_NAME_UPDATE="phone_number_name_update",i.UNKNOWN="unknown",i))(X||{});function U(t){return typeof t=="object"&&t!==null}function m(t){return typeof t=="string"}var z=["data_exchange","INIT","BACK"],Q=["data_exchange","INIT"];function x(t){if(!("flow_token"in t&&m(t.flow_token)&&"action"in t))return false;let{action:e,version:o,screen:s,data:r}=t,a=o==="3.0",i=z.includes(e),n=typeof s>"u"||m(s)&&s!=="SUCCESS",c=e==="data_exchange"||U(r);return a&&i&&n&&c}function A(t){if(!("flow_token"in t&&m(t.flow_token)&&"action"in t))return false;let{action:e,screen:o,data:s}=t,r=Q.includes(e),a=m(o),i=U(s)&&"error_key"in s&&m(s.error)&&"error_message"in s&&m(s.error_message);return r&&a&&i}function P(t){return "action"in t&&t.action==="ping"}var Y="WEBHOOK",Z=false,d=new a(Y,process.env.DEBUG==="true"||Z),S=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(e){let o=a$1(e);this.config=o,this.client=new b$1(e),d.log("WebhookHandler instantiated!");}handleVerificationRequest(e,o){let s=e.query["hub.mode"],r=e.query["hub.verify_token"],a=e.query["hub.challenge"];if(s==="subscribe"&&r===this.config.WEBHOOK_VERIFICATION_TOKEN)if(d.log("Webhook verified successfully"),o){o.status(200).send(a);return}else return d.log("Returning challenge for manual handling"),a;else if(d.log("Webhook verification failed"),o){o.status(403).end();return}else throw d.log("Verification failed - throwing error for manual handling"),new Error("Webhook verification failed")}async handleWebhookRequest(e,o){let s=e.body,r=[];if(s.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";if(d.log(a),o){o.status(404).end();return}else return r.push(a),{success:false,errors:r}}for(let a of s.entry)try{let i=a.changes;for(let n of i)n.field==="messages"?await this.processMessages(n.value):await this.processEvent(n.field,n.value);}catch(i){let n=`Error processing webhook: ${i}`;d.log(n),r.push(n);}if(o){o.status(200).end();return}else return {success:r.length===0,errors:r.length>0?r:void 0}}handleRequest(e,o){if(e.method==="GET")return o?this.handleVerificationRequest(e,o):this.handleVerificationRequest(e);if(e.method==="POST")return o?this.handleWebhookRequest(e,o):this.handleWebhookRequest(e);if(o){o.status(405).end();return}else throw new Error("Method not allowed")}async processMessages(e){let o=e.metadata,s=o.display_phone_number,r=o.phone_number_id,a=e.contacts[0]?.profile?.name||"",i=e.messages;if(i&&i.length>0)for(let n of i){let c=n.type,u={id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:r,displayPhoneNumber:s,profileName:a,originalData:n};switch(n.type){case "text":u.text=n.text;break;case "image":u.image=n.image;break;case "video":u.video=n.video;break;case "audio":u.audio=n.audio;break;case "document":u.document=n.document;break;case "sticker":u.sticker=n.sticker;break;case "location":u.location=n.location;break;case "contacts":u.contacts=n.contacts;break;case "interactive":u.interactive=n.interactive;break;case "button":u.button=n.button;break;case "order":u.order=n.order;break;case "system":u.system=n.system;break;}if(n.context&&(u.context=n.context),n.errors&&(u.errors=n.errors),this.preProcessHandler)try{await this.preProcessHandler(this.client,u);}catch(l){d.log(`Error in pre-process handler: ${l}`);}let p=this.messageHandlers.get(c);if(p)try{await p(this.client,u);}catch(l){d.log(`Error in message handler for ${c}: ${l}`);}if(this.postProcessHandler)try{await this.postProcessHandler(this.client,u);}catch(l){d.log(`Error in post-process handler: ${l}`);}}}async processEvent(e,o){let s={field:e,value:o,timestamp:Date.now()},r=this.eventHandlers.get(e);if(r)try{await r(s);}catch(a){d.log(`Error in event handler for ${e}: ${a}`);}}onMessage(e,o){this.messageHandlers.set(e,o),d.log(`Registered message handler for ${e}`);}onEvent(e,o){this.eventHandlers.set(e,o),d.log(`Registered event handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,d.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,d.log("Registered post-process handler");}async handleFlowRequest(e,o){try{if(!this.isRequestSignatureValid(e)){let n={error:"Unauthorized"};if(d.log("Invalid request signature"),o){o.status(401).json(n);return}else return {statusCode:401,body:n}}let s=JSON.parse(e.rawBody),{decryptedBody:r}=this.decryptRequest(s),a=this.flowHandlers.get("*");if(!a){let n={error:"Handler not found"};if(d.log(`No handler registered for flow action: ${r.action}`),o){o.status(404).json(n);return}else return {statusCode:404,body:n}}if(P(r)){let n={version:"3.0",data:{status:"active"}};if(o){o.status(200).json(n);return}else return {statusCode:200,body:n}}if(A(r)){d.log(`Flow error: ${JSON.stringify(r)}`);let n={};if(o){o.status(200).json(n);return}else return {statusCode:200,body:n}}if(x(r)){let n=await a(this.client,r),c=this.encryptResponse(n,Buffer.from(s.aes_key,"base64"),Buffer.from(s.initial_vector,"base64"));if(o){o.status(200).json(c);return}else return {statusCode:200,body:c}}let i={error:"Unknown request type"};if(d.log(`Unknown flow request type: ${JSON.stringify(r)}`),o){o.status(400).json(i);return}else return {statusCode:400,body:i}}catch(s){let r={error:"Internal server error"};if(d.log(`Error handling flow request: ${s}`),o){o.status(500).json(r);return}else return {statusCode:500,body:r}}}isRequestSignatureValid(e){let o=e.headers["x-hub-signature-256"];if(!o)return false;let r=`sha256=${g__default.createHmac("sha256",this.config.WEBHOOK_VERIFICATION_TOKEN||"").update(e.rawBody,"utf8").digest("hex")}`;return g__default.timingSafeEqual(Buffer.from(o),Buffer.from(r))}decryptRequest(e){d.log("Received body for decryption:",JSON.stringify(e,null,2));let{encrypted_aes_key:o,encrypted_flow_data:s,initial_vector:r}=e;if(!o)throw new Error("Missing required property: encrypted_aes_key");if(!s)throw new Error("Missing required property: encrypted_flow_data");if(!r)throw new Error("Missing required property: initial_vector");d.log("Received body for privatePem:",JSON.stringify(this.config.FLOW_API_PRIVATE_PEM,null,2)),d.log("Received body for passphrase:",JSON.stringify(this.config.FLOW_API_PASSPHRASE,null,2));let a=this.config.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
- `),i=this.config.FLOW_API_PASSPHRASE,n=g__default.createPrivateKey({key:a,passphrase:i}),c=null;try{c=g__default.privateDecrypt({key:n,padding:g__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(o,"base64"));}catch(F){throw d.error(F),new Error("Failed to decrypt the request. Please verify your private key.")}let u=Buffer.from(s,"base64"),p=Buffer.from(r,"base64"),H=u.subarray(0,-16),O=u.subarray(-16),y=g__default.createDecipheriv("aes-128-gcm",c,p);y.setAuthTag(O);let B=Buffer.concat([y.update(H),y.final()]).toString("utf-8");return {decryptedBody:JSON.parse(B),aesKeyBuffer:c,initialVectorBuffer:p}}encryptResponse(e,o,s){let r=[];for(let a of Array.from(s.entries()))r.push(~a[1]);try{let a=g__default.createCipheriv("aes-128-gcm",o,Buffer.from(r));return Buffer.concat([a.update(JSON.stringify(e||{}),"utf-8"),a.final(),a.getAuthTag()]).toString("base64")}catch(a){throw d.error("Response encryption error:",a),new Error("Failed to encrypt response. Internal server error.")}}onFlow(e,o){this.flowHandlers.set(e,o),d.log(`Registered flow handler for ${e}`);}};var xe=(t,e)=>g.createHmac("sha256",e).update(t,"utf-8").digest("hex");var ee="WEBHOOK_UTILS",h=new a(ee,process.env.DEBUG==="true");function te(t,e){let o=t.query["hub.mode"],s=t.query["hub.verify_token"],r=t.query["hub.challenge"];return o==="subscribe"&&s===e?(h.log("Webhook verified successfully"),{statusCode:200,body:r}):(h.log("Webhook verification failed"),{statusCode:403})}async function oe(t,e,o){let s=t.body,r=[];if(s.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";return h.log(a),{statusCode:404,body:{error:a}}}for(let a of s.entry)try{let i=a.changes;for(let n of i)n.field==="messages"?await re(n.value,e,o):await ae(n.field,n.value,o.eventHandlers);}catch(i){let n=`Error processing webhook: ${i}`;h.log(n),r.push(n);}return {statusCode:200,body:r.length>0?{errors:r}:void 0}}async function se(t,e,o,s){try{if(!ie(t,e.WEBHOOK_VERIFICATION_TOKEN||""))return h.log("Invalid request signature"),{statusCode:401,body:{error:"Unauthorized"}};let r=JSON.parse(t.rawBody||"{}"),{decryptedBody:a}=ce(r,e),i=s.get("*");if(!i)return h.log(`No handler registered for flow action: ${a.action}`),{statusCode:404,body:{error:"Handler not found"}};if(P(a))return {statusCode:200,body:{version:"3.0",data:{status:"active"}}};if(A(a))return h.log(`Flow error: ${JSON.stringify(a)}`),{statusCode:200,body:{}};if(x(a)){let n=await i(o,a);return {statusCode:200,body:ue(n,Buffer.from(r.aes_key,"base64"),Buffer.from(r.initial_vector,"base64"))}}return h.log(`Unknown flow request type: ${JSON.stringify(a)}`),{statusCode:400,body:{error:"Unknown request type"}}}catch(r){return h.log(`Error handling flow request: ${r}`),{statusCode:500,body:{error:"Internal server error"}}}}async function re(t,e,o){let s=t.metadata,r=s.display_phone_number,a=s.phone_number_id,i=t.contacts[0]?.profile?.name||"",n=t.messages;if(n&&n.length>0)for(let c of n){let u=c.type,p={id:c.id,from:c.from,timestamp:c.timestamp,type:c.type,phoneNumberId:a,displayPhoneNumber:r,profileName:i,originalData:c};Object.assign(p,ne(c)),c.context&&(p.context=c.context),c.errors&&(p.errors=c.errors),await C(o.preProcessHandler,e,p,"pre-process"),await C(o.messageHandlers.get(u),e,p,u),await C(o.postProcessHandler,e,p,"post-process");}}function ne(t){let e={};switch(t.type){case "text":e.text=t.text;break;case "image":e.image=t.image;break;case "video":e.video=t.video;break;case "audio":e.audio=t.audio;break;case "document":e.document=t.document;break;case "sticker":e.sticker=t.sticker;break;case "location":e.location=t.location;break;case "contacts":e.contacts=t.contacts;break;case "interactive":e.interactive=t.interactive;break;case "button":e.button=t.button;break;case "order":e.order=t.order;break;case "system":e.system=t.system;break}return e}async function C(t,e,o,s){if(t)try{await t(e,o);}catch(r){h.log(`Error in ${s} handler: ${r}`);}}async function ae(t,e,o){let s={field:t,value:e,timestamp:Date.now()},r=o.get(t);if(r)try{await r(s);}catch(a){h.log(`Error in event handler for ${t}: ${a}`);}}function ie(t,e){let o=t.headers["x-hub-signature-256"];if(!o||!t.rawBody)return false;let r=`sha256=${g__default.createHmac("sha256",e).update(t.rawBody,"utf8").digest("hex")}`;return g__default.timingSafeEqual(Buffer.from(o),Buffer.from(r))}function ce(t,e){let{encrypted_aes_key:o,encrypted_flow_data:s,initial_vector:r}=t;if(!o||!s||!r)throw new Error("Missing required encryption properties");let a=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
3
- `),i=e.FLOW_API_PASSPHRASE,n=g__default.createPrivateKey({key:a,passphrase:i}),c;try{c=g__default.privateDecrypt({key:n,padding:g__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(o,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let u=Buffer.from(s,"base64"),p=Buffer.from(r,"base64"),H=u.subarray(0,-16),O=u.subarray(-16),y=g__default.createDecipheriv("aes-128-gcm",c,p);y.setAuthTag(O);let B=Buffer.concat([y.update(H),y.final()]).toString("utf-8");return {decryptedBody:JSON.parse(B),aesKeyBuffer:c,initialVectorBuffer:p}}function ue(t,e,o){let s=[];for(let r of Array.from(o.entries()))s.push(~r[1]);try{let r=g__default.createCipheriv("aes-128-gcm",e,Buffer.from(s));return Buffer.concat([r.update(JSON.stringify(t||{}),"utf-8"),r.final(),r.getAuthTag()]).toString("base64")}catch(r){throw h.log("Response encryption error:",r),new Error("Failed to encrypt response. Internal server error.")}}function I(t){return {method:t.method,query:t.query,body:t.body,headers:t.headers,rawBody:t.rawBody||JSON.stringify(t.body)}}function k(t,e){e.status(t.statusCode),t.headers&&Object.entries(t.headers).forEach(([o,s])=>{e.set(o,s);}),t.body!==void 0?typeof t.body=="string"?e.send(t.body):e.json(t.body):e.end();}function de(){return {handleVerification:t=>(e,o)=>{let s=I(e),r=t(s);k(r,o);},handleWebhook:t=>async(e,o)=>{try{let s=I(e),r=await t(s);k(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleFlow:t=>async(e,o)=>{try{let s=I(e),r=await t(s);k(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleRequest:t=>async(e,o)=>{try{let s=I(e);if(e.method==="GET"){let r=t.verification(s);k(r,o);}else if(e.method==="POST"){let r=await t.webhook(s);k(r,o);}else o.status(405).json({error:"Method not allowed"});}catch{o.status(500).json({error:"Internal server error"});}}}}function N(t){return {method:t.method,query:t.query,body:t.body,headers:t.headers,rawBody:t.rawBody||JSON.stringify(t.body)}}async function q(t,e){return e.status(t.statusCode),t.headers&&Object.entries(t.headers).forEach(([o,s])=>{e.header(o,s);}),t.body!==void 0?e.send(t.body):e.send()}function pe(){return {handleVerification:t=>async(e,o)=>{let s=N(e),r=t(s);return q(r,o)},handleWebhook:t=>async(e,o)=>{try{let s=N(e),r=await t(s);return q(r,o)}catch{return o.status(500).send({error:"Internal server error"})}},handleFlow:t=>async(e,o)=>{try{let s=N(e),r=await t(s);return q(r,o)}catch{return o.status(500).send({error:"Internal server error"})}},handleRequest:t=>async(e,o)=>{try{let s=N(e);if(e.method==="GET"){let r=t.verification(s);return q(r,o)}else if(e.method==="POST"){let r=await t.webhook(s);return q(r,o)}else return o.status(405).send({error:"Method not allowed"})}catch{return o.status(500).send({error:"Internal server error"})}}}}function R(t){return {method:t.method,query:t.query,body:t.body,headers:t.headers,rawBody:t.rawBody||JSON.stringify(t.body)}}function f(t,e){e.status(t.statusCode),t.headers&&Object.entries(t.headers).forEach(([o,s])=>{e.set(o,s);}),t.body!==void 0?typeof t.body=="string"?e.send(t.body):e.json(t.body):e.end();}var ye=createParamDecorator((t,e)=>{let o=e.switchToHttp().getRequest();return R(o)}),L,M;L=[Injectable()];var w=class{intercept(e,o){let s=e.switchToHttp().getResponse();return o.handle().pipe(map(r=>{f(r,s);}))}};M=b(null),w=d$1(M,0,"WebhookResponseInterceptor",L,w),c(M,1,w);function ge(){return {handleVerification:t=>(e,o)=>{let s=R(e),r=t(s);f(r,o);},handleWebhook:t=>async(e,o)=>{try{let s=R(e),r=await t(s);f(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleFlow:t=>async(e,o)=>{try{let s=R(e),r=await t(s);f(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleRequest:t=>async(e,o)=>{try{let s=R(e);if(e.method==="GET"){let r=t.verification(s);f(r,o);}else if(e.method==="POST"){let r=await t.webhook(s);f(r,o);}else o.status(405).json({error:"Method not allowed"});}catch{o.status(500).json({error:"Internal server error"});}},createVerificationHandler:t=>(e,o,s)=>{let r=s.value;s.value=function(...a){let i=a.find(n=>n&&n.switchToHttp);if(i){let n=i.switchToHttp().getRequest(),c=i.switchToHttp().getResponse(),u=R(n),p=t(u);f(p,c);return}return r.apply(this,a)};},createWebhookHandler:t=>(e,o,s)=>{let r=s.value;s.value=async function(...a){let i=a.find(n=>n&&n.switchToHttp);if(i)try{let n=i.switchToHttp().getRequest(),c=i.switchToHttp().getResponse(),u=R(n),p=await t(u);f(p,c);return}catch{i.switchToHttp().getResponse().status(500).json({error:"Internal server error"});return}return r.apply(this,a)};}}}function T(t){return {method:t.method||"GET",query:t.query,body:t.body,headers:t.headers,rawBody:t.rawBody||JSON.stringify(t.body)}}function v(t,e){e.status(t.statusCode),t.headers&&Object.entries(t.headers).forEach(([o,s])=>{e.setHeader(o,s);}),t.body!==void 0?typeof t.body=="string"?e.send(t.body):e.json(t.body):e.end();}function be(){return {handleVerification:t=>(e,o)=>{let s=T(e),r=t(s);v(r,o);},handleWebhook:t=>async(e,o)=>{try{let s=T(e),r=await t(s);v(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleFlow:t=>async(e,o)=>{try{let s=T(e),r=await t(s);v(r,o);}catch{o.status(500).json({error:"Internal server error"});}},handleRequest:t=>async(e,o)=>{try{let s=T(e);if(e.method==="GET"){let r=t.verification(s);v(r,o);}else if(e.method==="POST"){let r=await t.webhook(s);v(r,o);}else o.status(405).json({error:"Method not allowed"});}catch{o.status(500).json({error:"Internal server error"});}}}}function W(t,e){return {method:t.method||"GET",query:e?Object.fromEntries(e.entries()):{},body:void 0,headers:Object.fromEntries(t.headers.entries()),rawBody:void 0}}function E(t){let e=new Headers;return t.headers&&Object.entries(t.headers).forEach(([o,s])=>{e.set(o,s);}),t.body!==void 0?typeof t.body=="string"?new Response(t.body,{status:t.statusCode,headers:e}):(e.set("Content-Type","application/json"),new Response(JSON.stringify(t.body),{status:t.statusCode,headers:e})):new Response(null,{status:t.statusCode,headers:e})}function Re(){return {handleVerification:t=>e=>{let o=e.nextUrl.searchParams,s=W(e,o),r=t(s);return E(r)},handleWebhook:t=>async e=>{try{let o=W(e);if(e.method==="POST")if((e.headers.get("content-type")||"").includes("application/json"))o.body=await e.json(),o.rawBody=JSON.stringify(o.body);else {let a=await e.text();o.rawBody=a,o.body=a;}let s=await t(o);return E(s)}catch{return new Response(JSON.stringify({error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}},handleFlow:t=>async e=>{try{let o=W(e);if(e.method==="POST")if((e.headers.get("content-type")||"").includes("application/json"))o.body=await e.json(),o.rawBody=JSON.stringify(o.body);else {let a=await e.text();o.rawBody=a,o.body=a;}let s=await t(o);return E(s)}catch{return new Response(JSON.stringify({error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}},createHandlers:t=>({GET:e=>{let o=e.nextUrl.searchParams,s=W(e,o),r=t.verification(s);return E(r)},POST:async e=>{try{let o=W(e);if((e.headers.get("content-type")||"").includes("application/json"))o.body=await e.json(),o.rawBody=JSON.stringify(o.body);else {let a=await e.text();o.rawBody=a,o.body=a;}let r=await t.webhook(o);return E(r)}catch{return new Response(JSON.stringify({error:"Internal server error"}),{status:500,headers:{"Content-Type":"application/json"}})}}})}}export{K as a,X as b,S as c,xe as d,te as e,oe as f,se as g,de as h,pe as i,ye as j,w as k,ge as l,be as m,Re as n};//# sourceMappingURL=chunk-FYHBS7Q5.js.map
4
- //# sourceMappingURL=chunk-FYHBS7Q5.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/webhook/types.ts","../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/WebhookHandler_temp.ts","../src/core/webhook/utils/generateXHub256Sig.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/adapters/expressAdapter.ts","../src/core/webhook/adapters/fastifyAdapter.ts","../src/core/webhook/adapters/nestjsAdapter.ts","../src/core/webhook/adapters/nextjsApiRouteAdapter.ts","../src/core/webhook/adapters/nextjsRouteHandlerAdapter.ts"],"names":["MessageStatus","EventField","isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOG_LOCAL","LOGGER","Logger","WebhookHandler","config","configuration","importConfig","WhatsApp","req","res","mode","token","challenge","body","errors","errorMsg","entry","changes","change","error","metadata","displayPhoneNumber","phoneNumberId","profileName","messages","message","messageType","processedMessage","handler","field","event","type","decryptedBody","response","result","encryptedResponse","errorResponse","signature","formattedExpectedSignature","crypto","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","aesKeyBuffer","flipped_iv","pair","cipher","generateXHub256Sig","appSecret","$","verifyWebhook","verificationToken","processWebhookMessages","whatsapp","handlers","processMessages","processEvent","processFlowRequest","flowHandlers","isRequestSignatureValid","decryptFlowRequest","encryptFlowResponse","getMessageTypeData","executeHandler","typeData","handlerType","eventHandlers","TAG_LENGTH","fromExpressRequest","toExpressResponse","webhookResponse","key","createExpressAdapter","webhookRequest","fromFastifyRequest","toFastifyReply","reply","createFastifyAdapter","fromNestJSRequest","toNestJSResponse","WebhookReq","createParamDecorator","ctx","_WebhookResponseInterceptor_decorators","_init","Injectable","WebhookResponseInterceptor","context","next","map","__decoratorStart","__decorateElement","__runInitializers","createNestJSAdapter","target","propertyName","descriptor","method","args","arg","fromNextJSRequest","toNextJSResponse","createNextJSAdapter","fromRouteHandlerRequest","searchParams","toRouteHandlerResponse","headers","createNextJSRouteHandlerAdapter","text"],"mappings":"6RAwgBO,IAAKA,CACRA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,SAAY,CAAA,WAAA,CACZA,EAAA,IAAO,CAAA,MAAA,CACPA,CAAA,CAAA,IAAA,CAAO,OAHCA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CASAC,CACRA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,SAAW,UACXA,CAAAA,CAAAA,CAAA,QAAW,CAAA,UAAA,CACXA,CAAA,CAAA,8BAAA,CAAiC,gCACjCA,CAAAA,CAAAA,CAAA,4BAA8B,6BAC9BA,CAAAA,CAAAA,CAAA,wBAA2B,CAAA,0BAAA,CAC3BA,EAAA,OAAU,CAAA,SAAA,CANFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,ECpgBZ,SAASC,CAASC,CAAAA,CAAAA,CAAkD,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,CAAAA,CAAwB,CAAuE,eAAA,CAAA,MAAA,CAAA,MAAA,CAAA,CAG/FC,EAAgB,CAAkD,eAAA,CAAA,MAAA,CAAA,CASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAA,GAAgBA,GAAWJ,CAASI,CAAAA,CAAAA,CAAQ,UAAU,CAAA,EAAK,WAAYA,CACzE,CAAA,CAAA,OAAO,MAGX,CAAA,GAAM,CAAE,MAAA,CAAAC,CAAQ,C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ACpE,MAAQ,CAAA,GAAA,CACR,OAAS,CAAA,CAAE,cAAgB,CAAA,kBAAmB,CAClD,CAAC,CACL,CACJ,CACJ,CAAA,CAER,CACJ","file":"chunk-FYHBS7Q5.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 /**\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 * Event handler function type\n */\nexport type EventHandler = (event: WebhookEvent) => void | Promise<void>;\n\n/**\n * Message status enum\n */\nexport enum MessageStatus {\n DELIVERED = 'delivered',\n READ = 'read',\n SENT = 'sent',\n}\n\n/**\n * Event field enum for webhook events\n */\nexport enum EventField {\n MESSAGES = 'messages',\n STATUSES = 'statuses',\n MESSAGE_TEMPLATE_STATUS_UPDATE = 'message_template_status_update',\n PHONE_NUMBER_QUALITY_UPDATE = 'phone_number_quality_update',\n PHONE_NUMBER_NAME_UPDATE = 'phone_number_name_update',\n UNKNOWN = 'unknown',\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 { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport { IncomingMessage } from 'http';\n\nimport { FlowEndpointRequest } from '@features/flow';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../whatsapp';\n\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport { EventField, WebhookEvent, WebhookMessage } from './types';\nconst LIB_NAME = 'WEBHOOK';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport interface IRequest extends IncomingMessage {\n body: any;\n query: Record<string, any>;\n method?: string;\n}\nexport interface IResponse {\n status: (code: number) => IResponse;\n send: (body: any) => IResponse | void;\n json: (body: any) => IResponse | void;\n end: () => void;\n}\n\n/**\n * Webhook handler for WhatsApp Cloud API\n */\nexport default class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<\n MessageTypesEnum,\n (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>\n > = new Map();\n private eventHandlers: Map<string, (event: WebhookEvent) => void | Promise<void>> = new Map();\n private preProcessHandler: ((whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>) | null = null;\n private postProcessHandler: ((whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>) | null = null;\n private flowHandlers: Map<FlowTypeEnum, (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>> =\n new Map();\n\n /**\n * Create a new WebhookHandler\n * @param config The WhatsApp configuration\n */\n constructor(config: WhatsAppConfig) {\n const configuration = importConfig(config);\n this.config = configuration;\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle a GET request for webhook verification\n */\n public handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void;\n public handleVerificationRequest<Req extends IRequest>(req: Req): string;\n public handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res?: Res): void | string {\n const mode = req.query['hub.mode'];\n const token = req.query['hub.verify_token'];\n const challenge = req.query['hub.challenge'];\n\n const VERIFICATION_SUCCESS = mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN;\n\n if (VERIFICATION_SUCCESS) {\n LOGGER.log('Webhook verified successfully');\n if (res) {\n res.status(200).send(challenge);\n return;\n } else {\n LOGGER.log('Returning challenge for manual handling');\n return challenge;\n }\n } else {\n LOGGER.log('Webhook verification failed');\n if (res) {\n res.status(403).end();\n return;\n } else {\n LOGGER.log('Verification failed - throwing error for manual handling');\n throw new Error('Webhook verification failed');\n }\n }\n }\n\n /**\n * Handle a POST request for webhook events\n */\n public async handleWebhookRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): Promise<void>;\n public async handleWebhookRequest<Req extends IRequest>(req: Req): Promise<{ success: boolean; errors?: string[] }>;\n public async handleWebhookRequest<Req extends IRequest, Res extends IResponse>(\n req: Req,\n res?: Res,\n ): Promise<void | { success: boolean; errors?: string[] }> {\n const body = req.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\n if (res) {\n res.status(404).end();\n return;\n } else {\n errors.push(errorMsg);\n return { success: false, errors };\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 === EventField.MESSAGES) {\n await this.processMessages(change.value);\n } else {\n // Handle other event types\n await this.processEvent(change.field, change.value);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n if (res) {\n // Always respond with 200 to acknowledge receipt\n res.status(200).end();\n return;\n } else {\n // Return processing result\n return { success: errors.length === 0, errors: errors.length > 0 ? errors : undefined };\n }\n }\n\n /**\n * Handle webhook requests (both verification and events)\n */\n public handleRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void | Promise<void>;\n public handleRequest<Req extends IRequest>(req: Req): string | Promise<{ success: boolean; errors?: string[] }>;\n public handleRequest<Req extends IRequest, Res extends IResponse>(\n req: Req,\n res?: Res,\n ): void | string | Promise<void | { success: boolean; errors?: string[] }> {\n if (req.method === 'GET') {\n if (res) {\n return this.handleVerificationRequest(req, res);\n } else {\n return this.handleVerificationRequest(req);\n }\n } else if (req.method === 'POST') {\n if (res) {\n return this.handleWebhookRequest(req, res);\n } else {\n return this.handleWebhookRequest(req);\n }\n } else {\n if (res) {\n res.status(405).end(); // Method not allowed\n return;\n } else {\n throw new Error('Method not allowed');\n }\n }\n }\n\n /**\n * Process incoming messages\n */\n private async processMessages(value: any): Promise<void> {\n // Extract metadata\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 // Process messages if present\n if (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n // Create the base message object\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n // Add type-specific data based on the message type\n switch (message.type) {\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 default:\n // Unknown message type\n break;\n }\n\n // Add context if available\n if (message.context) {\n processedMessage.context = message.context;\n }\n\n // Add errors if available\n if (message.errors) {\n processedMessage.errors = message.errors;\n }\n\n // 1. Execute pre-processing handler if exists\n if (this.preProcessHandler) {\n try {\n await this.preProcessHandler(this.client, processedMessage);\n } catch (error) {\n LOGGER.log(`Error in pre-process handler: ${error}`);\n }\n }\n\n // 2. Execute type-specific message handler if registered\n const handler = this.messageHandlers.get(messageType);\n if (handler) {\n try {\n await handler(this.client, processedMessage);\n } catch (error) {\n LOGGER.log(`Error in message handler for ${messageType}: ${error}`);\n }\n }\n\n // 3. Execute post-processing handler if exists\n if (this.postProcessHandler) {\n try {\n await this.postProcessHandler(this.client, processedMessage);\n } catch (error) {\n LOGGER.log(`Error in post-process handler: ${error}`);\n }\n }\n }\n }\n }\n\n /**\n * Process other webhook events\n */\n private async processEvent(field: string, value: any): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n timestamp: Date.now(),\n };\n\n const handler = this.eventHandlers.get(field);\n if (handler) {\n try {\n await handler(event);\n } catch (error) {\n LOGGER.log(`Error in event handler for ${field}: ${error}`);\n }\n }\n }\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(\n type: MessageTypesEnum,\n handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>,\n ): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register an event handler for a specific field\n */\n public onEvent(field: string, handler: (event: WebhookEvent) => void | Promise<void>): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered event handler for ${field}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): 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: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }, Res extends IResponse>(\n req: Req,\n res: Res,\n ): Promise<void>;\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }>(\n req: Req,\n ): Promise<{ statusCode: number; body: any; headers?: Record<string, string> }>;\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }, Res extends IResponse>(\n req: Req,\n res?: Res,\n ): Promise<void | { statusCode: number; body: any; headers?: Record<string, string> }> {\n try {\n // Validate request signature\n if (!this.isRequestSignatureValid(req)) {\n const error = { error: 'Unauthorized' };\n LOGGER.log('Invalid request signature');\n\n if (res) {\n res.status(401).json(error);\n return;\n } else {\n return { statusCode: 401, body: error };\n }\n }\n\n const body = JSON.parse(req.rawBody);\n\n // Decrypt the request\n const { decryptedBody } = this.decryptRequest(body);\n\n // Get the flow handler\n const handler = this.flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n const error = { error: 'Handler not found' };\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n\n if (res) {\n res.status(404).json(error);\n return;\n } else {\n return { statusCode: 404, body: error };\n }\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n // For ping requests, just respond with version\n const response = {\n version: '3.0',\n data: {\n status: 'active',\n },\n };\n\n if (res) {\n res.status(200).json(response);\n return;\n } else {\n return { statusCode: 200, body: response };\n }\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n const response = {};\n\n if (res) {\n res.status(200).json(response);\n return;\n } else {\n return { statusCode: 200, body: response };\n }\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n // Process data exchange request\n const result = await handler(this.client, decryptedBody);\n\n // Encrypt and send response\n const encryptedResponse = this.encryptResponse(\n result,\n Buffer.from(body.aes_key, 'base64'),\n Buffer.from(body.initial_vector, 'base64'),\n );\n\n if (res) {\n res.status(200).json(encryptedResponse);\n return;\n } else {\n return { statusCode: 200, body: encryptedResponse };\n }\n }\n\n // Unknown flow type\n const error = { error: 'Unknown request type' };\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n\n if (res) {\n res.status(400).json(error);\n return;\n } else {\n return { statusCode: 400, body: error };\n }\n } catch (error) {\n const errorResponse = { error: 'Internal server error' };\n LOGGER.log(`Error handling flow request: ${error}`);\n\n if (res) {\n res.status(500).json(errorResponse);\n return;\n } else {\n return { statusCode: 500, body: errorResponse };\n }\n }\n }\n\n /**\n * Validate the request signature\n */\n public isRequestSignatureValid(req: IRequest & { rawBody: string }): boolean {\n const signature = req.headers['x-hub-signature-256'] as string;\n if (!signature) {\n return false;\n }\n\n const expectedSignature = crypto\n .createHmac('sha256', this.config.WEBHOOK_VERIFICATION_TOKEN || '')\n .update(req.rawBody, 'utf8')\n .digest('hex');\n\n const formattedExpectedSignature = `sha256=${expectedSignature}`;\n\n return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(formattedExpectedSignature));\n }\n\n /**\n * Decrypt a flow request\n */\n public decryptRequest(body: any): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n } {\n LOGGER.log('Received body for decryption:', JSON.stringify(body, null, 2));\n\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key) {\n throw new Error('Missing required property: encrypted_aes_key');\n }\n if (!encrypted_flow_data) {\n throw new Error('Missing required property: encrypted_flow_data');\n }\n if (!initial_vector) {\n throw new Error('Missing required property: initial_vector');\n }\n\n LOGGER.log('Received body for privatePem:', JSON.stringify(this.config.FLOW_API_PRIVATE_PEM, null, 2));\n LOGGER.log('Received body for passphrase:', JSON.stringify(this.config.FLOW_API_PASSPHRASE, null, 2));\n\n const privatePem = this.config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = this.config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey = null;\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 LOGGER.error(error);\n /*\n Failed to decrypt. Please verify your private key.\n If you change your public key. You need to return HTTP status code 421 to refresh the public key on the client\n */\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n // decrypt flow data\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([\n decipher.update(encrypted_flow_data_body),\n decipher.final(),\n ]).toString('utf-8');\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n }\n\n /**\n * Encrypt a flow response\n */\n private encryptResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer) {\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 // encrypt response data\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.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(\n type: FlowTypeEnum,\n handler: (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>,\n ): 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","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 { EventField, WebhookEvent, WebhookMessage } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n// Framework-agnostic request/response types\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 EventHandler = (event: WebhookEvent) => 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: WebhookRequest, 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 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 eventHandlers: Map<string, EventHandler>;\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 === EventField.MESSAGES) {\n await processMessages(change.value, whatsapp, handlers);\n } else {\n await processEvent(change.field, change.value, handlers.eventHandlers);\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 (messages && messages.length > 0) {\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n // Add type-specific data\n Object.assign(processedMessage, getMessageTypeData(message));\n\n // Add context and errors if available\n if (message.context) processedMessage.context = message.context;\n if (message.errors) processedMessage.errors = message.errors;\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 }\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\nasync function processEvent(field: string, value: any, eventHandlers: Map<string, EventHandler>): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n timestamp: Date.now(),\n };\n\n const handler = eventHandlers.get(field);\n if (handler) {\n try {\n await handler(event);\n } catch (error) {\n LOGGER.log(`Error in event handler for ${field}: ${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 { Request, Response } from 'express';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Express request to framework-agnostic request\n */\nfunction fromExpressRequest(req: Request): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Express response\n */\nfunction toExpressResponse(webhookResponse: WebhookResponse, res: Response): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Create Express.js adapter for webhook handlers\n */\nexport function createExpressAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: Request, res: Response) => {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromExpressRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toExpressResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { FastifyReply, FastifyRequest } from 'fastify';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Fastify request to framework-agnostic request\n */\nfunction fromFastifyRequest(req: FastifyRequest): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Fastify reply\n */\nasync function toFastifyReply(webhookResponse: WebhookResponse, reply: FastifyReply): Promise<void> {\n reply.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n reply.header(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n return reply.send(webhookResponse.body);\n } else {\n return reply.send();\n }\n}\n\n/**\n * Create Fastify adapter for webhook handlers\n */\nexport function createFastifyAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = await handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n const webhookResponse = await handler(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: FastifyRequest, reply: FastifyReply) => {\n try {\n const webhookRequest = fromFastifyRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n return toFastifyReply(webhookResponse, reply);\n } else {\n return reply.status(405).send({ error: 'Method not allowed' });\n }\n } catch (error) {\n return reply.status(500).send({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { CallHandler, createParamDecorator, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';\nimport { Request, Response } from 'express';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert NestJS request to framework-agnostic request\n */\nfunction fromNestJSRequest(req: Request): WebhookRequest {\n return {\n method: req.method,\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to NestJS response\n */\nfunction toNestJSResponse(webhookResponse: WebhookResponse, res: Response): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Custom parameter decorator to inject WebhookRequest\n */\nexport const WebhookReq = createParamDecorator((data: unknown, ctx: ExecutionContext): WebhookRequest => {\n const request = ctx.switchToHttp().getRequest<Request>();\n return fromNestJSRequest(request);\n});\n\n/**\n * Interceptor to handle WebhookResponse conversion\n */\n@Injectable()\nexport class WebhookResponseInterceptor implements NestInterceptor<WebhookResponse, void> {\n intercept(context: ExecutionContext, next: CallHandler<WebhookResponse>): Observable<void> {\n const response = context.switchToHttp().getResponse<Response>();\n\n return next.handle().pipe(\n map((webhookResponse: WebhookResponse) => {\n toNestJSResponse(webhookResponse, response);\n return;\n }),\n );\n }\n}\n\n/**\n * Create NestJS adapter for webhook handlers\n */\nexport function createNestJSAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: Request, res: Response) => {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: Request, res: Response) => {\n try {\n const webhookRequest = fromNestJSRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toNestJSResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Create controller method decorator for webhook verification\n */\n createVerificationHandler: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (target: any, propertyName: string, descriptor: PropertyDescriptor) => {\n const method = descriptor.value;\n descriptor.value = function (...args: any[]) {\n const context = args.find((arg) => arg && arg.switchToHttp) as ExecutionContext;\n if (context) {\n const request = context.switchToHttp().getRequest<Request>();\n const response = context.switchToHttp().getResponse<Response>();\n const webhookRequest = fromNestJSRequest(request);\n const webhookResponse = handler(webhookRequest);\n toNestJSResponse(webhookResponse, response);\n return;\n }\n return method.apply(this, args);\n };\n };\n },\n\n /**\n * Create controller method decorator for webhook POST handling\n */\n createWebhookHandler: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return (target: any, propertyName: string, descriptor: PropertyDescriptor) => {\n const method = descriptor.value;\n descriptor.value = async function (...args: any[]) {\n const context = args.find((arg) => arg && arg.switchToHttp) as ExecutionContext;\n if (context) {\n try {\n const request = context.switchToHttp().getRequest<Request>();\n const response = context.switchToHttp().getResponse<Response>();\n const webhookRequest = fromNestJSRequest(request);\n const webhookResponse = await handler(webhookRequest);\n toNestJSResponse(webhookResponse, response);\n return;\n } catch (error) {\n const response = context.switchToHttp().getResponse<Response>();\n response.status(500).json({ error: 'Internal server error' });\n return;\n }\n }\n return method.apply(this, args);\n };\n };\n },\n };\n}\n","import { NextApiRequest, NextApiResponse } from 'next';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Next.js request to framework-agnostic request\n */\nfunction fromNextJSRequest(req: NextApiRequest): WebhookRequest {\n return {\n method: req.method || 'GET',\n query: req.query as Record<string, any>,\n body: req.body,\n headers: req.headers,\n rawBody: (req as any).rawBody || JSON.stringify(req.body),\n };\n}\n\n/**\n * Apply framework-agnostic response to Next.js response\n */\nfunction toNextJSResponse(webhookResponse: WebhookResponse, res: NextApiResponse): void {\n res.status(webhookResponse.statusCode);\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n res.send(webhookResponse.body);\n } else {\n res.json(webhookResponse.body);\n }\n } else {\n res.end();\n }\n}\n\n/**\n * Create Next.js Pages Router adapter for webhook handlers\n * For App Router, use createNextJSRouteHandlerAdapter instead\n */\nexport function createNextJSAdapter() {\n return {\n /**\n * Handle webhook verification requests\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: NextApiRequest, res: NextApiResponse) => {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n const webhookResponse = await handler(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n\n /**\n * Universal handler that routes based on method\n */\n handleRequest: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return async (req: NextApiRequest, res: NextApiResponse) => {\n try {\n const webhookRequest = fromNextJSRequest(req);\n\n if (req.method === 'GET') {\n const webhookResponse = handlers.verification(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } else if (req.method === 'POST') {\n const webhookResponse = await handlers.webhook(webhookRequest);\n toNextJSResponse(webhookResponse, res);\n } else {\n res.status(405).json({ error: 'Method not allowed' });\n }\n } catch (error) {\n res.status(500).json({ error: 'Internal server error' });\n }\n };\n },\n };\n}\n","import { NextRequest } from 'next/server';\nimport { WebhookRequest, WebhookResponse } from '../utils/webhookUtils';\n\n/**\n * Convert Route Handler request to framework-agnostic request\n */\nfunction fromRouteHandlerRequest(req: Request, searchParams?: URLSearchParams): WebhookRequest {\n return {\n method: req.method || 'GET',\n query: searchParams ? Object.fromEntries(searchParams.entries()) : {},\n body: undefined, // Will be populated when body is read\n headers: Object.fromEntries(req.headers.entries()),\n rawBody: undefined, // Will be populated when body is read\n };\n}\n\n/**\n * Apply framework-agnostic response to Route Handler response\n */\nfunction toRouteHandlerResponse(webhookResponse: WebhookResponse): Response {\n const headers = new Headers();\n\n if (webhookResponse.headers) {\n Object.entries(webhookResponse.headers).forEach(([key, value]) => {\n headers.set(key, value);\n });\n }\n\n if (webhookResponse.body !== undefined) {\n if (typeof webhookResponse.body === 'string') {\n return new Response(webhookResponse.body, {\n status: webhookResponse.statusCode,\n headers,\n });\n } else {\n headers.set('Content-Type', 'application/json');\n return new Response(JSON.stringify(webhookResponse.body), {\n status: webhookResponse.statusCode,\n headers,\n });\n }\n } else {\n return new Response(null, {\n status: webhookResponse.statusCode,\n headers,\n });\n }\n}\n\n/**\n * Create Next.js Route Handler adapter for webhook handlers\n */\nexport function createNextJSRouteHandlerAdapter() {\n return {\n /**\n * Handle webhook verification requests (GET)\n */\n handleVerification: (handler: (request: WebhookRequest) => WebhookResponse) => {\n return (req: NextRequest) => {\n const searchParams = req.nextUrl.searchParams;\n const webhookRequest = fromRouteHandlerRequest(req, searchParams);\n const webhookResponse = handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n };\n },\n\n /**\n * Handle webhook POST requests\n */\n handleWebhook: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n if (req.method === 'POST') {\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n }\n\n const webhookResponse = await handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n },\n\n /**\n * Handle flow requests\n */\n handleFlow: (handler: (request: WebhookRequest) => Promise<WebhookResponse>) => {\n return async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n if (req.method === 'POST') {\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n }\n\n const webhookResponse = await handler(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n };\n },\n\n /**\n * Universal handler that creates separate GET and POST handlers\n * Usage: export const { GET, POST } = adapter.createHandlers({ verification, webhook })\n */\n createHandlers: (handlers: {\n verification: (request: WebhookRequest) => WebhookResponse;\n webhook: (request: WebhookRequest) => Promise<WebhookResponse>;\n }) => {\n return {\n GET: (req: NextRequest) => {\n const searchParams = req.nextUrl.searchParams;\n const webhookRequest = fromRouteHandlerRequest(req, searchParams);\n const webhookResponse = handlers.verification(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n },\n\n POST: async (req: Request) => {\n try {\n const webhookRequest = fromRouteHandlerRequest(req);\n\n // Read body for POST requests\n const contentType = req.headers.get('content-type') || '';\n\n if (contentType.includes('application/json')) {\n webhookRequest.body = await req.json();\n webhookRequest.rawBody = JSON.stringify(webhookRequest.body);\n } else {\n const text = await req.text();\n webhookRequest.rawBody = text;\n webhookRequest.body = text;\n }\n\n const webhookResponse = await handlers.webhook(webhookRequest);\n return toRouteHandlerResponse(webhookResponse);\n } catch (error) {\n return new Response(JSON.stringify({ error: 'Internal server error' }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n };\n },\n };\n}\n"]}