meta-cloud-api 0.2.17 → 0.2.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -601,14 +601,23 @@ declare class WebhookHandler {
601
601
  * Handle a GET request for webhook verification
602
602
  */
603
603
  handleVerificationRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void;
604
+ handleVerificationRequest<Req extends IRequest>(req: Req): string;
604
605
  /**
605
606
  * Handle a POST request for webhook events
606
607
  */
607
608
  handleWebhookRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): Promise<void>;
609
+ handleWebhookRequest<Req extends IRequest>(req: Req): Promise<{
610
+ success: boolean;
611
+ errors?: string[];
612
+ }>;
608
613
  /**
609
614
  * Handle webhook requests (both verification and events)
610
615
  */
611
- handleRequest(req: IRequest, res: IResponse): void | Promise<void>;
616
+ handleRequest<Req extends IRequest, Res extends IResponse>(req: Req, res: Res): void | Promise<void>;
617
+ handleRequest<Req extends IRequest>(req: Req): string | Promise<{
618
+ success: boolean;
619
+ errors?: string[];
620
+ }>;
612
621
  /**
613
622
  * Process incoming messages
614
623
  */
@@ -636,6 +645,13 @@ declare class WebhookHandler {
636
645
  handleFlowRequest<Req extends IRequest & {
637
646
  rawBody: string;
638
647
  }, Res extends IResponse>(req: Req, res: Res): Promise<void>;
648
+ handleFlowRequest<Req extends IRequest & {
649
+ rawBody: string;
650
+ }>(req: Req): Promise<{
651
+ statusCode: number;
652
+ body: any;
653
+ headers?: Record<string, string>;
654
+ }>;
639
655
  /**
640
656
  * Validate the request signature
641
657
  */
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import {b as b$5}from'./chunk-O2OTHNWM.js';export{b as RegistrationApi}from'./chunk-O2OTHNWM.js';import {b as b$3}from'./chunk-7NQLQPLH.js';export{b as EncryptionApi}from'./chunk-7NQLQPLH.js';import {b as b$4}from'./chunk-UQPD6GIF.js';export{b as TwoStepVerificationApi}from'./chunk-UQPD6GIF.js';import {b as b$7}from'./chunk-5JGM556C.js';export{b as WabaApi}from'./chunk-5JGM556C.js';import {a as a$3}from'./chunk-3MO3BTBC.js';export{a as isMetaError}from'./chunk-3MO3BTBC.js';import {b as b$1}from'./chunk-2NJVBJUN.js';export{b as MessagesApi}from'./chunk-2NJVBJUN.js';import {b as b$6}from'./chunk-XPPDOFBN.js';import {b as b$9}from'./chunk-KFPOVYEJ.js';export{b as BusinessProfileApi}from'./chunk-KFPOVYEJ.js';import'./chunk-7GL74SXM.js';import {b as b$8}from'./chunk-A264MT4Q.js';export{b as FlowApi}from'./chunk-A264MT4Q.js';import {b as b$2}from'./chunk-GIQLIMOD.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';import {a as a$1}from'./chunk-XIIJD6SG.js';export{b as TemplateApi}from'./chunk-XIIJD6SG.js';import'./chunk-BZ5QDXNR.js';import {a as a$2}from'./chunk-FFOE5YKT.js';export{b as QrCodeApi}from'./chunk-FFOE5YKT.js';import {a}from'./chunk-VW3LGHTJ.js';import {z}from'./chunk-EYGUX4EA.js';export{c as HttpMethodsEnum,d as MessageTypesEnum,l as StatusEnum,r as WebhookTypesEnum}from'./chunk-EYGUX4EA.js';import'./chunk-4C666HHU.js';import g from'crypto';import {Agent}from'https';function K(r){return typeof r=="object"&&r!==null}function y(r){return typeof r=="string"}var se=["data_exchange","INIT","BACK"],te=["data_exchange","INIT"];function B(r){if(!("flow_token"in r&&y(r.flow_token)&&"action"in r))return false;let{action:e,version:s,screen:t,data:o}=r,a=s==="3.0",p=se.includes(e),n=typeof t>"u"||y(t)&&t!=="SUCCESS",d=e==="data_exchange"||K(o);return a&&p&&n&&d}function F(r){if(!("flow_token"in r&&y(r.flow_token)&&"action"in r))return false;let{action:e,screen:s,data:t}=r,o=te.includes(e),a=y(s),p=K(t)&&"error_key"in t&&y(t.error)&&"error_message"in t&&y(t.error_message);return o&&a&&p}function H(r){return "action"in r&&r.action==="ping"}var oe="UTILS",re=false,Q=new a(oe,process.env.DEBUG==="true"||re),ne=3e3,ae=30,ie=2e4,pe=r=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!r?.accessToken)throw Q.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},R=r=>{pe(r);let e={M4D_APP_ID:r?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:r?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:r?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:r?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:r?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:r?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:r?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:r?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:r?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||ne,MAX_RETRIES_AFTER_WAIT:r?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||ae,REQUEST_TIMEOUT:r?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||ie,DEBUG:r?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:r?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:r?.passphrase||process.env.FLOW_API_PASSPHRASE||""};return Q.log(`Configuration loaded for App Id ${e.M4D_APP_ID}`),e};var ue="HttpsClient",de=false,J=new a(ue,process.env.DEBUG==="true"||de),E=class{agent;constructor(){this.agent=new Agent({keepAlive:true});}clearSockets(){return this.agent.destroy(),true}async sendRequest(e,s,t,o,a,p){let n=`https://${e}/${s}`,d=new AbortController,i=setTimeout(()=>d.abort(),a);try{let u=await fetch(n,{method:t,headers:o,body:p,signal:d.signal});return J.log(`${t} : ${n} - ${JSON.stringify(u)}`),clearTimeout(i),new N(u)}catch(u){throw J.error(`${t} : ${n} - ${JSON.stringify(u)}`),u}}},N=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries());}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};var le="REQUESTER",me=false,fe=new a(le,process.env.DEBUG==="true"||me),b=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,s,t,o,a){this.client=new E,this.host="graph.facebook.com",this.apiVersion=e||"22",this.phoneNumberId=s,this.accessToken=t,this.businessAcctId=o,this.userAgent=a;}buildHeader(e,s){let t={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(t["Content-Type"]=e),s&&Object.assign(t,s),t}buildCAPIPath(e){return `v${this.apiVersion}.0/${e}`}async sendRequest(e,s,t,o,a="application/json",p){let n=a;o instanceof FormData?n="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(n="application/xml");let d=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;fe.log(`${e} : ${d} (${n})`);try{let i=await this.client.sendRequest(this.host,this.buildCAPIPath(s),e,this.buildHeader(n,p),t,e==="POST"||e==="PUT"?o:void 0);if(!i.rawResponse().ok){let u=await i.json();throw a$3(u)?u:{name:"MetaError",message:"Unknown error occurred",error:{message:u.message||"Unknown error occurred",type:"UnknownError",code:i.statusCode(),fbtrace_id:""}}}return i}catch(i){throw a$3(i)?i:{name:"MetaError",message:i instanceof Error?i.message:"Network error occurred",error:{message:i instanceof Error?i.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,s,t,o,a){return await(await this.sendRequest(e,s,t,o,"application/json",a)).json()}async sendFormData(e,s,t,o,a){return await(await this.sendRequest(e,s,t,o,"multipart/form-data",a)).json()}async sendUrlEncodedForm(e,s,t,o,a){let p=new URLSearchParams(o).toString();return await(await this.sendRequest(e,s,t,p,"application/x-www-form-urlencoded",a)).json()}};var ge="WHATSAPP",he=false,A=new a(ge,process.env.DEBUG==="true"||he),ye="WA_SDK",f=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=z;constructor(e){this.config=R(e),this.requester=new b(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new b$1(this.config,this.requester),this.templates=new a$1(this.config,this.requester),this.phoneNumber=new b$2(this.config,this.requester),this.qrCode=new a$2(this.config,this.requester),this.encryption=new b$3(this.config,this.requester),this.twoStepVerification=new b$4(this.config,this.requester),this.registration=new b$5(this.config,this.requester),this.media=new b$6(this.config,this.requester),this.waba=new b$7(this.config,this.requester),this.flow=new b$8(this.config,this.requester),this.businessProfile=new b$9(this.config,this.requester),A.log("WhatsApp Node.js SDK instantiated!");}userAgent(){return `${ye}/0.0.1 (Node.js ${process.version})`}updateTimeout(e){return this.config.REQUEST_TIMEOUT=e,A.log(`Updated request timeout to ${e}ms`),true}updatePhoneNumberId(e){return this.config.WA_PHONE_NUMBER_ID=e,A.log(`Updated sender phone number id to ${e}`),true}updateAccessToken(e){return this.config.CLOUD_API_ACCESS_TOKEN=e,A.log("Updated access token"),true}updateWabaId(e){return this.config.WA_BUSINESS_ACCOUNT_ID=e,A.log(`Updated business account id to ${e}`),true}};var Re="WEBHOOK",Ee=false,c=new a(Re,process.env.DEBUG==="true"||Ee),w=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(e){let s=R(e);this.config=s,this.client=new f(e),c.log("WebhookHandler instantiated!");}handleVerificationRequest(e,s){let t=e.query["hub.mode"],o=e.query["hub.verify_token"],a=e.query["hub.challenge"];t==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?(c.log("Webhook verified successfully"),s.status(200).send(a)):(c.log("Webhook verification failed"),s.status(403).end());}async handleWebhookRequest(e,s){let t=e.body;if(t.object!=="whatsapp_business_account"){c.log("Received webhook for non-WhatsApp event"),s.status(404).end();return}for(let o of t.entry)try{let a=o.changes;for(let p of a)p.field==="messages"?await this.processMessages(p.value):await this.processEvent(p.field,p.value);}catch(a){c.log(`Error processing webhook: ${a}`);}s.status(200).end();}handleRequest(e,s){if(e.method==="GET")return this.handleVerificationRequest(e,s);if(e.method==="POST")return this.handleWebhookRequest(e,s);s.status(405).end();}async processMessages(e){let s=e.metadata,t=s.display_phone_number,o=s.phone_number_id,a=e.contacts[0].profile.name,p=e.messages;if(p&&p.length>0)for(let n of p){let d=n.type,i={id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:o,displayPhoneNumber:t,profileName:a,originalData:n};switch(n.type){case "text":i.text=n.text;break;case "image":i.image=n.image;break;case "video":i.video=n.video;break;case "audio":i.audio=n.audio;break;case "document":i.document=n.document;break;case "sticker":i.sticker=n.sticker;break;case "location":i.location=n.location;break;case "contacts":i.contacts=n.contacts;break;case "interactive":i.interactive=n.interactive;break;case "button":i.button=n.button;break;case "order":i.order=n.order;break;case "system":i.system=n.system;break;}if(n.context&&(i.context=n.context),n.errors&&(i.errors=n.errors),this.preProcessHandler)try{await this.preProcessHandler(this.client,i);}catch(m){c.log(`Error in pre-process handler: ${m}`);}let u=this.messageHandlers.get(d);if(u)try{await u(this.client,i);}catch(m){c.log(`Error in message handler for ${d}: ${m}`);}if(this.postProcessHandler)try{await this.postProcessHandler(this.client,i);}catch(m){c.log(`Error in post-process handler: ${m}`);}}}async processEvent(e,s){let t={field:e,value:s,timestamp:Date.now()},o=this.eventHandlers.get(e);if(o)try{await o(t);}catch(a){c.log(`Error in event handler for ${e}: ${a}`);}}onMessage(e,s){this.messageHandlers.set(e,s),c.log(`Registered message handler for ${e}`);}onEvent(e,s){this.eventHandlers.set(e,s),c.log(`Registered event handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,c.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,c.log("Registered post-process handler");}async handleFlowRequest(e,s){try{if(!this.isRequestSignatureValid(e)){c.log("Invalid request signature"),s.status(401).json({error:"Unauthorized"});return}let t=JSON.parse(e.rawBody),{decryptedBody:o}=this.decryptRequest(t),a=this.flowHandlers.get("*");if(!a){c.log(`No handler registered for flow action: ${o.action}`),s.status(404).json({error:"Handler not found"});return}if(H(o)){let p={version:"3.0",data:{status:"active"}};s.status(200).json(p);return}if(F(o)){c.log(`Flow error: ${JSON.stringify(o)}`),s.status(200).json({});return}if(B(o)){let p=await a(this.client,o),n=this.encryptResponse(p,Buffer.from(t.aes_key,"base64"),Buffer.from(t.initial_vector,"base64"));s.status(200).json(n);return}c.log(`Unknown flow request type: ${JSON.stringify(o)}`),s.status(400).json({error:"Unknown request type"});}catch(t){c.log(`Error handling flow request: ${t}`),s.status(500).json({error:"Internal server error"});}}isRequestSignatureValid(e){let s=e.headers["x-hub-signature-256"];if(!s)return false;let o=`sha256=${g.createHmac("sha256",this.config.WEBHOOK_VERIFICATION_TOKEN||"").update(e.rawBody,"utf8").digest("hex")}`;return g.timingSafeEqual(Buffer.from(s),Buffer.from(o))}decryptRequest(e){c.log("Received body for decryption:",JSON.stringify(e,null,2));let{encrypted_aes_key:s,encrypted_flow_data:t,initial_vector:o}=e;if(!s)throw new Error("Missing required property: encrypted_aes_key");if(!t)throw new Error("Missing required property: encrypted_flow_data");if(!o)throw new Error("Missing required property: initial_vector");c.log("Received body for privatePem:",JSON.stringify(this.config.FLOW_API_PRIVATE_PEM,null,2)),c.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
- `),p=this.config.FLOW_API_PASSPHRASE,n=g.createPrivateKey({key:a,passphrase:p}),d=null;try{d=g.privateDecrypt({key:n,padding:g.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(s,"base64"));}catch(Z){throw c.error(Z),new Error("Failed to decrypt the request. Please verify your private key.")}let i=Buffer.from(t,"base64"),u=Buffer.from(o,"base64"),X=i.subarray(0,-16),z=i.subarray(-16),q=g.createDecipheriv("aes-128-gcm",d,u);q.setAuthTag(z);let Y=Buffer.concat([q.update(X),q.final()]).toString("utf-8");return {decryptedBody:JSON.parse(Y),aesKeyBuffer:d,initialVectorBuffer:u}}encryptResponse(e,s,t){let o=[];for(let a of Array.from(t.entries()))o.push(~a[1]);try{let a=g.createCipheriv("aes-128-gcm",s,Buffer.from(o));return Buffer.concat([a.update(JSON.stringify(e||{}),"utf-8"),a.final(),a.getAuthTag()]).toString("base64")}catch(a){throw c.error("Response encryption error:",a),new Error("Failed to encrypt response. Internal server error.")}}onFlow(e,s){this.flowHandlers.set(e,s),c.log(`Registered flow handler for ${e}`);}};var Gs=f;export{w as WebhookHandler,Gs as default,R as importConfig};//# sourceMappingURL=index.js.map
1
+ import {b as b$5}from'./chunk-O2OTHNWM.js';export{b as RegistrationApi}from'./chunk-O2OTHNWM.js';import {b as b$3}from'./chunk-7NQLQPLH.js';export{b as EncryptionApi}from'./chunk-7NQLQPLH.js';import {b as b$4}from'./chunk-UQPD6GIF.js';export{b as TwoStepVerificationApi}from'./chunk-UQPD6GIF.js';import {b as b$7}from'./chunk-5JGM556C.js';export{b as WabaApi}from'./chunk-5JGM556C.js';import {a as a$3}from'./chunk-3MO3BTBC.js';export{a as isMetaError}from'./chunk-3MO3BTBC.js';import {b as b$1}from'./chunk-2NJVBJUN.js';export{b as MessagesApi}from'./chunk-2NJVBJUN.js';import {b as b$6}from'./chunk-XPPDOFBN.js';import {b as b$9}from'./chunk-KFPOVYEJ.js';export{b as BusinessProfileApi}from'./chunk-KFPOVYEJ.js';import'./chunk-7GL74SXM.js';import {b as b$8}from'./chunk-A264MT4Q.js';export{b as FlowApi}from'./chunk-A264MT4Q.js';import {b as b$2}from'./chunk-GIQLIMOD.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';import {a as a$1}from'./chunk-XIIJD6SG.js';export{b as TemplateApi}from'./chunk-XIIJD6SG.js';import'./chunk-BZ5QDXNR.js';import {a as a$2}from'./chunk-FFOE5YKT.js';export{b as QrCodeApi}from'./chunk-FFOE5YKT.js';import {a}from'./chunk-VW3LGHTJ.js';import {z}from'./chunk-EYGUX4EA.js';export{c as HttpMethodsEnum,d as MessageTypesEnum,l as StatusEnum,r as WebhookTypesEnum}from'./chunk-EYGUX4EA.js';import'./chunk-4C666HHU.js';import g from'crypto';import {Agent}from'https';function K(n){return typeof n=="object"&&n!==null}function R(n){return typeof n=="string"}var se=["data_exchange","INIT","BACK"],te=["data_exchange","INIT"];function F(n){if(!("flow_token"in n&&R(n.flow_token)&&"action"in n))return false;let{action:e,version:s,screen:r,data:o}=n,a=s==="3.0",c=se.includes(e),t=typeof r>"u"||R(r)&&r!=="SUCCESS",u=e==="data_exchange"||K(o);return a&&c&&t&&u}function B(n){if(!("flow_token"in n&&R(n.flow_token)&&"action"in n))return false;let{action:e,screen:s,data:r}=n,o=te.includes(e),a=R(s),c=K(r)&&"error_key"in r&&R(r.error)&&"error_message"in r&&R(r.error_message);return o&&a&&c}function N(n){return "action"in n&&n.action==="ping"}var oe="UTILS",re=false,Q=new a(oe,process.env.DEBUG==="true"||re),ne=3e3,ae=30,ie=2e4,pe=n=>{if(!process.env.CLOUD_API_ACCESS_TOKEN&&!n?.accessToken)throw Q.log("Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined."),new Error("Missing WhatsApp access token.")},y=n=>{pe(n);let e={M4D_APP_ID:n?.appId||process.env.M4D_APP_ID||"",M4D_APP_SECRET:n?.appSecret||process.env.M4D_APP_SECRET||"",WA_PHONE_NUMBER_ID:n?.phoneNumberId||Number(process.env.WA_PHONE_NUMBER_ID),WA_BUSINESS_ACCOUNT_ID:n?.businessAcctId||process.env.WA_BUSINESS_ACCOUNT_ID||"",CLOUD_API_VERSION:n?.apiVersion||process.env.CLOUD_API_VERSION||"",CLOUD_API_ACCESS_TOKEN:n?.accessToken||process.env.CLOUD_API_ACCESS_TOKEN||"",WEBHOOK_ENDPOINT:n?.webhookEndpoint||process.env.WEBHOOK_ENDPOINT||"",WEBHOOK_VERIFICATION_TOKEN:n?.webhookVerificationToken||process.env.WEBHOOK_VERIFICATION_TOKEN||"",LISTENER_PORT:n?.listenerPort||parseInt(process.env.LISTENER_PORT||"")||ne,MAX_RETRIES_AFTER_WAIT:n?.maxRetriesAfterWait||parseInt(process.env.MAX_RETRIES_AFTER_WAIT||"")||ae,REQUEST_TIMEOUT:n?.requestTimeout||parseInt(process.env.REQUEST_TIMEOUT||"")||ie,DEBUG:n?.debug||process.env.DEBUG==="true",FLOW_API_PRIVATE_PEM:n?.privatePem||process.env.FLOW_API_PRIVATE_PEM||"",FLOW_API_PASSPHRASE:n?.passphrase||process.env.FLOW_API_PASSPHRASE||""};return Q.log(`Configuration loaded for App Id ${e.M4D_APP_ID}`),e};var ue="HttpsClient",de=false,J=new a(ue,process.env.DEBUG==="true"||de),E=class{agent;constructor(){this.agent=new Agent({keepAlive:true});}clearSockets(){return this.agent.destroy(),true}async sendRequest(e,s,r,o,a,c){let t=`https://${e}/${s}`,u=new AbortController,i=setTimeout(()=>u.abort(),a);try{let d=await fetch(t,{method:r,headers:o,body:c,signal:u.signal});return J.log(`${r} : ${t} - ${JSON.stringify(d)}`),clearTimeout(i),new H(d)}catch(d){throw J.error(`${r} : ${t} - ${JSON.stringify(d)}`),d}}},H=class{res;respStatusCode;respHeaders;constructor(e){this.res=e,this.respStatusCode=e.status,this.respHeaders=Object.fromEntries(e.headers.entries());}statusCode(){return this.respStatusCode}headers(){return this.respHeaders}rawResponse(){return this.res}async json(){try{return await this.res.json()}catch(e){throw new Error("Failed to parse response body to JSON: "+e.message)}}};var le="REQUESTER",me=false,fe=new a(le,process.env.DEBUG==="true"||me),b=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,s,r,o,a){this.client=new E,this.host="graph.facebook.com",this.apiVersion=e||"22",this.phoneNumberId=s,this.accessToken=r,this.businessAcctId=o,this.userAgent=a;}buildHeader(e,s){let r={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(r["Content-Type"]=e),s&&Object.assign(r,s),r}buildCAPIPath(e){return `v${this.apiVersion}.0/${e}`}async sendRequest(e,s,r,o,a="application/json",c){let t=a;o instanceof FormData?t="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(t="application/xml");let u=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;fe.log(`${e} : ${u} (${t})`);try{let i=await this.client.sendRequest(this.host,this.buildCAPIPath(s),e,this.buildHeader(t,c),r,e==="POST"||e==="PUT"?o:void 0);if(!i.rawResponse().ok){let d=await i.json();throw a$3(d)?d:{name:"MetaError",message:"Unknown error occurred",error:{message:d.message||"Unknown error occurred",type:"UnknownError",code:i.statusCode(),fbtrace_id:""}}}return i}catch(i){throw a$3(i)?i:{name:"MetaError",message:i instanceof Error?i.message:"Network error occurred",error:{message:i instanceof Error?i.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,s,r,o,a){return await(await this.sendRequest(e,s,r,o,"application/json",a)).json()}async sendFormData(e,s,r,o,a){return await(await this.sendRequest(e,s,r,o,"multipart/form-data",a)).json()}async sendUrlEncodedForm(e,s,r,o,a){let c=new URLSearchParams(o).toString();return await(await this.sendRequest(e,s,r,c,"application/x-www-form-urlencoded",a)).json()}};var ge="WHATSAPP",he=false,A=new a(ge,process.env.DEBUG==="true"||he),Re="WA_SDK",f=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=z;constructor(e){this.config=y(e),this.requester=new b(this.config.CLOUD_API_VERSION,this.config.WA_PHONE_NUMBER_ID,this.config.CLOUD_API_ACCESS_TOKEN,this.config.WA_BUSINESS_ACCOUNT_ID,this.userAgent()),this.messages=new b$1(this.config,this.requester),this.templates=new a$1(this.config,this.requester),this.phoneNumber=new b$2(this.config,this.requester),this.qrCode=new a$2(this.config,this.requester),this.encryption=new b$3(this.config,this.requester),this.twoStepVerification=new b$4(this.config,this.requester),this.registration=new b$5(this.config,this.requester),this.media=new b$6(this.config,this.requester),this.waba=new b$7(this.config,this.requester),this.flow=new b$8(this.config,this.requester),this.businessProfile=new b$9(this.config,this.requester),A.log("WhatsApp Node.js SDK instantiated!");}userAgent(){return `${Re}/0.0.1 (Node.js ${process.version})`}updateTimeout(e){return this.config.REQUEST_TIMEOUT=e,A.log(`Updated request timeout to ${e}ms`),true}updatePhoneNumberId(e){return this.config.WA_PHONE_NUMBER_ID=e,A.log(`Updated sender phone number id to ${e}`),true}updateAccessToken(e){return this.config.CLOUD_API_ACCESS_TOKEN=e,A.log("Updated access token"),true}updateWabaId(e){return this.config.WA_BUSINESS_ACCOUNT_ID=e,A.log(`Updated business account id to ${e}`),true}};var ye="WEBHOOK",Ee=false,p=new a(ye,process.env.DEBUG==="true"||Ee),w=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(e){let s=y(e);this.config=s,this.client=new f(e),p.log("WebhookHandler instantiated!");}handleVerificationRequest(e,s){let r=e.query["hub.mode"],o=e.query["hub.verify_token"],a=e.query["hub.challenge"];if(r==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN)if(p.log("Webhook verified successfully"),s){s.status(200).send(a);return}else return p.log("Returning challenge for manual handling"),a;else if(p.log("Webhook verification failed"),s){s.status(403).end();return}else throw p.log("Verification failed - throwing error for manual handling"),new Error("Webhook verification failed")}async handleWebhookRequest(e,s){let r=e.body,o=[];if(r.object!=="whatsapp_business_account"){let a="Received webhook for non-WhatsApp event";if(p.log(a),s){s.status(404).end();return}else return o.push(a),{success:false,errors:o}}for(let a of r.entry)try{let c=a.changes;for(let t of c)t.field==="messages"?await this.processMessages(t.value):await this.processEvent(t.field,t.value);}catch(c){let t=`Error processing webhook: ${c}`;p.log(t),o.push(t);}if(s){s.status(200).end();return}else return {success:o.length===0,errors:o.length>0?o:void 0}}handleRequest(e,s){if(e.method==="GET")return s?this.handleVerificationRequest(e,s):this.handleVerificationRequest(e);if(e.method==="POST")return s?this.handleWebhookRequest(e,s):this.handleWebhookRequest(e);if(s){s.status(405).end();return}else throw new Error("Method not allowed")}async processMessages(e){let s=e.metadata,r=s.display_phone_number,o=s.phone_number_id,a=e.contacts[0].profile.name,c=e.messages;if(c&&c.length>0)for(let t of c){let u=t.type,i={id:t.id,from:t.from,timestamp:t.timestamp,type:t.type,phoneNumberId:o,displayPhoneNumber:r,profileName:a,originalData:t};switch(t.type){case "text":i.text=t.text;break;case "image":i.image=t.image;break;case "video":i.video=t.video;break;case "audio":i.audio=t.audio;break;case "document":i.document=t.document;break;case "sticker":i.sticker=t.sticker;break;case "location":i.location=t.location;break;case "contacts":i.contacts=t.contacts;break;case "interactive":i.interactive=t.interactive;break;case "button":i.button=t.button;break;case "order":i.order=t.order;break;case "system":i.system=t.system;break;}if(t.context&&(i.context=t.context),t.errors&&(i.errors=t.errors),this.preProcessHandler)try{await this.preProcessHandler(this.client,i);}catch(m){p.log(`Error in pre-process handler: ${m}`);}let d=this.messageHandlers.get(u);if(d)try{await d(this.client,i);}catch(m){p.log(`Error in message handler for ${u}: ${m}`);}if(this.postProcessHandler)try{await this.postProcessHandler(this.client,i);}catch(m){p.log(`Error in post-process handler: ${m}`);}}}async processEvent(e,s){let r={field:e,value:s,timestamp:Date.now()},o=this.eventHandlers.get(e);if(o)try{await o(r);}catch(a){p.log(`Error in event handler for ${e}: ${a}`);}}onMessage(e,s){this.messageHandlers.set(e,s),p.log(`Registered message handler for ${e}`);}onEvent(e,s){this.eventHandlers.set(e,s),p.log(`Registered event handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,p.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,p.log("Registered post-process handler");}async handleFlowRequest(e,s){try{if(!this.isRequestSignatureValid(e)){let t={error:"Unauthorized"};if(p.log("Invalid request signature"),s){s.status(401).json(t);return}else return {statusCode:401,body:t}}let r=JSON.parse(e.rawBody),{decryptedBody:o}=this.decryptRequest(r),a=this.flowHandlers.get("*");if(!a){let t={error:"Handler not found"};if(p.log(`No handler registered for flow action: ${o.action}`),s){s.status(404).json(t);return}else return {statusCode:404,body:t}}if(N(o)){let t={version:"3.0",data:{status:"active"}};if(s){s.status(200).json(t);return}else return {statusCode:200,body:t}}if(B(o)){p.log(`Flow error: ${JSON.stringify(o)}`);let t={};if(s){s.status(200).json(t);return}else return {statusCode:200,body:t}}if(F(o)){let t=await a(this.client,o),u=this.encryptResponse(t,Buffer.from(r.aes_key,"base64"),Buffer.from(r.initial_vector,"base64"));if(s){s.status(200).json(u);return}else return {statusCode:200,body:u}}let c={error:"Unknown request type"};if(p.log(`Unknown flow request type: ${JSON.stringify(o)}`),s){s.status(400).json(c);return}else return {statusCode:400,body:c}}catch(r){let o={error:"Internal server error"};if(p.log(`Error handling flow request: ${r}`),s){s.status(500).json(o);return}else return {statusCode:500,body:o}}}isRequestSignatureValid(e){let s=e.headers["x-hub-signature-256"];if(!s)return false;let o=`sha256=${g.createHmac("sha256",this.config.WEBHOOK_VERIFICATION_TOKEN||"").update(e.rawBody,"utf8").digest("hex")}`;return g.timingSafeEqual(Buffer.from(s),Buffer.from(o))}decryptRequest(e){p.log("Received body for decryption:",JSON.stringify(e,null,2));let{encrypted_aes_key:s,encrypted_flow_data:r,initial_vector:o}=e;if(!s)throw new Error("Missing required property: encrypted_aes_key");if(!r)throw new Error("Missing required property: encrypted_flow_data");if(!o)throw new Error("Missing required property: initial_vector");p.log("Received body for privatePem:",JSON.stringify(this.config.FLOW_API_PRIVATE_PEM,null,2)),p.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
+ `),c=this.config.FLOW_API_PASSPHRASE,t=g.createPrivateKey({key:a,passphrase:c}),u=null;try{u=g.privateDecrypt({key:t,padding:g.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(s,"base64"));}catch(Z){throw p.error(Z),new Error("Failed to decrypt the request. Please verify your private key.")}let i=Buffer.from(r,"base64"),d=Buffer.from(o,"base64"),X=i.subarray(0,-16),z=i.subarray(-16),_=g.createDecipheriv("aes-128-gcm",u,d);_.setAuthTag(z);let Y=Buffer.concat([_.update(X),_.final()]).toString("utf-8");return {decryptedBody:JSON.parse(Y),aesKeyBuffer:u,initialVectorBuffer:d}}encryptResponse(e,s,r){let o=[];for(let a of Array.from(r.entries()))o.push(~a[1]);try{let a=g.createCipheriv("aes-128-gcm",s,Buffer.from(o));return Buffer.concat([a.update(JSON.stringify(e||{}),"utf-8"),a.final(),a.getAuthTag()]).toString("base64")}catch(a){throw p.error("Response encryption error:",a),new Error("Failed to encrypt response. Internal server error.")}}onFlow(e,s){this.flowHandlers.set(e,s),p.log(`Registered flow handler for ${e}`);}};var Gs=f;export{w as WebhookHandler,Gs as default,y as importConfig};//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/shared/config/importConfig.ts","../src/shared/http/httpsClient.ts","../src/shared/http/request.ts","../src/core/whatsapp/WhatsApp.ts","../src/core/webhook/WebhookHandler.ts","../src/index.ts"],"names":["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","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","wabaConfig","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","contentType","additionalHeaders","endpoint","effectiveContentType","errorData","isMetaError","formData","urlEncodedBody","headerPrefix","WhatsApp","enums_exports","messages_default","TemplateApi","phone_default","QrCodeApi","encryption_default","twoStepVerification_default","registration_default","media_default","waba_default","flow_default","profile_default","ms","wabaId","WebhookHandler","configuration","req","res","mode","token","challenge","entry","changes","change","metadata","displayPhoneNumber","profileName","messages","message","messageType","processedMessage","handler","field","event","type","decryptedBody","result","encryptedResponse","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","src_default"],"mappings":"y3CAaA,SAASA,CAAAA,CAASC,CAAkD,CAAA,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,CAASD,CAAAA,CAAAA,CAAiC,CAC/C,OAAO,OAAOA,CAAU,EAAA,QAC5B,CAGA,IAAME,EAAwB,CAAA,CAAA,eAAA,CAAA,MAAA,CAAA,MAAuE,CAG/FC,CAAAA,EAAAA,CAAgB,CAAkD,eAAA,CAAA,MAAA,CAAA,CASjE,SAASC,CAAAA,CAA0BC,EAKxC,CAEE,GAAI,EAAE,YAAA,GAAgBA,CAAWJ,EAAAA,CAAAA,CAASI,CAAQ,CAAA,UAAU,CAAK,EAAA,QAAA,GAAYA,CACzE,CAAA,CAAA,OAAO,MAGX,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AAMC,CAAmB,CAAA,CAC7C,aAAcN,CACd,CAAA,mBAAA,CAAAE,CACJ,CACJ,CAKQ,eAAA,CAAgBtE,EAAe2E,CAAsBL,CAAAA,CAAAA,CAA6B,CACtF,IAAMM,CAAuB,CAAA,GAC7B,IAAWC,IAAAA,CAAAA,IAAQ,KAAM,CAAA,IAAA,CAAKP,CAAoB,CAAA,OAAA,EAAS,CACvDM,CAAAA,CAAAA,CAAW,IAAK,CAAA,CAACC,CAAK,CAAA,CAAC,CAAC,CAG5B,CAAA,GAAI,CAEA,IAAMC,CAASjB,CAAAA,CAAAA,CAAO,eAAe,aAAec,CAAAA,CAAAA,CAAc,MAAO,CAAA,IAAA,CAAKC,CAAU,CAAC,EACzF,OAAO,MAAA,CAAO,MAAO,CAAA,CACjBE,CAAO,CAAA,MAAA,CAAO,KAAK,SAAU9E,CAAAA,CAAAA,EAAY,EAAE,CAAA,CAAG,OAAO,CACrD8E,CAAAA,CAAAA,CAAO,KAAM,EAAA,CACbA,CAAO,CAAA,UAAA,EACX,CAAC,CAAA,CAAE,QAAS,CAAA,QAAQ,CACxB,CAAA,MAAS5E,EAAO,CACZ,MAAAvB,CAAO,CAAA,KAAA,CAAM,4BAA8BuB,CAAAA,CAAK,EAC1C,IAAI,KAAA,CAAM,oDAAoD,CACxE,CACJ,CAKO,OACHqD,CACAH,CAAAA,CAAAA,CACI,CACJ,IAAA,CAAK,YAAa,CAAA,GAAA,CAAIG,EAAMH,CAAO,CAAA,CACnCzE,CAAO,CAAA,GAAA,CAAI,CAA+B4E,4BAAAA,EAAAA,CAAI,EAAE,EACpD,CACJ,EC3dA,IAAOwB,EAAQ3D,CAAAA","file":"index.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n LOGGER.log(`Configuration loaded for App Id ${wabaConfig[WabaConfigEnum.AppId]}`);\n\n return wabaConfig;\n};\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../types/httpsClient';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n LOGGER.error(`${method} : ${url} - ${JSON.stringify(error)}`);\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import type { HttpMethodsEnum } from '../types/enums';\nimport type { RequesterClass } from '../types/request';\nimport { isMetaError, MetaError } from '../utils/isMetaError';\nimport Logger from '../utils/logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","import { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport * as SDKEnums from '@shared/types/enums';\nimport Logger from '@shared/utils/logger';\n\nimport EncryptionApi from '@features/encryption';\nimport FlowApi from '@features/flow';\nimport MediaApi from '@features/media';\nimport MessagesApi from '@features/messages';\nimport PhoneNumberApi from '@features/phone';\nimport BusinessProfileApi from '@features/profile';\nimport QrCodeApi from '@features/qrCode/QrCodeApi';\nimport RegistrationApi from '@features/registration';\nimport TemplateApi from '@features/template/TemplateApi';\nimport TwoStepVerificationApi from '@features/twoStepVerification';\nimport WabaApi from '@features/waba';\nimport { importConfig } from '@shared/config/importConfig';\nimport Requester from '@shared/http/request';\nimport { WhatsAppClass } from './types';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nconst headerPrefix = 'WA_SDK';\n\nexport default class WhatsApp implements WhatsAppClass {\n config: WabaConfigType;\n\n requester: Readonly<Requester>;\n\n readonly messages: MessagesApi;\n readonly templates: TemplateApi;\n readonly phoneNumber: PhoneNumberApi;\n readonly qrCode: QrCodeApi;\n readonly encryption: EncryptionApi;\n readonly twoStepVerification: TwoStepVerificationApi;\n readonly registration: RegistrationApi;\n readonly media: MediaApi;\n readonly waba: WabaApi;\n readonly flow: FlowApi;\n readonly businessProfile: BusinessProfileApi;\n static readonly Enums = SDKEnums;\n\n constructor(config?: WhatsAppConfig) {\n this.config = importConfig(config);\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.userAgent(),\n );\n\n this.messages = new MessagesApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.phoneNumber = new PhoneNumberApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n this.flow = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n LOGGER.log('WhatsApp Node.js SDK instantiated!');\n }\n\n private userAgent(): string {\n const userAgentString = `${headerPrefix}/${'0.0.1'} (Node.js ${process.version})`;\n return userAgentString;\n }\n\n updateTimeout(ms: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = ms;\n LOGGER.log(`Updated request timeout to ${ms}ms`);\n return true;\n }\n\n updatePhoneNumberId(phoneNumberId: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Updated sender phone number id to ${phoneNumberId}`);\n return true;\n }\n\n updateAccessToken(accessToken: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n LOGGER.log(`Updated access token`);\n return true;\n }\n\n updateWabaId(wabaId: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId] = wabaId;\n LOGGER.log(`Updated business account id to ${wabaId}`);\n return true;\n }\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 const mode = req.query['hub.mode'];\n const token = req.query['hub.verify_token'];\n const challenge = req.query['hub.challenge'];\n\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n LOGGER.log('Webhook verified successfully');\n res.status(200).send(challenge);\n } else {\n LOGGER.log('Webhook verification failed');\n res.status(403).end();\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 const body = req.body;\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n LOGGER.log('Received webhook for non-WhatsApp event');\n res.status(404).end();\n return;\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 LOGGER.log(`Error processing webhook: ${error}`);\n }\n }\n\n // Always respond with 200 to acknowledge receipt\n res.status(200).end();\n }\n\n /**\n * Handle webhook requests (both verification and events)\n */\n public handleRequest(req: IRequest, res: IResponse): void | Promise<void> {\n if (req.method === 'GET') {\n return this.handleVerificationRequest(req, res);\n } else if (req.method === 'POST') {\n return this.handleWebhookRequest(req, res);\n } else {\n res.status(405).end(); // Method not allowed\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 try {\n // Validate request signature\n if (!this.isRequestSignatureValid(req)) {\n LOGGER.log('Invalid request signature');\n res.status(401).json({ error: 'Unauthorized' });\n return;\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 LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n res.status(404).json({ error: 'Handler not found' });\n return;\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 res.status(200).json(response);\n return;\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n res.status(200).json({});\n return;\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 res.status(200).json(encryptedResponse);\n return;\n }\n\n // Unknown flow type\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n res.status(400).json({ error: 'Unknown request type' });\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n res.status(500).json({ error: 'Internal server error' });\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 { WebhookHandler } from './core/webhook';\nimport { WhatsApp } from './core/whatsapp';\n\nexport default WhatsApp;\n\nexport type { IRequest, IResponse } from './core/webhook';\nexport { WebhookHandler };\n\nexport {\n BusinessProfileApi,\n EncryptionApi,\n FlowApi,\n MessagesApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n TemplateApi,\n TwoStepVerificationApi,\n WabaApi,\n} from './features';\n\nexport type {\n AudioMediaObject,\n BusinessProfileClass,\n BusinessProfileResponse,\n ContactObject,\n DocumentMediaObject,\n Flow,\n FlowClass,\n FlowEndpointRequest,\n FlowEndpointResponse,\n ImageMediaObject,\n InteractiveObject,\n LocationObject,\n MediaClass,\n MediaResponse,\n MediasResponse,\n MessageRequestParams,\n MessagesResponse,\n MessageTemplateObject,\n PhoneNumberClass,\n PhoneNumberResponse,\n QrCodeClass,\n QrCodeResponse,\n ReactionParams,\n RegistrationClass,\n StatusParams,\n StickerMediaObject,\n TemplateClass,\n TemplateResponse,\n TextMessageParams,\n TextObject,\n UploadMediaResponse,\n VideoMediaObject,\n WabaAccount,\n WABAClass,\n} from './features';\n\nexport { HttpMethodsEnum, importConfig, isMetaError, MessageTypesEnum, StatusEnum, WebhookTypesEnum } from './shared';\n\nexport type { MetaError, WabaConfigType } from './shared';\n"]}
1
+ {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/shared/config/importConfig.ts","../src/shared/http/httpsClient.ts","../src/shared/http/request.ts","../src/core/whatsapp/WhatsApp.ts","../src/core/webhook/WebhookHandler.ts","../src/index.ts"],"names":["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","DEFAULT_LISTENER_PORT","DEFAULT_MAX_RETRIES_AFTER_WAIT","DEFAULT_REQUEST_TIMEOUT","emptyConfigChecker","config","importConfig","inputConfig","wabaConfig","HttpsClient","Agent","hostname","path","method","headers","timeout","body","url","controller","timeoutId","response","HttpsClientResponse","error","resp","err","Requester","apiVersion","phoneNumberId","accessToken","businessAcctId","userAgent","contentType","additionalHeaders","endpoint","effectiveContentType","errorData","isMetaError","formData","urlEncodedBody","headerPrefix","WhatsApp","enums_exports","messages_default","TemplateApi","phone_default","QrCodeApi","encryption_default","twoStepVerification_default","registration_default","media_default","waba_default","flow_default","profile_default","ms","wabaId","WebhookHandler","configuration","req","res","mode","token","challenge","errors","errorMsg","entry","changes","change","metadata","displayPhoneNumber","profileName","messages","message","messageType","processedMessage","handler","field","event","type","decryptedBody","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","aesKeyBu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AA,GAC7B,IAAWC,IAAAA,CAAAA,IAAQ,KAAM,CAAA,IAAA,CAAKP,CAAoB,CAAA,OAAA,EAAS,CACvDM,CAAAA,CAAAA,CAAW,IAAK,CAAA,CAACC,CAAK,CAAA,CAAC,CAAC,CAG5B,CAAA,GAAI,CAEA,IAAMC,CAASjB,CAAAA,CAAAA,CAAO,eAAe,aAAec,CAAAA,CAAAA,CAAc,MAAO,CAAA,IAAA,CAAKC,CAAU,CAAC,EACzF,OAAO,MAAA,CAAO,MAAO,CAAA,CACjBE,CAAO,CAAA,MAAA,CAAO,KAAK,SAAUjF,CAAAA,CAAAA,EAAY,EAAE,CAAA,CAAG,OAAO,CACrDiF,CAAAA,CAAAA,CAAO,KAAM,EAAA,CACbA,CAAO,CAAA,UAAA,EACX,CAAC,CAAA,CAAE,QAAS,CAAA,QAAQ,CACxB,CAAA,MAAS/E,EAAO,CACZ,MAAAvB,CAAO,CAAA,KAAA,CAAM,4BAA8BuB,CAAAA,CAAK,EAC1C,IAAI,KAAA,CAAM,oDAAoD,CACxE,CACJ,CAKO,OACHuD,CACAH,CAAAA,CAAAA,CACI,CACJ,IAAA,CAAK,YAAa,CAAA,GAAA,CAAIG,EAAMH,CAAO,CAAA,CACnC3E,CAAO,CAAA,GAAA,CAAI,CAA+B8E,4BAAAA,EAAAA,CAAI,EAAE,EACpD,CACJ,EClkBA,IAAOyB,EAAQ9D,CAAAA","file":"index.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import type { WabaConfigType, WhatsAppConfig } from '../types/config';\nimport { WabaConfigEnum } from '../types/enums';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'UTILS';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\nconst DEFAULT_LISTENER_PORT = 3000;\nconst DEFAULT_MAX_RETRIES_AFTER_WAIT = 30;\nconst DEFAULT_REQUEST_TIMEOUT = 20000;\n\nconst emptyConfigChecker = (config: WhatsAppConfig | undefined) => {\n if (!process.env[WabaConfigEnum.AccessToken] && !config?.accessToken) {\n LOGGER.log(`Environmental variable: CLOUD_API_ACCESS_TOKEN and/or access token argument is undefined.`);\n throw new Error('Missing WhatsApp access token.');\n }\n};\n\nexport const importConfig = (inputConfig?: WhatsAppConfig) => {\n emptyConfigChecker(inputConfig);\n\n const wabaConfig: WabaConfigType = {\n [WabaConfigEnum.AppId]: inputConfig?.appId || process.env.M4D_APP_ID || '',\n [WabaConfigEnum.AppSecret]: inputConfig?.appSecret || process.env.M4D_APP_SECRET || '',\n [WabaConfigEnum.PhoneNumberId]: inputConfig?.phoneNumberId || Number(process.env.WA_PHONE_NUMBER_ID),\n [WabaConfigEnum.BusinessAcctId]: inputConfig?.businessAcctId || process.env.WA_BUSINESS_ACCOUNT_ID || '',\n [WabaConfigEnum.APIVersion]: inputConfig?.apiVersion || process.env.CLOUD_API_VERSION || '',\n [WabaConfigEnum.AccessToken]: inputConfig?.accessToken || process.env.CLOUD_API_ACCESS_TOKEN || '',\n [WabaConfigEnum.WebhookEndpoint]: inputConfig?.webhookEndpoint || process.env.WEBHOOK_ENDPOINT || '',\n [WabaConfigEnum.WebhookVerificationToken]:\n inputConfig?.webhookVerificationToken || process.env.WEBHOOK_VERIFICATION_TOKEN || '',\n [WabaConfigEnum.ListenerPort]:\n inputConfig?.listenerPort || parseInt(process.env.LISTENER_PORT || '') || DEFAULT_LISTENER_PORT,\n [WabaConfigEnum.MaxRetriesAfterWait]:\n inputConfig?.maxRetriesAfterWait ||\n parseInt(process.env.MAX_RETRIES_AFTER_WAIT || '') ||\n DEFAULT_MAX_RETRIES_AFTER_WAIT,\n [WabaConfigEnum.RequestTimeout]:\n inputConfig?.requestTimeout || parseInt(process.env.REQUEST_TIMEOUT || '') || DEFAULT_REQUEST_TIMEOUT,\n [WabaConfigEnum.Debug]: inputConfig?.debug || process.env.DEBUG === 'true',\n [WabaConfigEnum.PrivatePem]: inputConfig?.privatePem || process.env.FLOW_API_PRIVATE_PEM || '',\n [WabaConfigEnum.Passphrase]: inputConfig?.passphrase || process.env.FLOW_API_PASSPHRASE || '',\n };\n\n LOGGER.log(`Configuration loaded for App Id ${wabaConfig[WabaConfigEnum.AppId]}`);\n\n return wabaConfig;\n};\n","import { Agent } from 'https';\n\nimport { HttpMethodsEnum } from '../types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from '../types/httpsClient';\nimport Logger from '../utils/logger';\n\nconst LIB_NAME = 'HttpsClient';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class HttpsClient implements HttpsClientClass {\n agent: Agent;\n\n constructor() {\n this.agent = new Agent({ keepAlive: true });\n }\n\n clearSockets(): boolean {\n this.agent.destroy();\n return true;\n }\n\n async sendRequest(\n hostname: string,\n path: string,\n method: HttpMethodsEnum,\n headers: HeadersInit,\n timeout: number,\n body?: BodyInit | null,\n ): Promise<HttpsClientResponseClass> {\n const url = `https://${hostname}/${path}`;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(url, {\n method,\n headers,\n body,\n signal: controller.signal,\n });\n LOGGER.log(`${method} : ${url} - ${JSON.stringify(response)}`);\n\n clearTimeout(timeoutId);\n return new HttpsClientResponse(response);\n } catch (error) {\n LOGGER.error(`${method} : ${url} - ${JSON.stringify(error)}`);\n throw error;\n }\n }\n}\n\nexport class HttpsClientResponse implements HttpsClientResponseClass {\n res: Response;\n respStatusCode: number;\n respHeaders: ResponseHeaders;\n\n constructor(resp: Response) {\n this.res = resp;\n this.respStatusCode = resp.status;\n this.respHeaders = Object.fromEntries(resp.headers.entries());\n }\n\n statusCode(): number {\n return this.respStatusCode;\n }\n\n headers(): ResponseHeaders {\n return this.respHeaders;\n }\n\n rawResponse(): Response {\n return this.res;\n }\n\n async json(): Promise<ResponseJSONBody> {\n try {\n return (await this.res.json()) as ResponseJSONBody;\n } catch (err) {\n // TODO Error Handling\n throw new Error('Failed to parse response body to JSON: ' + (err as Error).message);\n }\n }\n}\n","import type { HttpMethodsEnum } from '../types/enums';\nimport type { RequesterClass } from '../types/request';\nimport { isMetaError, MetaError } from '../utils/isMetaError';\nimport Logger from '../utils/logger';\nimport HttpsClient from './httpsClient';\n\nconst LIB_NAME = 'REQUESTER';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nexport default class Requester implements RequesterClass {\n client: Readonly<HttpsClient>;\n accessToken: Readonly<string>;\n phoneNumberId: Readonly<number>;\n businessAcctId: Readonly<string>;\n apiVersion: Readonly<string>;\n userAgent: Readonly<string>;\n host: Readonly<string>;\n protocol: Readonly<string> = 'https:';\n\n constructor(\n apiVersion: string,\n phoneNumberId: number,\n accessToken: string,\n businessAcctId: string,\n userAgent: string,\n ) {\n this.client = new HttpsClient();\n this.host = 'graph.facebook.com';\n this.apiVersion = apiVersion || '22';\n this.phoneNumberId = phoneNumberId;\n this.accessToken = accessToken;\n this.businessAcctId = businessAcctId;\n this.userAgent = userAgent;\n }\n\n buildHeader(contentType: string, additionalHeaders?: Record<string, string>): HeadersInit {\n const headers: HeadersInit = {\n Authorization: `Bearer ${this.accessToken}`,\n 'User-Agent': this.userAgent,\n };\n\n if (contentType !== 'multipart/form-data') {\n headers['Content-Type'] = contentType;\n }\n\n if (additionalHeaders) {\n Object.assign(headers, additionalHeaders);\n }\n\n return headers;\n }\n\n buildCAPIPath(endpoint: string): string {\n return `v${this.apiVersion}.0/${endpoint}`;\n }\n\n async sendRequest(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n contentType: string = 'application/json',\n additionalHeaders?: Record<string, string>,\n ) {\n let effectiveContentType = contentType;\n\n if (body instanceof FormData) {\n effectiveContentType = 'multipart/form-data';\n } else if (typeof body === 'string' && body.startsWith('<?xml')) {\n effectiveContentType = 'application/xml';\n }\n\n const path = `${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(endpoint)}`;\n\n LOGGER.log(`${method} : ${path} (${effectiveContentType})`);\n\n try {\n const response = await this.client.sendRequest(\n this.host,\n this.buildCAPIPath(endpoint),\n method,\n this.buildHeader(effectiveContentType, additionalHeaders),\n timeout,\n method === 'POST' || method === 'PUT' ? body : undefined,\n );\n\n if (!response.rawResponse().ok) {\n const errorData = await response.json();\n if (isMetaError(errorData)) {\n throw errorData;\n }\n // If the error doesn't match Meta's format, create a generic MetaError\n throw {\n name: 'MetaError',\n message: 'Unknown error occurred',\n error: {\n message: errorData.message || 'Unknown error occurred',\n type: 'UnknownError',\n code: response.statusCode(),\n fbtrace_id: '',\n },\n } as MetaError;\n }\n\n return response;\n } catch (error) {\n if (isMetaError(error)) {\n throw error;\n }\n // Handle network errors or other unexpected errors\n throw {\n name: 'MetaError',\n message: error instanceof Error ? error.message : 'Network error occurred',\n error: {\n message: error instanceof Error ? error.message : 'Network error occurred',\n type: 'NetworkError',\n code: 500,\n fbtrace_id: '',\n },\n } as MetaError;\n }\n }\n\n async getJson<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n body?: any,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(method, endpoint, timeout, body, 'application/json', additionalHeaders);\n return (await res.json()) as T;\n }\n\n async sendFormData<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: FormData,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n formData,\n 'multipart/form-data',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n\n async sendUrlEncodedForm<T>(\n method: HttpMethodsEnum,\n endpoint: string,\n timeout: number,\n formData: Record<string, string>,\n additionalHeaders?: Record<string, string>,\n ): Promise<T> {\n const urlEncodedBody = new URLSearchParams(formData).toString();\n const res = await this.sendRequest(\n method,\n endpoint,\n timeout,\n urlEncodedBody,\n 'application/x-www-form-urlencoded',\n additionalHeaders,\n );\n return (await res.json()) as T;\n }\n}\n","import { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport * as SDKEnums from '@shared/types/enums';\nimport Logger from '@shared/utils/logger';\n\nimport EncryptionApi from '@features/encryption';\nimport FlowApi from '@features/flow';\nimport MediaApi from '@features/media';\nimport MessagesApi from '@features/messages';\nimport PhoneNumberApi from '@features/phone';\nimport BusinessProfileApi from '@features/profile';\nimport QrCodeApi from '@features/qrCode/QrCodeApi';\nimport RegistrationApi from '@features/registration';\nimport TemplateApi from '@features/template/TemplateApi';\nimport TwoStepVerificationApi from '@features/twoStepVerification';\nimport WabaApi from '@features/waba';\nimport { importConfig } from '@shared/config/importConfig';\nimport Requester from '@shared/http/request';\nimport { WhatsAppClass } from './types';\n\nconst LIB_NAME = 'WHATSAPP';\nconst LOG_LOCAL = false;\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true' || LOG_LOCAL);\n\nconst headerPrefix = 'WA_SDK';\n\nexport default class WhatsApp implements WhatsAppClass {\n config: WabaConfigType;\n\n requester: Readonly<Requester>;\n\n readonly messages: MessagesApi;\n readonly templates: TemplateApi;\n readonly phoneNumber: PhoneNumberApi;\n readonly qrCode: QrCodeApi;\n readonly encryption: EncryptionApi;\n readonly twoStepVerification: TwoStepVerificationApi;\n readonly registration: RegistrationApi;\n readonly media: MediaApi;\n readonly waba: WabaApi;\n readonly flow: FlowApi;\n readonly businessProfile: BusinessProfileApi;\n static readonly Enums = SDKEnums;\n\n constructor(config?: WhatsAppConfig) {\n this.config = importConfig(config);\n this.requester = new Requester(\n this.config[SDKEnums.WabaConfigEnum.APIVersion],\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId],\n this.config[SDKEnums.WabaConfigEnum.AccessToken],\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId],\n this.userAgent(),\n );\n\n this.messages = new MessagesApi(this.config, this.requester);\n this.templates = new TemplateApi(this.config, this.requester);\n this.phoneNumber = new PhoneNumberApi(this.config, this.requester);\n this.qrCode = new QrCodeApi(this.config, this.requester);\n this.encryption = new EncryptionApi(this.config, this.requester);\n this.twoStepVerification = new TwoStepVerificationApi(this.config, this.requester);\n this.registration = new RegistrationApi(this.config, this.requester);\n this.media = new MediaApi(this.config, this.requester);\n this.waba = new WabaApi(this.config, this.requester);\n this.flow = new FlowApi(this.config, this.requester);\n this.businessProfile = new BusinessProfileApi(this.config, this.requester);\n LOGGER.log('WhatsApp Node.js SDK instantiated!');\n }\n\n private userAgent(): string {\n const userAgentString = `${headerPrefix}/${'0.0.1'} (Node.js ${process.version})`;\n return userAgentString;\n }\n\n updateTimeout(ms: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.RequestTimeout] = ms;\n LOGGER.log(`Updated request timeout to ${ms}ms`);\n return true;\n }\n\n updatePhoneNumberId(phoneNumberId: number): boolean {\n this.config[SDKEnums.WabaConfigEnum.PhoneNumberId] = phoneNumberId;\n LOGGER.log(`Updated sender phone number id to ${phoneNumberId}`);\n return true;\n }\n\n updateAccessToken(accessToken: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.AccessToken] = accessToken;\n LOGGER.log(`Updated access token`);\n return true;\n }\n\n updateWabaId(wabaId: string): boolean {\n this.config[SDKEnums.WabaConfigEnum.BusinessAcctId] = wabaId;\n LOGGER.log(`Updated business account id to ${wabaId}`);\n return true;\n }\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 { WebhookHandler } from './core/webhook';\nimport { WhatsApp } from './core/whatsapp';\n\nexport default WhatsApp;\n\nexport type { IRequest, IResponse } from './core/webhook';\nexport { WebhookHandler };\n\nexport {\n BusinessProfileApi,\n EncryptionApi,\n FlowApi,\n MessagesApi,\n PhoneNumberApi,\n QrCodeApi,\n RegistrationApi,\n TemplateApi,\n TwoStepVerificationApi,\n WabaApi,\n} from './features';\n\nexport type {\n AudioMediaObject,\n BusinessProfileClass,\n BusinessProfileResponse,\n ContactObject,\n DocumentMediaObject,\n Flow,\n FlowClass,\n FlowEndpointRequest,\n FlowEndpointResponse,\n ImageMediaObject,\n InteractiveObject,\n LocationObject,\n MediaClass,\n MediaResponse,\n MediasResponse,\n MessageRequestParams,\n MessagesResponse,\n MessageTemplateObject,\n PhoneNumberClass,\n PhoneNumberResponse,\n QrCodeClass,\n QrCodeResponse,\n ReactionParams,\n RegistrationClass,\n StatusParams,\n StickerMediaObject,\n TemplateClass,\n TemplateResponse,\n TextMessageParams,\n TextObject,\n UploadMediaResponse,\n VideoMediaObject,\n WabaAccount,\n WABAClass,\n} from './features';\n\nexport { HttpMethodsEnum, importConfig, isMetaError, MessageTypesEnum, StatusEnum, WebhookTypesEnum } from './shared';\n\nexport type { MetaError, WabaConfigType } from './shared';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meta-cloud-api",
3
- "version": "0.2.17",
3
+ "version": "0.2.18",
4
4
  "description": "TypeScript wrapper for Meta's Cloud API",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",