4 Real Webhook Security Bugs I Hit (and Automated Tests For) While Building a Zero-Dep Verifier
Most webhook tutorials stop at crypto.createHmac('sha256', secret) and call it a day. In production, webhook handlers rarely break because someone forgot what SHA-256 is. They break on subtle middleware, concurrency, an
Most webhook tutorials stop at crypto.createHmac('sha256', secret) and call it a day.
In production, webhook handlers rarely break because someone forgot what SHA-256 is. They break on subtle middleware, concurrency, and stream edge cases that happy-path tests never trigger.
While building hookspec (a zero-dependency TypeScript webhook signer, verifier, and chaos test harness built on Web Crypto), I ran into four real-world failure modesβand built automated checks for each one.
1. The Raw-Body Re-Serialization Trap
The single most common webhook bug in Express, Fastify, and Next.js is verifying JSON.stringify(req.body) instead of the raw request bytes.
Here is why it slips past local tests: if your test fixture is already compact JSON.stringify(obj), re-serializing it produces the exact same bytesβso your test passes by luck. The moment Stripe, Paddle, or OpenAI sends pretty-printed JSON, a trailing newline, or escaped Unicode, every production webhook starts returning 400 Invalid Signature.
How to catch it in CI: Fire a validly signed payload formatted with non-canonical whitespace (JSON.stringify(obj, null, 2) + '\n'). If your endpoint rejects a cryptographically valid payload just because it contains indentation, you are verifying parsed JSON instead of raw bytes.
npx hookspec doctor stripe \
--url http://127.0.0.1:3000/api/webhooks/stripe \
--secret whsec_test_123
In hookspec, the raw-body-whitespace chaos scenario runs by default, and hookspec doctor flags this exact failure with the middleware fix (express.raw({ type: 'application/json' }), readRawBody(req), or verifyWebRequest()).
2. Fail-Open Empty Secrets
In real production advisories (like GHSA-x92v-rpx6-p6cw), webhook endpoints accidentally fail openβor throw unhandled 500sβwhen a signing secret env var is unset:
// Dangerous if STRIPE_WEBHOOK_SECRET is undefined in staging/prod
const secret = process.env.STRIPE_WEBHOOK_SECRET ?? '';
For token-based providers (like GitLab's X-Gitlab-Token), comparing an empty secret against an empty header can silently succeed. For Web Crypto HMAC, importing a zero-length key throws a DataError.
The fix: Every verification path (verifyWebhook, verifyWebRequest, verifyNodeRequest, and createWebhookHandler) must normalize and strip empty/whitespace secrets first, and strictly fail closed with INVALID_KEY when no valid key remains.
3. Simultaneous Duplicate Race Conditions
Providers guarantee at-least-once delivery, and retries don't always arrive seconds apartβsometimes two identical deliveries hit your endpoint in the same millisecond.
A sequential duplicate test won't catch a naive check-then-insert handler:
// Race condition under concurrent retries:
const exists = await db.events.findUnique({ where: { id: event.id } });
if (exists) return Response.json({ duplicate: true });
await db.events.create({ data: { id: event.id } }); // Boom: HTTP 500 unique constraint error
If your handler returns 500, the provider thinks delivery failed and keeps retrying.
The fix: Test with simultaneous Promise.all bursts (concurrent-duplicate in hookspec) and lock the delivery ID atomically before executing business logic:
import { createWebhookHandler } from 'hookspec';
export const POST = createWebhookHandler<{ id: string; type: string }>({
provider: 'stripe',
secret: [process.env.STRIPE_WEBHOOK_SECRET!, process.env.STRIPE_WEBHOOK_SECRET_PREV!],
idempotency: true, // Pass a Redis/Postgres IdempotencyStore for multi-instance prod
async onEvent({ payload }) {
// Verified, raw-body checked, bounded, and deduplicated even under concurrent retries
return Response.json({ received: true, id: payload.id });
},
});
4. Unbounded Body DoS & The WHATWG ReadableStream.tee() Deadlock
Calling await request.text() before verifying a webhook lets any unauthenticated caller POST a 500 MB body and OOM your process.
So in hookspec v1.3.0, I added streaming maxBodyBytes protection (default 1 MiB, returning HTTP 413 Payload Too Large) inside verifyWebRequest(). And that's where I hit a nasty WHATWG Streams gotcha on Node.js:
const cloned = request.clone(); // Internally calls ReadableStream.tee()
const reader = cloned.body.getReader();
if (total > maxBytes) {
await reader.cancel(); // DEADLOCK! Never resolves while request.body is still open!
throw new PayloadTooLargeError(maxBytes);
}
Per the WHATWG Streams spec, request.clone() tees the underlying stream into two branches (request.body and cloned.body). Calling await reader.cancel() on one branch waits until the other branch is also canceled or consumedβhanging the handler forever.
Switching to a non-blocking void reader.cancel().catch(() => {}) before throwing immediately broke the deadlock, and the 413 test dropped from an infinite hang to 17ms.
Try It Out
hookspec is MIT-licensed, has zero runtime dependencies, runs identically on Node 20+, Bun, Deno, Cloudflare Workers, and Next.js Edge, and supports 13 providers (Stripe, Paddle Billing, Lemon Squeezy, GitHub, GitLab, Shopify, Slack, Svix/Clerk/Resend, Standard Webhooks / OpenAI / Supabase / Polar, Linear, Vercel, Twilio, and Discord Ed25519).
npx hookspec doctor stripe --url http://127.0.0.1:3000/api/webhooks/stripe --secret whsec_test
If you've hit other weird webhook edge cases in production (or want another provider added), drop a comment or open an issue!
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.