Cluster 14 · Payment Provider · t=<unix>,v1=<hex>

Stripe Webhook Signature Verification, 300s Replay Window & 72h Retry SLA

Verify Stripe-Signature HMAC-SHA256 over `${t}.${rawBody}`, enforce a strict 300-second replay window, deduplicate evt_* IDs, and handle Stripe's 72-hour exponential retry SLA cleanly.

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. (126 UTF-8 bytes · Stripe signs `${t}.${rawBody}` with HMAC-SHA256 hex and enforces a 300-second default replay window.)
Computed HTTP Signature Header
Stripe-Signature: t=1795705200,v1=1c60a68742c053b3f0e262e2023bb7e9259b0db8e053a17857a45e79ff5aea39
HMAC-SHA256 Hex
1c60a68742c053b3f0e262e2023bb7e9259b0db8e053a17857a45e79ff5aea39
HMAC-SHA256 Base64
HGCmh0LAU7Pw4mLiAju36SWbDbjgU6F4V6Reef9a6jk=
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("stripe-signature") || "";
  const parts = Object.fromEntries(sigHeader.split(",").map((p) => p.split("=")));
  const ts = Number(parts.t || 0);
  const nowSec = Math.floor(Date.now() / 1000);
  if (!ts || nowSec - ts > REPLAY_TOLERANCE_SEC || ts - nowSec > 30) return { ok: false, reason: "replay_window_rejected", rawBody };
  const signedInput = `${ts}.${rawBody}`;
  const providedHex = (parts.v1 || "").toLowerCase();
  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 expectedHex = [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
  const ok = timingSafeEqual(enc.encode(providedHex), enc.encode(expectedHex));
  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 Stripe-Signature: t=...,v1=... Verify v1 hex HMAC-SHA256 over `${t}.${rawBody}` using constant-time comparison
Replay Window 300 seconds (5 min default) Reject events with stale `t` or >30s future clock skew to block captured payload replays
Retry Window SLA Up to 72 hours (live mode) Acknowledge HTTP 200 immediately before slow DB/email jobs; return 429 + Retry-After only when shedding load
Idempotency Key event.id (evt_*) Store processed `evt_*` IDs in Redis/Postgres UNIQUE index with >=72h TTL

Stripe WebCrypto Verifier + 300s Replay Guard (TypeScript)

stripe-webhook-verify.ts
export async function verifyStripeWebhook(rawBody: string, header: string, secret: string, toleranceSec = 300) {
  const parts = Object.fromEntries(header.split(",").map((kv) => kv.split("=")));
  const ts = Number(parts.t || 0);
  const nowSec = Math.floor(Date.now() / 1000);
  if (!ts || nowSec - ts > toleranceSec || ts - nowSec > 30) {
    throw new Error("Stripe replay window exceeded");
  }
  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(`${ts}.${rawBody}`)));
  const expected = [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
  const provided = (parts.v1 || "").toLowerCase();
  if (provided.length !== expected.length) return false;
  let diff = 0;
  for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ provided.charCodeAt(i);
  return diff === 0;
}

Stripe Idempotency + Queue ACK Handler

stripe-idempotency.sql
-- Atomic idempotency gate (PostgreSQL) before processing Stripe evt_* webhooks
CREATE TABLE IF NOT EXISTS webhook_deliveries (
  provider TEXT NOT NULL,
  event_id TEXT NOT NULL,
  received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, event_id)
);

-- Inside transaction before fulfilling order:
INSERT INTO webhook_deliveries (provider, event_id)
VALUES ('stripe', $1)
ON CONFLICT (provider, event_id) DO NOTHING
RETURNING event_id;

Implementation Steps & Key Insights

  1. Read the unmodified raw UTF-8 HTTP request body bytes before any JSON parser touches whitespace or key ordering.
  2. Parse `t=` and `v1=` from `Stripe-Signature`, verify `now - t <= 300s`, and compare `HMAC_SHA256(secret, t + '.' + rawBody)` in constant time.
  3. Insert `event.id` into an atomic idempotency table (`ON CONFLICT DO NOTHING`) so duplicate deliveries never double-provision seats.
  4. Push downstream billing/email work onto a durable queue with DLQ alerting and return `200 OK` within 2 seconds.
  • Re-serializing `JSON.stringify(req.body)` destroys key order, Unicode escapes, and trailing newlines — breaking HMAC verification silently in production.
  • Stripe rotates signing secrets gracefully by emitting multiple `v1=` pairs during rotation windows; check any `v1` match against active secrets.
  • Pair HMAC verification with `webhook.runglab.dev` live endpoint checks to confirm TLS, replay rejection, and 429 `Retry-After` behavior.

Common Production Pitfalls

  • Using `===` string comparison instead of constant-time comparison (`crypto.timingSafeEqual`).
  • Running PDF invoice generation or third-party CRM sync synchronously inside the webhook HTTP handler, triggering Stripe timeouts.
  • Omitting an idempotency store, causing duplicate license keys or refunds during Stripe's 72-hour retry retries.
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 Stripe sign `${timestamp}.${rawBody}` instead of just the raw body?

Binding the Unix timestamp `t` directly into the HMAC input guarantees an attacker cannot modify the timestamp on a captured request to bypass your 300-second replay window.

What HTTP status codes cause Stripe to stop vs retry delivery?

2xx responses mark delivery successful. Any 4xx/5xx or timeout triggers exponential backoff retries for up to 72 hours in live mode.

How can I audit my live Stripe webhook endpoint before launch?

Test signature generation & replay windows locally here, then run live endpoint header, replay, and rate-limit SLA checks at https://webhook.runglab.dev.