Mailerflow Start free
Blog › Transactional Email & Developer Tools › Email Webhooks

How to Secure a Webhook Endpoint: Signatures, Timestamps, IP Rules and Secret Rotation

Published November 18, 2026 · 9 min read

Illustration for How to Secure a Webhook Endpoint: Signatures, Timestamps, IP Rules and Secret Rotation

A secure webhook endpoint is one that proves three things about every request it accepts — that the sender really sent it, that the body wasn't altered, and that it isn't a replay of something older — and then processes each event exactly once even though the sender may deliver it twice. This article builds that endpoint step by step in Node.js: HMAC signature verification over the raw body, a timestamp tolerance window, IP allowlisting as a secondary gate, secret rotation that doesn't drop events, and idempotent processing backed by a unique constraint.

What "secure" actually means for a webhook endpoint

A webhook route is public, usually unauthenticated by default, accepts POST bodies, and triggers side effects — marking a contact bounced, firing an internal job, updating a CRM record. That combination is what makes it worth attacking.

Four properties cover the realistic threat model:

  • Authenticity — the request came from the party you expect, not from anyone who guessed the URL.
  • Integrity — the body arrived byte-for-byte as it was sent.
  • Freshness — the request is new, not a captured request replayed an hour later.
  • Idempotency — receiving the same event twice doesn't double-apply the side effect.

Anyone who learns the URL can POST to it, and a valid signature from last week is still a valid signature today unless you check the timestamp. On the sending side, Mailerflow's signed real-time webhooks with retries and delivery logs hold up their half of the contract; everything below is the receiving half.

Prerequisites

  • Node.js 20+ (the snippets use node:crypto and top-level await; adapt freely to Python, Go or PHP).
  • A framework that exposes the raw request body — Express, Fastify, Hono, or a Next.js route handler.
  • A publicly reachable HTTPS URL in production. Locally, use a tunnel such as ngrok or Cloudflare Tunnel. If you're setting that up for the first time, this walkthrough on testing webhooks locally covers tunnels, replays and fixtures.
  • Your webhook signing secret from the Mailerflow dashboard, stored in an environment variable or a secrets manager.

A very common setup mistake: a body parser consumes the JSON and re-serializes it before your handler runs. The signature is computed over the exact bytes the sender transmitted, so JSON.stringify(req.body) will almost never match. Fix it by mounting raw-body middleware on the webhook route only:

// Express
app.use('/webhooks/mailerflow', express.raw({ type: 'application/json' }));

// Next.js App Router
const raw = await req.text();

Verify the signature before you parse the body

The sender computes HMAC-SHA256 over a canonical string — typically timestamp + '.' + rawBody — using the shared secret, and puts the result in a header alongside the timestamp. You recompute it and compare in constant time.

The header names below (X-Webhook-Timestamp, X-Webhook-Signature) are placeholders. Check the Mailerflow developer docs and API reference for the exact header names and the exact canonical string your provider signs — the format varies between providers, and getting it wrong is the most frequent cause of signature mismatches.

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

const app = express();
const SECRET = process.env.MAILERFLOW_WEBHOOK_SECRET;
const TOLERANCE_SECONDS = 300;

function verifySignature(rawBody, timestamp, signature, secrets) {
  const signedPayload = `${timestamp}.${rawBody}`;
  const expected = crypto
    .createHmac('sha256', secrets[0])
    .update(signedPayload, 'utf8')
    .digest('hex');

  const a = Buffer.from(expected, 'utf8');
  const b = Buffer.from(signature, 'utf8');
  if (a.length !== b.length) return false; // timingSafeEqual throws on length mismatch
  return crypto.timingSafeEqual(a, b);
}

app.post(
  '/webhooks/mailerflow',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const timestamp = req.get('X-Webhook-Timestamp');
    const signature = req.get('X-Webhook-Signature');
    if (!timestamp || !signature) return res.status(400).send('missing headers');

    const rawBody = req.body.toString('utf8');
    if (!isFresh(timestamp)) return res.status(400).send('stale timestamp');
    if (!verifySignature(rawBody, timestamp, signature, [SECRET])) {
      return res.status(401).send('invalid signature');
    }

    const event = JSON.parse(rawBody);
    // ...handle event
    res.status(200).json({ received: true });
  }
);

Two details matter. First, compare with crypto.timingSafeEqual, never === — a naive string comparison leaks information through timing, and the length guard is required because timingSafeEqual throws when buffer lengths differ. Second, match the canonical string exactly to what the header format documents; if your sender signs timestamp.body and you hash body.timestamp, every request fails.

Reject replayed requests with a timestamp window

A valid signature stays valid forever. Anyone who captures one request — from logs, a misconfigured proxy, a leaked HAR file — can resend it indefinitely. The fix is a signed timestamp inside the signed payload plus a tolerance window. A few minutes is a reasonable starting point; pick a value that fits your clock discipline rather than copying one.

