meta-cloud-api 0.2.15 → 0.2.17
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/BusinessProfileApi-DDkv2WQK.d.ts +352 -0
- package/dist/EncryptionApi-CwxQlC-2.d.ts +21 -0
- package/dist/FlowApi-BIBrWYEv.d.ts +471 -0
- package/dist/MediaApi-VqxndaBJ.d.ts +89 -0
- package/dist/MessageApi-CHc6bn3g.d.ts +591 -0
- package/dist/PhoneNumberApi-C-bs6YAe.d.ts +141 -0
- package/dist/QrCodeApi-BjlyPUXV.d.ts +97 -0
- package/dist/RegistrationApi-D7Bg8BUz.d.ts +46 -0
- package/dist/TemplateApi-dmZbvMkO.d.ts +117 -0
- package/dist/TwoStepVerificationApi-DaYWPjY_.d.ts +32 -0
- package/dist/WabaApi-CMoTCWiH.d.ts +174 -0
- package/dist/base-BG2gtoDs.d.ts +46 -0
- package/dist/chunk-2NJVBJUN.js +2 -0
- package/dist/chunk-2NJVBJUN.js.map +1 -0
- package/dist/chunk-3MO3BTBC.js +2 -0
- package/dist/chunk-3MO3BTBC.js.map +1 -0
- package/dist/chunk-4C666HHU.js +2 -0
- package/dist/chunk-4C666HHU.js.map +1 -0
- package/dist/chunk-5JGM556C.js +2 -0
- package/dist/chunk-5JGM556C.js.map +1 -0
- package/dist/chunk-7GL74SXM.js +2 -0
- package/dist/chunk-7GL74SXM.js.map +1 -0
- package/dist/chunk-7NQLQPLH.js +2 -0
- package/dist/chunk-7NQLQPLH.js.map +1 -0
- package/dist/chunk-A264MT4Q.js +2 -0
- package/dist/chunk-A264MT4Q.js.map +1 -0
- package/dist/chunk-BZ5QDXNR.js +2 -0
- package/dist/chunk-BZ5QDXNR.js.map +1 -0
- package/dist/chunk-EYGUX4EA.js +2 -0
- package/dist/chunk-EYGUX4EA.js.map +1 -0
- package/dist/chunk-FFOE5YKT.js +2 -0
- package/dist/chunk-FFOE5YKT.js.map +1 -0
- package/dist/chunk-GIQLIMOD.js +2 -0
- package/dist/chunk-GIQLIMOD.js.map +1 -0
- package/dist/chunk-KFPOVYEJ.js +2 -0
- package/dist/chunk-KFPOVYEJ.js.map +1 -0
- package/dist/chunk-O2OTHNWM.js +2 -0
- package/dist/chunk-O2OTHNWM.js.map +1 -0
- package/dist/chunk-UQPD6GIF.js +2 -0
- package/dist/chunk-UQPD6GIF.js.map +1 -0
- package/dist/chunk-VW3LGHTJ.js +2 -0
- package/dist/chunk-VW3LGHTJ.js.map +1 -0
- package/dist/chunk-XIIJD6SG.js +2 -0
- package/dist/chunk-XIIJD6SG.js.map +1 -0
- package/dist/chunk-XPPDOFBN.js +2 -0
- package/dist/chunk-XPPDOFBN.js.map +1 -0
- package/dist/enums-Z1f7QuVx.d.ts +687 -0
- package/dist/features/encryption/index.d.ts +9 -0
- package/dist/features/encryption/index.js +2 -0
- package/dist/features/flow/index.d.ts +9 -0
- package/dist/features/flow/index.js +2 -0
- package/dist/features/media/index.d.ts +9 -0
- package/dist/features/media/index.js +2 -0
- package/dist/features/messages/index.d.ts +9 -0
- package/dist/features/messages/index.js +2 -0
- package/dist/features/messages/index.js.map +1 -0
- package/dist/features/phone/index.d.ts +9 -0
- package/dist/features/phone/index.js +2 -0
- package/dist/features/phone/index.js.map +1 -0
- package/dist/features/profile/index.d.ts +9 -0
- package/dist/features/profile/index.js +2 -0
- package/dist/features/profile/index.js.map +1 -0
- package/dist/features/qrCode/index.d.ts +9 -0
- package/dist/features/qrCode/index.js +2 -0
- package/dist/features/qrCode/index.js.map +1 -0
- package/dist/features/registration/index.d.ts +9 -0
- package/dist/features/registration/index.js +2 -0
- package/dist/features/registration/index.js.map +1 -0
- package/dist/features/template/index.d.ts +9 -0
- package/dist/features/template/index.js +2 -0
- package/dist/features/template/index.js.map +1 -0
- package/dist/features/twoStepVerification/index.d.ts +9 -0
- package/dist/features/twoStepVerification/index.js +2 -0
- package/dist/features/twoStepVerification/index.js.map +1 -0
- package/dist/features/waba/index.d.ts +9 -0
- package/dist/features/waba/index.js +2 -0
- package/dist/features/waba/index.js.map +1 -0
- package/dist/index.d.ts +546 -28
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/shared/types/config.d.ts +78 -0
- package/dist/shared/types/config.js +2 -0
- package/dist/shared/types/config.js.map +1 -0
- package/dist/shared/types/enums.d.ts +1 -0
- package/dist/shared/types/enums.js +2 -0
- package/dist/shared/types/enums.js.map +1 -0
- package/dist/shared/utils/isMetaError.d.ts +21 -0
- package/dist/shared/utils/isMetaError.js +2 -0
- package/dist/shared/utils/isMetaError.js.map +1 -0
- package/package.json +80 -15
- package/dist/api/index.d.ts +0 -496
- package/dist/api/index.js +0 -2
- package/dist/chunk-IE2YYEC7.js +0 -2
- package/dist/chunk-IE2YYEC7.js.map +0 -1
- package/dist/chunk-IMPHLXRA.js +0 -2
- package/dist/chunk-IMPHLXRA.js.map +0 -1
- package/dist/chunk-KW56EPP7.js +0 -2
- package/dist/chunk-KW56EPP7.js.map +0 -1
- package/dist/chunk-SLDCD6XR.js +0 -2
- package/dist/chunk-SLDCD6XR.js.map +0 -1
- package/dist/chunk-UVPYV4PL.js +0 -2
- package/dist/chunk-UVPYV4PL.js.map +0 -1
- package/dist/types/index.d.ts +0 -513
- package/dist/types/index.js +0 -2
- package/dist/utils/index.d.ts +0 -71
- package/dist/utils/index.js +0 -2
- package/dist/waba-RRlZTQUG.d.ts +0 -2229
- package/dist/whatsapp-DmeO83A8.d.ts +0 -46
- /package/dist/{api → features/encryption}/index.js.map +0 -0
- /package/dist/{types → features/flow}/index.js.map +0 -0
- /package/dist/{utils → features/media}/index.js.map +0 -0
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {f,j,g as g$1,h,c,k,i,e,l as l$1,d,b as b$1}from'./chunk-IMPHLXRA.js';import {b,f as f$1,d as d$1,e as e$1,c as c$1}from'./chunk-SLDCD6XR.js';export{a as generateXHub256Sig,b as importConfig,d as isFlowDataExchangeRequest,e as isFlowErrorRequest,f as isFlowPingRequest,c as isMetaError}from'./chunk-SLDCD6XR.js';import {a}from'./chunk-UVPYV4PL.js';export{b as objectToQueryString}from'./chunk-UVPYV4PL.js';export{j as EventField,c as FlowActionEnum,b as FlowCategoryEnum,a as FlowStatusEnum,d as FlowTypeEnum,i as MessageStatus,e as WabaAccountReviewStatus,g as WabaAccountStatus,h as WabaBusinessVerificationStatus,f as WabaHealthStatusCanSendMessage}from'./chunk-KW56EPP7.js';import {z as z$1}from'./chunk-IE2YYEC7.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,h as ButtonPositionEnum,g as ButtonTypesEnum,a as CategoryEnum,i as ComponentTypesEnum,k as ConversationTypesEnum,w as CurrencyCodesEnum,x as DataLocalizationRegionEnum,p as DocumentMediaTypesEnum,c as HttpMethodsEnum,o as ImageMediaTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum,t as ReferralSourceTypesEnum,u as RequestCodeMethodsEnum,l as StatusEnum,n as StickerMediaTypesEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'./chunk-IE2YYEC7.js';import h$1 from'crypto';import {Agent}from'https';var J="HttpsClient",Q=false,z=new a(J,process.env.DEBUG==="true"||Q),g=class{agent;constructor(){this.agent=new Agent({keepAlive:true});}clearSockets(){return this.agent.destroy(),true}async sendRequest(e,s,n,o,i,a){let r=`https://${e}/${s}`,d=new AbortController,t=setTimeout(()=>d.abort(),i);try{let c=await fetch(r,{method:n,headers:o,body:a,signal:d.signal});return z.log(`${n} : ${r} - ${JSON.stringify(c)}`),clearTimeout(t),new A(c)}catch(c){throw c}}},A=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 X="REQUESTER",Y=false,Z=new a(X,process.env.DEBUG==="true"||Y),m=class{client;accessToken;phoneNumberId;businessAcctId;apiVersion;userAgent;host;protocol="https:";constructor(e,s,n,o,i){this.client=new g,this.host="graph.facebook.com",this.apiVersion=e||"22",this.phoneNumberId=s,this.accessToken=n,this.businessAcctId=o,this.userAgent=i;}buildHeader(e,s){let n={Authorization:`Bearer ${this.accessToken}`,"User-Agent":this.userAgent};return e!=="multipart/form-data"&&(n["Content-Type"]=e),s&&Object.assign(n,s),n}buildCAPIPath(e){return `v${this.apiVersion}.0/${e}`}async sendRequest(e,s,n,o,i="application/json",a){let r=i;o instanceof FormData?r="multipart/form-data":typeof o=="string"&&o.startsWith("<?xml")&&(r="application/xml");let d=`${this.protocol.toLowerCase()}//${this.host}/${this.buildCAPIPath(s)}`;Z.log(`${e} : ${d} (${r})`);try{let t=await this.client.sendRequest(this.host,this.buildCAPIPath(s),e,this.buildHeader(r,a),n,e==="POST"||e==="PUT"?o:void 0);if(!t.rawResponse().ok){let c=await t.json();throw c$1(c)?c:{name:"MetaError",message:"Unknown error occurred",error:{message:c.message||"Unknown error occurred",type:"UnknownError",code:t.statusCode(),fbtrace_id:""}}}return t}catch(t){throw c$1(t)?t:{name:"MetaError",message:t instanceof Error?t.message:"Network error occurred",error:{message:t instanceof Error?t.message:"Network error occurred",type:"NetworkError",code:500,fbtrace_id:""}}}}async getJson(e,s,n,o,i){return await(await this.sendRequest(e,s,n,o,"application/json",i)).json()}async sendFormData(e,s,n,o,i){return await(await this.sendRequest(e,s,n,o,"multipart/form-data",i)).json()}async sendUrlEncodedForm(e,s,n,o,i){let a=new URLSearchParams(o).toString();return await(await this.sendRequest(e,s,n,a,"application/x-www-form-urlencoded",i)).json()}};var ee="WHATSAPP",se=false,y=new a(ee,process.env.DEBUG==="true"||se),te="WA_SDK",l=class{config;requester;messages;templates;phoneNumber;qrCode;encryption;twoStepVerification;registration;media;waba;flow;businessProfile;static Enums=z$1;constructor(e$1){this.config=b(e$1),this.requester=new m(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 f(this.config,this.requester),this.templates=new j(this.config,this.requester),this.phoneNumber=new g$1(this.config,this.requester),this.qrCode=new h(this.config,this.requester),this.encryption=new c(this.config,this.requester),this.twoStepVerification=new k(this.config,this.requester),this.registration=new i(this.config,this.requester),this.media=new e(this.config,this.requester),this.waba=new l$1(this.config,this.requester),this.flow=new d(this.config,this.requester),this.businessProfile=new b$1(this.config,this.requester),y.log("WhatsApp Node.js SDK instantiated!");}userAgent(){return `${te}/0.0.1 (Node.js ${process.version})`}updateTimeout(e){return this.config.REQUEST_TIMEOUT=e,y.log(`Updated request timeout to ${e}ms`),true}updatePhoneNumberId(e){return this.config.WA_PHONE_NUMBER_ID=e,y.log(`Updated sender phone number id to ${e}`),true}updateAccessToken(e){return this.config.CLOUD_API_ACCESS_TOKEN=e,y.log("Updated access token"),true}updateWabaId(e){return this.config.WA_BUSINESS_ACCOUNT_ID=e,y.log(`Updated business account id to ${e}`),true}};var re="WEBHOOK",oe=false,p=new a(re,process.env.DEBUG==="true"||oe),R=class{config;client;messageHandlers=new Map;eventHandlers=new Map;preProcessHandler=null;postProcessHandler=null;flowHandlers=new Map;constructor(e){let s=b(e);this.config=s,this.client=new l(e),p.log("WebhookHandler instantiated!");}handleVerificationRequest(e,s){let n=e.query["hub.mode"],o=e.query["hub.verify_token"],i=e.query["hub.challenge"];n==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?(p.log("Webhook verified successfully"),s.status(200).send(i)):(p.log("Webhook verification failed"),s.status(403).end());}async handleWebhookRequest(e,s){let n=e.body;if(n.object!=="whatsapp_business_account"){p.log("Received webhook for non-WhatsApp event"),s.status(404).end();return}for(let o of n.entry)try{let i=o.changes;for(let a of i)a.field==="messages"?await this.processMessages(a.value):await this.processEvent(a.field,a.value);}catch(i){p.log(`Error processing webhook: ${i}`);}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,n=s.display_phone_number,o=s.phone_number_id,i=e.contacts[0].profile.name,a=e.messages;if(a&&a.length>0)for(let r of a){let d=r.type,t={id:r.id,from:r.from,timestamp:r.timestamp,type:r.type,phoneNumberId:o,displayPhoneNumber:n,profileName:i,originalData:r};switch(r.type){case "text":t.text=r.text;break;case "image":t.image=r.image;break;case "video":t.video=r.video;break;case "audio":t.audio=r.audio;break;case "document":t.document=r.document;break;case "sticker":t.sticker=r.sticker;break;case "location":t.location=r.location;break;case "contacts":t.contacts=r.contacts;break;case "interactive":t.interactive=r.interactive;break;case "button":t.button=r.button;break;case "order":t.order=r.order;break;case "system":t.system=r.system;break;}if(r.context&&(t.context=r.context),r.errors&&(t.errors=r.errors),this.preProcessHandler&&await Promise.resolve(this.preProcessHandler(this.client,t)),this.messageHandlers.has(d)){let c=this.messageHandlers.get(d);c&&await Promise.resolve(c(this.client,t));}if(this.messageHandlers.has("*")){let c=this.messageHandlers.get("*");c&&await Promise.resolve(c(this.client,t));}this.postProcessHandler&&await Promise.resolve(this.postProcessHandler(this.client,t));}e.statuses&&e.statuses.length>0&&await this.processEvent("statuses",e);}async processEvent(e,s){let n={field:e,value:s};if(this.eventHandlers.has(e)){let o=this.eventHandlers.get(e);o&&await Promise.resolve(o(n));}if(this.eventHandlers.has("*")){let o=this.eventHandlers.get("*");o&&await Promise.resolve(o(n));}}onMessage(e,s){this.messageHandlers.set(e,s),p.log(`Registered handler for message type: ${e}`);}onEvent(e,s){this.eventHandlers.set(e,s),p.log(`Registered handler for event field: ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,p.log("Registered pre-processing handler for all messages");}onMessagePostProcess(e){this.postProcessHandler=e,p.log("Registered post-processing handler for all messages");}async handleFlowRequest(e,s){if(!this.isRequestSignatureValid(e)){s.status(403).end();return}let n;try{n=this.decryptRequest(e.body);}catch(t){if(p.error(t),t instanceof Error){s.status(421).send(t.message);return}s.status(500).send("internal server error, please check with logs");return}let{decryptedBody:o,aesKeyBuffer:i,initialVectorBuffer:a}=n,r;if(f$1(o)?r="ping":d$1(o)?r="data_exchange":e$1(o)&&(r="error"),r&&this.flowHandlers.has(r)){let t=this.flowHandlers.get(r);if(t){let c=await Promise.resolve(t(this.client,o)),f=this.encryptResponse(c,i,a);s.status(200).send(f);return}}if(this.flowHandlers.has("*")){let t=this.flowHandlers.get("*");if(t){let c=await Promise.resolve(t(this.client,o)),f=this.encryptResponse(c,i,a);s.status(200).send(f);return}}p.log("No handler found, sending an empty response body: ",o);let d=this.encryptResponse({},i,a);s.status(200).send(d);}isRequestSignatureValid(e){let s=this.config.M4D_APP_SECRET;if(!s)return p.warn("App Secret is not set up. Please Add M4D_APP_SECRET or configuration"),false;let n=e.headers["x-hub-signature-256"];if(!n||typeof n!="string")return p.warn("x-hub-signature-256 header is missing"),false;let o=Buffer.from(n.replace("sha256=",""),"utf-8"),a=h$1.createHmac("sha256",s).update(e.rawBody).digest("hex"),r=Buffer.from(a,"utf-8");return h$1.timingSafeEqual(r,o)?true:(p.error("Error: Request Signature did not match"),false)}decryptRequest(e){p.log("Received body for decryption:",JSON.stringify(e,null,2));let{encrypted_aes_key:s,encrypted_flow_data:n,initial_vector:o}=e;if(!s)throw new Error("Missing required property: encrypted_aes_key");if(!n)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 i=this.config.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
|
|
2
|
-
`),
|
|
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
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/httpsClient.ts","../src/request.ts","../src/whatsapp.ts","../src/webhook.ts","../src/index.ts"],"names":["LIB_NAME","LOG_LOCAL","LOGGER","Logger","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","config","importConfig","MessagesApi","TemplateApi","PhoneNumberApi","QrCodeAPI","EncryptionAPI","TwoStepVerificationAPI","RegistrationAPI","MediaAPI","WabaAPI","FlowAPI","BusinessProfileAPI","ms","wabaId","WebhookHandler","configuration","req","res","mode","token","challenge","entry","changes","change","value","metadata","displayPhoneNumber","profileName","messages","message","messageType","processedMessage","handler","field","event","type","flowRequestData","decryptedBody","aesKeyBuffer","initialVectorBuffer","flowType","isFlowPingRequest","isFlowDataExchangeRequest","isFlowErrorRequest","encryptedResponse","appSecret","signatureHeader","signatureBuffer","digestString","crypto","digestBuffer","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","flipped_iv","pair","cipher","src_default"],"mappings":"u4CAMA,IAAMA,CAAW,CAAA,aAAA,CACXC,CAAY,CAAA,KAAA,CACZC,EAAS,IAAIC,CAAAA,CAAOH,EAAU,OAAQ,CAAA,GAAA,CAAI,QAAU,MAAUC,EAAAA,CAAS,CAExDG,CAAAA,CAAAA,CAArB,KAA6D,CACzD,MAEA,WAAc,EAAA,CACV,KAAK,KAAQ,CAAA,IAAIC,MAAM,CAAE,SAAA,CAAW,IAAK,CAAC,EAC9C,CAEA,cAAwB,CACpB,OAAA,IAAA,CAAK,MAAM,OAAQ,EAAA,CACZ,IACX,CAEA,MAAM,WACFC,CAAAA,CAAAA,CACAC,CACAC,CAAAA,CAAAA,CACAC,EACAC,CACAC,CAAAA,CAAAA,CACiC,CACjC,IAAMC,CAAAA,CAAM,WAAWN,CAAQ,CAAA,CAAA,EAAIC,CAAI,CAAA,CAAA,CACjCM,CAAa,CAAA,IAAI,gBACjBC,CAAY,CAAA,UAAA,CAAW,IAAMD,CAAW,CAAA,KAAA,GAASH,CAAO,CAAA,CAE9D,GAAI,CACA,IAAMK,CAAAA,CAAW,MA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eA,IAAO+B,EAAQrE,CAAAA","file":"index.js","sourcesContent":["import { Agent } from 'https';\n\nimport Logger from './utils/logger';\nimport { HttpMethodsEnum } from './types/enums';\nimport { HttpsClientClass, HttpsClientResponseClass, ResponseHeaders, ResponseJSONBody } from './types/httpsClient';\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 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 HttpsClient from './httpsClient';\nimport type { HttpMethodsEnum } from './types/enums';\nimport type { RequesterClass } from './types/request';\nimport { isMetaError, MetaError } from './utils/isMetaError';\nimport Logger from './utils/logger';\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 } from './types/config';\nimport * as SDKEnums from './types/enums';\nimport Logger from './utils/logger';\n\nimport {\n BusinessProfileAPI,\n EncryptionAPI,\n FlowAPI,\n MediaAPI,\n MessagesAPI,\n PhoneNumberAPI,\n QrCodeAPI,\n RegistrationAPI,\n TemplateAPI,\n TwoStepVerificationAPI,\n WabaAPI,\n} from './api';\nimport Requester from './request';\nimport { WhatsAppClass, WhatsAppConfig } from './types/whatsapp';\nimport { importConfig } from './utils/importConfig';\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 { IncomingMessage } from 'http';\nimport { FlowEndpointRequest, FlowTypeEnum, MessageTypesEnum, WhatsAppConfig } from './types';\nimport { WabaConfigType } from './types/config';\n\nimport crypto from 'crypto';\nimport { EventField, WebhookEvent, WebhookMessage } from './types/webhook';\nimport { importConfig } from './utils';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from './utils/flowTypeGuards';\nimport Logger from './utils/logger';\nimport WhatsApp from './whatsapp';\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 await Promise.resolve(this.preProcessHandler(this.client, processedMessage));\n }\n\n // 2. Dispatch to appropriate message handler\n if (this.messageHandlers.has(messageType)) {\n const handler = this.messageHandlers.get(messageType);\n if (handler) {\n await Promise.resolve(handler(this.client, processedMessage));\n }\n }\n\n // Also dispatch to general message handler if exists\n if (this.messageHandlers.has(MessageTypesEnum['*'])) {\n const handler = this.messageHandlers.get(MessageTypesEnum['*']);\n if (handler) {\n await Promise.resolve(handler(this.client, processedMessage));\n }\n }\n\n // 3. Execute post-processing handler if exists\n if (this.postProcessHandler) {\n await Promise.resolve(this.postProcessHandler(this.client, processedMessage));\n }\n }\n }\n\n if (value.statuses && value.statuses.length > 0) {\n await this.processEvent(EventField.STATUSES, value);\n }\n }\n\n private async processEvent(field: string, value: any): Promise<void> {\n const event: WebhookEvent = {\n field,\n value,\n };\n\n if (this.eventHandlers.has(field)) {\n const handler = this.eventHandlers.get(field);\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n\n if (this.eventHandlers.has('*')) {\n const handler = this.eventHandlers.get('*');\n if (handler) {\n await Promise.resolve(handler(event));\n }\n }\n }\n\n /**\n * Register a message handler for a specific message type\n * @param type Message type to handle, or '*' for all types\n * @param handler The handler function\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 handler for message type: ${type}`);\n }\n\n /**\n * Register a general event handler\n * @param field Event field to handle, or '*' for all fields\n * @param handler The handler function\n */\n public onEvent(field: string, handler: (event: WebhookEvent) => void | Promise<void>): void {\n this.eventHandlers.set(field, handler);\n LOGGER.log(`Registered handler for event field: ${field}`);\n }\n\n /**\n * Register a pre-processing handler for all messages\n * @param handler The handler function\n */\n public onMessagePreProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-processing handler for all messages');\n }\n\n /**\n * Register a post-processing handler for all messages\n * @param handler The handler function\n */\n public onMessagePostProcess(handler: (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-processing handler for all messages');\n }\n\n public async handleFlowRequest<Req extends IRequest & { rawBody: string }, Res extends IResponse>(\n req: Req,\n res: Res,\n ): Promise<void> {\n if (!this.isRequestSignatureValid(req)) {\n res.status(403).end();\n return;\n }\n\n let flowRequestData: {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n };\n\n try {\n flowRequestData = this.decryptRequest(req.body);\n } catch (error) {\n LOGGER.error(error);\n if (error instanceof Error) {\n res.status(421).send(error.message);\n return;\n }\n\n res.status(500).send('internal server error, please check with logs');\n return;\n }\n\n const { decryptedBody, aesKeyBuffer, initialVectorBuffer } = flowRequestData;\n\n // Determine flow type\n let flowType: FlowTypeEnum | undefined = undefined;\n\n if (isFlowPingRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Ping;\n } else if (isFlowDataExchangeRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Change;\n } else if (isFlowErrorRequest(decryptedBody)) {\n flowType = FlowTypeEnum.Error;\n }\n\n // If we have a registered handler for this flow type, use it\n if (flowType && this.flowHandlers.has(flowType)) {\n const handler = this.flowHandlers.get(flowType);\n if (handler) {\n const response = await Promise.resolve(handler(this.client, decryptedBody));\n const encryptedResponse = this.encryptResponse(response, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n return;\n }\n }\n\n // If we have a catch-all handler, use it\n if (this.flowHandlers.has(FlowTypeEnum.All)) {\n const handler = this.flowHandlers.get(FlowTypeEnum.All);\n if (handler) {\n const response = await Promise.resolve(handler(this.client, decryptedBody));\n const encryptedResponse = this.encryptResponse(response, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n return;\n }\n }\n\n // No handler found, send an empty response\n // Add an empty response here for consistency\n LOGGER.log('No handler found, sending an empty response body: ', decryptedBody);\n const encryptedResponse = this.encryptResponse({}, aesKeyBuffer, initialVectorBuffer);\n res.status(200).send(encryptedResponse);\n }\n\n public isRequestSignatureValid(req: IRequest & { rawBody: string }): boolean {\n const appSecret = this.config.M4D_APP_SECRET;\n\n if (!appSecret) {\n LOGGER.warn('App Secret is not set up. Please Add M4D_APP_SECRET or configuration');\n return false;\n }\n\n const signatureHeader = req.headers['x-hub-signature-256'];\n\n if (!signatureHeader || typeof signatureHeader !== 'string') {\n LOGGER.warn('x-hub-signature-256 header is missing');\n return false;\n }\n\n const signatureBuffer = Buffer.from(signatureHeader.replace('sha256=', ''), 'utf-8');\n const hmac = crypto.createHmac('sha256', appSecret);\n\n const digestString = hmac.update(req.rawBody).digest('hex');\n const digestBuffer = Buffer.from(digestString, 'utf-8');\n\n // Note: This is corrected from the original code which had inverted logic\n if (!crypto.timingSafeEqual(digestBuffer, signatureBuffer)) {\n LOGGER.error('Error: Request Signature did not match');\n return false;\n }\n return true;\n }\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 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 action handler for a specific flow type\n * @param type The flow type to handle (ping, change, error), or '*' for all types\n * @param handler The handler function that receives the WhatsApp client and the Flow request\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 handler for Flow type: ${type}`);\n }\n}\n","import WebhookHandler, { IRequest, IResponse } from './webhook';\nimport WhatsApp from './whatsapp';\n\nexport default WhatsApp;\nexport * from './types';\nexport * from './utils';\nexport { WebhookHandler, type IRequest, type IResponse };\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","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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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"]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { f as WabaConfigEnum } from '../../enums-Z1f7QuVx.js';
|
|
2
|
+
|
|
3
|
+
type WhatsAppConfig = {
|
|
4
|
+
accessToken: string;
|
|
5
|
+
appId?: string;
|
|
6
|
+
appSecret?: string;
|
|
7
|
+
phoneNumberId?: number;
|
|
8
|
+
businessAcctId?: string;
|
|
9
|
+
apiVersion?: string;
|
|
10
|
+
webhookEndpoint?: string;
|
|
11
|
+
webhookVerificationToken?: string;
|
|
12
|
+
listenerPort?: number;
|
|
13
|
+
debug?: boolean;
|
|
14
|
+
maxRetriesAfterWait?: number;
|
|
15
|
+
requestTimeout?: number;
|
|
16
|
+
privatePem?: string;
|
|
17
|
+
passphrase?: string;
|
|
18
|
+
};
|
|
19
|
+
type WabaConfigType = {
|
|
20
|
+
/**
|
|
21
|
+
* The Meta for Developers business application Id for this registered application.
|
|
22
|
+
*/
|
|
23
|
+
[WabaConfigEnum.AppId]: string;
|
|
24
|
+
/**
|
|
25
|
+
* The Meta for Developers business application secret for this registered application.
|
|
26
|
+
*/
|
|
27
|
+
[WabaConfigEnum.AppSecret]: string;
|
|
28
|
+
/**
|
|
29
|
+
* The Meta for Developers phone number id used by the registered business.
|
|
30
|
+
*/
|
|
31
|
+
[WabaConfigEnum.PhoneNumberId]: number;
|
|
32
|
+
/**
|
|
33
|
+
* The Meta for Developers business id for the registered business.
|
|
34
|
+
*/
|
|
35
|
+
[WabaConfigEnum.BusinessAcctId]: string;
|
|
36
|
+
/**
|
|
37
|
+
* The version of the Cloud API being used. Starts with a "v" and follows the major number.
|
|
38
|
+
*/
|
|
39
|
+
[WabaConfigEnum.APIVersion]: string;
|
|
40
|
+
/**
|
|
41
|
+
* The access token to make calls on behalf of the signed in Meta for Developers account or business.
|
|
42
|
+
*/
|
|
43
|
+
[WabaConfigEnum.AccessToken]: string;
|
|
44
|
+
/**
|
|
45
|
+
* The endpoint path (e.g. if the value here is webhook, the webhook URL would look like http/https://{host}/webhook).
|
|
46
|
+
*/
|
|
47
|
+
[WabaConfigEnum.WebhookEndpoint]: string;
|
|
48
|
+
/**
|
|
49
|
+
* The verification token that needs to match what is sent by the Cloud API webhook in order to subscribe.
|
|
50
|
+
*/
|
|
51
|
+
[WabaConfigEnum.WebhookVerificationToken]: string;
|
|
52
|
+
/**
|
|
53
|
+
* The listener port for the webhook web server.
|
|
54
|
+
*/
|
|
55
|
+
[WabaConfigEnum.ListenerPort]: number;
|
|
56
|
+
/**
|
|
57
|
+
* To turn on global debugging of the logger to print verbose output across the APIs.
|
|
58
|
+
*/
|
|
59
|
+
[WabaConfigEnum.Debug]: boolean;
|
|
60
|
+
/**
|
|
61
|
+
* The total number of times a request should be retried after the wait period if it fails.
|
|
62
|
+
*/
|
|
63
|
+
[WabaConfigEnum.MaxRetriesAfterWait]: number;
|
|
64
|
+
/**
|
|
65
|
+
* The timeout period for a request to quit and destroy the attempt in ms.
|
|
66
|
+
*/
|
|
67
|
+
[WabaConfigEnum.RequestTimeout]: number;
|
|
68
|
+
/**
|
|
69
|
+
* The private key for the Meta for Developers business.
|
|
70
|
+
*/
|
|
71
|
+
[WabaConfigEnum.PrivatePem]: string;
|
|
72
|
+
/**
|
|
73
|
+
* The passphrase for the Meta for Developers business.
|
|
74
|
+
*/
|
|
75
|
+
[WabaConfigEnum.Passphrase]: string;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
export type { WabaConfigType, WhatsAppConfig };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"config.js"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { A as AudioMediaTypesEnum, d as BusinessVerticalEnum, c as ButtonPositionEnum, B as ButtonTypesEnum, e as CategoryEnum, C as ComponentTypesEnum, g as ConversationTypesEnum, b as CurrencyCodesEnum, D as DataLocalizationRegionEnum, j as DocumentMediaTypesEnum, H as HttpMethodsEnum, i as ImageMediaTypesEnum, I as InteractiveTypesEnum, L as LanguagesEnum, M as MessageTypesEnum, P as ParametersTypesEnum, R as ReferralSourceTypesEnum, l as RequestCodeMethodsEnum, a as StatusEnum, h as StickerMediaTypesEnum, k as SystemChangeTypesEnum, T as TemplateStatusEnum, V as VideoMediaTypesEnum, f as WabaConfigEnum, W as WebhookTypesEnum } from '../../enums-Z1f7QuVx.js';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,h as ButtonPositionEnum,g as ButtonTypesEnum,a as CategoryEnum,i as ComponentTypesEnum,k as ConversationTypesEnum,w as CurrencyCodesEnum,x as DataLocalizationRegionEnum,p as DocumentMediaTypesEnum,c as HttpMethodsEnum,o as ImageMediaTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum,t as ReferralSourceTypesEnum,u as RequestCodeMethodsEnum,l as StatusEnum,n as StickerMediaTypesEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'../../chunk-EYGUX4EA.js';import'../../chunk-4C666HHU.js';//# sourceMappingURL=enums.js.map
|
|
2
|
+
//# sourceMappingURL=enums.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"enums.js"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
interface MetaError extends Error {
|
|
2
|
+
error: {
|
|
3
|
+
message: string;
|
|
4
|
+
type: string;
|
|
5
|
+
code: number;
|
|
6
|
+
error_data?: {
|
|
7
|
+
messaging_product: 'whatsapp';
|
|
8
|
+
details: string;
|
|
9
|
+
};
|
|
10
|
+
error_subcode?: number;
|
|
11
|
+
fbtrace_id: string;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Determines if the error is a Meta API error response
|
|
16
|
+
* @param error Any error object to check
|
|
17
|
+
* @returns Type guard indicating if error is a Meta API error
|
|
18
|
+
*/
|
|
19
|
+
declare function isMetaError(error: any): error is MetaError;
|
|
20
|
+
|
|
21
|
+
export { type MetaError, isMetaError };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"isMetaError.js"}
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "meta-cloud-api",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.17",
|
|
4
4
|
"description": "TypeScript wrapper for Meta's Cloud API",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
|
+
"sideEffects": false,
|
|
8
9
|
"scripts": {
|
|
9
10
|
"prepare": "husky",
|
|
10
11
|
"cz": "cz",
|
|
@@ -13,7 +14,9 @@
|
|
|
13
14
|
"format": "prettier .",
|
|
14
15
|
"lint": "eslint .",
|
|
15
16
|
"clean": "rm -rf dist node_modules",
|
|
16
|
-
"typecheck": "tsc --noEmit"
|
|
17
|
+
"typecheck": "tsc --noEmit",
|
|
18
|
+
"test": "vitest run",
|
|
19
|
+
"test:watch": "vitest --watch"
|
|
17
20
|
},
|
|
18
21
|
"publishConfig": {
|
|
19
22
|
"access": "public"
|
|
@@ -24,20 +27,80 @@
|
|
|
24
27
|
"import": "./dist/index.js",
|
|
25
28
|
"default": "./dist/index.js"
|
|
26
29
|
},
|
|
27
|
-
"./
|
|
28
|
-
"types": "./dist/
|
|
29
|
-
"import": "./dist/
|
|
30
|
-
"default": "./dist/
|
|
30
|
+
"./messages": {
|
|
31
|
+
"types": "./dist/features/messages/index.d.ts",
|
|
32
|
+
"import": "./dist/features/messages/index.js",
|
|
33
|
+
"default": "./dist/features/messages/index.js"
|
|
31
34
|
},
|
|
32
|
-
"./
|
|
33
|
-
"types": "./dist/
|
|
34
|
-
"import": "./dist/
|
|
35
|
-
"default": "./dist/
|
|
35
|
+
"./media": {
|
|
36
|
+
"types": "./dist/features/media/index.d.ts",
|
|
37
|
+
"import": "./dist/features/media/index.js",
|
|
38
|
+
"default": "./dist/features/media/index.js"
|
|
36
39
|
},
|
|
37
|
-
"./
|
|
38
|
-
"types": "./dist/
|
|
39
|
-
"import": "./dist/
|
|
40
|
-
"default": "./dist/
|
|
40
|
+
"./profile": {
|
|
41
|
+
"types": "./dist/features/profile/index.d.ts",
|
|
42
|
+
"import": "./dist/features/profile/index.js",
|
|
43
|
+
"default": "./dist/features/profile/index.js"
|
|
44
|
+
},
|
|
45
|
+
"./flow": {
|
|
46
|
+
"types": "./dist/features/flow/index.d.ts",
|
|
47
|
+
"import": "./dist/features/flow/index.js",
|
|
48
|
+
"default": "./dist/features/flow/index.js"
|
|
49
|
+
},
|
|
50
|
+
"./phone": {
|
|
51
|
+
"types": "./dist/features/phone/index.d.ts",
|
|
52
|
+
"import": "./dist/features/phone/index.js",
|
|
53
|
+
"default": "./dist/features/phone/index.js"
|
|
54
|
+
},
|
|
55
|
+
"./template": {
|
|
56
|
+
"types": "./dist/features/template/index.d.ts",
|
|
57
|
+
"import": "./dist/features/template/index.js",
|
|
58
|
+
"default": "./dist/features/template/index.js"
|
|
59
|
+
},
|
|
60
|
+
"./waba": {
|
|
61
|
+
"types": "./dist/features/waba/index.d.ts",
|
|
62
|
+
"import": "./dist/features/waba/index.js",
|
|
63
|
+
"default": "./dist/features/waba/index.js"
|
|
64
|
+
},
|
|
65
|
+
"./qrCode": {
|
|
66
|
+
"types": "./dist/features/qrCode/index.d.ts",
|
|
67
|
+
"import": "./dist/features/qrCode/index.js",
|
|
68
|
+
"default": "./dist/features/qrCode/index.js"
|
|
69
|
+
},
|
|
70
|
+
"./twoStepVerification": {
|
|
71
|
+
"types": "./dist/features/twoStepVerification/index.d.ts",
|
|
72
|
+
"import": "./dist/features/twoStepVerification/index.js",
|
|
73
|
+
"default": "./dist/features/twoStepVerification/index.js"
|
|
74
|
+
},
|
|
75
|
+
"./encryption": {
|
|
76
|
+
"types": "./dist/features/encryption/index.d.ts",
|
|
77
|
+
"import": "./dist/features/encryption/index.js",
|
|
78
|
+
"default": "./dist/features/encryption/index.js"
|
|
79
|
+
},
|
|
80
|
+
"./registration": {
|
|
81
|
+
"types": "./dist/features/registration/index.d.ts",
|
|
82
|
+
"import": "./dist/features/registration/index.js",
|
|
83
|
+
"default": "./dist/features/registration/index.js"
|
|
84
|
+
},
|
|
85
|
+
"./shared/types": {
|
|
86
|
+
"types": "./dist/shared/types/index.d.ts",
|
|
87
|
+
"import": "./dist/shared/types/index.js",
|
|
88
|
+
"default": "./dist/shared/types/index.js"
|
|
89
|
+
},
|
|
90
|
+
"./shared/utils": {
|
|
91
|
+
"types": "./dist/shared/utils/index.d.ts",
|
|
92
|
+
"import": "./dist/shared/utils/index.js",
|
|
93
|
+
"default": "./dist/shared/utils/index.js"
|
|
94
|
+
},
|
|
95
|
+
"./core/webhook": {
|
|
96
|
+
"types": "./dist/core/webhook/index.d.ts",
|
|
97
|
+
"import": "./dist/core/webhook/index.js",
|
|
98
|
+
"default": "./dist/core/webhook/index.js"
|
|
99
|
+
},
|
|
100
|
+
"./core/whatsapp": {
|
|
101
|
+
"types": "./dist/core/whatsapp/index.d.ts",
|
|
102
|
+
"import": "./dist/core/whatsapp/index.js",
|
|
103
|
+
"default": "./dist/core/whatsapp/index.js"
|
|
41
104
|
},
|
|
42
105
|
"./package.json": "./package.json"
|
|
43
106
|
},
|
|
@@ -102,10 +165,12 @@
|
|
|
102
165
|
"eslint-plugin-unused-imports": "^4.1.4",
|
|
103
166
|
"husky": "^9.1.7",
|
|
104
167
|
"lint-staged": "^15.3.0",
|
|
168
|
+
"msw": "^2.9.0",
|
|
105
169
|
"prettier": "^3.5.0",
|
|
106
170
|
"tsup": "^8.3.6",
|
|
107
171
|
"typescript": "^5.7.3",
|
|
108
|
-
"typescript-eslint": "^8.23.0"
|
|
172
|
+
"typescript-eslint": "^8.23.0",
|
|
173
|
+
"vitest": "^2.1.8"
|
|
109
174
|
},
|
|
110
175
|
"lint-staged": {
|
|
111
176
|
"**/*.{ts,tsx}": [
|