跳到正文

Webhook

验证签名

Voaaro-Signature 请求头、其 HMAC-SHA256 的计算方式,以及如何在 Node、Python、PHP 和 Go 中验证签名。

每个 webhook 请求都带有以下请求头:

HTTP
Voaaro-Signature: t=1731403802,v1=5e2b0c…
  • t:发送时间,即自 1970 年(UTC)起的秒数;
  • v1:十六进制的 HMAC-SHA256(secret, "<t>.<原始请求体>"),其中以完整的签名密钥(whsec_…,包括前缀)作为密钥。

在带宽限期的签名密钥更换期间,请求头中带有两个 v1:第一个用新签名密钥计算,第二个用旧签名密钥计算(t=…,v1=…,v1=…)。

验证步骤:

  1. 在进行任何 JSON 解码之前,逐字节读取原始请求体;
  2. 用您的签名密钥重新计算 t + . + 请求体的 HMAC;
  3. 以恒定时间方式将其与每个 v1 进行比较;只要其中一个匹配即可接受;
  4. 如果 t 与当前时间相差超过 5 分钟,则拒绝(防止重放攻击)。

使用 SDK

每个 SDK 都会验证签名和消息的时效,并返回解码后的事件;签名错误时会抛出错误。

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

不使用 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")
}

示例:订阅

订阅相关的 webhook 的验证方式相同。例如,无论订阅来自哪种途径(source),都将每位新订阅者添加到您的 CRM:

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)

检查您的代码

使用签名密钥 whsec_test、时间 1700000000 和请求体 {"type":"email.delivered"} 时,预期的请求头为:

Texte
t=1700000000,v1=d4d4b7b21b35fef2e6cc16378126f64094d119127d0d71bd32b6d7ff75821fc8

在轮换期间,如果同时存在旧签名密钥 whsec_old,同一请求体会带有:

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

您的代码必须在使用 whsec_test 和使用 whsec_old 时都接受它,使用其他任何签名密钥时都拒绝它。

更换签名密钥

通过 API,不中断服务

POST /api/v1/webhooks/{id}/rotate-secret(详情)会生成一个新的签名密钥,并立即用它签名。旧签名密钥在宽限期内也会继续签名:宽限期由 grace_hours 指定,默认 24 小时,范围 0 到 72。在此期间,每个请求都带有两个 v1;只要其中一个与您的签名密钥匹配,请求即有效。

  1. 调用轮换接口,并保存返回的 signing_secret。
  2. 在 previous_secret_expires_at 之前的任意时间,将这个新签名密钥配置到您的应用中:无论使用旧的还是新的,请求都能通过验证。
  3. 到达 previous_secret_expires_at 时,旧签名密钥停止签名。

为了在更换签名密钥时不出现拒绝窗口,SDK 还支持多个签名密钥:在更换期间将旧签名密钥与新签名密钥一起保留,完成后再移除旧的。

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

上述示例和 SDK 都支持多个 v1。"grace_hours": 0 会立即停用旧签名密钥(适用于签名密钥已泄露的情况)。

在控制台中立即更换

在控制台中点击新密钥会立即替换签名密钥:旧签名密钥不再签名任何请求,适用于签名密钥已泄露的情况。请随即将新签名密钥配置到您的应用中;在此期间被拒绝的投递会通过后续的重试重新发送。

Esc