All files / routes/webhooks whatsapp.routes.ts

100% Statements 50/50
100% Branches 18/18
100% Functions 3/3
100% Lines 50/50

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151                                            1x     1x 5x 5x 5x   5x       2x     3x       1x   12x     12x 1x     11x 12x         11x 2x         9x 9x   1x     8x           8x   8x             8x 8x 3x     5x 5x 5x   5x 5x 5x 5x 5x             5x 5x 5x 1x     1x         1x       4x 4x 4x 2x       2x 2x             2x             4x 4x 1x     1x          
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { Services } from "../../services";
import { createWhatsAppClient } from "../../lib/whatsapp/client";
import {
	verifyWebhookSignature,
	extractMessages,
	extractStatuses,
	extractTemplateStatuses,
} from "../../lib/whatsapp/webhook";
import type { WhatsAppWebhookPayload } from "../../lib/whatsapp/types";
import { getWhatsAppIds } from "../../lib/env-config";
import { logger } from "../../lib/logger";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		dal: Dal;
		services: Services;
	};
};
 
const whatsapp = new Hono<Env>();
 
// GET /whatsapp - Webhook verification (Meta sends this to verify the endpoint)
whatsapp.get("/whatsapp", async (c) => {
	const mode = c.req.query("hub.mode");
	const token = c.req.query("hub.verify_token");
	const challenge = c.req.query("hub.challenge");
 
	if (
		mode === "subscribe" &&
		token === c.env.WHATSAPP_WEBHOOK_VERIFY_TOKEN
	) {
		return c.text(challenge ?? "", 200);
	}
 
	return c.text("Forbidden", 403);
});
 
// POST /whatsapp - Receive inbound messages and status updates
whatsapp.post("/whatsapp", async (c) => {
	// Capture raw body BEFORE parsing (needed for signature verification)
	const rawBody = await c.req.text();
 
	// Signature verification is mandatory — reject if secret is not configured
	if (!c.env.WHATSAPP_APP_SECRET) {
		return c.text("Webhook not configured", 503);
	}
 
	const signature = c.req.header("x-hub-signature-256") ?? "";
	const isValid = await verifyWebhookSignature(
		rawBody,
		signature,
		c.env.WHATSAPP_APP_SECRET,
	);
	if (!isValid) {
		return c.text("Invalid signature", 401);
	}
 
	// Always respond 200 immediately (Meta requires fast response)
	let payload: WhatsAppWebhookPayload;
	try {
		payload = JSON.parse(rawBody);
	} catch {
		return c.text("Invalid JSON", 400);
	}
 
	logger.info(
		"[WEBHOOK] Received WhatsApp event",
		JSON.stringify(payload).substring(0, 500),
	);
 
	// Process in background
	c.executionCtx.waitUntil(processWebhook(payload, c.env));
 
	return c.text("OK", 200);
});
 
async function processWebhook(
	payload: WhatsAppWebhookPayload,
	env: CloudflareBindings,
) {
	try {
		if (!env.WHATSAPP_ACCESS_TOKEN) {
			return;
		}
 
		const { getDb } = await import("../../db");
		const { createDal } = await import("../../dal");
		const { createServices } = await import("../../services");
 
		const db = getDb(env.DB);
		const dal = createDal(db);
		const services = createServices(dal, env);
		const { phoneNumberId, wabaId } = getWhatsAppIds();
		const client = createWhatsAppClient({
			phoneNumberId,
			accessToken: env.WHATSAPP_ACCESS_TOKEN,
			wabaId,
		});
 
		// Process inbound messages
		const messages = extractMessages(payload);
		logger.info(`[WEBHOOK] Extracted ${messages.length} inbound messages`);
		for (const { message, contactName } of messages) {
			logger.info(
				`[WEBHOOK] Inbound: from=${message.from}, type=${message.type}, id=${message.id}`,
			);
			await services.waConversation.addInboundMessage(
				message,
				contactName,
			);
			// Auto mark as read
			await client.markAsRead(message.id);
		}
 
		// Process status updates
		const statuses = extractStatuses(payload);
		logger.info(`[WEBHOOK] Extracted ${statuses.length} status updates`);
		for (const status of statuses) {
			logger.info(
				`[WEBHOOK] Status: wamid=${status.id}, status=${status.status}, errors=${JSON.stringify(status.errors ?? [])}`,
			);
			const errorCode =
				status.errors?.[0]?.code?.toString() ?? undefined;
			await services.waConversation.updateMessageStatus(
				status.id,
				status.status,
				errorCode,
			);
 
			// Also update campaign recipient if applicable
			await dal.waCampaigns.updateRecipientStatusByWamid(
				status.id,
				status.status,
			);
		}
 
		// Process template status updates (approvals, rejections, etc.)
		const templateStatuses = extractTemplateStatuses(payload);
		for (const event of templateStatuses) {
			await services.waTemplate.handleStatusWebhook(event);
		}
	} catch (err) {
		logger.error("[WEBHOOK] WhatsApp processing error:", err);
	}
}
 
export default whatsapp;