Toda petición de webhook lleva el encabezado:
Voaaro-Signature: t=1731403802,v1=5e2b0c…t: la hora del envío, en segundos desde 1970 (UTC);v1:HMAC-SHA256(secret, "<t>.<cuerpo sin procesar>")en hexadecimal, donde la clave es el secreto completo (whsec_…, prefijo incluido).
Durante un cambio de secreto con periodo de gracia, el encabezado lleva dos v1: el primero calculado con el secreto nuevo y el segundo con el anterior (t=…,v1=…,v1=…).
Para verificarla:
- lee el cuerpo sin procesar, byte a byte, antes de cualquier decodificación JSON;
- vuelve a calcular el HMAC de
t+.+ cuerpo con tu secreto; - compáralo con cada
v1en tiempo constante; acepta la petición si uno de ellos coincide; - recházala si
tse aleja más de 5 minutos de la hora actual (protección contra la reutilización).
Con los SDK
Cada SDK verifica la firma y la antigüedad del mensaje, y devuelve el evento decodificado; una firma incorrecta lanza un error.
Node / Bun
import express from "express"
import { Voaaro } from "@deveryidea/voaaro"
const voaaro = new Voaaro(process.env.VOAARO_API_KEY, { baseUrl: "https://mail.example.com" })
const app = express()
// Raw body: express.raw, not express.json.
app.post("/webhooks/voaaro", express.raw({ type: "application/json" }), (req, res) => {
let event
try {
event = voaaro.webhooks.verify(req.body, req.headers, process.env.VOAARO_WEBHOOK_SECRET!)
} catch {
return res.status(400).send("invalid signature")
}
if (event.type === "email.bounced") console.log("bounce", event.data.recipient)
res.sendStatus(204)
})Python
import os
import voaaro
from flask import Flask, request
app = Flask(__name__)
@app.post("/webhooks/voaaro")
def webhook():
try:
event = voaaro.Webhooks.verify(request.get_data(), request.headers, os.environ["VOAARO_WEBHOOK_SECRET"])
except voaaro.WebhookVerificationError:
return "invalid signature", 400
if event["type"] == "email.bounced":
print("bounce", event["data"]["recipient"])
return "", 204PHP
use Voaaro\Webhook;
use Voaaro\Exceptions\WebhookVerificationException;
$payload = file_get_contents('php://input');
try {
$event = Webhook::verify($payload, getallheaders(), getenv('VOAARO_WEBHOOK_SECRET'));
} catch (WebhookVerificationException $e) {
http_response_code(400);
exit('invalid signature');
}
if ($event->type === 'email.bounced') {
error_log('bounce ' . $event->data->recipient);
}
http_response_code(204);Go
http.HandleFunc("/webhooks/voaaro", func(w http.ResponseWriter, r *http.Request) {
event, err := voaaro.VerifyWebhookRequest(r, os.Getenv("VOAARO_WEBHOOK_SECRET"))
if err != nil {
http.Error(w, "invalid signature", http.StatusBadRequest)
return
}
if event.Type == "email.bounced" {
log.Println("bounce", event.Data.Recipient)
}
w.WriteHeader(http.StatusNoContent)
})Sin SDK
Node / Bun
import { createHmac, timingSafeEqual } from "node:crypto"
export function verify(rawBody: string, header: string, secret: string) {
let t = 0
const signatures: Buffer[] = []
for (const part of header.split(",")) {
const [key, value = ""] = part.trim().split("=", 2)
if (key === "t") t = Number(value)
else if (key === "v1") signatures.push(Buffer.from(value, "hex"))
}
if (!t || Math.abs(Date.now() / 1000 - t) > 300) throw new Error("too old")
const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest()
// During a rotation, the header carries two v1: only one has to match.
if (!signatures.some((s) => s.length === 32 && timingSafeEqual(s, expected))) throw new Error("invalid signature")
return JSON.parse(rawBody)
}Python
import hashlib, hmac, json, time
def verify(raw_body: bytes, header: str, secret: str) -> dict:
t, signatures = 0, []
for part in header.split(","):
key, _, value = part.strip().partition("=")
if key == "t":
t = int(value)
elif key == "v1":
signatures.append(value)
if abs(time.time() - t) > 300:
raise ValueError("too old")
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
# During a rotation, the header carries two v1: only one has to match.
if not any(hmac.compare_digest(expected, s) for s in signatures):
raise ValueError("invalid signature")
return json.loads(raw_body)PHP
function verify(string $rawBody, string $header, string $secret): array {
$t = 0;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
if ($key === 't') {
$t = (int) $value;
} elseif ($key === 'v1') {
$signatures[] = $value;
}
}
if (abs(time() - $t) > 300) {
throw new RuntimeException('too old');
}
$expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
// During a rotation, the header carries two v1: only one has to match.
foreach ($signatures as $given) {
if (hash_equals($expected, $given)) {
return json_decode($rawBody, true, flags: JSON_THROW_ON_ERROR);
}
}
throw new RuntimeException('invalid signature');
}Go
func verify(rawBody []byte, header, secret string) error {
var t int64
var signatures [][]byte
for _, p := range strings.Split(header, ",") {
k, v, _ := strings.Cut(strings.TrimSpace(p), "=")
switch k {
case "t":
t, _ = strconv.ParseInt(v, 10, 64)
case "v1":
if sig, err := hex.DecodeString(v); err == nil {
signatures = append(signatures, sig)
}
}
}
if d := time.Since(time.Unix(t, 0)); d > 5*time.Minute || d < -5*time.Minute {
return errors.New("too old")
}
mac := hmac.New(sha256.New, []byte(secret))
fmt.Fprintf(mac, "%d.", t)
mac.Write(rawBody)
expected := mac.Sum(nil)
// During a rotation, the header carries two v1: only one has to match.
for _, sig := range signatures {
if hmac.Equal(sig, expected) {
return nil
}
}
return errors.New("invalid signature")
}Ejemplo: una suscripción
Los webhooks de suscripción se verifican de la misma forma. Por ejemplo, para añadir a tu CRM cada nuevo suscriptor, sea cual sea la vía de suscripción (source):
Node / Bun
app.post("/webhooks/voaaro", express.raw({ type: "application/json" }), (req, res) => {
let event
try {
event = voaaro.webhooks.verify(req.body, req.headers, process.env.VOAARO_WEBHOOK_SECRET!)
} catch {
return res.status(400).send("invalid signature")
}
// At-least-once delivery: ignore a Voaaro-Event-Id already handled.
if (event.type === "contact.subscribed") crm.upsert(event.data.email, { newsletter: true, via: event.data.source })
if (event.type === "contact.unsubscribed") crm.upsert(event.data.email, { newsletter: false })
res.sendStatus(204)
})Python
@app.post("/webhooks/voaaro")
def webhook():
try:
event = voaaro.Webhooks.verify(request.get_data(), request.headers, os.environ["VOAARO_WEBHOOK_SECRET"])
except voaaro.WebhookVerificationError:
return "invalid signature", 400
if event["type"] == "contact.subscribed":
crm.upsert(event["data"]["email"], newsletter=True, via=event["data"]["source"])
return "", 204PHP
try {
$event = Webhook::verify(file_get_contents('php://input'), getallheaders(), getenv('VOAARO_WEBHOOK_SECRET'));
} catch (WebhookVerificationException $e) {
http_response_code(400);
exit('invalid signature');
}
if ($event->type === 'contact.subscribed') {
$crm->upsert($event->data->email, ['newsletter' => true, 'via' => $event->data->source]);
}
http_response_code(204);Go
event, err := voaaro.VerifyWebhookRequest(r, os.Getenv("VOAARO_WEBHOOK_SECRET"))
if err != nil {
http.Error(w, "invalid signature", http.StatusBadRequest)
return
}
if event.Type == "contact.subscribed" {
crm.Upsert(event.Data.Email, true, string(event.Data.Source))
}
w.WriteHeader(http.StatusNoContent)Comprobar tu código
Con el secreto whsec_test, la hora 1700000000 y el cuerpo {"type":"email.delivered"}, el encabezado esperado es:
t=1700000000,v1=d4d4b7b21b35fef2e6cc16378126f64094d119127d0d71bd32b6d7ff75821fc8Durante una rotación, con el secreto anterior whsec_old además, el mismo cuerpo lleva:
t=1700000000,v1=d4d4b7b21b35fef2e6cc16378126f64094d119127d0d71bd32b6d7ff75821fc8,v1=ac4e8aa630365d68e2e6ad561135cfe2268e0eba907aa5ef10693a8a42f0f2c8Tu código debe aceptarlo tanto con whsec_test como con whsec_old, y rechazarlo con cualquier otro secreto.
Cambiar el secreto
Con la API, sin interrupción
POST /api/v1/webhooks/{id}/rotate-secret (detalles) genera un nuevo secreto, que firma de inmediato. El anterior también firma durante el periodo de gracia: grace_hours, 24 horas por defecto, de 0 a 72. Durante ese periodo, cada petición lleva dos v1; una petición es válida si uno de ellos coincide con tu secreto.
- Llama a la rotación y guarda el
signing_secretrecibido. - Pon este nuevo secreto en tu aplicación cuando quieras antes de
previous_secret_expires_at: las peticiones se aceptan tanto con el anterior como con el nuevo. - Al llegar
previous_secret_expires_at, el anterior deja de firmar.
Para cambiar de secreto sin ningún intervalo de rechazo, los SDK también aceptan varios secretos: conserva el anterior junto al nuevo durante el cambio y retíralo después.
Node / Bun
// VOAARO_WEBHOOK_SECRET_OLD: empty once the period is over (an empty secret is ignored)
const event = voaaro.webhooks.verify(req.body, req.headers, [
process.env.VOAARO_WEBHOOK_SECRET!,
process.env.VOAARO_WEBHOOK_SECRET_OLD ?? "",
])Python
secrets = [os.environ["VOAARO_WEBHOOK_SECRET"], os.environ.get("VOAARO_WEBHOOK_SECRET_OLD", "")]
event = voaaro.Webhooks.verify(request.get_data(), request.headers, secrets) # an empty secret is ignoredPHP
$event = Webhook::verify($payload, getallheaders(), [
getenv('VOAARO_WEBHOOK_SECRET'),
getenv('VOAARO_WEBHOOK_SECRET_OLD'), // empty or missing: ignored
]);Go
event, err := voaaro.VerifyWebhookRequestWithSecrets(r,
os.Getenv("VOAARO_WEBHOOK_SECRET"),
os.Getenv("VOAARO_WEBHOOK_SECRET_OLD")) // an empty secret is ignoredLos ejemplos anteriores y los SDK aceptan varios v1. "grace_hours": 0 desactiva el secreto anterior al instante (secreto comprometido).
En la consola, al instante
Nuevo secreto (en la consola) sustituye el secreto al instante: el anterior deja de firmar, para el caso de un secreto comprometido. Pon el nuevo secreto en tu aplicación justo después; las entregas rechazadas mientras tanto se reenviarán en los intentos siguientes.