meta-cloud-api 0.2.43 → 0.2.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ import {a as a$1,b as b$1}from'./chunk-5O5GLWIE.js';import {a}from'./chunk-VW3LGHTJ.js';import*as m from'crypto';import m__default from'crypto';function A(o){return typeof o=="object"&&o!==null}function h(o){return typeof o=="string"}var v=["data_exchange","INIT","BACK"],W=["data_exchange","INIT"];function P(o){if(!("flow_token"in o&&h(o.flow_token)&&"action"in o))return false;let{action:e,version:t,screen:r,data:n}=o,i=t==="3.0",p=v.includes(e),c=typeof r>"u"||h(r)&&r!=="SUCCESS",u=e==="data_exchange"||A(n);return i&&p&&c&&u}function _(o){if(!("flow_token"in o&&h(o.flow_token)&&"action"in o))return false;let{action:e,screen:t,data:r}=o,n=W.includes(e),i=h(t),p=A(r)&&"error_key"in r&&h(r.error)&&"error_message"in r&&h(r.error_message);return n&&i&&p}function S(o){return "action"in o&&o.action==="ping"}var C="WEBHOOK_UTILS",s=new a(C,process.env.DEBUG==="true");async function M(o,e,t){try{s.info("Processing webhook messages request");let r=await o.json();if(s.info("Webhook request body:",r),r.object!=="whatsapp_business_account"){let i="Received webhook for non-WhatsApp event";return s.warn(i,{body:r}),new Response(JSON.stringify({error:i}),{status:404})}let n=[];for(let i of r.entry)try{s.info("Processing webhook entry:",{entryId:i.id});let p=i.changes;for(let c of p)c.field==="messages"&&(s.info("Processing messages change:",{change:c}),await B(i.id,c.value,e,t));}catch(p){let c=`Error processing webhook: ${p}`;s.error(c,{entry:i,error:p}),n.push(c);}return s.info("Webhook processing complete",{errorCount:n.length}),new Response(n.length>0?JSON.stringify({errors:n}):null,{status:200})}catch(r){return s.error("Error processing webhook:",r),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}async function F(o,e,t,r){try{s.info("Processing flow request");let n=await o.text(),i=o.headers.get("x-hub-signature-256");if(s.info("Flow request signature:",{signature:i}),!T(n,i,e.WEBHOOK_VERIFICATION_TOKEN||""))return s.warn("Invalid request signature",{signature:i}),new Response(JSON.stringify({error:"Unauthorized"}),{status:401});let p=JSON.parse(n);s.info("Flow request data:",p);let{decryptedBody:c}=x(p,e);s.info("Decrypted flow request:",c);let u=r.get("*");if(!u)return s.warn("No handler registered for flow action:",{action:c.action}),new Response(JSON.stringify({error:"Handler not found"}),{status:404});if(S(c))return s.info("Handling flow ping request"),new Response(JSON.stringify({version:"3.0",data:{status:"active"}}),{status:200});if(_(c))return s.warn("Flow error request received:",c),new Response(null,{status:200});if(P(c)){s.info("Processing flow data exchange request");let g=await u(t,c);s.info("Flow handler result:",g);let d=D(g,Buffer.from(p.aes_key,"base64"),Buffer.from(p.initial_vector,"base64"));return s.info("Encrypted flow response generated"),new Response(JSON.stringify(d),{status:200})}return s.warn("Unknown flow request type:",c),new Response(JSON.stringify({error:"Unknown request type"}),{status:400})}catch(n){return s.error("Error handling flow request:",n),new Response(JSON.stringify({error:"Internal server error"}),{status:500})}}function T(o,e,t){if(!e)return s.warn("Missing signature in request"),false;let r=m__default.createHmac("sha256",t).update(o).digest("hex");return s.info("Signature verification:",{received:e.replace("sha256=",""),expected:r}),m__default.timingSafeEqual(Buffer.from(e.replace("sha256=","")),Buffer.from(r))}async function B(o,e,t,r){s.info("Processing messages:",{waba_id:o,value:e});let n=e.metadata,i=e.contacts,p=o,c=n?.display_phone_number||"",u=n?.phone_number_id||"",g=i?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){s.info("Processing statuses:",{statusCount:e.statuses.length});let d=e.statuses;for(let a of d){let l={wabaId:p,id:a.id,from:a.recipient_id,timestamp:a.timestamp,type:"statuses",phoneNumberId:u,displayPhoneNumber:c,profileName:g,statuses:e.statuses[0],originalData:a};s.info("Processing status:",l),await E(r.messageHandlers.get("statuses"),t,l,"statuses");}return}if(e.messages&&e.messages.length>0){s.info("Processing messages:",{messageCount:e.messages.length});let d=e.messages;for(let a of d){let l=a.type;s.info("Processing message:",{messageType:l,messageId:a.id});let f={wabaId:p,id:a.id,from:a.from,timestamp:a.timestamp,type:a.type,phoneNumberId:u,displayPhoneNumber:c,profileName:g,originalData:a};switch(l){case "text":f.text=a.text;break;case "image":f.image=a.image;break;case "video":f.video=a.video;break;case "audio":f.audio=a.audio;break;case "document":f.document=a.document;break;case "sticker":f.sticker=a.sticker;break;case "location":f.location=a.location;break;case "contacts":f.contacts=a.contacts;break;case "interactive":f.interactive=a.interactive;break;case "button":f.button=a.button;break;case "order":f.order=a.order;break;case "system":f.system=a.system;break;case "reaction":f.reaction=a.reaction;break;default:s.warn("Unknown message type:",{messageType:l});break}s.info("Executing message handlers"),await E(r.preProcessHandler,t,f,"pre-process"),await E(r.messageHandlers.get(l),t,f,l),await E(r.postProcessHandler,t,f,"post-process");}}}async function E(o,e,t,r){if(o)try{s.info("Executing handler:",{handlerType:r,messageId:t.id}),await o(e,t),s.info("Handler execution complete:",{handlerType:r,messageId:t.id});}catch(n){s.error(`Error in ${r} handler:`,{error:n,messageId:t.id});}else s.info("No handler registered:",{handlerType:r});}function x(o,e){s.info("Decrypting flow request");let{encrypted_aes_key:t,encrypted_flow_data:r,initial_vector:n}=o;if(!t||!r||!n)throw s.error("Missing required encryption properties"),new Error("Missing required encryption properties");let i=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
+ `),p=e.FLOW_API_PASSPHRASE,c=m__default.createPrivateKey({key:i,passphrase:p}),u;try{s.info("Decrypting AES key"),u=m__default.privateDecrypt({key:c,padding:m__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(t,"base64"));}catch(I){throw s.error("Failed to decrypt AES key:",I),new Error("Failed to decrypt the request. Please verify your private key.")}let g=Buffer.from(r,"base64"),d=Buffer.from(n,"base64"),l=g.subarray(0,-16),f=g.subarray(-16);s.info("Decrypting flow data");let R=m__default.createDecipheriv("aes-128-gcm",u,d);R.setAuthTag(f);let N=Buffer.concat([R.update(l),R.final()]).toString("utf-8");return s.info("Flow request decryption complete"),{decryptedBody:JSON.parse(N),aesKeyBuffer:u,initialVectorBuffer:d}}function D(o,e,t){s.info("Encrypting flow response");let r=[];for(let n of Array.from(t.entries()))r.push(~n[1]);try{let n=m__default.createCipheriv("aes-128-gcm",e,Buffer.from(r)),i=Buffer.concat([n.update(JSON.stringify(o||{}),"utf-8"),n.final(),n.getAuthTag()]).toString("base64");return s.info("Flow response encryption complete"),i}catch(n){throw s.error("Response encryption error:",n),new Error("Failed to encrypt response. Internal server error.")}}var V="WEBHOOK",y=new a(V,process.env.DEBUG==="true"),b=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$1(e),this.client=new b$1(e),y.log("WebhookHandler instantiated!");}async handleWebhook(e){try{if(e.method==="GET"){let t=new URL(e.url),r=t.searchParams.get("hub.mode"),n=t.searchParams.get("hub.verify_token"),i=t.searchParams.get("hub.challenge");return r==="subscribe"&&n===this.config.WEBHOOK_VERIFICATION_TOKEN?new Response(i,{status:200}):new Response(null,{status:403})}return e.method==="POST"?M(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}):new Response(null,{status:405})}catch(t){return y.log(`Error handling webhook: ${t}`),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}async handleFlow(e){try{return F(e,this.config,this.client,this.flowHandlers)}catch(t){return y.log(`Error handling flow: ${t}`),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}verifySignature(e,t){if(!t)return false;let r=m__default.createHmac("sha256",this.config.WEBHOOK_VERIFICATION_TOKEN).update(e).digest("hex");return m__default.timingSafeEqual(Buffer.from(t.replace("sha256=","")),Buffer.from(r))}onMessage(e,t){this.messageHandlers.set(e,t),y.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,y.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,y.log("Registered post-process handler");}onFlow(e,t){this.flowHandlers.set(e,t),y.log(`Registered flow handler for ${e}`);}};var ae=(o,e)=>m.createHmac("sha256",e).update(o,"utf-8").digest("hex");export{P as a,_ as b,S as c,M as d,F as e,b as f,ae as g};//# sourceMappingURL=chunk-JGX3AVD7.js.map
3
+ //# sourceMappingURL=chunk-JGX3AVD7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","processWebhookMessages","whatsapp","handlers","body","errorMsg","errors","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","signature","verifySignature","decryptedBody","decryptFlowRequest","handler","result","encryptedResponse","encryptFlowResponse","verificationToken","expectedSignature","crypto","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","url","mode","token","challenge","type","generateXHub256Sig","appSecret","q"],"mappings":"gJAaA,SAASA,CAAAA,CAASC,CAAkD,CAAA,CAChE,OAAO,OAAOA,CAAU,EAAA,QAAA,EAAYA,CAAU,GAAA,IAClD,CAOA,SAASC,CAASD,CAAAA,CAAAA,CAAiC,CAC/C,OAAO,OAAOA,CAAAA,EAAU,QAC5B,CAGA,IAAME,CAAAA,CAAwB,CAAuE,eAAA,CAAA,MAAA,CAAA,MAA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lowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n LOGGER.info('Processing webhook messages request');\n const body = await request.json();\n LOGGER.info('Webhook request body:', body);\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.warn(errorMsg, { body });\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n LOGGER.info('Processing webhook entry:', { entryId: entry.id });\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n LOGGER.info('Processing messages change:', { change });\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.error(errorMsg, { entry, error });\n errors.push(errorMsg);\n }\n }\n\n LOGGER.info('Webhook processing complete', { errorCount: errors.length });\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.error('Error processing webhook:', error);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n LOGGER.info('Processing flow request');\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n LOGGER.info('Flow request signature:', { signature });\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.warn('Invalid request signature', { signature });\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n LOGGER.info('Flow request data:', data);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, config);\n LOGGER.info('Decrypted flow request:', decryptedBody);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.warn('No handler registered for flow action:', { action: decryptedBody.action });\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n LOGGER.info('Handling flow ping request');\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.warn('Flow error request received:', decryptedBody);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n LOGGER.info('Processing flow data exchange request');\n const result = await handler(whatsapp, decryptedBody);\n LOGGER.info('Flow handler result:', result);\n\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n LOGGER.info('Encrypted flow response generated');\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.warn('Unknown flow request type:', decryptedBody);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.error('Error handling flow request:', error);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) {\n LOGGER.warn('Missing signature in request');\n return false;\n }\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n LOGGER.info('Signature verification:', {\n received: signature.replace('sha256=', ''),\n expected: expectedSignature,\n });\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n LOGGER.info('Processing messages:', { waba_id, value });\n\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n LOGGER.info('Processing statuses:', { statusCount: value.statuses.length });\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n LOGGER.info('Processing status:', processedStatus);\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n LOGGER.info('Processing messages:', { messageCount: value.messages.length });\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n LOGGER.info('Processing message:', { messageType, messageId: message.id });\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.warn('Unknown message type:', { messageType });\n break;\n }\n\n // Execute handlers in sequence\n LOGGER.info('Executing message handlers');\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n LOGGER.info('Executing handler:', { handlerType, messageId: message.id });\n await handler(whatsapp, message);\n LOGGER.info('Handler execution complete:', { handlerType, messageId: message.id });\n } catch (error) {\n LOGGER.error(`Error in ${handlerType} handler:`, { error, messageId: message.id });\n }\n } else {\n LOGGER.info('No handler registered:', { handlerType });\n }\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n LOGGER.info('Decrypting flow request');\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n LOGGER.error('Missing required encryption properties');\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n LOGGER.info('Decrypting AES key');\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('Failed to decrypt AES key:', error);\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n LOGGER.info('Decrypting flow data');\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n LOGGER.info('Flow request decryption complete');\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n LOGGER.info('Encrypting flow response');\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n const encryptedResponse = Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n\n LOGGER.info('Flow response encryption complete');\n return encryptedResponse;\n } catch (error) {\n LOGGER.error('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../whatsapp';\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WebhookHandler based on Web Standard API\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook requests using Web Standard API\n */\n public async handleWebhook(request: Request): Promise<Response> {\n try {\n // Handle GET request (verification)\n if (request.method === 'GET') {\n const url = new URL(request.url);\n const mode = url.searchParams.get('hub.mode');\n const token = url.searchParams.get('hub.verify_token');\n const challenge = url.searchParams.get('hub.challenge');\n\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return new Response(challenge, { status: 200 });\n }\n return new Response(null, { status: 403 });\n }\n\n // Handle POST request (webhook)\n if (request.method === 'POST') {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n }\n\n return new Response(null, { status: 405 });\n } catch (error) {\n LOGGER.log(`Error handling webhook: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n }\n\n /**\n * Handle flow requests\n */\n public async handleFlow(request: Request): Promise<Response> {\n try {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n } catch (error) {\n LOGGER.log(`Error handling flow: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n }\n\n /**\n * Verify webhook signature\n */\n private verifySignature(body: string, signature: string | null): boolean {\n if (!signature) return false;\n\n const expectedSignature = crypto\n .createHmac('sha256', this.config.WEBHOOK_VERIFICATION_TOKEN)\n .update(body)\n .digest('hex');\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n }\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"]}
@@ -1,2 +1,2 @@
1
- export{f as WebhookHandler,g as generateXHub256Sig,e as processFlowRequest,d as processWebhookMessages}from'../../chunk-WR6KABCQ.js';import'../../chunk-5O5GLWIE.js';import'../../chunk-3MO3BTBC.js';import'../../chunk-R36L2XYO.js';import'../../chunk-GT3XQN7Y.js';import'../../chunk-O2OTHNWM.js';import'../../chunk-7NQLQPLH.js';import'../../chunk-UQPD6GIF.js';import'../../chunk-5JGM556C.js';import'../../chunk-2NJVBJUN.js';import'../../chunk-XPPDOFBN.js';import'../../chunk-KFPOVYEJ.js';import'../../chunk-7GL74SXM.js';import'../../chunk-LGLRGXCE.js';import'../../chunk-GIQLIMOD.js';import'../../chunk-BZ5QDXNR.js';import'../../chunk-VW3LGHTJ.js';import'../../chunk-4O3T25CT.js';import'../../chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
1
+ export{f as WebhookHandler,g as generateXHub256Sig,e as processFlowRequest,d as processWebhookMessages}from'../../chunk-JGX3AVD7.js';import'../../chunk-5O5GLWIE.js';import'../../chunk-3MO3BTBC.js';import'../../chunk-R36L2XYO.js';import'../../chunk-GT3XQN7Y.js';import'../../chunk-O2OTHNWM.js';import'../../chunk-7NQLQPLH.js';import'../../chunk-UQPD6GIF.js';import'../../chunk-5JGM556C.js';import'../../chunk-2NJVBJUN.js';import'../../chunk-XPPDOFBN.js';import'../../chunk-KFPOVYEJ.js';import'../../chunk-7GL74SXM.js';import'../../chunk-LGLRGXCE.js';import'../../chunk-GIQLIMOD.js';import'../../chunk-BZ5QDXNR.js';import'../../chunk-VW3LGHTJ.js';import'../../chunk-4O3T25CT.js';import'../../chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import'./chunk-CNGQISKS.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';export{f as WebhookHandler,a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'./chunk-WR6KABCQ.js';export{b as WhatsApp}from'./chunk-5O5GLWIE.js';export{a as isMetaError}from'./chunk-3MO3BTBC.js';export{a as TemplateApi}from'./chunk-R36L2XYO.js';import'./chunk-GT3XQN7Y.js';export{b as RegistrationApi}from'./chunk-O2OTHNWM.js';export{b as EncryptionApi}from'./chunk-7NQLQPLH.js';export{b as TwoStepVerificationApi}from'./chunk-UQPD6GIF.js';export{b as WabaApi}from'./chunk-5JGM556C.js';export{b as MessagesApi}from'./chunk-2NJVBJUN.js';import'./chunk-XPPDOFBN.js';export{b as BusinessProfileApi}from'./chunk-KFPOVYEJ.js';export{a as buildFieldsQueryString}from'./chunk-7GL74SXM.js';export{c as FlowApi}from'./chunk-LGLRGXCE.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';export{a as objectToQueryString}from'./chunk-BZ5QDXNR.js';export{b as BaseAPI,a as Logger}from'./chunk-VW3LGHTJ.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,g as ButtonPositionEnum,a as CategoryEnum,i as ComponentTypesEnum,k as ConversationTypesEnum,w as CurrencyCodesEnum,x as DataLocalizationRegionEnum,p as DocumentMediaTypesEnum,c as HttpMethodsEnum,o as ImageMediaTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum,t as ReferralSourceTypesEnum,u as RequestCodeMethodsEnum,l as StatusEnum,n as StickerMediaTypesEnum,h as SubTypeEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'./chunk-4O3T25CT.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
1
+ import'./chunk-CNGQISKS.js';export{a as QrCodeApi}from'./chunk-I222VSWK.js';export{f as WebhookHandler,a as isFlowDataExchangeRequest,b as isFlowErrorRequest,c as isFlowPingRequest}from'./chunk-JGX3AVD7.js';export{b as WhatsApp}from'./chunk-5O5GLWIE.js';export{a as isMetaError}from'./chunk-3MO3BTBC.js';export{a as TemplateApi}from'./chunk-R36L2XYO.js';import'./chunk-GT3XQN7Y.js';export{b as RegistrationApi}from'./chunk-O2OTHNWM.js';export{b as EncryptionApi}from'./chunk-7NQLQPLH.js';export{b as TwoStepVerificationApi}from'./chunk-UQPD6GIF.js';export{b as WabaApi}from'./chunk-5JGM556C.js';export{b as MessagesApi}from'./chunk-2NJVBJUN.js';import'./chunk-XPPDOFBN.js';export{b as BusinessProfileApi}from'./chunk-KFPOVYEJ.js';export{a as buildFieldsQueryString}from'./chunk-7GL74SXM.js';export{c as FlowApi}from'./chunk-LGLRGXCE.js';export{b as PhoneNumberApi}from'./chunk-GIQLIMOD.js';export{a as objectToQueryString}from'./chunk-BZ5QDXNR.js';export{b as BaseAPI,a as Logger}from'./chunk-VW3LGHTJ.js';export{q as AudioMediaTypesEnum,y as BusinessVerticalEnum,g as ButtonPositionEnum,a as CategoryEnum,i as ComponentTypesEnum,k as ConversationTypesEnum,w as CurrencyCodesEnum,x as DataLocalizationRegionEnum,p as DocumentMediaTypesEnum,c as HttpMethodsEnum,o as ImageMediaTypesEnum,f as InteractiveTypesEnum,v as LanguagesEnum,d as MessageTypesEnum,e as ParametersTypesEnum,t as ReferralSourceTypesEnum,u as RequestCodeMethodsEnum,l as StatusEnum,n as StickerMediaTypesEnum,h as SubTypeEnum,s as SystemChangeTypesEnum,b as TemplateStatusEnum,m as VideoMediaTypesEnum,j as WabaConfigEnum,r as WebhookTypesEnum}from'./chunk-4O3T25CT.js';import'./chunk-4C666HHU.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meta-cloud-api",
3
- "version": "0.2.43",
3
+ "version": "0.2.44",
4
4
  "description": "TypeScript wrapper for Meta's Cloud API",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,3 +0,0 @@
1
- import {a as a$1,b}from'./chunk-5O5GLWIE.js';import {a}from'./chunk-VW3LGHTJ.js';import*as m from'crypto';import m__default from'crypto';function k(s){return typeof s=="object"&&s!==null}function h(s){return typeof s=="string"}var v=["data_exchange","INIT","BACK"],B=["data_exchange","INIT"];function A(s){if(!("flow_token"in s&&h(s.flow_token)&&"action"in s))return false;let{action:e,version:r,screen:t,data:o}=s,c=r==="3.0",p=v.includes(e),a=typeof t>"u"||h(t)&&t!=="SUCCESS",l=e==="data_exchange"||k(o);return c&&p&&a&&l}function S(s){if(!("flow_token"in s&&h(s.flow_token)&&"action"in s))return false;let{action:e,screen:r,data:t}=s,o=B.includes(e),c=h(r),p=k(t)&&"error_key"in t&&h(t.error)&&"error_message"in t&&h(t.error_message);return o&&c&&p}function M(s){return "action"in s&&s.action==="ping"}var W="WEBHOOK_UTILS",f=new a(W,process.env.DEBUG==="true");async function O(s,e,r){try{let t=await s.json();if(t.object!=="whatsapp_business_account"){let c="Received webhook for non-WhatsApp event";return f.log(c),new Response(JSON.stringify({error:c}),{status:404})}let o=[];for(let c of t.entry)try{let p=c.changes;for(let a of p)a.field==="messages"&&await I(c.id,a.value,e,r);}catch(p){let a=`Error processing webhook: ${p}`;f.log(a),o.push(a);}return new Response(o.length>0?JSON.stringify({errors:o}):null,{status:200})}catch(t){return f.log(`Error processing webhook: ${t}`),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}async function P(s,e,r,t){try{let o=await s.text(),c=s.headers.get("x-hub-signature-256");if(!C(o,c,e.WEBHOOK_VERIFICATION_TOKEN||""))return f.log("Invalid request signature"),new Response(JSON.stringify({error:"Unauthorized"}),{status:401});let p=JSON.parse(o),{decryptedBody:a}=x(p,e),l=t.get("*");if(!l)return f.log(`No handler registered for flow action: ${a.action}`),new Response(JSON.stringify({error:"Handler not found"}),{status:404});if(M(a))return new Response(JSON.stringify({version:"3.0",data:{status:"active"}}),{status:200});if(S(a))return f.log(`Flow error: ${JSON.stringify(a)}`),new Response(null,{status:200});if(A(a)){let d=await l(r,a),u=q(d,Buffer.from(p.aes_key,"base64"),Buffer.from(p.initial_vector,"base64"));return new Response(JSON.stringify(u),{status:200})}return f.log(`Unknown flow request type: ${JSON.stringify(a)}`),new Response(JSON.stringify({error:"Unknown request type"}),{status:400})}catch(o){return f.log(`Error handling flow request: ${o}`),new Response(JSON.stringify({error:"Internal server error"}),{status:500})}}function C(s,e,r){if(!e)return false;let t=m__default.createHmac("sha256",r).update(s).digest("hex");return m__default.timingSafeEqual(Buffer.from(e.replace("sha256=","")),Buffer.from(t))}async function I(s,e,r,t){let o=e.metadata,c=e.contacts,p=s,a=o?.display_phone_number||"",l=o?.phone_number_id||"",d=c?.[0]?.profile?.name||"";if(e.statuses&&e.statuses.length>0){let u=e.statuses;for(let n of u){let g={wabaId:p,id:n.id,from:n.recipient_id,timestamp:n.timestamp,type:"statuses",phoneNumberId:l,displayPhoneNumber:a,profileName:d,statuses:e.statuses[0],originalData:n};await R(t.messageHandlers.get("statuses"),r,g,"statuses");}return}if(e.messages&&e.messages.length>0){let u=e.messages;for(let n of u){let g=n.type,i={wabaId:p,id:n.id,from:n.from,timestamp:n.timestamp,type:n.type,phoneNumberId:l,displayPhoneNumber:a,profileName:d,originalData:n};switch(g){case "text":i.text=n.text;break;case "image":i.image=n.image;break;case "video":i.video=n.video;break;case "audio":i.audio=n.audio;break;case "document":i.document=n.document;break;case "sticker":i.sticker=n.sticker;break;case "location":i.location=n.location;break;case "contacts":i.contacts=n.contacts;break;case "interactive":i.interactive=n.interactive;break;case "button":i.button=n.button;break;case "order":i.order=n.order;break;case "system":i.system=n.system;break;case "reaction":i.reaction=n.reaction;break;default:f.log(`Unknown message type: ${g}`);break}await R(t.preProcessHandler,r,i,"pre-process"),await R(t.messageHandlers.get(g),r,i,g),await R(t.postProcessHandler,r,i,"post-process");}}}async function R(s,e,r,t){if(s)try{await s(e,r);}catch(o){f.log(`Error in ${t} handler: ${o}`);}}function x(s,e){let{encrypted_aes_key:r,encrypted_flow_data:t,initial_vector:o}=s;if(!r||!t||!o)throw new Error("Missing required encryption properties");let c=e.FLOW_API_PRIVATE_PEM.replace(/\\n/g,`
2
- `),p=e.FLOW_API_PASSPHRASE,a=m__default.createPrivateKey({key:c,passphrase:p}),l;try{l=m__default.privateDecrypt({key:a,padding:m__default.constants.RSA_PKCS1_OAEP_PADDING,oaepHash:"sha256"},Buffer.from(r,"base64"));}catch{throw new Error("Failed to decrypt the request. Please verify your private key.")}let d=Buffer.from(t,"base64"),u=Buffer.from(o,"base64"),g=d.subarray(0,-16),i=d.subarray(-16),b=m__default.createDecipheriv("aes-128-gcm",l,u);b.setAuthTag(i);let T=Buffer.concat([b.update(g),b.final()]).toString("utf-8");return {decryptedBody:JSON.parse(T),aesKeyBuffer:l,initialVectorBuffer:u}}function q(s,e,r){let t=[];for(let o of Array.from(r.entries()))t.push(~o[1]);try{let o=m__default.createCipheriv("aes-128-gcm",e,Buffer.from(t));return Buffer.concat([o.update(JSON.stringify(s||{}),"utf-8"),o.final(),o.getAuthTag()]).toString("base64")}catch(o){throw f.log("Response encryption error:",o),new Error("Failed to encrypt response. Internal server error.")}}var D="WEBHOOK",y=new a(D,process.env.DEBUG==="true"),E=class{config;client;messageHandlers=new Map;preProcessHandler=void 0;postProcessHandler=void 0;flowHandlers=new Map;constructor(e){this.config=a$1(e),this.client=new b(e),y.log("WebhookHandler instantiated!");}async handleWebhook(e){try{if(e.method==="GET"){let r=new URL(e.url),t=r.searchParams.get("hub.mode"),o=r.searchParams.get("hub.verify_token"),c=r.searchParams.get("hub.challenge");return t==="subscribe"&&o===this.config.WEBHOOK_VERIFICATION_TOKEN?new Response(c,{status:200}):new Response(null,{status:403})}return e.method==="POST"?O(e,this.client,{messageHandlers:this.messageHandlers,preProcessHandler:this.preProcessHandler,postProcessHandler:this.postProcessHandler}):new Response(null,{status:405})}catch(r){return y.log(`Error handling webhook: ${r}`),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}async handleFlow(e){try{return P(e,this.config,this.client,this.flowHandlers)}catch(r){return y.log(`Error handling flow: ${r}`),new Response(JSON.stringify({error:"Internal Server Error"}),{status:500})}}verifySignature(e,r){if(!r)return false;let t=m__default.createHmac("sha256",this.config.WEBHOOK_VERIFICATION_TOKEN).update(e).digest("hex");return m__default.timingSafeEqual(Buffer.from(r.replace("sha256=","")),Buffer.from(t))}onMessage(e,r){this.messageHandlers.set(e,r),y.log(`Registered message handler for ${e}`);}onMessagePreProcess(e){this.preProcessHandler=e,y.log("Registered pre-process handler");}onMessagePostProcess(e){this.postProcessHandler=e,y.log("Registered post-process handler");}onFlow(e,r){this.flowHandlers.set(e,r),y.log(`Registered flow handler for ${e}`);}};var ae=(s,e)=>m.createHmac("sha256",e).update(s,"utf-8").digest("hex");export{A as a,S as b,M as c,O as d,P as e,E as f,ae as g};//# sourceMappingURL=chunk-WR6KABCQ.js.map
3
- //# sourceMappingURL=chunk-WR6KABCQ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/shared/utils/flowTypeGuards.ts","../src/core/webhook/utils/webhookUtils.ts","../src/core/webhook/WebhookHandler.ts","../src/core/webhook/utils/generateXHub256Sig.ts"],"names":["isObject","value","isString","DATA_EXCHANGE_ACTIONS","ERROR_ACTIONS","isFlowDataExchangeRequest","request","action","version","screen","data","hasValidVersion","hasValidAction","hasValidScreen","hasValidData","isFlowErrorRequest","isFlowPingRequest","LIB_NAME","LOGGER","Logger","processWebhookMessages","whatsapp","handlers","body","errorMsg","errors","entry","changes","change","processMessages","error","processFlowRequest","config","flowHandlers","signature","verifySignature","decryptedBody","decryptFlowRequest","handler","result","encryptedResponse","encryptFlowResponse","verificationToken","expectedSignature","crypto","waba_id","metadata","contacts","wabaId","displayPhoneNumber","phoneNumberId","profileName","statuses","status","processedStatus","executeHandler","messages","message","messageType","processedMessage","handlerType","encrypted_aes_key","encrypted_flow_data","initial_vector","privatePem","passphrase","privateKey","decryptedAesKey","flowDataBuffer","initialVectorBuffer","TAG_LENGTH","encrypted_flow_data_body","encrypted_flow_data_tag","decipher","decryptedJSONString","response","aesKeyBuffer","flipped_iv","pair","cipher","WebhookHandler","importConfig","WhatsApp","url","mode","token","challenge","type","generateXHub256Sig","appSecret","F"],"mappings":"yIAaA,SAASA,CAAAA,CAASC,EAAkD,CAChE,OAAO,OAAOA,CAAAA,EAAU,QAAYA,EAAAA,CAAAA,GAAU,IAClD,CAOA,SAASC,CAASD,CAAAA,CAAAA,CAAiC,CAC/C,OAAO,OAAOA,CAAU,EAAA,QAC5B,CAGA,IAAME,CAAwB,CAAA,CAA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AG,MAAO,CAAA,IAAA,CAAKS,CAAiB,CAAC,CAC/G,CAKO,SAAU4C,CAAAA,CAAAA,CAAwBjD,CAA+B,CAAA,CACpE,IAAK,CAAA,eAAA,CAAgB,GAAIiD,CAAAA,CAAAA,CAAMjD,CAAO,CAAA,CACtCpB,CAAO,CAAA,GAAA,CAAI,CAAkCqE,+BAAAA,EAAAA,CAAI,CAAE,CAAA,EACvD,CAKO,mBAAA,CAAoBjD,CAA+B,CAAA,CACtD,IAAK,CAAA,iBAAA,CAAoBA,CACzBpB,CAAAA,CAAAA,CAAO,GAAI,CAAA,gCAAgC,EAC/C,CAKO,oBAAqBoB,CAAAA,CAAAA,CAA+B,CACvD,IAAA,CAAK,kBAAqBA,CAAAA,CAAAA,CAC1BpB,CAAO,CAAA,GAAA,CAAI,iCAAiC,EAChD,CAKO,MAAA,CAAOqE,CAAoBjD,CAAAA,CAAAA,CAA4B,CAC1D,IAAA,CAAK,YAAa,CAAA,GAAA,CAAIiD,CAAMjD,CAAAA,CAAO,CACnCpB,CAAAA,CAAAA,CAAO,GAAI,CAAA,CAAA,4BAAA,EAA+BqE,CAAI,CAAA,CAAE,EACpD,CACJ,ECtHaC,IAAAA,EAAAA,CAAqB,CAACjE,CAAAA,CAAckE,CAC/B,GAAAC,CAAA,CAAA,UAAA,CAAW,QAAUD,CAAAA,CAAS,CAAE,CAAA,MAAA,CAAOlE,CAAM,CAAA,OAAO,CAAE,CAAA,MAAA,CAAO,KAAK","file":"chunk-WR6KABCQ.js","sourcesContent":["import {\n FlowActionEnum,\n FlowDataExchangeRequest,\n FlowEndpointRequest,\n FlowErrorNotificationRequest,\n FlowHealthCheckRequest,\n} from '@features/flow/types';\n\n/**\n * Helper function to check if a value is an object\n * @param value The value to check\n * @returns True if the value is a non-null object\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Helper function to check if a value is a string\n * @param value The value to check\n * @returns True if the value is a string\n */\nfunction isString(value: unknown): value is string {\n return typeof value === 'string';\n}\n\n// Array of allowed action types for data exchange requests\nconst DATA_EXCHANGE_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT, FlowActionEnum.BACK] as const;\n\n// Array of allowed action types for error notification requests\nconst ERROR_ACTIONS = [FlowActionEnum.DATA_EXCHANGE, FlowActionEnum.INIT] as const;\n\n/**\n * Type guard to check if a request is a Data Exchange request\n * Validates the request structure according to the Flow API specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Data Exchange request, false otherwise\n */\nexport function isFlowDataExchangeRequest(request: FlowEndpointRequest): request is FlowDataExchangeRequest & {\n action: (typeof DATA_EXCHANGE_ACTIONS)[number];\n screen?: string;\n flow_token: string;\n data?: Record<string, any>;\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, version, screen, data } = request;\n\n // Validate API version\n const hasValidVersion = version === '3.0';\n\n // Check if the action is one of the allowed actions for data exchange\n const hasValidAction = DATA_EXCHANGE_ACTIONS.includes(action as any);\n\n // Screen is optional, but when present must be a string and not 'SUCCESS'\n const hasValidScreen = typeof screen === 'undefined' || (isString(screen) && screen !== 'SUCCESS');\n\n // Data is required except for DATA_EXCHANGE action\n const hasValidData = action === FlowActionEnum.DATA_EXCHANGE || isObject(data);\n\n // All conditions must be met for a valid data exchange request\n return hasValidVersion && hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is an Error Notification request\n * Validates the request structure according to the Flow API error specifications\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a valid Error Notification request, false otherwise\n */\nexport function isFlowErrorRequest(request: FlowEndpointRequest): request is FlowErrorNotificationRequest & {\n action: (typeof ERROR_ACTIONS)[number];\n screen: string;\n flow_token: string;\n data: {\n error: string;\n error_message: string;\n };\n} {\n // Check for basic required fields\n if (!('flow_token' in request && isString(request.flow_token) && 'action' in request)) {\n return false;\n }\n\n const { action, screen, data } = request;\n\n // Check if the action is one of the allowed actions for error notifications\n const hasValidAction = ERROR_ACTIONS.includes(action as any);\n\n // Screen is required for error notifications\n const hasValidScreen = isString(screen);\n\n // Validate error data structure\n const hasValidData =\n isObject(data) &&\n 'error_key' in data &&\n isString(data.error) &&\n 'error_message' in data &&\n isString(data.error_message);\n\n // All conditions must be met for a valid error notification request\n return hasValidAction && hasValidScreen && hasValidData;\n}\n\n/**\n * Type guard to check if a request is a Ping (health check) request\n * Simple validation for health check endpoints in the Flow API\n *\n * @param request The Flow endpoint request to check\n * @returns True if the request is a Ping request, false otherwise\n */\nexport function isFlowPingRequest(request: FlowEndpointRequest): request is FlowHealthCheckRequest {\n // A ping request only requires the 'action' field with value 'ping'\n return 'action' in request && request.action === 'ping';\n}\n","import { FlowEndpointRequest } from '@features/flow';\nimport { FlowTypeEnum } from '@features/flow/types';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType } from '@shared/types/config';\nimport { isFlowDataExchangeRequest, isFlowErrorRequest, isFlowPingRequest } from '@shared/utils/flowTypeGuards';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../../whatsapp';\nimport { WebhookMessage, WebhookMessageValue } from '../types';\n\nconst LIB_NAME = 'WEBHOOK_UTILS';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\nexport type MessageHandler = (whatsapp: WhatsApp, message: WebhookMessage) => void | Promise<void>;\nexport type FlowHandler = (whatsapp: WhatsApp, request: FlowEndpointRequest) => any | Promise<any>;\n\n/**\n * Process webhook messages\n */\nexport async function processWebhookMessages(\n request: Request,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<Response> {\n try {\n const body = await request.json();\n\n // Check this is a WhatsApp Business Account webhook\n if (body.object !== 'whatsapp_business_account') {\n const errorMsg = 'Received webhook for non-WhatsApp event';\n LOGGER.log(errorMsg);\n return new Response(JSON.stringify({ error: errorMsg }), { status: 404 });\n }\n\n const errors: string[] = [];\n\n // Process each entry\n for (const entry of body.entry) {\n try {\n const changes = entry.changes;\n for (const change of changes) {\n if (change.field === 'messages') {\n await processMessages(entry.id, change.value, whatsapp, handlers);\n }\n }\n } catch (error) {\n const errorMsg = `Error processing webhook: ${error}`;\n LOGGER.log(errorMsg);\n errors.push(errorMsg);\n }\n }\n\n return new Response(errors.length > 0 ? JSON.stringify({ errors }) : null, { status: 200 });\n } catch (error) {\n LOGGER.log(`Error processing webhook: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n}\n\n/**\n * Handle flow requests\n */\nexport async function processFlowRequest(\n request: Request,\n config: WabaConfigType,\n whatsapp: WhatsApp,\n flowHandlers: Map<FlowTypeEnum, FlowHandler>,\n): Promise<Response> {\n try {\n const body = await request.text();\n const signature = request.headers.get('x-hub-signature-256');\n\n // Validate request signature\n if (!verifySignature(body, signature, config.WEBHOOK_VERIFICATION_TOKEN || '')) {\n LOGGER.log('Invalid request signature');\n return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });\n }\n\n const data = JSON.parse(body);\n\n // Decrypt the request\n const { decryptedBody } = decryptFlowRequest(data, config);\n\n // Get the flow handler\n const handler = flowHandlers.get(FlowTypeEnum.All);\n if (!handler) {\n LOGGER.log(`No handler registered for flow action: ${decryptedBody.action}`);\n return new Response(JSON.stringify({ error: 'Handler not found' }), { status: 404 });\n }\n\n // Handle different flow types\n if (isFlowPingRequest(decryptedBody)) {\n return new Response(\n JSON.stringify({\n version: '3.0',\n data: { status: 'active' },\n }),\n { status: 200 },\n );\n }\n\n if (isFlowErrorRequest(decryptedBody)) {\n LOGGER.log(`Flow error: ${JSON.stringify(decryptedBody)}`);\n return new Response(null, { status: 200 });\n }\n\n if (isFlowDataExchangeRequest(decryptedBody)) {\n const result = await handler(whatsapp, decryptedBody);\n const encryptedResponse = encryptFlowResponse(\n result,\n Buffer.from(data.aes_key, 'base64'),\n Buffer.from(data.initial_vector, 'base64'),\n );\n\n return new Response(JSON.stringify(encryptedResponse), { status: 200 });\n }\n\n LOGGER.log(`Unknown flow request type: ${JSON.stringify(decryptedBody)}`);\n return new Response(JSON.stringify({ error: 'Unknown request type' }), { status: 400 });\n } catch (error) {\n LOGGER.log(`Error handling flow request: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500 });\n }\n}\n\n/**\n * Verify webhook signature\n */\nfunction verifySignature(body: string, signature: string | null, verificationToken: string): boolean {\n if (!signature) return false;\n\n const expectedSignature = crypto.createHmac('sha256', verificationToken).update(body).digest('hex');\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n}\n\n/**\n * Private helper functions\n */\nasync function processMessages(\n waba_id: string,\n value: WebhookMessageValue,\n whatsapp: WhatsApp,\n handlers: {\n messageHandlers: Map<MessageTypesEnum, MessageHandler>;\n preProcessHandler?: MessageHandler;\n postProcessHandler?: MessageHandler;\n },\n): Promise<void> {\n const metadata = value.metadata;\n const contacts = value.contacts;\n const wabaId = waba_id;\n const displayPhoneNumber = metadata?.display_phone_number || '';\n const phoneNumberId = metadata?.phone_number_id || '';\n const profileName = contacts?.[0]?.profile?.name || '';\n\n if (value.statuses && value.statuses.length > 0) {\n const statuses = value.statuses;\n for (const status of statuses) {\n const processedStatus: WebhookMessage = {\n wabaId,\n id: status.id,\n from: status.recipient_id,\n timestamp: status.timestamp,\n type: MessageTypesEnum.Statuses,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n statuses: value.statuses[0],\n originalData: status,\n };\n\n await executeHandler(\n handlers.messageHandlers.get(MessageTypesEnum.Statuses),\n whatsapp,\n processedStatus,\n MessageTypesEnum.Statuses,\n );\n }\n return;\n }\n\n if (value.messages && value.messages.length > 0) {\n const messages = value.messages;\n\n for (const message of messages) {\n const messageType = message.type;\n\n const processedMessage: WebhookMessage = {\n wabaId,\n id: message.id,\n from: message.from,\n timestamp: message.timestamp,\n type: message.type,\n phoneNumberId,\n displayPhoneNumber,\n profileName,\n originalData: message,\n };\n\n switch (messageType) {\n case MessageTypesEnum.Text:\n processedMessage.text = message.text;\n break;\n case MessageTypesEnum.Image:\n processedMessage.image = message.image;\n break;\n case MessageTypesEnum.Video:\n processedMessage.video = message.video;\n break;\n case MessageTypesEnum.Audio:\n processedMessage.audio = message.audio;\n break;\n case MessageTypesEnum.Document:\n processedMessage.document = message.document;\n break;\n case MessageTypesEnum.Sticker:\n processedMessage.sticker = message.sticker;\n break;\n case MessageTypesEnum.Location:\n processedMessage.location = message.location;\n break;\n case MessageTypesEnum.Contacts:\n processedMessage.contacts = message.contacts;\n break;\n case MessageTypesEnum.Interactive:\n processedMessage.interactive = message.interactive;\n break;\n case MessageTypesEnum.Button:\n processedMessage.button = message.button;\n break;\n case MessageTypesEnum.Order:\n processedMessage.order = message.order;\n break;\n case MessageTypesEnum.System:\n processedMessage.system = message.system;\n break;\n case MessageTypesEnum.Reaction:\n processedMessage.reaction = message.reaction;\n break;\n default:\n LOGGER.log(`Unknown message type: ${messageType}`);\n break;\n }\n\n // Execute handlers in sequence\n await executeHandler(handlers.preProcessHandler, whatsapp, processedMessage, 'pre-process');\n await executeHandler(handlers.messageHandlers.get(messageType), whatsapp, processedMessage, messageType);\n await executeHandler(handlers.postProcessHandler, whatsapp, processedMessage, 'post-process');\n }\n }\n}\n\nasync function executeHandler(\n handler: MessageHandler | undefined,\n whatsapp: WhatsApp,\n message: WebhookMessage,\n handlerType: string,\n): Promise<void> {\n if (handler) {\n try {\n await handler(whatsapp, message);\n } catch (error) {\n LOGGER.log(`Error in ${handlerType} handler: ${error}`);\n }\n }\n}\n\nfunction decryptFlowRequest(\n body: any,\n config: WabaConfigType,\n): {\n decryptedBody: FlowEndpointRequest;\n aesKeyBuffer: Buffer;\n initialVectorBuffer: Buffer;\n} {\n const { encrypted_aes_key, encrypted_flow_data, initial_vector } = body;\n\n if (!encrypted_aes_key || !encrypted_flow_data || !initial_vector) {\n throw new Error('Missing required encryption properties');\n }\n\n const privatePem = config.FLOW_API_PRIVATE_PEM.replace(/\\\\n/g, '\\n');\n const passphrase = config.FLOW_API_PASSPHRASE;\n\n const privateKey = crypto.createPrivateKey({ key: privatePem, passphrase });\n let decryptedAesKey: Buffer;\n\n try {\n decryptedAesKey = crypto.privateDecrypt(\n {\n key: privateKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256',\n },\n Buffer.from(encrypted_aes_key, 'base64'),\n );\n } catch (error) {\n throw new Error('Failed to decrypt the request. Please verify your private key.');\n }\n\n const flowDataBuffer = Buffer.from(encrypted_flow_data, 'base64');\n const initialVectorBuffer = Buffer.from(initial_vector, 'base64');\n\n const TAG_LENGTH = 16;\n const encrypted_flow_data_body = flowDataBuffer.subarray(0, -TAG_LENGTH);\n const encrypted_flow_data_tag = flowDataBuffer.subarray(-TAG_LENGTH);\n\n const decipher = crypto.createDecipheriv('aes-128-gcm', decryptedAesKey, initialVectorBuffer);\n decipher.setAuthTag(encrypted_flow_data_tag);\n\n const decryptedJSONString = Buffer.concat([decipher.update(encrypted_flow_data_body), decipher.final()]).toString(\n 'utf-8',\n );\n\n return {\n decryptedBody: JSON.parse(decryptedJSONString),\n aesKeyBuffer: decryptedAesKey,\n initialVectorBuffer,\n };\n}\n\nfunction encryptFlowResponse(response: any, aesKeyBuffer: Buffer, initialVectorBuffer: Buffer): string {\n const flipped_iv: number[] = [];\n for (const pair of Array.from(initialVectorBuffer.entries())) {\n flipped_iv.push(~pair[1]);\n }\n\n try {\n const cipher = crypto.createCipheriv('aes-128-gcm', aesKeyBuffer, Buffer.from(flipped_iv));\n return Buffer.concat([\n cipher.update(JSON.stringify(response || {}), 'utf-8'),\n cipher.final(),\n cipher.getAuthTag(),\n ]).toString('base64');\n } catch (error) {\n LOGGER.log('Response encryption error:', error);\n throw new Error('Failed to encrypt response. Internal server error.');\n }\n}\n","import { FlowTypeEnum } from '@features/flow/types';\nimport { importConfig } from '@shared/config/importConfig';\nimport { MessageTypesEnum } from '@shared/types';\nimport { WabaConfigType, WhatsAppConfig } from '@shared/types/config';\nimport Logger from '@shared/utils/logger';\nimport crypto from 'crypto';\nimport { WhatsApp } from '../whatsapp';\nimport { FlowHandler, MessageHandler, processFlowRequest, processWebhookMessages } from './utils/webhookUtils';\n\nconst LIB_NAME = 'WEBHOOK';\nconst LOGGER = new Logger(LIB_NAME, process.env.DEBUG === 'true');\n\n/**\n * WebhookHandler based on Web Standard API\n */\nexport class WebhookHandler {\n private config: WabaConfigType;\n private client: WhatsApp;\n private messageHandlers: Map<MessageTypesEnum, MessageHandler> = new Map();\n private preProcessHandler: MessageHandler | undefined = undefined;\n private postProcessHandler: MessageHandler | undefined = undefined;\n private flowHandlers: Map<FlowTypeEnum, FlowHandler> = new Map();\n\n constructor(config: WhatsAppConfig) {\n this.config = importConfig(config);\n this.client = new WhatsApp(config);\n LOGGER.log('WebhookHandler instantiated!');\n }\n\n /**\n * Handle webhook requests using Web Standard API\n */\n public async handleWebhook(request: Request): Promise<Response> {\n try {\n // Handle GET request (verification)\n if (request.method === 'GET') {\n const url = new URL(request.url);\n const mode = url.searchParams.get('hub.mode');\n const token = url.searchParams.get('hub.verify_token');\n const challenge = url.searchParams.get('hub.challenge');\n\n if (mode === 'subscribe' && token === this.config.WEBHOOK_VERIFICATION_TOKEN) {\n return new Response(challenge, { status: 200 });\n }\n return new Response(null, { status: 403 });\n }\n\n // Handle POST request (webhook)\n if (request.method === 'POST') {\n return processWebhookMessages(request, this.client, {\n messageHandlers: this.messageHandlers,\n preProcessHandler: this.preProcessHandler,\n postProcessHandler: this.postProcessHandler,\n });\n }\n\n return new Response(null, { status: 405 });\n } catch (error) {\n LOGGER.log(`Error handling webhook: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n }\n\n /**\n * Handle flow requests\n */\n public async handleFlow(request: Request): Promise<Response> {\n try {\n return processFlowRequest(request, this.config, this.client, this.flowHandlers);\n } catch (error) {\n LOGGER.log(`Error handling flow: ${error}`);\n return new Response(JSON.stringify({ error: 'Internal Server Error' }), { status: 500 });\n }\n }\n\n /**\n * Verify webhook signature\n */\n private verifySignature(body: string, signature: string | null): boolean {\n if (!signature) return false;\n\n const expectedSignature = crypto\n .createHmac('sha256', this.config.WEBHOOK_VERIFICATION_TOKEN)\n .update(body)\n .digest('hex');\n\n return crypto.timingSafeEqual(Buffer.from(signature.replace('sha256=', '')), Buffer.from(expectedSignature));\n }\n\n /**\n * Register a message handler for a specific message type\n */\n public onMessage(type: MessageTypesEnum, handler: MessageHandler): void {\n this.messageHandlers.set(type, handler);\n LOGGER.log(`Registered message handler for ${type}`);\n }\n\n /**\n * Register a pre-process handler that runs before all message handlers\n */\n public onMessagePreProcess(handler: MessageHandler): void {\n this.preProcessHandler = handler;\n LOGGER.log('Registered pre-process handler');\n }\n\n /**\n * Register a post-process handler that runs after all message handlers\n */\n public onMessagePostProcess(handler: MessageHandler): void {\n this.postProcessHandler = handler;\n LOGGER.log('Registered post-process handler');\n }\n\n /**\n * Register a flow handler for a specific flow type\n */\n public onFlow(type: FlowTypeEnum, handler: FlowHandler): void {\n this.flowHandlers.set(type, handler);\n LOGGER.log(`Registered flow handler for ${type}`);\n }\n}\n","import * as crypto from 'crypto';\n\nexport const generateXHub256Sig = (body: string, appSecret: string) => {\n return crypto.createHmac('sha256', appSecret).update(body, 'utf-8').digest('hex');\n};\n"]}