DocTransform

Verificare i webhook

Verifica che ogni evento arrivi davvero da DocTransform e che non sia stato modificato né ripetuto

Chiunque conosca l’indirizzo del tuo webhook potrebbe inviargli eventi falsi. DocTransform firma ogni evento, e il tuo codice controlla quella firma prima di fidarsi del contenuto. Salta questa pagina se usi Zapier, Make o n8n: non serve. Sei nuovo con i webhook? Inizia da Webhook.

Intestazioni che inviamo

Firmiamo con Standard Webhooks, lo schema usato anche da OpenAI, Twilio e Resend, quindi qualsiasi sua libreria può verificarci. Ogni evento porta queste intestazioni:

IntestazioneCosa contiene
webhook-idL’id dell’evento. È lo stesso a ogni nuovo tentativo e a ogni reinvio.
webhook-timestampL’ora di questo tentativo, in secondi Unix.
webhook-signatureUna o più voci v1,<base64> separate da spazi. Sono due mentre si cambia un segreto.
content-typeapplication/json
user-agentDocTransform-Webhooks/1

Verificare con una libreria

È la strada più breve. Tieni il tuo segreto di firma in una variabile d’ambiente chiamata DOCTRANSFORM_WEBHOOK_SECRET, mai nel codice. Incolla il valore come lo mostra la schermata del webhook, a partire da 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);
}

Se verify fallisce, rispondi 400. Se funziona, rispondi subito con un 2xx e fai il lavoro dopo. Esistono librerie anche per Go, Ruby, PHP, Java e Kotlin, Rust, C# ed Elixir: vedi l’elenco delle librerie Standard Webhooks.

Leggere il corpo grezzo

Attenzione Verifica esattamente i byte ricevuti, prima che qualsiasi parser JSON li tocchi.

Un parser può cambiare gli spazi o l’ordine delle chiavi, e allora la firma non coincide più. 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 un route handler di Next.js usa await req.text(). Su una piattaforma serverless che può codificare il corpo in base64, decodificalo prima.

Verificare a mano

Nessuna libreria? Cinque passi, in qualsiasi linguaggio:

  1. Costruisci il testo firmato

    Unisci webhook-id, webhook-timestamp e il corpo grezzo con un punto tra l’uno e l’altro: <id>.<timestamp>.<body>.

  2. Decodifica la chiave

    Prendi la parte del segreto dopo whsec_ e decodificala da base64.

  3. Firma

    Calcola un HMAC-SHA256 del testo con quella chiave e codifica il risultato in base64.

  4. Confronta

    Confrontalo con ogni voce v1, di webhook-signature, a tempo costante.

  5. Accetta se una coincide

    Basta una voce che coincide. Se nessuna coincide, rifiuta.

In Python, senza dipendenze:

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, senza dipendenze:

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');
}

Fermare ripetizioni e duplicati

Rifiuta un webhook-timestamp a più di 5 minuti dal tuo orologio. Le librerie lo fanno di default: non disattivarlo mai. Salva anche ogni webhook-id già gestito e rispondi 2xx senza agire di nuovo su una ripetizione. La consegna è «almeno una volta», quindi una ripetizione è normale. È il gemello, lato ricevente, di Idempotency-Key sulle esecuzioni.

Cambiare il segreto di firma

Apri il webhook, premi Cambia segreto e copia quello nuovo. Il vecchio segreto continua a funzionare per 24 ore, e ogni evento porta intanto entrambe le firme: aggiorna il tuo server in qualsiasi momento di quel giorno. Se il vecchio segreto è trapelato, premi Interrompi subito il vecchio segreto.