Cluster 14 · Messaging Provider · Auth + Fallback

Twilio Webhook Validation, Replay Mitigation & Fallback SLA Pattern

Harden Twilio messaging & Event Streams webhooks with constant-time signature checks, `I-Twilio-Idempotency-Token` deduplication, 429 `Retry-After`, and fallback URL failover.

100% Browser-Side · WebCrypto crypto.subtle · Strict CSP

1. Webhook Signature & Replay-Window Inputs

crypto.subtle HMAC-SHA256
Paste an incoming signature header to run constant-time verification.
Replay-Window & Clock-Skew Gate
42s age vs 300s max
PASS: WITHIN REPLAY WINDOW
Event age 42s is within <=300s tolerance window (258s remaining). Pair with Idempotency/Delivery ID cache. (75 UTF-8 bytes · Use HTTPS + constant-time signature validation and cache `I-Twilio-Idempotency-Token` against replay.)
Computed HTTP Signature Header
X-Twilio-Signature: VY/fcfZ2yec/yjJW3YhbsAnr+Wesn1xz9JqoiTLdxIs=
HMAC-SHA256 Hex
558fdf71f676c9e73fca3256dd885bb009ebf967ac9f5c73f49aa88932ddc48b
HMAC-SHA256 Base64
VY/fcfZ2yec/yjJW3YhbsAnr+Wesn1xz9JqoiTLdxIs=
Drop-In WebCrypto Verifier + Replay Guard (verifyWebhook.ts)
// Strict WebCrypto Webhook Verifier + Replay Guard (Cloudflare Workers / Node 20+)
const REPLAY_TOLERANCE_SEC = 300;

function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean {
  if (a.length !== b.length) return false;
  let diff = 0;
  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
  return diff === 0;
}

export async function verifyWebhookRequest(request: Request, secret: string): Promise<{ ok: boolean; reason: string; rawBody: string }> {
  const rawBody = await request.text();
  const sigHeader = request.headers.get("x-twilio-signature") || "";
  const signedInput = rawBody;
  const providedSig = sigHeader.trim();
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(signedInput)));
  const expected = btoa(String.fromCharCode(...mac));
  const ok = timingSafeEqual(enc.encode(providedSig), enc.encode(expected));
  return { ok, reason: ok ? "verified" : "invalid_signature", rawBody };
}
WebhookSLA Guard · Live Check $29 WebhookSLA Guard Kit

Verify Live Webhook Replay Defense, 429 Retry-After & DLQ SLA Readiness

Run a live webhook endpoint & SLA audit on WebhookSLA Guard (webhook.runglab.dev), grab the turnkey $29 WebhookSLA Guard Kit (WebCrypto HMAC verifiers, replay-window store, RFC RateLimit-* middleware & DLQ runbooks) on Creem, or audit webhook OpenAPI specs on SpecDiff (spec.runglab.dev). Need a PayPal invoice? Email [email protected].

Webhook SLA, Signature & Retry Specification Matrix

Control / Header Production Baseline Reliability & Security Rationale
Signature Header X-Twilio-Signature Validate Event Streams body hash or classic URL+sorted-form-params signature
Idempotency Header I-Twilio-Idempotency-Token Deduplicate status callbacks and voice/SMS retries cleanly
Fallback SLA Primary + Fallback Webhook URL Configure deterministic fallback handler and fast 2xx XML/JSON responses
Rate-Limit Shedding HTTP 429 + Retry-After Throttle burst delivery-receipt storms without dropping receipts

Twilio Idempotency & Replay Gate Middleware (TypeScript)

twilio-idempotency-guard.ts
export function extractTwilioAuditContext(request: Request) {
  const signature = request.headers.get("X-Twilio-Signature") || "";
  const idempotencyToken = request.headers.get("I-Twilio-Idempotency-Token") || "";
  const bodySha256Param = new URL(request.url).searchParams.get("bodySHA256") || "";
  return {
    hasSignature: Boolean(signature),
    idempotencyToken,
    hasBodySha256: /^[a-f0-9]{64}$/i.test(bodySha256Param)
  };
}

Twilio Burst Callback 429 + Retry-After Policy

twilio-ratelimit.http
HTTP/1.1 429 Too Many Requests
RateLimit-Policy: "twilio-callbacks";q=250;w=10
RateLimit: "twilio-callbacks";r=0;t=5
Retry-After: 5
Cache-Control: no-store

Implementation Steps & Key Insights

  1. Always verify `X-Twilio-Signature` over the exact public HTTPS URL (watch out for reverse-proxy `http://` vs `https://` rewrite bugs).
  2. For JSON payloads, validate the `bodySHA256` query digest in constant time before parsing the JSON body.
  3. Persist `I-Twilio-Idempotency-Token` (and `MessageSid` + `MessageStatus`) to prevent duplicate SMS alert triggers.
  4. Configure a lightweight static/edge Fallback URL and shed overload traffic cleanly using `429` + `Retry-After`.
  • When running behind Cloudflare, Nginx, or AWS ALB, reconstructed request URLs often show `http://` instead of `https://` — causing `X-Twilio-Signature` checks to fail unless you reconstruct using the canonical external origin.
  • JSON-based Twilio webhooks append `?bodySHA256=<hex>` to the URL before computing the signature, making raw-body SHA-256 verification mandatory.
  • Separate synchronous TwiML/200 responses from slow database analytics writes using a worker queue + DLQ.

Common Production Pitfalls

  • Trusting `request.url` behind TLS-terminating proxies without enforcing `https://` canonical scheme.
  • Sending SMS/email alerts twice when Twilio retries a timed-out delivery receipt.
  • Returning `500` without `Retry-After` during database maintenance instead of controlled `503`/`429` backpressure.
Ship Faster: Audit your live endpoint on webhook.runglab.dev or grab the $29 WebhookSLA Guard Kit.

More Enterprise Webhook SLA & Signature Guides

← Back to Webhook SLA Kit Hub · WebhookSLA Guard ($29 Kit) → · SpecDiff OpenAPI Audit → · Cluster 7B: CORS & HMAC → · Cluster 9: OpenAPI OWASP →

Frequently Asked Questions

Why does `X-Twilio-Signature` fail behind reverse proxies?

Classic Twilio signatures include the full request URL; if your app server sees `http://` behind a TLS proxy instead of `https://`, signature validation fails.

How do I validate JSON Twilio webhooks?

Verify the SHA-256 hex digest of the exact raw request body matches the `bodySHA256` query parameter, then validate the signature over the full URL.

Does WebhookSLA Guard test 429 Retry-After compliance?

Yes — visit https://webhook.runglab.dev to run live webhook ingestion, signature, and SLA header checks.