How to Verify HMAC-Signed Webhooks in Node.js and Python (Solana API Worked Example)

A complete guide to verifying HMAC-SHA256 signatures on incoming Solana webhooks — with working Node.js and Python handlers, replay-attack protection, and the exact header spec the MadeOnSol copy-trade API uses.

MadeOnSol··Updated · 8 min read
How to Verify HMAC-Signed Webhooks in Node.js and Python (Solana API Worked Example)

If your Solana bot takes trading actions on an incoming webhook, you need to know the request actually came from your data provider — not a scanner that noticed your endpoint and started firing forged payloads. HMAC-SHA256 signatures solve this, but most webhook docs stop at "here is the header" and leave the tricky parts (raw-body handling, timestamp windows, constant-time comparison) to the reader.

This guide walks through a complete verification implementation in both Node.js and Python, using the MadeOnSol copy-trade webhook as a concrete example. The same technique applies to any webhook that signs with HMAC: Stripe, GitHub, Shopify, and most Solana data APIs use the same general pattern.

The threat model

An unsigned webhook endpoint has two obvious problems:

  1. Forgery — anyone who discovers the URL can POST fake trade signals to it. A bot that auto-buys tokens on receipt is a drained wallet waiting to happen.
  2. Replay — even a real webhook payload can be captured (by a middlebox, a logged reverse proxy, an exposed Cloudflare tunnel) and replayed later, when the underlying signal is no longer fresh.

HMAC signatures solve #1 by requiring a shared secret. Timestamped signatures solve #2 by binding the signature to a moment in time, so replays outside a short window can be rejected. If you're hardening the on-chain side of your stack as well, our Solana program security audit checklist covers the smart-contract vulnerabilities that webhook auth alone won't catch.

What MadeOnSol sends

Every copy-trade webhook POST includes three headers:

HeaderValue
X-MadeOnSol-TimestampUnix millis at signing time, e.g. 1713556200123
X-MadeOnSol-Signaturehex(HMAC-SHA256(secret, timestamp + "." + rawBody))
X-MadeOnSol-EventEvent type, e.g. copytrade:signal

The signed string is literally ${timestamp}.${rawBody}. The raw body is the exact bytes of the JSON request — not a re-serialized object. This is the single most common mistake: verifying against JSON.stringify(req.body) after your framework has already parsed it. Keys reorder, spaces vanish, and your HMAC no longer matches.

The shared secret is generated when you create a copy-trade subscription and is visible once in the response. Store it like any other API credential — environment variable, secrets manager, never in code.

Node.js + Express

Express's default express.json() middleware parses and then discards the raw body. We need it back. The cleanest fix is to mount a raw-body parser on the webhook route only, leaving the rest of the app untouched.

import express from "express";
import crypto from "node:crypto";

const app = express();
const SECRET = process.env.MADEONSOL_WEBHOOK_SECRET!;
const MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes

app.post(
  "/webhooks/madeonsol",
  express.raw({ type: "application/json" }),
  (req, res) => {
    const timestamp = req.header("x-madeonsol-timestamp");
    const signature = req.header("x-madeonsol-signature");
    const event = req.header("x-madeonsol-event");

    if (!timestamp || !signature) {
      return res.status(400).send("Missing signature headers");
    }

    // Reject anything outside the 5-minute window
    const age = Date.now() - Number(timestamp);
    if (Number.isNaN(age) || age > MAX_AGE_MS || age < -30_000) {
      return res.status(400).send("Stale timestamp");
    }

    // req.body is a Buffer because of express.raw()
    const rawBody = req.body.toString("utf8");
    const expected = crypto
      .createHmac("sha256", SECRET)
      .update(`${timestamp}.${rawBody}`)
      .digest("hex");

    const sigBuf = Buffer.from(signature, "hex");
    const expBuf = Buffer.from(expected, "hex");

    if (
      sigBuf.length !== expBuf.length ||
      !crypto.timingSafeEqual(sigBuf, expBuf)
    ) {
      return res.status(401).send("Invalid signature");
    }

    // Signature verified — safe to parse and act
    const payload = JSON.parse(rawBody);
    console.log(`[${event}]`, payload.data);
    res.status(200).send("ok");
  }
);

app.listen(3000);

A few non-obvious details in this handler:

  • express.raw({ type: "application/json" }) overrides the global JSON parser for this one route. Remove it and your HMAC will never match.
  • -30_000 on the lower bound of the age check allows for small clock skew between the signing server and yours. Without it, a webhook signed 2 seconds in the future (common with NTP drift) gets rejected.
  • crypto.timingSafeEqual prevents timing attacks. Never use === to compare signatures — a byte-by-byte string comparison returns fractionally faster on mismatch at later positions, and attackers can exploit that to brute-force one byte at a time.
  • Parse after verify, never before. If the body is forged, you don't want its contents anywhere near JSON.parse or your logic.

Building a product on Solana or Robinhood Chain data?

