Saltar al contenido principal

Verificar firmas de webhook

Cada petición a un endpoint de webhook incluye el header X-Onvo-Signature. Verificalo antes de procesar el evento: así confirmás que la petición viene de ONVO, que el cuerpo no cambió y que no es una petición vieja reenviada por un tercero.

X-Onvo-Signature: t=1785758400,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
ParteDescripción
tMarca de tiempo Unix, en segundos, del momento en que ONVO envió el intento. Cada intento tiene una nueva.
v1Firma HMAC-SHA256 en hexadecimal. Durante la rotación del secreto, el header incluye dos valores v1: uno por cada secreto vigente.

Algoritmo​

  1. Leé el cuerpo crudo de la petición, exactamente como llegó, antes de convertirlo a JSON. Cualquier cambio, aunque sea de espacios, invalida la firma.
  2. Separá el header por comas y leé el valor de t y todos los valores de v1.
  3. Rechazá la petición si t está a más de 300 segundos de la hora actual de tu servidor.
  4. Calculá HMAC-SHA256, en hexadecimal, del texto t + . + cuerpo crudo, usando el secreto de firma del endpoint (whsec_...).
  5. Aceptá la petición si el resultado coincide con alguno de los valores v1. Compará con una función de tiempo constante.
  6. Solo entonces convertí el cuerpo a JSON y procesá el evento.

Guardá el secreto de firma en una variable de entorno o un gestor de secretos, nunca en el código. Si tu servidor recibe eventos de varios endpoints, usá el secreto de cada uno.

Node.js​

import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyOnvoWebhook(rawBody, signatureHeader, secret, now = Date.now()) {
const parts = signatureHeader.split(",").map((part) => part.trim().split("=", 2));
const timestamp = Number(parts.find(([key]) => key === "t")?.[1]);
const signatures = parts.filter(([key]) => key === "v1").map(([, value]) => value);
if (!Number.isSafeInteger(timestamp) || Math.abs(Math.floor(now / 1000) - timestamp) > 300) {
return false;
}

const expected = createHmac("sha256", secret)
.update(`${timestamp}.`)
.update(rawBody)
.digest();

return signatures.some((candidate) => {
if (!/^[0-9a-f]{64}$/i.test(candidate)) return false;
const received = Buffer.from(candidate, "hex");
return received.length === expected.length && timingSafeEqual(received, expected);
});
}

Con Express, usá express.raw en la ruta del webhook para recibir el cuerpo como Buffer, antes de cualquier parser de JSON:

import express from "express";

const app = express();

app.post("/webhooks/onvo", express.raw({ type: "application/json" }), (req, res) => {
const signature = req.get("X-Onvo-Signature") ?? "";
if (!verifyOnvoWebhook(req.body, signature, process.env.ONVO_WEBHOOK_SECRET)) {
return res.sendStatus(400);
}

const event = JSON.parse(req.body.toString("utf8"));
// Guardá el evento por su `event.id` y procesalo en segundo plano.
res.sendStatus(200);
});

PHP​

<?php
function verifyOnvoWebhook(string $rawBody, string $header, string $secret, ?int $now = null): bool {
$timestamp = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, null);
if ($key === 't' && ctype_digit((string) $value)) $timestamp = (int) $value;
if ($key === 'v1' && is_string($value)) $signatures[] = $value;
}
$now = $now ?? time();
if ($timestamp === null || abs($now - $timestamp) > 300) return false;
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
foreach ($signatures as $candidate) {
if (preg_match('/^[0-9a-f]{64}$/i', $candidate) && hash_equals($expected, strtolower($candidate))) return true;
}
return false;
}

$rawBody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_ONVO_SIGNATURE'] ?? '';
if (!verifyOnvoWebhook($rawBody, $signature, getenv('ONVO_WEBHOOK_SECRET'))) {
http_response_code(400);
exit;
}
$event = json_decode($rawBody, true);
http_response_code(200);

Python​

import hashlib
import hmac
import time

def verify_onvo_webhook(raw_body: bytes, header: str, secret: str, now: int | None = None) -> bool:
pairs = [part.strip().split("=", 1) for part in header.split(",") if "=" in part]
timestamp_values = [value for key, value in pairs if key == "t" and value.isdigit()]
signatures = [value.lower() for key, value in pairs if key == "v1"]
if not timestamp_values:
return False
timestamp = int(timestamp_values[0])
if abs((now or int(time.time())) - timestamp) > 300:
return False
signed = str(timestamp).encode() + b"." + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return any(len(candidate) == 64 and hmac.compare_digest(expected, candidate) for candidate in signatures)

En Flask, leé el cuerpo crudo con request.get_data() y el header con request.headers.get("X-Onvo-Signature", "").

Probar la verificación​

Usá Probar conexión en el detalle del endpoint. ONVO envía un evento webhook_endpoint.test firmado igual que una entrega, con cada secreto vigente (durante una rotación, con el nuevo y con el anterior); si tu servidor responde 2xx, la prueba queda registrada como exitosa.

Si la verificación falla:

  • Revisá que estás firmando el cuerpo crudo y no un JSON vuelto a serializar.
  • Confirmá que usás el secreto de este endpoint y del mismo modo (prueba o producción).
  • Revisá que el reloj de tu servidor esté sincronizado con NTP.