function isFresh(timestamp, toleranceSeconds = TOLERANCE_SECONDS) {
  const ts = Number(timestamp);
  if (!Number.isFinite(ts)) return false;
  const skew = Math.abs(Math.floor(Date.now() / 1000) - ts);
  return skew <= toleranceSeconds;
}

// inside the handler, before signature verification:
if (!isFresh(timestamp)) return res.status(400).send('stale timestamp');

For high-value events, add a second layer: a short-lived dedupe key on the event ID so a replay inside the tolerance window still can't fire the side effect twice.

import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

async function firstTimeSeen(eventId, ttlSeconds = 600) {
  const result = await redis.set(`wh:${eventId}`, '1', { NX: true, EX: ttlSeconds });
  return result === 'OK'; // false means we've seen it
}

This depends on reasonably accurate clocks. Run NTP on your hosts; a server drifting minutes behind will reject legitimate traffic and look like a signature bug.

IP allowlisting: useful, but never your only control

Allowlisting the sender's published IP ranges is a cheap extra gate, and it is genuinely worth having — but understand its limits. It breaks behind shared NAT, serverless egress and any time the provider adds or rotates ranges. It does nothing against an attacker routing through the same range. Treat it as defense in depth that sits behind signature verification, never as a replacement.

Fetch the provider's published ranges, keep them in config rather than hardcoded, and refresh on a schedule — check the current Mailerflow documentation for the published source ranges rather than copying a list from a blog post, since ranges change and a stale list is worse than none.

import net from 'node:net';

function ipInCidr(ip, cidr) {
  const [range, bitsStr] = cidr.split('/');
  const bits = Number(bitsStr);
  const toInt = (addr) =>
    addr.split('.').reduce((acc, oct) => (acc << 8) + Number(oct), 0) >>> 0;
  const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0;
  return (toInt(ip) & mask) === (toInt(range) & mask);
}

const ALLOWED = process.env.WEBHOOK_SOURCE_CIDRS.split(',');

app.use('/webhooks/mailerflow', (req, res, next) => {
  const ip = req.socket.remoteAddress?.replace('::ffff:', '');
  if (!ip || !ALLOWED.some((cidr) => ipInCidr(ip, cidr))) {
    return res.status(403).send('forbidden');
  }
  next();
});

Rotating the signing secret without dropping events

This part is often skipped. The dual-secret pattern makes rotation boring: during the transition, accept a request if it verifies against either the current or the previous secret; once the grace period ends, drop the old one.

function verifyAny(rawBody, timestamp, signature, secrets) {
  const signedPayload = `${timestamp}.${rawBody}`;
  for (const secret of secrets) {
    const expected = crypto
      .createHmac('sha256', secret)
      .update(signedPayload, 'utf8')
      .digest('hex');
    const a = Buffer.from(expected, 'utf8');
    const b = Buffer.from(signature, 'utf8');
    if (a.length === b.length && crypto.timingSafeEqual(a, b)) return true;
  }
  return false;
}

// secrets[0] = current, secrets[1] = previous (during rotation only)
const activeSecrets = [process.env.WEBHOOK_SECRET_CURRENT, process.env.WEBHOOK_SECRET_PREVIOUS].filter(Boolean);

The operational sequence:

  1. Generate a new secret in your provider's dashboard if it supports overlapping secrets, and add it as a secondary value your code accepts. If it doesn't, you'll need a short maintenance window instead.
  2. Wait long enough for in-flight retries to drain. Retries can arrive well after the original attempt — check your provider's retry schedule and size the window to that, not to how long a deploy takes.
  3. Promote the new secret to primary.
  4. Remove the old secret from config and from your secrets manager.

Don't rotate during an incident or in the middle of a bulk send. Store secrets in a secrets manager or environment variables, never in the repository, and rotate immediately if one leaks. If you want the fuller picture of what happens when rotation and retries collide, this piece on reliable webhook processing goes deeper on queues and backoff.

Idempotency and retries: assume every event arrives twice

Senders retry on non-2xx responses and on timeouts — and a timeout can mean your handler succeeded while the response was lost. Design for at-least-once delivery, not exactly-once.

Three rules:

  • Acknowledge fast. Return 2xx as soon as the event is safely recorded, then process asynchronously via a queue. Never do slow work inline.
  • Key on the event ID. A unique constraint turns duplicate delivery into a no-op.
  • Distinguish 4xx from 5xx. A malformed-but-authentic payload is a 4xx: retrying it will never help. Returning 500 for it causes a pointless retry storm.
import pg from 'pg';
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

async function recordEvent(event) {
  const { rowCount } = await pool.query(
    `INSERT INTO webhook_events (provider_event_id, type, payload)
     VALUES ($1, $2, $3)
     ON CONFLICT (provider_event_id) DO NOTHING`,
    [event.id, event.type, event]
  );
  return rowCount === 1; // false = already processed
}

