Ir al contenido

Verificar la firma (Node, Python y PHP)

Al terminar esta página tendrás una función que verifica la firma de un webhook entrante antes de procesarlo, en Node, en Python y en PHP.

Nunca proceses un evento sin verificar su firma

Sección titulada «Nunca proceses un evento sin verificar su firma»

Cualquiera puede enviar un POST con la forma de un evento de Neat a tu URL de webhook. La firma es lo único que confirma que el cuerpo salió de Neat y que no fue alterado en tránsito. Verifica la firma antes de leer el contenido del evento, no solo antes de aplicarlo.

Neat-Signature trae t=<segundos unix>,v1=<hexadecimal>. El valor v1 es un HMAC-SHA256:

hex( HMAC_SHA256( key = webhook_secret, message = "<t>" + "." + <cuerpo crudo> ) )

Puntos que suelen romper una implementación de verificación:

  • Usa el cuerpo crudo (los bytes tal como llegaron), antes de parsear el JSON o cambiar espacios. Si tu framework ya parseó el body antes de que tu middleware de verificación lo vea, tendrás que capturar el buffer crudo aparte.
  • El secreto es el texto UTF-8 que Neat te entregó, no lo decodifiques como Base64.
  • Compara la firma con una comparación de tiempo constante (timingSafeEqual en Node, hmac.compare_digest en Python, hash_equals en PHP), nunca con === ni ==.
  • Rechaza un t demasiado viejo o demasiado adelantado; Neat recomienda una tolerancia de 5 minutos. Esto exige que el reloj de tu servidor esté sincronizado.
verify-neat-signature.js
import { createHmac, timingSafeEqual } from 'node:crypto';
const TOLERANCE_SECONDS = 5 * 60;
export function verifyNeatSignature(rawBody, header, secret, nowSeconds = Math.floor(Date.now() / 1000)) {
if (!Buffer.isBuffer(rawBody) || typeof header !== 'string' || typeof secret !== 'string' || !secret) {
return false;
}
let timestamp;
let signature;
for (const part of header.split(',')) {
const separator = part.indexOf('=');
if (separator < 1) return false;
const key = part.slice(0, separator).trim();
const value = part.slice(separator + 1).trim();
if (key === 't') timestamp = value;
else if (key === 'v1') signature = value;
}
if (timestamp === undefined || signature === undefined) return false;
if (!/^\d{1,12}$/.test(timestamp) || !/^[a-f0-9]{64}$/.test(signature)) return false;
const timestampNumber = Number(timestamp);
if (Math.abs(nowSeconds - timestampNumber) > TOLERANCE_SECONDS) return false;
const expected = createHmac('sha256', secret).update(`${timestamp}.`, 'utf8').update(rawBody).digest();
const provided = Buffer.from(signature, 'hex');
return expected.length === provided.length && timingSafeEqual(expected, provided);
}

rawBody debe ser el Buffer sin procesar del cuerpo de la petición. En Express, por ejemplo, monta express.raw({ type: 'application/json' }) en la ruta del webhook en vez del parser JSON por defecto, y parsea el JSON tú mismo después de verificar.

verify_neat_signature.py
import hashlib
import hmac
import re
import time
TOLERANCE_SECONDS = 5 * 60
def verify_neat_signature(
raw_body: bytes, header: str, secret: str, now_seconds: int | None = None
) -> bool:
if not isinstance(raw_body, bytes) or not header or not secret:
return False
timestamp = None
signature = None
for part in header.split(","):
if "=" not in part:
return False
key, _, value = part.partition("=")
key, value = key.strip(), value.strip()
if key == "t":
timestamp = value
elif key == "v1":
signature = value
if timestamp is None or signature is None:
return False
if not re.fullmatch(r"\d{1,12}", timestamp) or not re.fullmatch(r"[a-f0-9]{64}", signature):
return False
now = now_seconds if now_seconds is not None else int(time.time())
if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
return False
message = f"{timestamp}.".encode("utf-8") + raw_body
expected = hmac.new(secret.encode("utf-8"), message, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature)

En Flask, lee request.get_data() antes de acceder a request.json para conservar el cuerpo crudo; en Django, usa request.body.

verify_neat_signature.php
<?php
const NEAT_SIGNATURE_TOLERANCE_SECONDS = 5 * 60;
function verify_neat_signature(string $rawBody, string $header, string $secret, ?int $nowSeconds = null): bool
{
if ($header === '' || $secret === '') {
return false;
}
$timestamp = null;
$signature = null;
foreach (explode(',', $header) as $part) {
$separator = strpos($part, '=');
if ($separator === false || $separator < 1) {
return false;
}
$key = trim(substr($part, 0, $separator));
$value = trim(substr($part, $separator + 1));
if ($key === 't') {
$timestamp = $value;
} elseif ($key === 'v1') {
$signature = $value;
}
}
if ($timestamp === null || $signature === null) {
return false;
}
if (!preg_match('/^\d{1,12}$/D', $timestamp) || !preg_match('/^[a-f0-9]{64}$/D', $signature)) {
return false;
}
$now = $nowSeconds ?? time();
if (abs($now - (int) $timestamp) > NEAT_SIGNATURE_TOLERANCE_SECONDS) {
return false;
}
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
return hash_equals($expected, $signature);
}

En el script que recibe el webhook, lee el cuerpo crudo de php://input y verifica antes de decodificar el JSON. La cabecera llega en $_SERVER['HTTP_NEAT_SIGNATURE']:

webhook.php
<?php
require __DIR__ . '/verify_neat_signature.php';
$rawBody = file_get_contents('php://input');
$header = $_SERVER['HTTP_NEAT_SIGNATURE'] ?? '';
$secret = getenv('NEAT_WEBHOOK_SECRET') ?: '';
if ($rawBody === false || !verify_neat_signature($rawBody, $header, $secret)) {
http_response_code(401);
exit;
}
$event = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);

No uses $_POST: con Content-Type: application/json viene vacío. En Laravel o Symfony, $request->getContent() devuelve el cuerpo crudo.

Verificar la firma solo confirma el origen y la integridad del cuerpo. Todavía debes:

  1. Validar que provider_id sea el tuyo.
  2. Confirmar que Neat-Event-Id coincide con event_id dentro del cuerpo.
  3. Deduplicar por event_id antes de aplicar el efecto, ver Reintentos e idempotencia.

El webhook_secret es uno solo por comercio y no tiene período de gracia: al rotarlo, el anterior deja de firmar en el momento del corte, a diferencia de tu API key. Coordina ese momento con tu contacto técnico en Neat y ten lista la actualización de tu lado para aplicarla en el corte.

Hasta que tu servidor tenga el secreto nuevo, los eventos firmados con él no van a verificar. Si les respondes 401, como el ejemplo de PHP, o cualquier otro 4xx, quedan como entregas fallidas y Neat no los reintenta. Por eso conviene aplicar el secreto nuevo apenas Neat confirma la rotación. Un cobro cuyo evento se perdió así sigue visible en GET /v1/checkout-sessions/{sessionId}.