In e-commerce and order-management platforms, inbound webhook endpoints drive critical state transitions: payment gateways report settled charges, logistics carriers push cash-on-delivery (COD) status updates, and CRM partners trigger customer provisioning. If an endpoint relies only on URL obscurity or loose IP filtering, an attacker who discovers the route can forge a POST request with payment.succeeded, causing the backend to ship inventory or credit an account for an unpaid order.
According to the OWASP API Security Project, weak validation around external callbacks falls under Unsafe Consumption of APIs, exposing core workflows to direct abuse. Protecting machine-to-machine webhooks requires enforcing cryptographic integrity, strict freshness windows, and idempotent event handling together.
1. Verifying HMAC-SHA256 on the raw body with constant-time comparison
Many teams start with source IP allowlists or static bearer tokens in query parameters. Both shortcuts break in production: cloud partners rotate outbound egress IPs without notice, and reverse proxies trusting unstripped X-Forwarded-For headers let callers spoof origin addresses.
A reliable pattern documented in Stripe Docs for webhook endpoints is verifying an HMAC-SHA256 signature computed with a shared endpoint secret. The critical rule is that HMAC must be calculated over the exact raw request body bytes sent over the wire. Running express.json() first and re-serializing via JSON.stringify(req.body) alters whitespace, key order, decimal precision, or Unicode escapes, breaking valid signatures.
When comparing digests, never use === or ==. Standard equality exits on the first mismatched byte, leaking timing side-channels that attackers can probe repeatedly. Check matching buffer lengths and call crypto.timingSafeEqual in Node.js (or hmac.compare_digest in Python):
export function verifyWebhookSignature( rawBody: Buffer, signatureHeader: string, secrets: string[], toleranceSeconds = 300 ): boolean { const parts = Object.fromEntries( signatureHeader.split(",").map((item) => item.split("=", 2)) ); const timestamp = Number(parts.t); const receivedHex = parts.v1; if (!Number.isFinite(timestamp) || !receivedHex) return false;
const nowSeconds = Math.floor(Date.now() / 1000); if (Math.abs(nowSeconds - timestamp) > toleranceSeconds) return false;
const signedPayload = Buffer.concat([ Buffer.from(${timestamp}., "utf8"), rawBody, ]); const receivedBuf = Buffer.from(receivedHex, "hex");
return secrets.some((secret) => { const expectedBuf = crypto .createHmac("sha256", secret) .update(signedPayload) .digest(); return ( expectedBuf.length === receivedBuf.length && crypto.timingSafeEqual(expectedBuf, receivedBuf) ); }); } ```
This keeps rawBody as an untouched Buffer and parses JSON only after verification succeeds.
2. Blocking replay attacks and rotating webhook secrets
A valid HMAC signature confirms authenticity, yet cannot stop replay attacks alone. An attacker who captures a legitimate signed request from transit logs or proxies can resend that identical payload and signature hours later to trigger duplicate credits, permissions, or shipments.
To block replays, bind the Unix timestamp (t) inside the HMAC input (${timestamp}.${rawBody}), matching the Stripe-Signature header scheme. Because t is signed, modifying it invalidates v1 immediately. Your endpoint checks Math.abs(nowSeconds - timestamp) and rejects requests outside a tight window (commonly 300 seconds to absorb minor NTP drift) with HTTP 400 or 401.
Integrations also need zero-downtime secret rotation. Instead of checking one string, load an active list containing both the new secret and the retiring secret during a 24-hour transition window, testing each candidate with timingSafeEqual before revoking the old key.
3. Idempotent event handling, async queues, and control comparison
A 5-minute window still permits duplicates during normal operation. Payment processors and carriers use at-least-once delivery: whenever an endpoint returns 5xx or exceeds a short timeout (typically 3 to 10 seconds), partners retry the exact same event repeatedly.
When designing partner gateways for enterprise systems and ERP platforms, ToanKhonTech decouples signature checks from slow downstream work. Once HMAC and timestamp checks pass, the endpoint extracts the partner's event_id, writes (provider, event_id) to a webhook_events table under a UNIQUE constraint inside the order-update transaction (or pushes a background queue job), and immediately returns 200 OK.
| Security control | Risk mitigated | Common flaw | Production rule |
|---|
| IP allowlist | Unlisted caller origins | Trusting raw X-Forwarded-For or breaking on IP shifts | Use only as secondary WAF or trusted-proxy filtering |
| Static header token | Unauthenticated basic probes | Logging plain tokens or comparing with === | Never use alone for payment or fulfillment webhooks |
| Raw-body HMAC-SHA256 | Tampering and spoofing | Parsing JSON before hashing; comparing via === | Hash raw Buffer bytes and compare with crypto.timingSafeEqual |
| Signed timestamp window | Replay of captured requests | Reading timestamp from JSON outside the HMAC | Sign ${timestamp}.${rawBody}, reject skew over 300s |
Unique event_id lock |
For verification failures, log only the error code and source IP, never raw secrets or expected signature strings.
Scope and technical caveats
The signed-timestamp layout and raw-body verification flow reference Stripe's official webhook documentation, while the threat model draws on the OWASP API Security Project. The dual-secret rotation, transactional event_id locking, and background queue patterns reflect ToanKhonTech's engineering practice rather than an audit of any specific payment gateway or carrier.
HMAC-SHA256 remains only as strong as key storage and transport security: keep secrets in a secret manager outside Git and enforce HTTPS with TLS 1.2 or higher. Because partners use different headers and signing strings (such as Stripe-Signature with t=...,v1=... versus X-Hub-Signature-256 hashing raw bytes directly), each adapter needs automated tests covering bad signatures, modified JSON whitespace, expired timestamps, and duplicate event_id deliveries.