Artag.dev
Cybersecurity & APIsPublished: 2026-11-16Updated: 2026-11-2110 min read

B2B Webhook Security: Cryptographic HMAC-SHA256 Verification and Anti-Replay

Production engineering guide to hardening B2B webhook receivers against spoofing, timing attacks, and replay attacks using raw-body HMAC-SHA256, crypto.timingSafeEqual, zero-downtime secret rotation, and Redis rate limiting.

HMAC-SHA256WebhooksAppSecAnti-ReplayNode.jsAPIs
O(n)
Constant-time comparison
300s
Strict anti-replay window
0
Downtime on secret rotation

Webhooks power modern B2B automation: payment confirmations from Stripe, inbound customer messages from WhatsApp Business API, and real-time inventory updates from ERPs. Because webhook endpoints sit directly on the public internet, weak signature verification is an open backdoor that lets attackers forge paid orders, trigger refunds, or flood expensive AI worker queues.

In this note, I walk through the four mandatory controls we implement on every B2B webhook receiver at Artag Dev: raw-body HMAC-SHA256 verification, constant-time comparison with `crypto.timingSafeEqual`, timestamp + Redis anti-replay protection, and zero-downtime dual-secret rotation.

Spoofing, timing side channels, and replay attacks

A surprisingly common bug in Node.js services is parsing JSON first (`express.json()`) and then calling `JSON.stringify(req.body)` to recompute the HMAC digest. Any whitespace difference, key reordering, or Unicode escape breaks valid signatures—often tempting teams to disable verification in production.

A second flaw is comparing hex digests with `===`, which short-circuits on the first mismatched byte and leaks timing information. A third is skipping replay protection: even without knowing the shared secret, an attacker who captures one valid request can replay it repeatedly unless you enforce a signed timestamp window and deduplicate seen signatures.

  • Never compute HMAC over `JSON.stringify(req.body)`: always hash the exact raw HTTP `Buffer`.
  • Never compare cryptographic digests with `===`: always use `crypto.timingSafeEqual` after checking equal byte lengths.
  • Bind a timestamp header inside the signed payload and reject requests outside a tight window (e.g. ±300 seconds).

Constant-time HMAC-SHA256 verification with zero-downtime secret rotation

Rotating webhook secrets without breaking active partner integrations requires accepting both the new secret and the previous secret during the cutover window. Our verifier iterates over `[currentSecret, previousSecret]`, computes the HMAC over `<timestamp>.<rawBody>`, and checks equality in constant time. Any failure returns a uniform `401 Unauthorized` without leaking which check failed.

In practice, secret rotation follows a three-step operational runbook: first, generate a 256-bit cryptographically random secret and deploy it as `secondarySecret` alongside the active `primarySecret`; second, update the partner dashboard or webhook issuer to sign with the new key while monitoring metrics to confirm traffic has shifted over; third, promote the new key to `primarySecret` and retire the old key after 24 hours. Because both keys are evaluated in constant time over the exact raw request buffer, partners experience zero dropped deliveries during rotation.

src/security/webhook-hmac.verifier.tstypescript
import crypto from "node:crypto";

export interface WebhookVerifyOptions {
  rawBody: Buffer;
  signatureHeader: string | undefined;
  timestampHeader: string | undefined;
  secrets: string[]; // [currentSecret, previousSecretDuringRotation]
  toleranceSeconds?: number;
}

export function verifyWebhookSignature(opts: WebhookVerifyOptions): {
  valid: boolean;
  reason?: "missing_headers" | "stale_timestamp" | "invalid_signature";
} {
  const { rawBody, signatureHeader, timestampHeader, secrets, toleranceSeconds = 300 } = opts;

  if (!signatureHeader || !timestampHeader) {
    return { valid: false, reason: "missing_headers" };
  }

  const parsedTs = Number.parseInt(timestampHeader, 10);
  const nowSeconds = Math.floor(Date.now() / 1000);
  if (!Number.isFinite(parsedTs) || Math.abs(nowSeconds - parsedTs) > toleranceSeconds) {
    return { valid: false, reason: "stale_timestamp" };
  }

  // Expected signature over: "<timestamp>.<rawBody>"
  const signedPayload = Buffer.concat([
    Buffer.from(`${parsedTs}.`, "utf8"),
    rawBody,
  ]);

  const providedHex = signatureHeader.replace(/^sha256=/i, "").trim();
  const providedBuf = Buffer.from(providedHex, "hex");

  for (const secret of secrets) {
    if (!secret) continue;
    const expectedBuf = crypto
      .createHmac("sha256", secret)
      .update(signedPayload)
      .digest();

    if (
      providedBuf.length === expectedBuf.length &&
      crypto.timingSafeEqual(providedBuf, expectedBuf)
    ) {
      return { valid: true };
    }
  }

  return { valid: false, reason: "invalid_signature" };
}

