Open in
驗證 webhook 簽署
ThunderPhone 發出的每個 webhook 及工具請求均會附帶時間戳記簽署。使用此處的範例或 SDK 輔助工具驗證簽署,並拒絕超過五分鐘的重播請求。
我們傳送至你伺服器的每個請求(webhook 傳送、舊有的 單一 URL webhook 及工具端點呼叫)均附帶兩個簽名 標頭。兩者均使用相同密鑰的 HMAC-SHA256。
| 標頭 | 簽署內容 | 防重放保護 |
|---|---|---|
X-ThunderPhone-Signature-V2(建議使用) | 時間戳記、方法、路徑、查詢及主體 | 拒絕超過 5 分鐘前的請求 |
X-ThunderPhone-Signature | 僅主體 | 無:已擷取的請求可永久通過驗證 |
在新的整合中驗證 X-ThunderPhone-Signature-V2,並將現有整合
遷移至此版本。X-ThunderPhone-Signature 仍會在每個
請求中原樣傳送,因此基於此標頭建立的驗證器將繼續運作。我們會在停止傳送前公布日期。
簽名 V2
X-ThunderPhone-Signature-V2: t=1767225600,v1=03a89bec521f78d55727237ca4713bb0b8dcdf2e09e450865b5b5637b80c1c4et是我們傳送請求時的 Unix 時間,以秒為單位。重試傳送時會再次簽名,並使用其專屬的t。v1是以下已簽名字串的十六進位 HMAC-SHA256,使用你的密鑰作為金鑰。
此值是由逗號分隔的 key=value 配對清單。請忽略無法識別的金鑰,並在任何一個 v1 相符時接受請求:我們日後變更時可能會新增第二個簽名。
已簽名字串
共四個欄位,每個欄位後面均有一個換行字元(\n,位元組 0x0A),最後一個欄位除外:
<t>\n<METHOD>\n<path and query>\n<body>| 欄位 | 值 |
|---|---|
t | 標頭中的 t 值 |
METHOD | 大寫 HTTP 方法:POST、GET、PUT、PATCH 或 DELETE |
| path and query | HTTP 請求列中的請求目標:先是路徑,如有查詢字串則接著是 ? 及查詢字串。不包括通訊協定、主機或片段。請完全按接收時的原樣使用,不要解碼或重新排列參數 |
body | 原始請求主體。GET 及 DELETE 工具呼叫沒有主體,因此其已簽名字串會在路徑後的換行字元結束 |
驗證步驟:
- 在進行任何剖析前,讀取標頭、方法、原始路徑及查詢字串,以及原始主體。
- 從標頭擷取
t及所有v1。 - 如
t比你的時鐘早或遲超過 300 秒,拒絕該請求。 - 使用你的密鑰計算已簽名字串的十六進位 HMAC-SHA256。
- 以固定時間方式與
v1比較。如沒有任何值相符,回應401。
完整範例
密鑰為 whsec_example_4c1f2a9b。我們在
t = 1767225600(2026-01-01 00:00:00 UTC)傳送以下請求:
POST /tools/lookup?region=us HTTP/1.1
Host: api.example.com
Content-Type: application/json
X-ThunderPhone-Signature-V2: t=1767225600,v1=03a89bec521f78d55727237ca4713bb0b8dcdf2e09e450865b5b5637b80c1c4e
{"customer_id":"cust_123"}已簽名字串為以下四行,主體後沒有換行字元:
1767225600
POST
/tools/lookup?region=us
{"customer_id":"cust_123"}其 HMAC-SHA256 為
03a89bec521f78d55727237ca4713bb0b8dcdf2e09e450865b5b5637b80c1c4e。
請用此值核對你的實作,或以 openssl 重現:
printf '1767225600\nPOST\n/tools/lookup?region=us\n{"customer_id":"cust_123"}' \
| openssl dgst -sha256 -hmac 'whsec_example_4c1f2a9b'在同一秒內,對 /tools/lookup?customer_id=cust_123 的 GET 工具呼叫主體為空。其已簽名字串為
1767225600\nGET\n/tools/lookup?customer_id=cust_123\n,而其簽名為
3ce214cb0b8f2bf39b1d19d4e7265df9dbaff5a5f838d3cc6c753a8f7a4ad280。
使用 SDK
Python 及 TypeScript SDK 包含輔助函式
(thunderphone 0.2.0 或以上版本,或 @thunderphone/sdk 0.2.0 或以上版本)。它會檢查 5 分鐘時限、以固定時間方式比較,並接受密鑰清單,讓你可在不中斷服務的情況下輪替密鑰。
from thunderphone import verify_signature
ok = verify_signature(
header, # the X-ThunderPhone-Signature-V2 value
secret=SECRET, # or [NEW_SECRET, OLD_SECRET] while rotating
method=method, # "POST"
path=path, # "/tools/lookup?region=us", exactly as received
body=raw_body, # bytes, before any JSON parsing
tolerance=300, # optional; seconds
)import { verifySignature } from "@thunderphone/sdk";
const ok = verifySignature({
header, // the X-ThunderPhone-Signature-V2 value
secret: SECRET, // or [NEW_SECRET, OLD_SECRET] while rotating
method, // "POST"
path, // "/tools/lookup?region=us", exactly as received
body: rawBody, // Buffer or string, before any JSON parsing
toleranceSeconds: 300, // optional
});不使用 SDK
import hashlib
import hmac
import time
TOLERANCE_SECONDS = 300
def verify_v2(header: str, secret: str, method: str, path: str, body: bytes) -> bool:
"""path is the path plus ?query exactly as received; body is the raw body."""
timestamp, signatures = None, []
for item in (header or "").split(","):
key, _, value = item.strip().partition("=")
if key == "t" and value.isdigit() and len(value) <= 15:
timestamp = int(value)
elif key == "v1":
signatures.append(value)
if timestamp is None or abs(time.time() - timestamp) > TOLERANCE_SECONDS:
return False
signed = f"{timestamp}\n{method.upper()}\n{path}\n".encode() + body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected.encode(), s.encode()) for s in signatures)import crypto from "node:crypto";
const TOLERANCE_SECONDS = 300;
// path is the path plus ?query exactly as received; body is the raw Buffer.
export function verifyV2(header, secret, method, path, body) {
let timestamp;
const signatures = [];
for (const item of (header || "").split(",")) {
const [key, value = ""] = item.trim().split("=", 2);
if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);
else if (key === "v1") signatures.push(value);
}
if (timestamp === undefined) return false;
if (Math.abs(Date.now() / 1000 - timestamp) > TOLERANCE_SECONDS) return false;
const expected = Buffer.from(
crypto
.createHmac("sha256", secret)
.update(`${timestamp}\n${method.toUpperCase()}\n${path}\n`)
.update(body)
.digest("hex"),
);
return signatures.some((sig) => {
const candidate = Buffer.from(sig);
return (
candidate.length === expected.length &&
crypto.timingSafeEqual(candidate, expected)
);
});
}框架接線
每個範例都會讀取原始路徑、查詢字串及原始請求本文,然後呼叫 SDK 輔助函式。
import json
from fastapi import FastAPI, HTTPException, Request
from thunderphone import verify_signature
app = FastAPI()
def raw_path_and_query(request: Request) -> str:
path = (request.scope.get("raw_path") or request.url.path.encode()).decode("latin-1")
query = request.scope.get("query_string", b"").decode("latin-1")
return f"{path}?{query}" if query else path
@app.post("/thunderphone-webhook")
async def hook(request: Request):
body = await request.body() # raw bytes, NOT request.json()
if not verify_signature(
request.headers.get("X-ThunderPhone-Signature-V2"),
secret=SECRET,
method=request.method,
path=raw_path_and_query(request),
body=body,
):
raise HTTPException(status_code=401)
event = json.loads(body)
# … dispatch on event["type"] …
return {"ok": True}import express from "express";
import { verifySignature } from "@thunderphone/sdk";
const app = express();
app.post(
"/thunderphone-webhook",
// IMPORTANT: parse as raw; do NOT use express.json() here.
express.raw({ type: "application/json" }),
(req, res) => {
const ok = verifySignature({
header: req.header("X-ThunderPhone-Signature-V2"),
secret: process.env.WEBHOOK_SECRET,
method: req.method,
path: req.originalUrl, // path and query as received
body: req.body,
});
if (!ok) return res.sendStatus(401);
const event = JSON.parse(req.body.toString("utf8"));
// … dispatch on event.type …
res.sendStatus(204);
},
);import json
from django.http import HttpResponseForbidden, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from thunderphone import verify_signature
@csrf_exempt
@require_POST
def hook(request):
if not verify_signature(
request.headers.get("X-ThunderPhone-Signature-V2"),
secret=SECRET,
method=request.method,
path=request.get_full_path(),
body=request.body, # raw bytes
):
return HttpResponseForbidden("invalid signature")
event = json.loads(request.body)
# … dispatch on event["type"] …
return JsonResponse({"ok": True})req.originalUrl(Express)以及 ASGI 的 raw_path 和 query_string
(FastAPI)均為完全按接收時的原始目標。Django 的
get_full_path() 及 Flask 的 request.path 會先解碼路徑,對一般路徑而言
會產生相同字串。如你的端點路徑包含經百分比編碼或保留字元,例如 %2F、; 或 =,請改為讀取伺服器提供的原始目標(例如 Gunicorn 的
request.META["RAW_URI"])。
使用哪個密鑰?
兩個標頭均使用同一密鑰簽署。
| 來源 | 密鑰 |
|---|---|
Webhook 端點(/v1/developer/webhook-endpoints) | 建立時僅會傳回一次的每端點 secret(48 個十六進位字元) |
| 舊版單一 URL webhook | 透過 GET /v1/webhook 傳回的每組織 secret |
工具端點調用(直接調用你的 endpoint.url) | 組織層級 webhook 密鑰(與舊版單一 URL webhook 使用相同密鑰)——並非每端點密鑰 |
將密鑰儲存於你的密鑰管理工具或環境變數中——切勿提交至程式碼庫。
驗證工具呼叫
當智能體直接調用你的
功能工具(工具設有
endpoint)時,請求會連同你已設定的 endpoint.headers 一併帶有以下 ThunderPhone 標頭:
X-ThunderPhone-Call-ID—— 進行中通話的數字 ID。X-ThunderPhone-Signature-V2—— 以上附有時間戳記的簽名,使用你的組織層級 Webhook 密鑰作為金鑰。X-ThunderPhone-Signature—— 舊版僅涵蓋請求主體的簽名,使用相同金鑰。
電話通話亦會附帶 X-ThunderPhone-From-Number、X-ThunderPhone-To-Number 及 X-ThunderPhone-Call-Direction
(詳情)。與所有標頭一樣,兩種簽署均不涵蓋這些標頭。
每個工具請求均會簽署,即使你的機構從未設定舊版 webhook:ThunderPhone 會自動建立機構密鑰。可透過 GET /v1/webhook 讀取。
有一點與 webhook 不同:GET / DELETE 工具沒有請求主體。 引數會透過查詢參數傳送。V2 簽署會透過路徑及查詢涵蓋這些引數,而請求主體欄位為空。請使用原始查詢字串驗證:解析參數後再建立新的查詢字串,可能會改變其順序或編碼。舊版標頭會簽署空位元組字串。
@app.api_route("/tools/search-appointments", methods=["GET", "POST"])
async def tool(request: Request):
body = await request.body() # b"" for GET/DELETE tools
if not verify_signature(
request.headers.get("X-ThunderPhone-Signature-V2"),
secret=ORG_WEBHOOK_SECRET,
method=request.method,
path=raw_path_and_query(request),
body=body,
):
raise HTTPException(status_code=401)
call_id = request.headers.get("X-ThunderPhone-Call-ID", "")
args = json.loads(body) if body else dict(request.query_params)
...在 Express 中,請求主體剖析器會在 GET 請求中將 req.body 保留為空物件,因此請傳入 Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0)。
Webhook-模式工具分派(沒有 endpoint 的工具,會以 telephony.tool / web.tool
傳送至你的組織 webhook)屬於一般已簽署 webhook——適用上述標準做法。請參閱
函式工具 了解兩種請求格式。
舊版簽名:X-ThunderPhone-Signature
原始標頭僅包含原始主體的十六進位 HMAC-SHA256,並使用相同密鑰。它不帶時間戳記,因此任何截取到一個已簽名請求的人都可以重放該請求。整合項目遷移至 V2 期間,每個請求仍會附帶此標頭。
- 讀取原始請求主體——即我們傳送給你的確切位元組。
- 計算
hmac_sha256(secret, body).hexdigest()。 - 以固定時間方式與
X-ThunderPhone-Signature比較。
我們會簽署所傳送的確切位元組。這些位元組亦是負載的標準 JSON 序列化——索引鍵按字母順序排列、使用緊湊分隔符號(, 及不含空格的 :)、UTF-8。若你的框架只提供已剖析的 JSON,請以標準格式重新序列化,然後對其計算 HMAC:
# Equivalent to hashing the raw body:
import json
canonical = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")建議使用原始主體——可省卻一個步驟,亦可避免某些程式語言中 JSON 數字來回轉換的問題。V2 的主體欄位亦同樣適用。
import hashlib
import hmac
def verify(body: bytes, signature: str, secret: str) -> bool:
"""Constant-time HMAC-SHA256 verification."""
expected = hmac.new(
secret.encode("utf-8"),
body,
hashlib.sha256,
).hexdigest()
return hmac.compare_digest(expected, signature or "")import crypto from "node:crypto";
export function verify(body, signature, secret) {
const expected = crypto
.createHmac("sha256", secret)
.update(body)
.digest("hex");
if (!signature || expected.length !== signature.length) return false;
return crypto.timingSafeEqual(
Buffer.from(expected),
Buffer.from(signature),
);
}package webhook
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
)
func Verify(body []byte, signature, secret string) bool {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
expected := hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(expected), []byte(signature))
}require "openssl"
def verify(body, signature, secret)
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, body)
Rack::Utils.secure_compare(expected, signature.to_s)
end常見陷阱
時鐘偏差
5 分鐘時限是根據你的伺服器時鐘計算。請與 NTP 保持 同步;時鐘偏差超過 5 分鐘會拒絕所有 請求。
代理伺服器改寫路徑
已簽署的路徑是我們請求的路徑:即你在 ThunderPhone 中 設定的 URL 路徑。如果反向代理伺服器或 API 閘道在你的 應用程式收到請求前移除或加入前綴,請在驗證前重建我們 傳送的路徑(例如將前綴加回去)。
以預設格式重新序列化
解析主體後,再以 JSON 函式庫的預設設定
重新輸出(在 , / : 後加入空格、按插入順序排列金鑰),會產生
不同的位元組並導致 HMAC 失效。請驗證原始主體——如必須
重新序列化,請完全符合我們的規範格式:排序
金鑰、精簡分隔符號、UTF-8。
框架自動解析 JSON
Express 的 express.json() 中介軟件會讀取主體串流,令你失去原始位元組。請在 webhook 路由專門使用 express.raw(),或在前置中介軟件中緩衝原始主體。NestJS / Koa 亦然——請查閱其「原始主體」文件。
非時間安全的比較
JS 中的 expected === signature 或 Python 中的 expected == signature 都是耗時可變的比較方式。請分別使用 crypto.timingSafeEqual
或 hmac.compare_digest。效能差異可以忽略不計。
工具端點使用錯誤密鑰
直接呼叫工具端點會使用 機構層級 Webhook
密鑰(GET /v1/webhook)簽署——而非使用
/v1/developer/webhook-endpoints 中任何個別端點的密鑰。重用相同的輔助程式,
但請確保在工具路由中向它提供機構密鑰。
GET/DELETE 工具的查詢字串
V2 會完全按照傳送時的格式簽署查詢字串。舊版標頭簽署的是 空白主體,從不簽署查詢字串,因此為舊版標頭雜湊 URL 永遠不會相符。
時限內的重複項目
時間戳可阻止超過 5 分鐘的重放,無法阻止時限內的第二個副本。
端點交付採用至少一次模式,因此同一事件的重試亦可能送達;請根據
封套中的 event_id 去除重複項目。
不在不符時回傳 401
驗證失敗時回傳 200,會令處理程式成為重放攻擊目標。驗證失敗時,務必回應非 2xx 狀態碼。