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

154 lines
6.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Engineering Review: Twilio WhatsApp Inbound Webhook
**Date:** 2026-06-10
**Status:** REVIEWED — cleared to implement
**Spec:** [[2026-06-10-twilio-whatsapp-inbound-webhook]]
**Related:** [[2026-06-09-tracking-links-deployment]]
---
## Decisions
### D1 — Meta hardening included in this PR
Include both Meta webhook fixes (fail-open + timingSafeEqual length guard) in the same PR. They are 5–10 lines each, adjacent to the Twilio route, and closing a live security hole deferred is worse than a slightly larger PR.
### D2 — Keep RoutedWebhookEvent as-is (user override)
Spec says normalize Twilio payload to `RoutedWebhookEvent`. The interface has two Meta-specific fields (`phoneNumberId` = Meta internal ID, `credentials: WhatsAppCredentials` = Meta access token). For the Twilio path: stuff the Twilio `To` number (stripped of `whatsapp:`) into `phoneNumberId`, load credentials from store even if unused by the reply path. Recommended against; user chose this for future-transport consistency.
### D3 — Redis seed at startup with new PILOT_CUSTOMER_ID env var
At pod startup, call `redis.set('twilio_wa_number:+19547385805', PILOT_CUSTOMER_ID)` using the existing `TWILIO_WHATSAPP_NUMBER` env var for the key and a new `PILOT_CUSTOMER_ID` env var for the value. This is consistent with the spec's multi-tenant design intent. New K8s env var required: `PILOT_CUSTOMER_ID`.
---
## Scope (4 files)
| File | Change |
|---|---|
| `src/webhooks/twilio-whatsapp.ts` | **New.** HMAC-SHA1 validation, normalization, approval handler |
| `src/webhooks/twilio-whatsapp.test.ts` | **New.** 12 tests |
| `src/index.ts` | **Modify.** One `app.post` line + Meta fail-open fix + length guard |
| `hermes-k8s.yaml` | **Modify.** Add `PUBLIC_WEBHOOK_BASE_URL` + `PILOT_CUSTOMER_ID` (kimi-cli) |
---
## Architecture Notes
### HMAC-SHA1 validation — no Twilio SDK
The Twilio SDK is NOT a dependency. Implement manually:
```
sorted_params = sort(POST params by key), then concat key+value pairs
hmac_input = fullURL + sorted_params (no separators)
signature = Base64(HMAC-SHA1(TWILIO_AUTH_TOKEN, hmac_input))
compare with X-Twilio-Signature header (timingSafeEqual, with length check first)
```
URL to validate against: `PUBLIC_WEBHOOK_BASE_URL + /webhook/twilio/whatsapp`.
**Do NOT** use `req.protocol + '://' + req.hostname` — Express sees internal http:// behind the K8s ingress. Pin via `PUBLIC_WEBHOOK_BASE_URL=https://hermes.squaremcp.com`.
### Customer resolution
At module init (called once at pod startup):
```typescript
const twilioNumber = (process.env.TWILIO_WHATSAPP_NUMBER ?? '').replace(/^whatsapp:/, '');
const pilotCustomerId = process.env.PILOT_CUSTOMER_ID ?? '';
if (twilioNumber && pilotCustomerId) {
await redis.set(`twilio_wa_number:${twilioNumber}`, pilotCustomerId);
}
```
When a message arrives: `redis.get('twilio_wa_number:' + toNumber)`.
### Reply transport
`twilioSend(to: string, body: string)` at `src/clients/whatsapp.ts:16` — already exists. Reuse directly from the approval handler. Credentials loaded via RoutedWebhookEvent are unused for replies; Twilio uses env vars.
### express.urlencoded already global
The global `express.urlencoded({ extended: true, limit: '100kb' })` middleware already parses Twilio's `application/x-www-form-urlencoded` body. No raw body middleware needed (unlike the Meta handler which needs `express.raw` to verify HMAC over the raw bytes). Twilio signs over the sorted POST params directly.
---
## Code Quality Issues
### 1. Meta fail-open (src/index.ts:1351) — MUST FIX
```typescript
// BEFORE (fail-open — processes unsigned requests when env unset)
if (WHATSAPP_APP_SECRET) { /* validate */ }
// AFTER (fail-closed)
if (!WHATSAPP_APP_SECRET) {
console.error('[webhook/whatsapp] WHATSAPP_APP_SECRET not set — refusing to process');
res.status(503).send('Webhook validation not configured');
return;
}
// ... then validate unconditionally
```
### 2. timingSafeEqual length guard (src/index.ts:1358) — MUST FIX
```typescript
// BEFORE — throws RangeError → 500 if header is malformed/short
if (!crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected))) {
// AFTER — malformed header → 403, not 500
const sigBuf = Buffer.from(sig);
const expectedBuf = Buffer.from(expected);
if (sigBuf.length !== expectedBuf.length ||
!crypto.timingSafeEqual(sigBuf, expectedBuf)) {
```
Apply the same pattern in the Twilio handler.
### 3. TWILIO_AUTH_TOKEN unset → 503
Twilio handler must be fail-closed:
```typescript
const TWILIO_AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN ?? '';
// At request time:
if (!TWILIO_AUTH_TOKEN) {
console.error('[webhook/twilio/whatsapp] TWILIO_AUTH_TOKEN not set');
res.status(503).send('Webhook validation not configured');
return;
}
```
---
## Tests (12 cases, vitest + vi.mock style)
Mirror `src/tracking-links.test.ts` structure. Mock: `redis`, `mysql pool`, `twilioSend`, `crypto.createHmac`.
1. Valid signature → 200 TwiML, message processed async
2. Invalid signature → 403, nothing processed
3. Missing `X-Twilio-Signature` header → 403 (no throw)
4. Malformed/short signature → 403 (no 500 — length guard fires)
5. `TWILIO_AUTH_TOKEN` unset → 503, nothing processed
6. Duplicate `MessageSid` → second delivery returns 200 but approval skipped
7. Sender ≠ `pilot_owner_phone` → 200 TwiML, no draft query, no reply
8. Body "1" with pending batch → correct draft approved, tracking link created, publish called, confirm reply sent
9. Body "1" with expired batch (>7 days old) → expiry reply, no publish
10. Body "hello" (unrecognized) → help reply listing pending drafts
11. `NumMedia > 0` (image/voice note) → polite "text 1, 2 or 3" reply, no draft query
12. URL reconstruction behind proxy (`X-Forwarded-Proto: https`) → note: implementation uses `PUBLIC_WEBHOOK_BASE_URL` pin, so proxy header is NOT used; test validates pin takes precedence
---
## New Env Vars (K8s manifest — kimi-cli)
| Var | Value | Notes |
|---|---|---|
| `PUBLIC_WEBHOOK_BASE_URL` | `https://hermes.squaremcp.com` | Required for Twilio HMAC URL reconstruction |
| `PILOT_CUSTOMER_ID` | `<Lodge Brothers customer ID from DB>` | Seeded into Redis at pod startup |
`TWILIO_AUTH_TOKEN` already present at line 146 of hermes-k8s.yaml — no duplicate.
---
## Out of Scope (this PR)
- Pilot draft cron (`src/pilot/cron.ts`) — weekly Claude API draft generation
- `GET /dashboard` — lead dashboard
- Multi-tenant Twilio number registration (the Redis pattern is future-proofed; `PILOT_CUSTOMER_ID` is the pilot seed)