DEV Community

Cover image for Verifying crypto payment webhooks by hand: raw bytes, timestamps and the headers you shouldn't trust
Coldtill
Coldtill

Posted on

Verifying crypto payment webhooks by hand: raw bytes, timestamps and the headers you shouldn't trust

Most payment webhook bugs I've seen aren't in the business logic. They're in the first ten lines of the handler: the part that decides whether the request is real at all.

A webhook endpoint is a public URL that, when it receives the right JSON, marks an order as paid and ships something. If the check at the top is wrong, anyone who can guess the URL and the payload shape can get free goods. With crypto payments there's no chargeback to save you later, so it's worth getting this part boringly right.

I'll use the webhook format from Coldtill, the self-hosted gateway we build, because it's documented publicly and has a replay-protected signature. But the mistakes are the same with any provider.

The scheme in one line

Every delivery carries a timestamp header and a signature header. The signature is:

"sha256=" + hex( HMAC-SHA256( secret, timestamp + "." + rawBody ) )
Enter fullscreen mode Exit fullscreen mode

In Coldtill's case the headers are X-Coldtill-Timestamp and X-Coldtill-Signature-V2, and each webhook endpoint gets its own signing secret, shown once when you create it.

Signing the timestamp together with the body is what gives you replay protection. Someone who captures one valid request can't resend it next week, because you reject anything whose timestamp is more than a few minutes from your clock, and they can't change the timestamp without breaking the signature.

Mistake 1: verifying the parsed body

This is the classic. Your framework parses JSON for you, you re-serialise it, HMAC that, and it fails maybe one time in fifty. Key order changes, a number like 25.00000000 becomes 25, whitespace disappears. Then someone "fixes" the flaky check by loosening it.

The signature is over bytes, so verify the bytes. In Express that means a raw body parser on this one route:

app.post('/webhooks/payments', express.raw({ type: 'application/json' }), handler)
Enter fullscreen mode Exit fullscreen mode

Parse JSON only after the signature checks out.

Mistake 2: comparing with ===

String equality returns as soon as it finds a different character, which leaks timing information. Over the internet that's hard to exploit, but the fix costs nothing, so use your language's constant-time compare: crypto.timingSafeEqual in Node, hmac.compare_digest in Python, hash_equals in PHP, hmac.Equal in Go.

Here's the whole check in Python, close to what the docs show:

import hashlib, hmac, time

def verify(headers, raw: bytes, secret: bytes) -> bool:
    ts = headers.get("X-Coldtill-Timestamp", "")
    if not ts.isdigit() or abs(time.time() - int(ts)) > 300:
        return False
    want = "sha256=" + hmac.new(secret, ts.encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(want, headers.get("X-Coldtill-Signature-V2", "").lower())
Enter fullscreen mode Exit fullscreen mode

Note the order: the timestamp window first, then the HMAC. Both have to pass.

Mistake 3: forgetting your own clock

A five-minute window only works if your server's clock is right. If the box running your shop drifts, every webhook starts failing with "timestamp too old", and it looks like the gateway is broken. Run NTP (timedatectl should say the clock is synchronised) and log the difference between the header and your clock when you reject a request. That one log line saves a lot of guessing.

Mistake 4: trusting the headers that aren't signed

This one is subtle. A delivery usually comes with an event-name header and a delivery-ID header too. In Coldtill they're X-Coldtill-Event (for example payment.filled) and X-Coldtill-Delivery. Neither is covered by the signature.

So don't branch on the event header. An attacker who replays a real payment.partially_filled body within the window can't change the body, but they could change an unsigned header. Decide what to do from the signed body: its status field, and the reference_id that identifies the payment. The official TypeScript SDK goes a step further and rejects a request where the header disagrees with the body.

Mistake 5: assuming one delivery, in order

Webhooks get retried. Coldtill retries final events on a schedule that runs out to 48 hours, and retries reuse the same delivery ID. Ordering isn't guaranteed either. That means:

  • Store the delivery IDs you've processed and ignore repeats, or make the handler idempotent on reference_id + status so a second "filled" does nothing.
  • If two events arrive out of order, use timestamp_ms from the body, not arrival time. Two events can share a second, which is why the millisecond field exists.
  • Return a 2xx quickly. Do the slow work (emails, fulfilment) after you've recorded the event, so a timeout doesn't trigger a retry for a request you actually handled.

Mistake 6: a legacy signature hanging around

Many providers keep an older signature header for compatibility. Coldtill still sends X-Coldtill-Signature, an HMAC of the raw body alone, with no timestamp, so no replay protection. If you're writing a new handler, verify the V2 header and ignore the old one. If you have an old handler, it's worth a ticket to move it.

Test the failure paths, not just the happy one

The dashboard has a "Send test" button that posts a signed test event to an endpoint, which is good for checking the happy path. I also like a small set of tests that should all return 401:

  1. Correct body, signature from the wrong secret.
  2. Correct signature, body with one character changed.
  3. A valid request with a timestamp ten minutes old.
  4. A valid request whose event header says payment.filled while the body says PARTIALLY_FILLED (this should not mark anything paid).

If all four fail the way you expect, your handler is in better shape than most.

Payments list in the Coldtill dashboard

Where to read more

The full header list, retry schedule and examples in Node, PHP, Go and Python are on Coldtill's webhooks docs page. If you'd rather see how the gateway side fits together, the self-hosted gateway is on GitHub, and the free edition installs with one command on any Linux box with Docker.

Top comments (0)