跳到主要内容

Webhook签名与验证

当生命周期事件发生在非直接HTTP请求周期时,Blüdhaven Pets平台会发送异步Webhook。

今日将发送以下两个事件:

事件触发条件载荷内容亮点
adoption.hold.expired预订在30分钟后未收到申请时被取消hold_id, animal_id, reason
veterinary.clearance.filed市政兽医完成动物认证,使其符合领养条件animal_id, certificate_number, status

每个传输的数据包都采用 HTTP POST 的格式进行传输,其中包含 JSON 类型的数据负载(payload)以及 X-Bludhaven-Signature 标头中的 HMAC-SHA256 签名(signature)。

为何需要验证签名?​

公开的Webhook端点会接收来自互联网的HTTP请求。如果没有加密验证:

  • 攻击者可以伪造adoption.hold.expired事件,导致动物被提前释放。
  • 攻击者可以注入伪造的 veterinary.clearance.filed 事件来绕过强制性的狂犬病隔离措施。
  • 攻击者可以重放旧的、有效的有效载荷,导致系统重复处理该数据。

签名验证可以证明 Blüdhaven Pets 是该有效载荷的真正生成者,并且该数据是新鲜的(未被篡改的)。

签名头的格式:​

X-Bludhaven-Signature 标头中包含 UNIX 时间戳(timestamp)和 HMAC-SHA256 十六进制摘要(hex digest):

X-Bludhaven-Signature: t=1795123456,v1=5d41402abc4b2a76b9719d911017c5926c459992f026a0b72a6a8b1a7f05252b
  • t:网关签署交付记录时的UNIX纪元时间戳(以秒为单位)。
  • v1:使用您的 Webhook 签名密钥,对 t={timestamp},v1={raw_body} 中的数据进行计算后得到的小写十六进制摘要(长度为 HMAC 到 SHA256 个字符)。

在 Node.js 中验证签名​

验证过程需要在 JSON 进行解析之前获取原始请求体(即请求数据本身)。解析器会修改请求中的空白字符和键的排列顺序,这会导致加密验证失败。

verify-webhook.mjs
import crypto from 'node:crypto';

export function verifyWebhookSignature({ rawBody, signatureHeader, secret, toleranceSeconds = 300 }) {
if (!signatureHeader) {
throw new Error('Missing X-Bludhaven-Signature header');
}

// 1. Extract timestamp and signature from the header
const elements = Object.fromEntries(
signatureHeader.split(',').map((pair) => pair.split('='))
);

const timestamp = parseInt(elements.t, 10);
const expectedSignature = elements.v1;

if (isNaN(timestamp) || !expectedSignature) {
throw new Error('Malformed X-Bludhaven-Signature header');
}

// 2. Reject replays outside tolerance window (default 5 minutes)
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - timestamp) > toleranceSeconds) {
throw new Error('Webhook timestamp falls outside tolerance window');
}

// 3. Recreate the signed string: t={timestamp},v1={raw_body}
const signedPayload = `t=${timestamp},v1=${rawBody}`;

// 4. Compute expected HMAC-SHA256
const computedSignature = crypto
.createHmac('sha256', secret)
.update(signedPayload, 'utf8')
.digest('hex');

// 5. Compare in constant time to prevent timing attacks. A digest of the
// wrong length makes timingSafeEqual throw RangeError, so check the length.
const computed = Buffer.from(computedSignature, 'hex');
const expected = Buffer.from(expectedSignature, 'hex');
const valid =
computed.length === expected.length &&
crypto.timingSafeEqual(computed, expected);

if (!valid) {
throw new Error('Invalid webhook signature');
}

return JSON.parse(rawBody);
}

在 Python 中验证签名​

verify_webhook.py
import hmac
import hashlib
import time
import json

def verify_webhook(raw_bytes: bytes, sig_header: str, secret: str, tolerance: int = 300) -> dict:
parts = dict(item.split("=", 1) for item in sig_header.split(","))
timestamp = int(parts.get("t", 0))
expected_hex = parts.get("v1", "")

if abs(time.time() - timestamp) > tolerance:
raise ValueError("Timestamp outside acceptable replay window")

signed_data = f"t={timestamp},v1=".encode("utf-8") + raw_bytes
computed_hex = hmac.new(secret.encode("utf-8"), signed_data, hashlib.sha256).hexdigest()

if not hmac.compare_digest(computed_hex, expected_hex):
raise ValueError("Signature mismatch")

return json.loads(raw_bytes.decode("utf-8"))

在沙箱环境中测试调度功能​

沙箱网关提供了一个用于测试的发送端点(test dispatch endpoint)。它会为实际的数据内容(payload)生成签名,并返回相应的请求头(headers)。将接收器的地址指向该端点,即可无需等待后台事件的发生即可测试签名处理功能。

参考控制台将相同的调用记录在“Webhooks”类别下。请选择“Browser demo”服务器并将请求发送到该服务器。该演示功能会在接收到请求时使用已发布的签名密钥进行签名;因此,您从控制台复制的请求头信息需要与whsec_sandbox_bludhaven_test_secret_9981中的内容进行比对。如果使用的是存储的测试数据(fixture),则其中的时间戳和摘要信息可能会失效(因为数据已经过时)。

curl -X POST https://sandbox.bludhaven-pets.workers.dev/webhooks/test-dispatch \
-H "Content-Type: application/json" \
-o webhook-dispatch.json

不需要发送请求体(request body)——网关会自动生成完整的请求负载(payload)。只需发送{"event": "veterinary.clearance.filed"}即可,该对象将作为请求负载被处理。

webhook-dispatch.json
{
"dispatched": true,
"event": "adoption.hold.expired",
"secret_used": "whsec_sandbox_bludhaven_test_secret_9981",
"headers": {
"Content-Type": "application/json",
"X-Bludhaven-Signature": "t=1795123456,v1=5d41402abc4b...",
"X-Bludhaven-Timestamp": "1795123456"
},
"payload": {
"id": "evt_wh_901ab2cd",
"event": "adoption.hold.expired",
"created_at": "2026-11-19T13:30:00Z",
"data": {
"hold_id": "hld_a8f90b",
"animal_id": "pet_krypto_210",
"reason": "30_MINUTE_WINDOW_LAPSED"
}
},
"verification_guide": {
"scheme": "HMAC-SHA256",
"signed_template": "t={timestamp},v1={raw_body}",
"header_format": "t={timestamp},v1={hex_signature}"
}
}

响应中包含签名密钥、计算出的签名值以及请求负载本身。请使用沙箱工作区(sandbox worker repository)中的验证工具对这些数据进行验证。

node scripts/verify-webhook.mjs webhook-dispatch.json
Output
event adoption.hold.expired
secret whsec_sandbox_bludhaven_test_secret_9981
signature header t=1795123456,v1=5d41402a...
computed header t=1795123456,v1=5d41402a...
signature match YES
delivery age 2s (tolerance 300s): fresh

PASS: HMAC-SHA256 signature verified.

验证工具会从文件中读取响应内容并重新计算摘要值。切勿通过shell变量或内嵌的node -e字符串来传递请求负载;否则会导致嵌套的JSON结构被破坏,从而导致验证失败(返回结果为ReferenceError)。

更改有效载荷(payload)中的一个字符后,验证器会从状态 1 转变为状态 FAIL: signature does not match。

验证工具还会拒绝超过300秒旧时的请求;在重放存档的测试数据时,请务必再次发送--ignore-age。

相关指南:​