# 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.

```http 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.

> **Use the raw body:** Verify the body exactly as it arrived. Parsing the JSON and serializing it again changes whitespace and key order, and the signature will no longer match. In frameworks that parse JSON automatically, read the raw body for this route (as in the receivers below).

```js Node.js
// 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);
  });
}
```

```python Python
# verify_ipscope.py
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300

def verify_ipscope_signature(raw_body: bytes, header: str | None, secret: str, now: float | None = None) -> bool:
    """True when `header` is a valid IPScope-Signature for `raw_body` (the exact bytes received)."""
    if not header:
        return False
    timestamp = None
    signatures = []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            timestamp = value
        elif key == "v1" and value:
            signatures.append(value)
    if not timestamp or not (timestamp.isascii() and timestamp.isdigit()) or not signatures:
        return False
    current = int(time.time() if now is None else now)
    if abs(current - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(secret.encode("utf-8"), timestamp.encode() + b"." + raw_body, hashlib.sha256).digest()
    for signature in signatures:
        try:
            given = bytes.fromhex(signature)
        except ValueError:
            continue
        if hmac.compare_digest(given, expected):
            return True
    return False
```

```go Go
package ipscopewebhook

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"
)

const tolerance = 300 * time.Second

// Verify reports whether header is a valid IPScope-Signature for rawBody,
// the exact bytes of the request body.
func Verify(rawBody []byte, header, secret string, now time.Time) bool {
	var timestamp string
	var signatures [][]byte
	for _, part := range strings.Split(header, ",") {
		key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
		if !ok {
			continue
		}
		switch key {
		case "t":
			timestamp = value
		case "v1":
			if sig, err := hex.DecodeString(value); err == nil {
				signatures = append(signatures, sig)
			}
		}
	}
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil || len(signatures) == 0 {
		return false
	}
	if age := now.Sub(time.Unix(seconds, 0)); age > tolerance || age < -tolerance {
		return false
	}

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(timestamp + "."))
	mac.Write(rawBody)
	expected := mac.Sum(nil)
	for _, sig := range signatures {
		if hmac.Equal(sig, expected) {
			return true
		}
	}
	return false
}
```

```php PHP
<?php

function verify_ipscope_signature(string $rawBody, ?string $header, string $secret, int $tolerance = 300): bool
{
    if (!$header) {
        return false;
    }
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($key === 't') {
            $timestamp = $value;
        } elseif ($key === 'v1' && $value !== '') {
            $signatures[] = strtolower($value);
        }
    }
    if ($timestamp === null || !ctype_digit($timestamp) || !$signatures) {
        return false;
    }
    if (abs(time() - (int) $timestamp) > $tolerance) {
        return false;
    }

    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

// The raw body, before json_decode():
$rawBody = file_get_contents('php://input');
$header = $_SERVER['HTTP_IPSCOPE_SIGNATURE'] ?? null;
if (!verify_ipscope_signature($rawBody, $header, getenv('IPSCOPE_WEBHOOK_SECRET'))) {
    http_response_code(400);
    exit;
}
```

```ruby Ruby
require "openssl"

TOLERANCE_SECONDS = 300

# True when header is a valid IPScope-Signature for raw_body (the exact bytes received).
def verify_ipscope_signature(raw_body, header, secret, now: Time.now.to_i)
  return false if header.nil? || header.empty?

  timestamp = nil
  signatures = []
  header.split(",").each do |part|
    key, value = part.strip.split("=", 2)
    if key == "t"
      timestamp = value
    elsif key == "v1" && value && !value.empty?
      signatures << value.downcase
    end
  end
  return false unless timestamp&.match?(/\A\d+\z/) && signatures.any?
  return false if (now - timestamp.to_i).abs > TOLERANCE_SECONDS

  expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp}.#{raw_body}")
  signatures.any? { |signature| OpenSSL.secure_compare(expected, signature) }
end

# Rack / Sinatra / Rails: read the raw body before parsing it.
# raw_body = request.body.read
# verify_ipscope_signature(raw_body, request.env["HTTP_IPSCOPE_SIGNATURE"], ENV.fetch("IPSCOPE_WEBHOOK_SECRET"))
```

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

> **Note:** Keep your server's clock synchronized (NTP). A clock that is more than 5 minutes off makes every valid request fail the timestamp check.

## 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](https://ipscope.io/docs/databases/updating).

```js Node.js (Express)
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);
```

```python Python (Flask)
import hashlib
import json
import os
import queue
import tempfile
import threading
import urllib.request

