// Local stand-in for the WhatsApp Cloud (Graph) API and for Meta's signed webhook. Never part of release packaging. // Env: PORT (8080), WEBHOOK_URL, WHATSAPP_COMPANIES=INS,CV and per company WHATSAPP__PHONE_NUMBER_ID / _WABA_ID / _ACCESS_TOKEN / _APP_SECRET. const http = require('node:http'); const crypto = require('node:crypto'); const env = process.env; const companies = (env.WHATSAPP_COMPANIES || '').split(',').map((s) => s.trim()).filter(Boolean).map((code) => ({ code, phoneNumberId: env[`WHATSAPP_${code}_PHONE_NUMBER_ID`], wabaId: env[`WHATSAPP_${code}_WABA_ID`], token: env[`WHATSAPP_${code}_ACCESS_TOKEN`], secret: env[`WHATSAPP_${code}_APP_SECRET`], })); const tokens = new Set(companies.map((c) => c.token).filter(Boolean)); const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64'); const PDF = Buffer.from('%PDF-1.1\n1 0 obj<>endobj\n2 0 obj<>endobj\n' + '3 0 obj<>endobj\ntrailer<>\n%%EOF\n'); let counter = 0; function send(res, status, body, type = 'application/json') { res.writeHead(status, { 'Content-Type': type }); res.end(Buffer.isBuffer(body) || typeof body === 'string' ? body : JSON.stringify(body)); } function readBody(req) { return new Promise((resolve) => { const chunks = []; req.on('data', (c) => chunks.push(c)); req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); }); } function templates(wabaId, host, page) { const expo = { name: 'expo_followup', language: 'en', category: 'MARKETING', status: 'APPROVED', components: [{ type: 'BODY', text: 'Hi {{1}}, thanks for visiting us at {{2}}.' }] }; const promo = { name: 'promo_header', language: 'en', category: 'MARKETING', status: 'APPROVED', components: [{ type: 'HEADER', format: 'IMAGE' }, { type: 'BODY', text: 'Big sale this weekend.' }] }; return page === 'p2' ? { data: [promo], paging: {} } : { data: [expo], paging: { next: `http://${host}/${wabaId}/message_templates?status=APPROVED&limit=200&after=p2` } }; } // Delivers a signed webhook the way Meta does: HMAC-SHA256 over the exact bytes, header "sha256=". async function deliver(company, payload) { const body = JSON.stringify(payload); const signature = 'sha256=' + crypto.createHmac('sha256', company.secret).update(body).digest('hex'); const r = await fetch(env.WEBHOOK_URL, { method: 'POST', body, headers: { 'Content-Type': 'application/json', 'X-Hub-Signature-256': signature } }); return r.status; } function envelope(company, value) { return { object: 'whatsapp_business_account', entry: [{ id: company.wabaId, changes: [{ field: 'messages', value: { messaging_product: 'whatsapp', metadata: { display_phone_number: '15550000000', phone_number_id: company.phoneNumberId }, ...value } }] }] }; } async function simulate(path, req, res) { let input; try { input = JSON.parse(await readBody(req)); } catch (e) { return send(res, 400, { error: 'invalid json' }); } const company = companies.find((c) => c.code === input.companyCode); if (!company || !env.WEBHOOK_URL) return send(res, 400, { error: 'unknown companyCode or WEBHOOK_URL not set' }); const now = Math.floor(Date.now() / 1000); let payload; if (path === '/simulate/status') { payload = envelope(company, { statuses: [{ id: input.wamid, status: input.status, timestamp: String(now), recipient_id: input.from || '60100000000' }] }); } else { const type = input.type || 'text'; const message = { from: input.from, id: `wamid.MOCKIN${++counter}`, timestamp: String(now), type }; if (type === 'text') message.text = { body: input.text || 'hello' }; else if (type === 'location') message.location = { latitude: 3.139, longitude: 101.6869, name: 'Mock Location' }; else if (type === 'document') message.document = { id: input.mediaId, mime_type: 'application/pdf', filename: 'quote.pdf' }; else message[type] = { id: input.mediaId, mime_type: 'image/png' }; payload = envelope(company, { contacts: [{ profile: { name: 'Mock Contact' }, wa_id: input.from }], messages: [message] }); } try { send(res, await deliver(company, payload), { delivered: true }); } catch (e) { send(res, 502, { error: 'webhook unreachable' }); } } http.createServer(async (req, res) => { const url = new URL(req.url, 'http://mock'); const path = url.pathname.replace(/^\/v\d+\.\d+/, ''); // the client may add a Graph version prefix if (req.method === 'GET' && path === '/health') return send(res, 200, { status: 'UP' }); if (req.method === 'POST' && (path === '/simulate/inbound' || path === '/simulate/status')) return simulate(path, req, res); const auth = /^Bearer (.+)$/.exec(req.headers.authorization || ''); if (!auth || !tokens.has(auth[1])) return send(res, 401, { error: { code: 190, title: 'Invalid OAuth access token' } }); // media bytes: Meta wants the bearer token on the download too const bytes = path.match(/^\/media-bytes\/([^/]+)$/); if (req.method === 'GET' && bytes) { const id = bytes[1]; if (id.startsWith('expired')) return send(res, 404, { error: { code: 100, title: 'Media expired' } }); return id.startsWith('doc') ? send(res, 200, PDF, 'application/pdf') : send(res, 200, PNG, 'image/png'); } const parts = path.split('/').filter(Boolean); if (req.method === 'POST' && parts.length === 2 && parts[1] === 'messages') { let input; try { input = JSON.parse(await readBody(req)); } catch (e) { return send(res, 400, { error: { code: 100, title: 'Invalid parameter' } }); } if (String(input.to || '').endsWith('0000')) return send(res, 400, { error: { code: 131026, title: 'Message undeliverable' } }); return send(res, 200, { messaging_product: 'whatsapp', messages: [{ id: `wamid.MOCK${++counter}` }] }); } if (req.method === 'GET' && parts.length === 2 && parts[1] === 'message_templates') { return send(res, 200, templates(parts[0], req.headers.host, url.searchParams.get('after'))); } if (req.method === 'GET' && parts.length === 1) { // media lookup const id = parts[0]; return send(res, 200, { id, url: `http://whatsapp-mock:8080/media-bytes/${id}`, mime_type: id.startsWith('doc') ? 'application/pdf' : 'image/png' }); } send(res, 404, { error: { code: 100, title: 'Unknown path' } }); }).listen(Number(env.PORT || 8080));