Verificar webhooks
Comprueba que cada evento viene de DocTransform y que nadie lo cambió ni lo repitió
Quien conozca la dirección de tu webhook podría enviarle eventos falsos. DocTransform firma cada evento, y tu código comprueba esa firma antes de fiarse del cuerpo. Sáltate esta página si usas Zapier, Make o n8n: no la necesitan. ¿Eres nuevo en los webhooks? Empieza por Webhooks.
Cabeceras que enviamos
Firmamos con Standard Webhooks, el esquema que también usan OpenAI, Twilio y Resend, así que cualquiera de sus bibliotecas puede verificarnos. Cada evento lleva estas cabeceras:
| Cabecera | Qué contiene |
|---|---|
webhook-id | El id del evento. Es el mismo en cada reintento y en cada reenvío. |
webhook-timestamp | La hora de este intento, en segundos Unix. |
webhook-signature | Una o más entradas v1,<base64> separadas por espacios. Hay dos mientras se cambia un secreto. |
content-type | application/json |
user-agent | DocTransform-Webhooks/1 |
Verificar con una biblioteca
Es el camino más corto. Guarda tu secreto de firma en una variable de entorno llamada DOCTRANSFORM_WEBHOOK_SECRET, nunca en el código. Pega el valor tal como lo muestra la pantalla del webhook, empezando por whsec_. En 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)En 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);
}Si verify falla, responde 400. Si funciona, responde rápido un 2xx y haz el trabajo después. También hay bibliotecas para Go, Ruby, PHP, Java y Kotlin, Rust, C# y Elixir: mira la lista de bibliotecas de Standard Webhooks.
Leer el cuerpo en bruto
Un analizador puede cambiar espacios o el orden de las claves, y entonces la firma ya no coincide. En 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
});En 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 afterwardsEn 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 afterwardsEn un route handler de Next.js, usa await req.text(). En una plataforma serverless que pueda codificar el cuerpo en base64, decodifícalo primero.
Verificar a mano
¿Sin biblioteca? Cinco pasos, en cualquier lenguaje:
Construye el texto firmado
Une el
webhook-id, elwebhook-timestampy el cuerpo en bruto con un punto entre cada uno:<id>.<timestamp>.<body>.Decodifica la clave
Toma la parte del secreto que va después de
whsec_y decodifícala desde base64.Firma
Calcula un HMAC-SHA256 del texto con esa clave y codifica el resultado en base64.
Compara
Compáralo con cada entrada
v1,dewebhook-signature, en tiempo constante.Acepta si coincide alguna
Basta una entrada que coincida. Si ninguna coincide, rechaza.
En Python, sin dependencias:
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")En Node.js, sin dependencias:
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');
}Evitar repeticiones y duplicados
Rechaza un webhook-timestamp a más de 5 minutos de tu reloj. Las bibliotecas lo hacen por defecto: nunca lo desactives. Guarda también cada webhook-id que ya tramitaste, y responde 2xx sin volver a actuar ante una repetición. La entrega es de al menos una vez, así que una repetición es normal. Es el gemelo, del lado del receptor, de Idempotency-Key en las ejecuciones.
Cambiar el secreto de firma
Abre el webhook, pulsa Cambiar secreto y copia el nuevo. Tu secreto anterior sigue funcionando 24 horas, y cada evento lleva las dos firmas mientras tanto, así que actualiza tu servidor cualquier momento de ese día. Si el secreto anterior se filtró, pulsa Detener el secreto anterior ahora.