from flask import Flask, abort, request

from verify_ipscope import verify_ipscope_signature

SECRET = os.environ["IPSCOPE_WEBHOOK_SECRET"]
API_KEY = os.environ["IPSCOPE_API_KEY"]  # needs the `download` scope
DEST = "/var/lib/ipscope/ipscope.mmdb"

app = Flask(__name__)
jobs: "queue.Queue[dict]" = queue.Queue()

# Event ids already accepted. With several workers or hosts, use a shared store
# (a database table with a unique key, or a key-value store with a TTL of a few days).
seen: set[str] = set()
seen_lock = threading.Lock()

@app.post("/hooks/ipscope")
def ipscope_webhook():
    raw = request.get_data()  # the exact bytes, before any JSON parsing
    if not verify_ipscope_signature(raw, request.headers.get("IPScope-Signature"), SECRET):
        abort(400)
    event_id = request.headers.get("IPScope-Event-Id", "")
    with seen_lock:
        if event_id in seen:
            return "", 200  # a retry of an event we already have
        seen.add(event_id)
    jobs.put(json.loads(raw))
    return "", 204  # acknowledge right away; a worker does the rest

def worker() -> None:
    while True:
        event = jobs.get()
        try:
            handle_event(event)
        except Exception:
            app.logger.exception("ipscope event %s failed", event.get("id"))

def handle_event(event: dict) -> None:
    if event["type"] in ("database.created", "database.updated"):
        for file in event["data"]["release"]["files"]:
            if file["format"] == "mmdb":
                download_and_swap(file)
    elif event["type"] == "database.build_failed":
        app.logger.warning("ipscope build failed for %s; the current release stays available", event["data"]["database"]["name"])

def download_and_swap(file: dict) -> None:
    req = urllib.request.Request(file["download_url"], headers={"Authorization": f"Bearer {API_KEY}"})
    digest = hashlib.sha256()
    # Same directory as DEST, so os.replace is an atomic rename.
    with urllib.request.urlopen(req, timeout=300) as resp, tempfile.NamedTemporaryFile(dir=os.path.dirname(DEST), delete=False) as tmp:
        for chunk in iter(lambda: resp.read(1 << 20), b""):
            digest.update(chunk)
            tmp.write(chunk)
    if digest.hexdigest() != file["sha256"]:
        os.unlink(tmp.name)
        raise ValueError(f"checksum mismatch for {file['filename']}")
    os.chmod(tmp.name, 0o644)
    os.replace(tmp.name, DEST)

threading.Thread(target=worker, daemon=True).start()
```

```python Python (FastAPI)
import json
import os

from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response

from verify_ipscope import verify_ipscope_signature
from ipscope_jobs import handle_event  # your download logic, as in the Flask tab

SECRET = os.environ["IPSCOPE_WEBHOOK_SECRET"]
app = FastAPI()

# Event ids already accepted. With several workers or hosts, use a shared store.
seen: set[str] = set()

@app.post("/hooks/ipscope", status_code=204)
async def ipscope_webhook(request: Request, background: BackgroundTasks) -> Response:
    raw = await request.body()  # the exact bytes, before any JSON parsing
    if not verify_ipscope_signature(raw, request.headers.get("ipscope-signature"), SECRET):
        raise HTTPException(status_code=400, detail="invalid signature")
    event_id = request.headers.get("ipscope-event-id", "")
    if event_id in seen:
        return Response(status_code=200)  # a retry of an event we already have
    seen.add(event_id)
    # Background tasks run after the response is sent; a plain def runs in a thread pool.
    background.add_task(handle_event, json.loads(raw))
    return Response(status_code=204)
```

> **Tip:** Answer within 10 seconds even when the work takes longer: a slow answer counts as a failure and the event is sent again. If your background job can fail, give it its own retries (a job queue), because ipscope stops retrying once you have answered `2xx`.

## 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:

```bash 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`](https://ipscope.io/docs/webhooks/api#rotate-the-signing-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](https://ipscope.io/docs/webhooks/api#resend-a-delivery).
