Verify signatures

Anyone who learns your webhook URL could send fake data to it. Every request from KnownVisitors is signed with your address's signing secret, so you can check that it is real before you trust it.

The signature header

Each request carries an X-KV-Signature header:

X-KV-Signature: t=1764086400,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
tinteger

When we sent this request, in Unix seconds. Each retry gets a new timestamp and a new signature.

v1string

An HMAC-SHA256, in lowercase hex, of the timestamp, a period and the raw request body, signed with your signing secret.

Verify a request

  1. Read the raw bodyUse the request body exactly as it arrived. Do not parse the JSON and turn it back into text first.
  2. Build the signed textJoin the t value, a period and the raw body: 1764086400.{"id":"evt_...
  3. Compute the expected signatureTake the HMAC-SHA256 of that text with your signing secret as the key, as lowercase hex.
  4. CompareCompare it to v1 using a constant-time comparison. If they differ, reject the request.
  5. Check the timestampReject the request if t is more than 5 minutes from your server's clock.

Use the raw body. Most frameworks parse JSON automatically. Parsing and re-encoding changes spacing and key order, and the signature will no longer match.

const crypto = require("crypto");
const express = require("express");
const app = express();

function fromKnownVisitors(rawBody, header, secret) {
  if (!header) return false;
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const t = parts.t, v1 = parts.v1;
  if (!t || !v1) return false;
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${t}.${rawBody}`)
    .digest("hex");
  return v1.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
}

// express.raw keeps the body exactly as it arrived
app.post("/knownvisitors", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body.toString("utf8");
  if (!fromKnownVisitors(raw, req.get("X-KV-Signature"), process.env.KV_WEBHOOK_SECRET)) {
    return res.status(401).send("bad signature");
  }
  const event = JSON.parse(raw);
  // Save event here, then answer quickly
  res.sendStatus(200);
});
import hashlib, hmac, os, time
from flask import Flask, request

app = Flask(__name__)

def from_knownvisitors(raw_body: bytes, header: str, secret: str) -> bool:
    if not header:
        return False
    parts = dict(p.split("=", 1) for p in header.split(","))
    t, v1 = parts.get("t"), parts.get("v1")
    if not t or not v1 or abs(time.time() - int(t)) > 300:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)

@app.post("/knownvisitors")
def knownvisitors():
    raw = request.get_data()  # the raw body, before any parsing
    if not from_knownvisitors(raw, request.headers.get("X-KV-Signature"), os.environ["KV_WEBHOOK_SECRET"]):
        return "bad signature", 401
    event = request.get_json()
    # Save event here, then answer quickly
    return "", 200

Replay protection

The timestamp is part of the signed text, so it cannot be changed without breaking the signature. Rejecting requests older than 5 minutes stops someone who captured a real request from sending it to you again later. Keep your server's clock in sync for this check to work.

Your signing secret