Files
conversation-history/SquareMCP/2026-06-10-twilio-whatsapp-inbound-webhook.md
T

100 lines
6.9 KiB
Markdown

# 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) validates `x-hub-signature-256` (Meta HMAC)
- `routeWhatsAppWebhook` (src/multitenancy/webhook-router.ts) hard-requires `body.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 handling
- `src/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 `twilio` SDK's `validateRequest(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 env `PUBLIC_WEBHOOK_BASE_URL`. This is the #1 cause of "signature always invalid" behind proxies.
- **If `TWILIO_AUTH_TOKEN` is unset → 503 and log loudly. Do NOT process unsigned requests.** (Lesson from the Meta webhook: src/index.ts:1350 currently skips validation entirely when `WHATSAPP_APP_SECRET` is unset — fail-open. Do not repeat; fix the Meta one too, see Hardening.)
- Length-check before any `crypto.timingSafeEqual` comparison — 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` ← `From` stripped of `whatsapp:` prefix
- `message.id` ← `MessageSid`
- `message.text.body` ← `Body`
- `message.type` ← `'text'` when `NumMedia === '0'`, else the media type
- `customerId` ← resolve from `To` number. 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)
1. **Sender allowlist:** `message.from` must equal the customer's `customers.pilot_owner_phone` (schema column shipped in `5effb41`). Anyone else → ignore + log; do NOT reply (no oracle for strangers).
2. **Idempotency:** dedupe on `MessageSid` (Twilio retries on timeout). Redis `SET NX EX 86400` on `wa_msg_seen:<MessageSid>`; if already seen, ack and skip.
3. **Command parsing:** trimmed body `1`/`2`/`3` → approve the corresponding draft from the customer's most recent PENDING draft batch in `post_drafts`. Anything else → reply with a short help message listing pending drafts.
4. **Staleness:** drafts older than 7 days (or superseded by a newer batch) cannot be approved — reply "those drafts expired, new ones arrive Monday."
5. **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.
6. Every step logs with `customerId` + `MessageSid` context (3-week-later debuggability).
### Hardening (same PR, small)
- Fix the Meta webhook fail-open: `WHATSAPP_APP_SECRET` unset should refuse to process (503 + loud log) in production, not skip validation (src/index.ts:1350).
- Add length guard before `timingSafeEqual` in the Meta handler (src/index.ts:~1358) — malformed `x-hub-signature-256` currently 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_TOKEN` unset → 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 `runInvoiceCron` has NO caller today, so the scheduler trigger must actually be wired: in-process `setInterval` like email-poller.ts:41, or a K8s CronJob)
- Lead dashboard, research_competitor, generate_report — separate eng-review items, review still in progress