Redis anti-replay guards and layered rate limiting

A 300-second timestamp tolerance blocks stale traffic, yet still leaves a five-minute window where a captured request could be replayed. We close that window by storing a SHA-256 fingerprint of `(provider, timestamp, signature)` in Redis using `SET NX EX` for twice the tolerance window (600 seconds).

In parallel, we enforce two-tier rate limiting ahead of business logic: IP-level throttling at the edge WAF to absorb volumetric floods, and per-tenant integration quotas in Redis so one misbehaving partner cannot starve shared workers.

Whenever a replay or rate-limit violation triggers, the endpoint immediately returns `409 Conflict` or `429 Too Many Requests` without enqueuing a BullMQ job or touching PostgreSQL, keeping database CPU flat even under sustained abusive traffic.

src/security/anti-replay.guard.tstypescript
import crypto from "node:crypto";
import type { Redis } from "ioredis";

export async function assertNotReplayed(
  redis: Redis,
  provider: string,
  timestampHeader: string,
  signatureHeader: string,
  ttlSeconds = 600
): Promise<boolean> {
  const fingerprint = crypto
    .createHash("sha256")
    .update(`${provider}:${timestampHeader}:${signatureHeader}`)
    .digest("hex");

  const result = await redis.set(`wh:replay:${fingerprint}`, "1", "EX", ttlSeconds, "NX");
  return result === "OK";
}

Production B2B webhook hardening checklist

Before exposing any external webhook endpoint, we verify the following controls via automated security tests in CI and staging. Each control is designed to fail closed so misconfiguration never silently degrades verification:

In addition to cryptographic validation, pay close attention to reverse-proxy buffering and header forwarding. When running behind Cloudflare, NGINX, or an application load balancer, verify that raw body bytes are never mutated by middleware, that client IP headers (`CF-Connecting-IP` or trusted `X-Forwarded-For`) are extracted safely for rate limiting, and that signature verification runs before any database query or queue write.

  • Strict request body size limit (e.g., 256 KB max) to prevent memory-exhaustion DoS.
  • Enforced TLS 1.2+ with HSTS and zero unencrypted HTTP redirects.
  • Structured audit logs for rejected signatures (IP, provider, reason) without ever logging secrets or authorization headers.
  • Fast `200 OK` acknowledgement right after verification and persistence, delegating all downstream work to async queues.
  • Automated negative tests in CI: tampered payload byte, expired timestamp (> 300s), replayed valid request, and rotation cutover with secondary secret.
  • Alerting on sudden spikes in `401 invalid_signature` responses to catch either an active spoofing probe or an uncoordinated partner secret rotation.

Closing thoughts: verifiable cryptography at the perimeter

Proper raw-body HMAC-SHA256 verification, dual-secret rotation, and Redis anti-replay guards take less than a day to implement and eliminate one of the most common attack surfaces in B2B APIs. Treating every inbound webhook as untrusted network input until proven authentic protects both your transactional database and your downstream AI or billing workers from abuse.

If your engineering team needs an API security audit, zero-downtime secret rotation design, or hardened webhook ingestion architecture, explore our Application Security, API Hardening & DevSecOps Engineering service for concrete deliverables and engagement details.

Next architectural step

Application Security, API Hardening & DevSecOps Engineering

Want to apply this architecture in your stack? Reach out at info@artagdev.com.co or review the full deliverables of our dedicated service.