DocTransform

Verify webhooks

Check that each event really came from DocTransform and was not changed or replayed

Anyone who learns your Webhook address could send it fake events. DocTransform signs every event, and your code checks that signature before it trusts the body. Skip this page if you use Zapier, Make or n8n: they do not need it. New to Webhooks? Start with Webhooks.

Headers we send

We sign with Standard Webhooks, the scheme OpenAI, Twilio and Resend also use, so any of its libraries can verify us. Every event has these headers:

HeaderWhat it holds
webhook-idThe event's id. It is the same on every retry and every Resend.
webhook-timestampThe time of this attempt, in Unix seconds.
webhook-signatureOne or more v1,<base64> entries separated by spaces. There are two while a secret is being changed.
content-typeapplication/json
user-agentDocTransform-Webhooks/1

Verify with a library

This is the shortest way. Keep your Signing secret in an environment variable called DOCTRANSFORM_WEBHOOK_SECRET, never in the code. Paste the value as the Webhook screen shows it, starting with whsec_. In Python:

pip install standardwebhooks
import os

from standardwebhooks import Webhook


def verify(raw_body, headers):
    # Pass the secret exactly as the Webhook screen shows it, whsec_ included.
    secret = os.environ["DOCTRANSFORM_WEBHOOK_SECRET"]
    # Raises if the signature is wrong or the timestamp is older than 5 minutes.
    return Webhook(secret).verify(raw_body, headers)

In Node.js:

npm install standardwebhooks
import { Webhook } from 'standardwebhooks';

export function verify(rawBody, headers) {
  // Pass the secret exactly as the Webhook screen shows it, whsec_ included.
  const secret = process.env.DOCTRANSFORM_WEBHOOK_SECRET;
  // Throws if the signature is wrong or the timestamp is older than 5 minutes.
  return new Webhook(secret).verify(rawBody, headers);
}

If verify fails, answer 400. If it works, answer a 2xx fast and do the work after. Libraries also exist for Go, Ruby, PHP, Java and Kotlin, Rust, C# and Elixir: see the Standard Webhooks library list.

Read the raw body

Warning Verify the exact bytes you received, before any JSON parser touches them.

A parser can change spaces or key order, and then the signature no longer matches. In Express:

import { verify } from './verifyLibrary.mjs';

// express.raw keeps the exact bytes. Put it on this route before express.json().
app.post('/doctransform', express.raw({ type: 'application/json' }), (req, res) => {
  try {
    verify(req.body, req.headers);
  } catch {
    return res.sendStatus(400);
  }
  res.sendStatus(200); // answer fast, do the work afterwards
});

In FastAPI:

from fastapi import FastAPI, HTTPException, Request
from verify_library import verify

app = FastAPI()


@app.post("/doctransform")
async def doctransform(request: Request):
    raw_body = await request.body()  # the bytes, never a parsed model
    try:
        verify(raw_body, dict(request.headers))
    except Exception:
        raise HTTPException(status_code=400)
    return {"ok": True}  # answer fast, do the work afterwards

In Flask:

from flask import Flask, abort, request
from verify_library import verify

app = Flask(__name__)


@app.post("/doctransform")
def doctransform():
    raw_body = request.get_data()  # the bytes, before any JSON parsing
    try:
        verify(raw_body, dict(request.headers))
    except Exception:
        abort(400)
    return "", 200  # answer fast, do the work afterwards

In a Next.js route handler, use await req.text(). On a serverless platform that may base64-encode the body, decode it first.

Verify by hand

No library? Five steps, in any language:

  1. Build the signed text

    Join the webhook-id, the webhook-timestamp and the raw body with a dot between each: <id>.<timestamp>.<body>.

  2. Decode the key

    Take the part of the secret after whsec_ and decode it from base64.

  3. Sign

    Compute an HMAC-SHA256 of the text with that key, and encode the result in base64.

  4. Compare

    Compare it with each v1, entry of webhook-signature, in constant time.

  5. Accept on any match

    One matching entry is enough. No match means reject.

In Python, with no dependencies:

import base64
import hashlib
import hmac
import json
import os
import time


def verify(raw_body, headers):
    secret = os.environ["DOCTRANSFORM_WEBHOOK_SECRET"]
    event_id = headers["webhook-id"]
    timestamp = headers["webhook-timestamp"]

    # Reject a message more than 5 minutes from your clock.
    if abs(time.time() - int(timestamp)) > 300:
        raise ValueError("timestamp outside 5 minutes")

    # Sign "<id>.<timestamp>.<raw body>" with the key inside the secret.
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{event_id}.{timestamp}.".encode() + raw_body
    digest = hmac.new(key, signed, hashlib.sha256).digest()
    expected = base64.b64encode(digest).decode()

    # The header holds one "v1,<signature>" per live secret. Any match is enough.
    for entry in headers["webhook-signature"].split():
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return json.loads(raw_body)
    raise ValueError("signature does not match")

In Node.js, with no dependencies:

import crypto from 'node:crypto';

export function verify(rawBody, headers) {
  const secret = process.env.DOCTRANSFORM_WEBHOOK_SECRET;
  const eventId = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];

  // Reject a message more than 5 minutes from your clock.
  const seconds = Number(timestamp);
  if (!Number.isFinite(seconds) || Math.abs(Date.now() / 1000 - seconds) > 300) {
    throw new Error('timestamp outside 5 minutes');
  }

  // Sign "<id>.<timestamp>.<raw body>" with the key inside the secret.
  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto
    .createHmac('sha256', key)
    .update(`${eventId}.${timestamp}.`)
    .update(rawBody)
    .digest();

  // The header holds one "v1,<signature>" per live secret. Any match is enough.
  for (const entry of headers['webhook-signature'].split(' ')) {
    const [version, signature = ''] = entry.split(',');
    const given = Buffer.from(signature, 'base64');
    if (
      version === 'v1' &&
      given.length === expected.length &&
      crypto.timingSafeEqual(given, expected)
    ) {
      return JSON.parse(rawBody);
    }
  }
  throw new Error('signature does not match');
}

Stop replays and duplicates

Reject a webhook-timestamp more than 5 minutes from your clock. The libraries do this by default: never turn it off. Also store each webhook-id you have handled, and answer 2xx without acting again on a repeat. Delivery is at least once, so a repeat is normal. It is the receiver's twin of the Idempotency-Key on Runs.

Change the signing secret

Open the Webhook, click Change secret and copy the new one. Your old secret keeps working for 24 hours, and every event carries both signatures meanwhile, so update your server at any time that day. If the old secret leaked, click Stop old secret now.