Skip the Geyser pipeline — embed KOL flow, deployer reputation, and the all-DEX firehose over REST, WebSocket, or webhooks. The Business tier (€400/mo) is the self-serve embed license at 500k calls/day — Enterprise adds white-label & redistribution.

See Business pricing

Python + FastAPI

FastAPI has the same raw-body-vs-parsed-body issue. Pydantic models want to parse the JSON, but we need the untouched bytes first. Read the raw body directly via await request.body():

import hmac
import hashlib
import json
import os
import re
import time
from fastapi import FastAPI, Request, HTTPException

app = FastAPI()
SECRET = os.environ["MADEONSOL_WEBHOOK_SECRET"].encode()
MAX_AGE_MS = 5 * 60 * 1000
HEX64 = re.compile(r"[0-9a-fA-F]{64}")

@app.post("/webhooks/madeonsol")
async def madeonsol_webhook(request: Request):
    timestamp = request.headers.get("x-madeonsol-timestamp")
    signature = request.headers.get("x-madeonsol-signature")
    event = request.headers.get("x-madeonsol-event")

    if not timestamp or not signature:
        raise HTTPException(400, "Missing signature headers")
    # 64 ASCII hex characters, no prefix. Checking this first also keeps
    # hmac.compare_digest from raising TypeError on a non-ASCII header.
    if not HEX64.fullmatch(signature):
        raise HTTPException(401, "Invalid signature")
    if not timestamp.isascii() or not timestamp.isdigit():
        raise HTTPException(400, "Bad timestamp")

    # Clock-skew tolerant age check
    age = int(time.time() * 1000) - int(timestamp)
    if age > MAX_AGE_MS or age < -30_000:
        raise HTTPException(400, "Stale timestamp")

    raw_body = await request.body()
    signed = f"{timestamp}.".encode() + raw_body
    expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest()

    if not hmac.compare_digest(expected, signature.lower()):
        raise HTTPException(401, "Invalid signature")

    payload = json.loads(raw_body)
    print(f"[{event}]", payload["data"])
    return {"status": "ok"}

Two details worth calling out:

  • hmac.compare_digest is Python's constant-time comparison. It's in the standard library, so don't write your own. It raises TypeError when given a str containing non-ASCII characters, which is why the handler checks the header against a 64-character hex pattern first.
  • await request.body() gives you the exact bytes. Using await request.json() first and re-encoding will not match the signature if the producer's JSON serializer emitted any different whitespace or key order.

Testing your handler

The best way to confirm a signature verifier works is to sign a payload yourself and fire it at localhost. Here is a one-off signer you can run to generate matching headers:

import crypto from "node:crypto";

const SECRET = "your_webhook_secret";
const body = JSON.stringify({
  event: "copytrade:signal",
  data: { token_mint: "So11...", action: "buy", sol_amount: 0.5 },
  timestamp: new Date().toISOString(),
});
const timestamp = Date.now().toString();
const signature = crypto
  .createHmac("sha256", SECRET)
  .update(`${timestamp}.${body}`)
  .digest("hex");

console.log(`curl -X POST http://localhost:3000/webhooks/madeonsol \\
  -H "Content-Type: application/json" \\
  -H "X-MadeOnSol-Timestamp: ${timestamp}" \\
  -H "X-MadeOnSol-Signature: ${signature}" \\
  -H "X-MadeOnSol-Event: copytrade:signal" \\
  -d '${body}'`);

Run it, paste the curl command into your terminal, and you should see a 200 ok. Then flip one character in the signature and confirm you get 401 Invalid signature. If both behave correctly, your handler is ready.

Common mistakes to avoid

  • Verifying the parsed body. Frameworks reorder keys and normalize whitespace. Always sign against the raw bytes.
  • Using === or == for signature comparison. Timing attacks on webhook endpoints are real and have been demonstrated in the wild. Use timingSafeEqual or compare_digest.
  • Skipping the timestamp check. A signature alone, without a timestamp window, can be replayed forever by anyone who captured one valid request.
  • Logging the raw body before verification. If an attacker can trigger an error that dumps the request body into your logs, they've just populated your logs with whatever they wanted to inject.
  • Using the same secret across subscriptions. MadeOnSol issues a unique secret per copy-trade subscription so a leak of one doesn't compromise all of them. Store them individually.

Beyond verification

Once the signature check passes, the payload is authenticated but you still need to handle delivery semantics:

  • Idempotency. The same signal may be delivered more than once if your endpoint times out, and a retry resends the same body. The envelope carries no event id, so deduplicate on the payload's own identity: for copytrade:signal that is data.subscription_id plus data.tx_signature (one signal per rule per source trade).
  • Ack quickly. MadeOnSol retries on 5xx, on 429, on timeouts and on socket errors. Return 200 as soon as you've persisted the payload, and do the actual trade execution in a background worker.
  • Monitor delivery failures. The dashboard shows per-subscription delivery stats, but also log them yourself so you can alert on sustained errors.

