Dev.to Security 🔐 Cybersecurity 👁 2 📖 4 min read

Verify webhook signatures over the raw bytes, and three other rules for a receiver that holds up

Most webhook bugs we've run into in payment and swap integrations have nothing to do with the signature math. HMAC-SHA256 is one line in every language. The trouble starts around it: the body gets parsed before it's chec

Most webhook bugs we've run into in payment and swap integrations have nothing to do with the signature math. HMAC-SHA256 is one line in every language. The trouble starts around it: the body gets parsed before it's checked, the same event gets processed twice, or the handler does slow work before it answers.

Below is a small Express receiver and the four rules we follow when we build one. The examples assume a generic X-Signature header that carries a hex HMAC-SHA256 of the request body. Your provider may use a different header name or encoding, so check their docs before you copy anything.

1. Verify the raw body, not the parsed JSON

The provider signs the exact bytes it sends. If your framework parses the JSON first and you rebuild it with JSON.stringify, the key order, whitespace or unicode escaping can change. The HMAC stops matching, and the fix people tend to reach for at 2 a.m. is turning verification off.

In Express, put express.raw on the webhook route only, so the rest of the app keeps using express.json:

import crypto from 'node:crypto';
import express from 'express';

const app = express();
const secret = process.env.WEBHOOK_SECRET;

app.post('/webhooks/provider', express.raw({ type: 'application/json' }), async (req, res) => {
  const received = req.get('X-Signature') ?? '';
  const expected = crypto
    .createHmac('sha256', secret)
    .update(req.body) // a Buffer, exactly as it arrived
    .digest('hex');

  const valid =
    received.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));

  if (!valid) return res.sendStatus(401);

  const event = JSON.parse(req.body.toString('utf8'));
  // rules 2 to 4 below
});

app.use(express.json()); // the rest of the app

Order matters here. If app.use(express.json()) is registered above the webhook route, the body is already parsed by the time your handler runs and req.body is an object, not a Buffer.

On the Next.js App Router, await request.text() gives you the raw string. Hash that before you call JSON.parse.

The length check comes first because timingSafeEqual throws when the two buffers differ in length. The constant-time comparison itself keeps response timing from telling an attacker how many characters of their guess were right.

2. Save the event id before you do anything else

Providers retry. If your server answered 200 but the response got lost, or answered after the provider's timeout, the same event comes again. That's expected behaviour, so plan for it.

A unique constraint does most of the work:

CREATE TABLE webhook_events (
  event_id    text PRIMARY KEY,
  payload     jsonb NOT NULL,
  received_at timestamptz NOT NULL DEFAULT now()
);
const { rowCount } = await db.query(
  `INSERT INTO webhook_events (event_id, payload)
   VALUES ($1, $2)
   ON CONFLICT (event_id) DO NOTHING`,
  [event.id, event]
);
const isNew = rowCount === 1;

With node-postgres, rowCount is 0 when the row already existed, so a duplicate falls through without side effects.

3. Answer fast and do the work later

Every provider gives you a fixed window to return a 2xx before it counts the delivery as failed. GitHub, for example, allows 10 seconds. Some swap and payment APIs allow 3. Sending emails, updating a CRM or recalculating balances inside the handler will push you past that sooner or later, and then you get retries for events you already handled.

  res.sendStatus(200);
  if (isNew) await queue.add('sync-order', { orderId: event.data.id });

The handler does three things: it checks the signature, stores the event and enqueues a job. Everything else happens in the worker.

4. Treat an event as "something changed", then read the current state

Events can arrive out of order. A retry of an older event can land after a newer one. If the handler writes status = event.status straight into your table, an order can move from sending back to exchanging on the user's screen.

What we do instead: the worker fetches the object from the provider's API and stores whatever it gets back. The event only tells you which object to look at. If you can't refetch, keep a version or timestamp per object and ignore anything older than what you have.

After an outage

Retries don't go on forever. Providers stop after a set number of attempts or hours. If your receiver was down longer than that, the missed events are gone, so after recovery go through the orders that aren't finished yet and reconcile them through the API.

Keep the webhook secret in your secrets store, apart from the API key. Some providers issue a new secret every time you change the webhook URL. If yours does, update the receiver in the same deploy, or let it accept both the old and the new secret for a short overlap.

Checklist

  • Verify the signature over the raw request bytes, with a constant-time compare.
  • Store the event id under a unique constraint before any side effects.
  • Return 2xx within the provider's window, then do the heavy work in a queue.
  • Refetch the object instead of trusting the order events arrive in.
  • After downtime, reconcile unfinished orders through the API.

How do you deal with out-of-order events in your own integrations: refetching, version numbers, or something else? We'd like to hear what has held up in production.

This article was created with the help of AI. The code samples were run and checked before publishing.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.