Webhooks
Markdown

Verifying signatures

Check the IPScope-Signature header on every webhook request, with code for Node.js, Python, Go, PHP and Ruby and complete receivers.

Anyone who learns your endpoint's URL can send it requests. The IPScope-Signature header proves a request came from ipscope and was not changed on the way: it is an HMAC-SHA256 of the request body made with your endpoint's signing secret, which only you and ipscope know.

Header
IPScope-Signature: t=1793761929,v1=d48dd86bdda97d482f2cc4a81cc14e88692654757a8c027f39c1d95a52ad8776

# How the signature is made

  1. t is the time the request was sent, in Unix seconds. It is fresh on every attempt, so a retry has a new t and a new signature.
  2. The signed string is t, a period, and the raw request body: "<t>.<raw body>".
  3. The signature is HMAC-SHA256 of that string, keyed with the endpoint's whole secret (including the whsec_ prefix) as UTF-8 bytes, written as lowercase hex.
  4. It is sent as v1=<hex>. The header may hold more than one v1= entry; a request is valid when any of them matches.

# Checking a request

  1. Read the raw body bytes before any JSON parsing.
  2. Split the header on , and each part on the first =: take t and every v1.
  3. Reject the request if t is more than 300 seconds away from your clock, in either direction. This stops someone replaying an old request.
  4. Compute the HMAC-SHA256 of "<t>.<raw body>" with your secret and compare it with each v1 value in constant time.
  5. If nothing matches, answer 400 and do not process the event.
// verify-ipscope-signature.js
import crypto from 'node:crypto';

const TOLERANCE_SECONDS = 300;

/**
 * True when `header` is a valid IPScope-Signature for `rawBody`.
 * `rawBody` is the exact bytes received (a Buffer), before any JSON parsing.
 */
export function verifyIpscopeSignature(rawBody, header, secret, nowMs = Date.now()) {
  if (!header) return false;
  let timestamp = null;
  const signatures = [];
  for (const part of header.split(',')) {
    const [key, value = ''] = part.trim().split('=', 2);
    if (key === 't') timestamp = value;
    else if (key === 'v1' && value) signatures.push(value);
  }
  if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false;
  if (Math.abs(Math.floor(nowMs / 1000) - Number(timestamp)) > TOLERANCE_SECONDS) return false;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(timestamp + '.')
    .update(rawBody)
    .digest();
  return signatures.some((signature) => {
    const given = Buffer.from(signature, 'hex');
    return given.length === expected.length && crypto.timingSafeEqual(given, expected);
  });
}

The Python samples need Python 3.10 or later (they use str | None annotations); the Ruby sample needs Ruby 2.7 or later.

# A complete receiver

A production receiver does four things, in this order: verify the signature, skip events it has already accepted, answer 2xx immediately, and do the real work (downloading a release can take minutes) in the background. These examples download the new .mmdb, check its SHA-256 against the event and swap it in atomically, as described in Automated zero-downtime updates.

import crypto from 'node:crypto';
import { createWriteStream } from 'node:fs';
import { rename } from 'node:fs/promises';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import express from 'express';
import { verifyIpscopeSignature } from './verify-ipscope-signature.js';

const SECRET = process.env.IPSCOPE_WEBHOOK_SECRET;
const API_KEY = process.env.IPSCOPE_API_KEY; // needs the `download` scope
const app = express();

// Event ids already accepted. With more than one instance, use a shared store
// (a database table with a unique key, or a key-value store with a TTL of a few days).
const seen = new Set();

// express.raw keeps the body as a Buffer: the signature covers the exact bytes.
app.post('/hooks/ipscope', express.raw({ type: 'application/json', limit: '1mb' }), (req, res) => {
  if (!verifyIpscopeSignature(req.body, req.get('IPScope-Signature'), SECRET)) {
    return res.sendStatus(400);
  }
  const eventId = req.get('IPScope-Event-Id');
  if (seen.has(eventId)) return res.sendStatus(200); // a retry of an event we already have
  seen.add(eventId);

  const event = JSON.parse(req.body.toString('utf8'));
  res.sendStatus(204); // acknowledge right away; the work happens after the response

  setImmediate(() => {
    handleEvent(event).catch((err) => console.error('ipscope webhook', event.id, err));
  });
});

async function handleEvent(event) {
  switch (event.type) {
    case 'database.created':
    case 'database.updated': {
      const mmdb = event.data.release.files.find((file) => file.format === 'mmdb');
      if (mmdb) await downloadAndSwap(mmdb, '/var/lib/ipscope/ipscope.mmdb');
      break;
    }
    case 'database.build_failed':
      console.warn('ipscope build failed for', event.data.database.name, '- the current release stays available');
      break;
    default:
      break; // webhook.test, and event types added later
  }
}

async function downloadAndSwap(file, dest) {
  const res = await fetch(file.download_url, { headers: { Authorization: 'Bearer ' + API_KEY } });
  if (!res.ok) throw new Error('download failed: HTTP ' + res.status);

  const tmp = dest + '.' + process.pid + '.tmp'; // same filesystem as dest, so rename is atomic
  const hash = crypto.createHash('sha256');
  await pipeline(
    Readable.fromWeb(res.body),
    async function* (chunks) {
      for await (const chunk of chunks) {
        hash.update(chunk);
        yield chunk;
      }
    },
    createWriteStream(tmp, { mode: 0o644 }),
  );
  if (hash.digest('hex') !== file.sha256) throw new Error('checksum mismatch for ' + file.filename);
  await rename(tmp, dest);
}

app.listen(3000);

# Testing your receiver

From the dashboard, Send test event delivers a signed webhook.test event to a public endpoint. To test a receiver running on your own machine, sign a request yourself with the same secret:

Sign a test request
SECRET="$IPSCOPE_WEBHOOK_SECRET"
BODY='{"id":"evt_local_test","object":"event","type":"webhook.test","api_version":"2026-11-04","created_at":"2026-11-04T03:12:09.512Z","data":{"endpoint_id":"local","message":"Local test"}}'
T=$(date +%s)
SIG=$(printf '%s.%s' "$T" "$BODY" | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')

curl -sS -i -X POST http://localhost:3000/hooks/ipscope \
  -H "Content-Type: application/json" \
  -H "IPScope-Signature: t=$T,v1=$SIG" \
  -H "IPScope-Event-Id: evt_local_test" \
  -H "IPScope-Event-Type: webhook.test" \
  -d "$BODY"

# Rotating the secret

Rotate a secret from the endpoint's page in the dashboard or with POST /v1/webhooks/{id}/rotate-secret. The old secret stops working immediately, so deploy the new secret to your receiver right after rotating. A delivery that fails verification in the meantime is retried and will verify once the new secret is in place; you can also resend it.