If you want to see this exact signature scheme wired into a full production bot rather than an isolated handler, the Discord deployer-alert bot and Telegram deployer-alert bot tutorials both build on it end-to-end.

Resources

The 40-line Express handler and 30-line FastAPI handler above are all you need to securely receive copy-trade signals in production. The same pattern applies to any HMAC-signed webhook — only the header names change.

Tools mentioned

Compare features and read reviews.

Live health scores, average ratings, and direct links on MadeOnSol.

Get this data via API

Stream real-time KOL trades, PnL rankings, and coordination signals programmatically.

Start free
import { MadeOnSol } from "madeonsol";

const client = new MadeOnSol({ apiKey: "msk_your_key" });

// Real-time KOL trades
const { trades } = await client.kol.feed({ limit: 10, action: "buy" });

// KOL convergence signals
const { tokens } = await client.kol.coordination({ min_kols: 3 });
npm install madeonsolFull API docs

Building a product on Solana or Robinhood Chain data?

MadeOnSol isn't an RPC or another generic token API — it's Solana & Robinhood Chain memecoin intelligence that's painful to build in-house, pulled from dual-region gRPC shred streams and our own Robinhood Chain node, pushed to your app as events land.

Signals you'd otherwise build

KOL & smart-money flow from 2,000+ labeled wallets, deployer reputation, coordination clusters, linked-wallet entity resolution, and an all-DEX firehose.

Embed it in your product

The Business tier (€400/mo, self-serve) licenses you to display MadeOnSol data inside your own product — 500k calls/day, 15 WS + 6 firehose connections. Enterprise above adds white-label & redistribution rights and custom endpoints.

Evaluate first, commit later

Test everything on a free ULTRA key — no commitment. If it fits, we scope volume or white-label pricing.

Keep reading

More from the blog.

All Developer Tools
Copy-Trade Solana KOL Wallets: Build a Paper-Trading Bot in 5 Minutes

Developer Tools

Copy-Trade Solana KOL Wallets: Build a Paper-Trading Bot in 5 Minutes

Watch live smart-money trades on Solana and paper-trade them in real time: open a virtual position when a tracked KOL buys, close when they sell, and track PnL from the market-cap multiple. This tutorial walks the open-source kol-copytrade-bot-starter — ~300 lines, one dependency, free API key — and shows how to filter by KOL win rate, deployer tier, and multi-KOL confirmation before risking anything real.

5 minJuly 5, 2026
Solana Smart Money Tracker: Find Wallets Worth Following

Guides

Solana Smart Money Tracker: Find Wallets Worth Following

A walkthrough with live Solana data: judge a wallet's track record, separate realized from unrealized profit, and check a wallet's later sales before you follow its buy.

33 minOctober 28, 2026
How to Get pump.fun Token Trades via API: the Per-Mint Trade Tape (2026)

Guides

How to Get pump.fun Token Trades via API: the Per-Mint Trade Tape (2026)

One GET returns every buy and sell on a pump.fun token, newest first, with the executed price, the pool price at that slot, the wallet and the early-buyer rank. Cursor paging, buy/sell and wallet filters, and what the coverage block tells you before you trust the numbers.

9 minSeptember 5, 2026
How to Stream New Solana Token Launches over WebSocket: Deploys, Graduations, Surges (2026)

Guides

How to Stream New Solana Token Launches over WebSocket: Deploys, Graduations, Surges (2026)

One socket, three channels: sniper:deploys pushes every pump.fun launch a few hundred milliseconds before the chain confirms it, token:graduations pushes every bonding-curve completion, token:surges pushes young tokens running 3×, 6× or 8× against their launch cap. Handshake, real frames, filters, and what each channel does not tell you.

10 minSeptember 5, 2026
How to Track Solana KOL Wallet Trades via API: since-Cursor Polling or WebSocket Push (2026)

Guides

How to Track Solana KOL Wallet Trades via API: since-Cursor Polling or WebSocket Push (2026)

Two ways to follow the trades of 1,000+ tracked Solana KOL wallets: poll GET /api/v1/kol/feed with the next_since cursor, or subscribe to the kol:trades WebSocket channel. Real response fields, the per-KOL scores that ride on every row, and how to pick wallets from the leaderboard.

9 minSeptember 5, 2026
Mizar Review 2026: Multi-Chain Copy Trading and DCA Bots — Including Solana

Reviews

Mizar Review 2026: Multi-Chain Copy Trading and DCA Bots — Including Solana

Mizar bundles copy trading, DCA, and automated take-profit/stop-loss into one pay-per-trade platform across Solana, Ethereum, Base, and BNB Chain. Here's what it costs, what it does well, and why it's not a Solana-exclusive tool.

5 minJuly 6, 2026

Enjoyed this article?

Explore the live data.

Real-time KOL trades, Pump.fun deployer intel, and 1,200+ ranked Solana & Robinhood Chain tools — free to explore.

Open the KOL Tracker