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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | 1x 1x 5x 5x 5x 5x 2x 3x 1x 20x 20x 1x 19x 20x 19x 2x 17x 17x 1x 16x 16x 16x 16x 16x 3x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 11x 11x 11x 11x 8x 8x 7x 7x 3x 2x 12x 12x 12x 2x 2x 2x 2x 2x 2x 2x 12x 12x 1x 1x | import { Hono } from "hono";
import type { Dal } from "../../dal";
import { resolveEnvironment } from "../../lib/domain-utils";
import { getWhatsAppIds } from "../../lib/env-config";
import { logger } from "../../lib/logger";
import { notifyPartnerReferralUpdate } from "../../lib/partners/notify";
import { createWhatsAppClient } from "../../lib/whatsapp/client";
import type { WhatsAppWebhookPayload } from "../../lib/whatsapp/types";
import {
extractMessages,
extractStatuses,
extractTemplateStatuses,
verifyWebhookSignature,
} from "../../lib/whatsapp/webhook";
import type { Services } from "../../services";
import {
metaTimestampToDate,
recordRrmDeliveryStatus,
} from "../../services/rrm/delivery.service";
import { handleRrmInbound } from "../../services/rrm/inbound.service";
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(
resolveEnvironment(env.ENVIRONMENT),
);
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`);
const marketingId = env.WA_MARKETING_PHONE_NUMBER_ID;
for (const { message, contactName, phoneNumberId } 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);
// RRM + referral routing: only messages that arrived on the marketing
// number feed either funnel. `WA_MARKETING_PHONE_NUMBER_ID` IS set in
// every environment (wrangler.jsonc), so this gate is live — the
// comment that used to say otherwise was written before the id was
// configured and outlived it. A failure here must never break the
// webhook's 200 or stop the remaining messages in this batch.
if (marketingId && phoneNumberId === marketingId) {
try {
const outcome = await handleRrmInbound(
{
db,
env,
// The homeowner acknowledgement, injected rather than
// imported, so the service that decides WHETHER to
// acknowledge never has to know how to send. It also
// keeps the send out of the unit tests, which have no
// WhatsApp client and should not need one to assert a
// state transition.
acknowledge: async ({
phoneNorm,
contactName: name,
partnerName,
}) => {
const conversation =
await services.waConversation.getOrCreateConversation(
phoneNorm,
name,
);
await services.waConversation.reply(
conversation.id,
acknowledgementText(partnerName),
// null = a system send. `sent_by` is an FK to
// users.id, so a fabricated id would throw.
null,
client,
);
},
},
{
from: message.from,
wamid: message.id,
contactName,
phoneNumberId,
text: message.text?.body,
},
);
logger.info(`[WEBHOOK] RRM inbound outcome: ${outcome.outcome}`);
// The first of the four promises the partner app makes: "we
// will let you know the moment they message us". Only on the
// message that actually MOVED the referral — a homeowner's
// later messages match the same live referral and land here
// too, and one template per message is spam the partner
// cannot switch off without switching all of them off.
//
// Already inside `processWebhook`, which the route runs in
// `waitUntil` and which swallows its own errors; the notifier
// never throws either. Awaited rather than fired, so the batch
// keeps its order.
if (outcome.outcome === "referral_engaged" && outcome.engaged) {
await notifyPartnerReferralUpdate(
{ db, env, dal },
{ referral: outcome.referralId, state: "engaged" },
);
}
} catch (err) {
logger.error("[WEBHOOK] RRM inbound routing error:", err);
}
}
}
// 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,
);
// RRM: complete the funnel event the gateway opened at send time.
// Discriminated by WAMID, not phone_number_id — one number serves
// OTP, homeowner and partner traffic, so the id cannot tell them
// apart; a wa_messages row with a prospect_id can. A no-op for
// every non-RRM status. Must never break the webhook's 200 or
// stop the remaining statuses in this batch.
try {
const rrmOutcome = await recordRrmDeliveryStatus(
{ db },
{
wamid: status.id,
status: status.status,
errorCode: status.errors?.[0]?.code,
errorTitle: status.errors?.[0]?.title,
occurredAt: metaTimestampToDate(status.timestamp),
},
);
logger.info(`[WEBHOOK] RRM delivery outcome: ${rrmOutcome.outcome}`);
} catch (err) {
logger.error("[WEBHOOK] RRM delivery status error:", err);
}
}
// 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;
/**
* What a homeowner hears back, once, immediately.
*
* Free-form and in-window: they messaged us seconds ago, so this needs no
* approved template and costs nothing against the ceiling.
*
* Deliberately says almost nothing. It confirms we have them and that a person
* is coming — it does not ask the five qualification questions, because those
* are an operator's job until the slot-filler exists, and a bot interrogating
* someone who just acted on a friend's recommendation is a worse first
* impression than a short wait.
*/
export function acknowledgementText(partnerName: string | null): string {
const who = partnerName ? `${partnerName} ` : "Someone ";
return (
`Thanks for getting in touch! ${who}asked us to put together a free ` +
"interior design estimate for your home — no cost and no obligation.\n\n" +
"One of our team will message you shortly to understand what you have in mind."
);
}
|