Skip to content

Webhooks

Verifying the signature

The Voaaro-Signature header, how its HMAC-SHA256 is computed, and how to verify it in Node, Python, PHP and Go.

Every webhook request carries the header:

HTTP
Voaaro-Signature: t=1731403802,v1=5e2b0c…
  • t: the time of sending, in seconds since 1970 (UTC);
  • v1: HMAC-SHA256(secret, "<t>.<raw body>") in hexadecimal, where the whole secret (whsec_…, prefix included) is the key.

During a secret change with a grace period, the header carries two v1: the first computed with the new secret, the second with the old one (t=…,v1=…,v1=…).

To verify:

  1. read the raw body, byte for byte, before any JSON decoding;
  2. recompute the HMAC of t + . + body with your secret;
  3. compare it to each v1 in constant time; accept if one of them matches;
  4. refuse if t is more than 5 minutes away from the current time (replay protection).

With the SDKs

Each SDK verifies the signature and the message's age, and returns the decoded event; a wrong signature raises an 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 "", 204

PHP

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)
})

Without an 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")
}

Example: a subscription

The subscription webhooks are verified the same way. For instance, to add every new subscriber to your CRM, whatever the signup path (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 "", 204

PHP

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)

Checking your code

With the secret whsec_test, the time 1700000000 and the body {"type":"email.delivered"}, the expected header is:

Texte
t=1700000000,v1=d4d4b7b21b35fef2e6cc16378126f64094d119127d0d71bd32b6d7ff75821fc8

During a rotation, with the old secret whsec_old as well, the same body carries:

Texte
t=1700000000,v1=d4d4b7b21b35fef2e6cc16378126f64094d119127d0d71bd32b6d7ff75821fc8,v1=ac4e8aa630365d68e2e6ad561135cfe2268e0eba907aa5ef10693a8a42f0f2c8

Your code must accept it with whsec_test as well as with whsec_old, and refuse it with any other secret.

Changing the secret

Through the API, without interruption

POST /api/v1/webhooks/{id}/rotate-secret (details) gives a new secret, which signs right away. The old one also signs during the grace period: grace_hours, 24 hours by default, from 0 to 72. During that period, each request carries two v1; a request is valid if one of them matches your secret.

  1. Call the rotation and keep the signing_secret received.
  2. Put this new secret in your application, whenever you want before previous_secret_expires_at: with the old one as with the new one, requests go through.
  3. At previous_secret_expires_at, the old one stops signing.

To change the secret without a refusal window, the SDKs also accept several secrets: keep the old one next to the new one during the change, then remove it.

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 ignored

PHP

$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 ignored

The examples above and the SDKs accept several v1. "grace_hours": 0 stops the old secret at once (compromised secret).

In the console, immediately

New secret (in the console) replaces the secret immediately: the old one no longer signs anything, for the case of a compromised secret. Put the new secret in your application right after; deliveries refused in the meantime will be sent again by the following attempts.

Esc