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:
| Intestazione | Cosa contiene |
|---|---|
webhook-id | L’id dell’evento. È lo stesso a ogni nuovo tentativo e a ogni reinvio. |
webhook-timestamp | L’ora di questo tentativo, in secondi Unix. |
webhook-signature | Una o più voci v1,<base64> separate da spazi. Sono due mentre si cambia un segreto. |
content-type | application/json |
user-agent | DocTransform-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 standardwebhooksimport 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 standardwebhooksimport { 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
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 afterwardsIn 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 afterwardsIn 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:
Costruisci il testo firmato
Unisci
webhook-id,webhook-timestampe il corpo grezzo con un punto tra l’uno e l’altro:<id>.<timestamp>.<body>.Decodifica la chiave
Prendi la parte del segreto dopo
whsec_e decodificala da base64.Firma
Calcola un HMAC-SHA256 del testo con quella chiave e codifica il risultato in base64.
Confronta
Confrontalo con ogni voce
v1,diwebhook-signature, a tempo costante.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.