6.9 KiB
Twilio WhatsApp Inbound Webhook — Pilot Approval Loop (Decision 1A)
Date: 2026-06-10
Status: APPROVED — ready to implement
Source: /plan-eng-review, Architecture Issue 1
Related: 2026-06-09-mysql-backed-tracking-links, 2026-06-09-marketplace-release-checklist
Repo copy: spv/2026-06-10-twilio-whatsapp-inbound-webhook.md
Decision
1A: Build a Twilio inbound message route. The pilot approval loop ("reply 1/2/3 → publish") runs on the existing Twilio number +19547385805. We add one new inbound route with signature validation rather than migrating the pilot to a Meta Cloud API number.
Why: the Twilio number is already live and credentialed (commit dcc1c39); Meta business number provisioning before July is schedule risk we don't control. One new validated route < carrier migration mid-pilot.
The problem this fixes
Sending uses Twilio; the only inbound WhatsApp handler is Meta Cloud API format:
POST /webhook/whatsapp(src/index.ts:1349) validatesx-hub-signature-256(Meta HMAC)routeWhatsAppWebhook(src/multitenancy/webhook-router.ts) hard-requiresbody.object === 'whatsapp_business_account'— Twilio payloads never match- The only Twilio route is
POST /webhook/twilio/voice(call rejection)
So today, Alex's "1" reply to the Twilio number has no webhook to land on — the approval silently vanishes. This route is the missing leg of the loop:
weekly cron ──Claude API──▶ post_drafts ──Twilio send──▶ Alex's phone
│ reply "1"
publish + tracked link ◀── approval handler ◀── [THIS ROUTE] ◀── Twilio
Spec
New files
src/webhooks/twilio-whatsapp.ts— parsing, signature validation, normalization, approval handlingsrc/webhooks/twilio-whatsapp.test.ts— full suite (see Tests)
Route registration in src/index.ts stays thin (one app.post line delegating to the module) — follow the tracking-links house style, do not grow the monolith.
Endpoint
POST /webhook/twilio/whatsapp — Twilio posts application/x-www-form-urlencoded with fields: From (whatsapp:+1...), To, Body, MessageSid, NumMedia, etc.
Configure this URL as the WhatsApp inbound webhook on the Twilio number in the console (the voice webhook on the same number stays as-is).
Signature validation (fail CLOSED)
- Twilio signs with
X-Twilio-Signature: Base64(HMAC-SHA1(authToken, fullURL + params sorted by key, concatenated)). - Prefer the
twilioSDK'svalidateRequest(authToken, signature, url, params)if the SDK is already a dependency; otherwise implement the HMAC-SHA1 directly. - Gotcha (behind k8s ingress/TLS termination): the URL you validate against must be the public HTTPS URL Twilio called, not the internal http:// one Express sees. Reconstruct from
X-Forwarded-Proto+Host+ original path, or pin via envPUBLIC_WEBHOOK_BASE_URL. This is the #1 cause of "signature always invalid" behind proxies. - If
TWILIO_AUTH_TOKENis unset → 503 and log loudly. Do NOT process unsigned requests. (Lesson from the Meta webhook: src/index.ts:1350 currently skips validation entirely whenWHATSAPP_APP_SECRETis unset — fail-open. Do not repeat; fix the Meta one too, see Hardening.) - Length-check before any
crypto.timingSafeEqualcomparison — it THROWS on length mismatch (a malformed header must 403, not 500).
Response
Reply 200 with empty TwiML (<Response></Response>, text/xml) immediately; process the message async after responding — same ack-fast pattern as the Meta handler.
Normalization
Map the Twilio payload into the existing RoutedWebhookEvent shape (src/multitenancy/webhook-router.ts) so there is ONE approval handler regardless of transport:
message.from←Fromstripped ofwhatsapp:prefixmessage.id←MessageSidmessage.text.body←Bodymessage.type←'text'whenNumMedia === '0', else the media typecustomerId← resolve fromTonumber. Reuse the Redis mapping pattern (wa_phone_id:*in webhook-router.ts) with a parallel key, e.g.twilio_wa_number:<E164> → customerId, registered at pilot onboarding.
Approval handler semantics (per-tenant, idempotent)
- Sender allowlist:
message.frommust equal the customer'scustomers.pilot_owner_phone(schema column shipped in5effb41). Anyone else → ignore + log; do NOT reply (no oracle for strangers). - Idempotency: dedupe on
MessageSid(Twilio retries on timeout). RedisSET NX EX 86400onwa_msg_seen:<MessageSid>; if already seen, ack and skip. - Command parsing: trimmed body
1/2/3→ approve the corresponding draft from the customer's most recent PENDING draft batch inpost_drafts. Anything else → reply with a short help message listing pending drafts. - Staleness: drafts older than 7 days (or superseded by a newer batch) cannot be approved — reply "those drafts expired, new ones arrive Monday."
- On approve: create tracking link (
createTrackingLink, src/tracking-links.ts:52) → publish via the platform client → set draft status → confirm to Alex via WhatsApp with the live post URL. - Every step logs with
customerId+MessageSidcontext (3-week-later debuggability).
Hardening (same PR, small)
- Fix the Meta webhook fail-open:
WHATSAPP_APP_SECRETunset should refuse to process (503 + loud log) in production, not skip validation (src/index.ts:1350). - Add length guard before
timingSafeEqualin the Meta handler (src/index.ts:~1358) — malformedx-hub-signature-256currently throws RangeError → 500.
Tests (mirror tracking-links.test.ts style)
- Valid signature → 200, message processed
- Invalid signature → 403, nothing processed
- Missing signature header → 403 (no throw)
- Malformed/short signature → 403 (no 500 — length guard)
TWILIO_AUTH_TOKENunset → 503, nothing processed- Duplicate
MessageSid→ second delivery ignored - Sender ≠
pilot_owner_phone→ ignored, no reply - Body "1" with pending batch → correct draft approved, tracking link created, publish called
- Body "1" with expired batch → expiry reply, no publish
- Body "hello" → help reply listing pending drafts
NumMedia > 0(voice note/image) → polite "text 1, 2 or 3" reply- URL reconstruction behind proxy (X-Forwarded-Proto) → signature validates
Env additions
TWILIO_AUTH_TOKEN(may already exist for the send path — verify, don't duplicate)PUBLIC_WEBHOOK_BASE_URL(for signature URL reconstruction)
Out of scope (this note)
- The weekly draft cron itself (separate module; copy the Redis-lock pattern from src/billing/cron.ts — and note
runInvoiceCronhas NO caller today, so the scheduler trigger must actually be wired: in-processsetIntervallike email-poller.ts:41, or a K8s CronJob) - Lead dashboard, research_competitor, generate_report — separate eng-review items, review still in progress