Seguridad (HMAC)
Los webhooks con autenticación HMAC, la opción por defecto para nuevos webhooks, firman cada solicitud para que puedas verificar que vino de Magnet Customer.
Importante: Valida siempre la firma antes de procesar cualquier contenido de webhook. Rechaza las solicitudes con firmas inválidas o ausentes.
Cómo se genera la firma
Calculamos HMAC-SHA256 sobre el cuerpo de la solicitud serializado en JSON usando tu webhook secret, y enviamos el resultado en el header X-Webhook-Signature, con el formato sha256=<hex digest>. Ese header solo se envía cuando el tipo de autenticación del webhook es HMAC con un secret configurado: los webhooks con Bearer, Basic, headers personalizados o sin autenticación no reciben esa firma.
Validación en Node.js
const crypto = require('crypto');
function verifyWebhook(req) {
const signature = req.headers['x-webhook-signature'];
const secret = process.env.WEBHOOK_SECRET;
// Use raw body buffer — parsed JSON will break the signature
const hmac = crypto
.createHmac('sha256', secret)
.update(req.rawBody) // rawBody must be the original Buffer
.digest('hex');
const expected = `sha256=${hmac}`;
// Use timingSafeEqual to prevent timing attacks
const sigBuffer = Buffer.from(signature ?? '', 'utf8');
const expBuffer = Buffer.from(expected, 'utf8');
if (sigBuffer.length !== expBuffer.length) {
throw new Error('Invalid signature');
}
if (!crypto.timingSafeEqual(sigBuffer, expBuffer)) {
throw new Error('Invalid signature');
}
}
// Express example
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
try {
verifyWebhook({ headers: req.headers, rawBody: req.body });
} catch {
return res.status(401).json({ error: 'Unauthorized' });
}
const event = JSON.parse(req.body.toString());
// Process event...
res.sendStatus(200);
});Validación en Python
import hmac
import hashlib
import os
def verify_webhook(raw_body: bytes, signature_header: str) -> bool:
"""Verify HMAC-SHA256 signature from Magnet Customer webhook."""
secret = os.environ["WEBHOOK_SECRET"].encode("utf-8")
expected = "sha256=" + hmac.new(secret, raw_body, hashlib.sha256).hexdigest()
# Use compare_digest to prevent timing attacks
return hmac.compare_digest(expected, signature_header)
# Flask example
from flask import Flask, request, abort
app = Flask(__name__)
@app.route("/webhook", methods=["POST"])
def webhook():
signature = request.headers.get("X-Webhook-Signature", "")
if not verify_webhook(request.get_data(), signature):
abort(401)
event = request.json
# Process event...
return "", 200Headers enviados en cada solicitud
X-Webhook-Signature solo aparece en webhooks con autenticación HMAC. Los demás headers de abajo se envían en toda entrega, sin importar el tipo de autenticación.
| Header | Valor de ejemplo |
|---|---|
| X-Webhook-Signature | sha256=3ecb5a3d8f... |
| X-Webhook-Id | 65f2c1a4e8b9a400123abcde |
| X-Webhook-Event-Id | evt_1737054821123_k9d3f7a1x |
| X-Webhook-Timestamp | 1737054821123 |
| X-Webhook-Delivery-Attempt | 1 |
| User-Agent | MagnetCustomer-Webhook/1.0 |
Protección contra repetición
La firma no cubre X-Webhook-Timestamp: la marca de tiempo y la firma son independientes, así que una solicitud capturada podría, técnicamente, reenviarse con la firma original todavía válida. Como capa adicional de defensa, recomendamos rechazar las entregas cuyo X-Webhook-Timestamp (epoch Unix, en milisegundos) tenga más de unos minutos. Es una recomendación para tu propia integración, no una garantía criptográfica dada por la firma.