app.post('/webhooks/mailerflow', express.raw({ type: 'application/json' }), async (req, res) => {
  const rawBody = req.body.toString('utf8');
  const timestamp = req.get('X-Webhook-Timestamp');
  const signature = req.get('X-Webhook-Signature');

  if (!timestamp || !signature) return res.status(400).send('missing headers');
  if (!isFresh(timestamp)) return res.status(400).send('stale timestamp');
  if (!verifyAny(rawBody, timestamp, signature, activeSecrets)) {
    return res.status(401).send('invalid signature');
  }

  let event;
  try {
    event = JSON.parse(rawBody);
  } catch {
    return res.status(400).send('malformed json'); // don't make the sender retry this
  }

  try {
    const isNew = await recordEvent(event);
    if (isNew) await queue.publish('webhook-events', event);
    return res.status(200).json({ received: true });
  } catch (err) {
    console.error('webhook persist failed', { eventId: event.id, err });
    return res.status(500).send('retry');
  }
});

When a handler silently 500s, the sender's delivery logs are how you find out which events were retried and which eventually failed. Mailerflow's delivery logs show exactly that; if events are vanishing without a trace, debugging webhook deliveries walks through the usual causes.

Testing the endpoint before you ship it

Unit tests should cover the four failure modes directly. Sign a fixture body with a known secret and assert 200; tamper one byte and assert 401; send an old timestamp and assert 400; send the same event ID twice and assert the side effect ran once.

import { describe, it, expect } from 'vitest';
import request from 'supertest';
import crypto from 'node:crypto';
import { app } from '../app.js';

const SECRET = 'test_secret';

function sign(body, ts = Math.floor(Date.now() / 1000)) {
  const signature = crypto
    .createHmac('sha256', SECRET)
    .update(`${ts}.${body}`, 'utf8')
    .digest('hex');
  return { ts, signature };
}

describe('webhook endpoint', () => {
  const body = JSON.stringify({ id: 'evt_1', type: 'email.bounced' });

  it('accepts a correctly signed request', async () => {
    const { ts, signature } = sign(body);
    const res = await request(app)
      .post('/webhooks/mailerflow')
      .set('Content-Type', 'application/json')
      .set('X-Webhook-Timestamp', String(ts))
      .set('X-Webhook-Signature', signature)
      .send(body);
    expect(res.status).toBe(200);
  });

  it('rejects a tampered body', async () => {
    const { ts, signature } = sign(body);
    const res = await request(app)
      .post('/webhooks/mailerflow')
      .set('Content-Type', 'application/json')
      .set('X-Webhook-Timestamp', String(ts))
      .set('X-Webhook-Signature', signature)
      .send(body.replace('bounced', 'delivered'));
    expect(res.status).toBe(401);
  });

  it('rejects a stale timestamp', async () => {
    const { ts, signature } = sign(body, Math.floor(Date.now() / 1000) - 3600);
    const res = await request(app)
      .post('/webhooks/mailerflow')
      .set('Content-Type', 'application/json')
      .set('X-Webhook-Timestamp', String(ts))
      .set('X-Webhook-Signature', signature)
      .send(body);
    expect(res.status).toBe(400);
  });
});

For integration, point a real webhook at your tunnel, trigger a real event (for example a test send) and confirm the delivery log shows a 2xx. Then replay a captured request with curl, flip one character in the signature, and confirm the 401. Log the event ID, the verification result and the response code — never the secret, and not the full payload if it carries personal data.

Troubleshooting

Symptom Likely cause Fix
Signature mismatch on every request Body parser re-serialized the JSON Read the raw bytes; mount express.raw() on the route
Intermittent mismatches Proxy or framework alters the body, or encoding differs Verify against the raw stream; check for a rewriting proxy
Everything rejected after a deploy Secret env var missing in the new environment Add the secret to the new environment's config
Duplicate side effects No idempotency key, or 2xx returned before work completes Unique constraint on event ID; ack then queue
Events stop arriving Endpoint returning 5xx repeatedly, or URL changed Check delivery logs; fix the handler or update the URL
Replay window false positives Server clock drift Sync with NTP

FAQ

Is HMAC-SHA256 enough on its own? For authenticity and integrity, yes — provided you also check the timestamp and use a long, random secret. Without the freshness check, a leaked request stays valid forever.

Should I use a WAF instead? Complementary, not a substitute. A WAF can rate-limit and block by IP, but it can't tell a legitimate event from a forged one.

Can I verify the signature in a serverless function? Yes, but you must obtain the raw body. Framework-specific APIs differ; check whether your runtime gives you the unparsed string or a stream.

What if my framework parses the body before I can access it? Reorder middleware so raw-body handling runs first on the webhook route, or read the raw stream directly in the handler.

How often should I rotate secrets? On a schedule you can actually follow, and immediately after any suspected leak. The dual-secret pattern makes it a non-event.

How do I handle events for a contact that no longer exists? Acknowledge and discard. Return 2xx; a 500 just triggers retries for an event you'll never process.


If you're building the sending side too, the Mailerflow transactional email API gives you signed real-time webhooks with retries and delivery logs, a REST API with scoped keys and idempotency keys, an OpenAPI spec and a JS SDK — so the events arriving at your endpoint are the ones you can actually verify. Start free.