for agents: this page is markdown at https://switchyard.so/docs/verify-webhooks.md; every page is listed in llms.txt.
Verify a webhook signature
Check that a request to your receiver came from Switchyard and was not changed on the way, in your own code or from a terminal.
You will have: a receiver that accepts a signed test event and refuses a request with a wrong signature. Works with: yard, MCP, REST, and TypeScript, Python or Go in your receiver. Takes: about 10 minutes.
Before you start
- You added an endpoint and kept its signing secret (Receive webhooks, step 1). The secret starts with
whsec_. - Your receiver can read the body of a request as the bytes that arrived, before any JSON parsing.
Step 1 — Give the receiver the secret
Put the signing secret in the receiver's environment so that the code reads it and no file in your repository holds it.
export SWITCHYARD_WEBHOOK_SECRET='<signing secret>'
Each endpoint has its own secret. A receiver for two endpoints holds two secrets.
The receiver has the secret. Next, it checks each request with it.
Step 2 — Check each request in your receiver
Check the signature before your receiver acts on a request. Every request carries three headers:
| Header | Content |
|---|---|
webhook-id | the event's id, the same on every attempt |
webhook-timestamp | when the request was signed, in seconds since 1970 |
webhook-signature | v1, and then the base64 HMAC-SHA256 of <webhook-id>.<webhook-timestamp>.<body> |
The HMAC key is the signing secret without its whsec_ prefix, base64-decoded. A request is valid when all of these hold:
- The timestamp is within 300 seconds of your receiver's clock, earlier or later.
- One
v1,entry ofwebhook-signatureequals the HMAC of the three parts, joined by dots, over the body's bytes as they arrived. The header can hold several entries separated by spaces. Pass over an entry of another version. - The comparison takes the same time whatever the bytes are.
Copy the function for your language. Each one needs no package.
TypeScript (Node 20 or later, Deno, Bun, Cloudflare Workers):
// Verifies one Switchyard webhook delivery (Standard Webhooks, version 1). It needs no package: it uses Web Crypto,
// which Node 20 and later, Deno, Bun and Cloudflare Workers have.
//
// `body` is the request's body as it arrived, before any JSON parsing. The function returns when the delivery is
// valid and throws an Error that says why when it is not.
export interface WebhookHeaders {
id: string | null | undefined; // webhook-id
timestamp: string | null | undefined; // webhook-timestamp
signature: string | null | undefined; // webhook-signature
}
export async function verifyWebhook(secret: string, headers: WebhookHeaders, body: string | Uint8Array, toleranceSeconds = 300, nowSeconds = Math.floor(Date.now() / 1000)): Promise<void> {
if (!secret.startsWith("whsec_")) throw new Error("the secret must start with whsec_");
const { id, timestamp, signature } = headers;
if (!id || !timestamp || !signature) throw new Error("a webhook-id, webhook-timestamp or webhook-signature header is missing");
if (!/^[0-9]+$/.test(timestamp)) throw new Error("the timestamp is not a number of seconds");
// Refuse a delivery signed too long ago, or too far ahead of this machine's clock: it may be a replay.
const age = nowSeconds - Number(timestamp);
if (age > toleranceSeconds) throw new Error(`the timestamp is ${age} seconds old; the limit is ${toleranceSeconds}`);
if (-age > toleranceSeconds) throw new Error(`the timestamp is ${-age} seconds ahead; check this machine's clock`);
// The signed content is "<webhook-id>.<webhook-timestamp>.<body>", and the key is what the secret encodes after whsec_.
const encoder = new TextEncoder();
const prefix = encoder.encode(`${id}.${timestamp}.`);
const bytes = typeof body === "string" ? encoder.encode(body) : body;
const content = new Uint8Array(prefix.length + bytes.length);
content.set(prefix);
content.set(bytes, prefix.length);
const keyBytes = fromBase64(secret.slice("whsec_".length));
if (!keyBytes) throw new Error("the secret is not base64 after whsec_");
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
// The header holds one signature or several separated by spaces. One "v1," entry that matches is enough; an entry of
// another version is passed over. crypto.subtle.verify compares in constant time.
for (const entry of signature.split(" ")) {
if (!entry.startsWith("v1,")) continue;
const candidate = fromBase64(entry.slice("v1,".length));
if (candidate && (await crypto.subtle.verify("HMAC", key, candidate, content))) return;
}
throw new Error("no signature matches: the secret is another endpoint's, or the body is not the bytes as sent");
}
// The bytes a base64 text encodes, or undefined when it is not base64.
function fromBase64(text: string) {
try {
const binary = atob(text);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
return bytes;
} catch {
return undefined;
}
}
Python:
"""Verifies one Switchyard webhook delivery (Standard Webhooks, version 1). It needs only the standard library.
`body` is the request's body as it arrived, before any JSON parsing. The function returns when the delivery is valid
and raises ValueError, which says why, when it is not.
"""
import base64
import binascii
import hashlib
import hmac
import time
def verify_webhook(secret, webhook_id, timestamp, signature, body, tolerance_seconds=300, now_seconds=None):
if not secret.startswith("whsec_"):
raise ValueError("the secret must start with whsec_")
if not webhook_id or not timestamp or not signature:
raise ValueError("a webhook-id, webhook-timestamp or webhook-signature header is missing")
if not (timestamp.isascii() and timestamp.isdigit()):
raise ValueError("the timestamp is not a number of seconds")
# Refuse a delivery signed too long ago, or too far ahead of this machine's clock: it may be a replay.
now = int(time.time()) if now_seconds is None else int(now_seconds)
age = now - int(timestamp)
if age > tolerance_seconds:
raise ValueError(f"the timestamp is {age} seconds old; the limit is {tolerance_seconds}")
if -age > tolerance_seconds:
raise ValueError(f"the timestamp is {-age} seconds ahead; check this machine's clock")
# The signed content is "<webhook-id>.<webhook-timestamp>.<body>", and the key is what the secret encodes after whsec_.
if isinstance(body, str):
body = body.encode("utf-8")
key = base64.b64decode(secret[len("whsec_"):])
expected = hmac.new(key, f"{webhook_id}.{timestamp}.".encode("utf-8") + body, hashlib.sha256).digest()
# The header holds one signature or several separated by spaces. One "v1," entry that matches is enough; an entry
# of another version is passed over. hmac.compare_digest compares in constant time.
for entry in signature.split(" "):
if not entry.startswith("v1,"):
continue
try:
candidate = base64.b64decode(entry[len("v1,"):], validate=True)
except (binascii.Error, ValueError):
continue
if hmac.compare_digest(candidate, expected):
return
raise ValueError("no signature matches: the secret is another endpoint's, or the body is not the bytes as sent")
Go:
// Package webhooks verifies one Switchyard webhook delivery (Standard Webhooks, version 1). It needs only the standard
// library.
package webhooks
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"strconv"
"strings"
"time"
)
// Verify returns nil when the delivery is valid and an error that says why when it is not. id, timestamp and signature
// are the webhook-id, webhook-timestamp and webhook-signature headers. body is the request's body as it arrived, before
// any JSON parsing. Pass 5*time.Minute as the tolerance and time.Now() as now.
func Verify(secret, id, timestamp, signature string, body []byte, tolerance time.Duration, now time.Time) error {
encoded, found := strings.CutPrefix(secret, "whsec_")
if !found {
return errors.New("the secret must start with whsec_")
}
if id == "" || timestamp == "" || signature == "" {
return errors.New("a webhook-id, webhook-timestamp or webhook-signature header is missing")
}
seconds, err := strconv.ParseUint(timestamp, 10, 63)
if err != nil {
return errors.New("the timestamp is not a number of seconds")
}
// Refuse a delivery signed too long ago, or too far ahead of this machine's clock: it may be a replay.
age := now.Unix() - int64(seconds)
limit := int64(tolerance / time.Second)
if age > limit {
return fmt.Errorf("the timestamp is %d seconds old; the limit is %d", age, limit)
}
if -age > limit {
return fmt.Errorf("the timestamp is %d seconds ahead; check this machine's clock", -age)
}
// The signed content is "<webhook-id>.<webhook-timestamp>.<body>", and the key is what the secret encodes after whsec_.
key, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return errors.New("the secret is not base64 after whsec_")
}
mac := hmac.New(sha256.New, key)
mac.Write([]byte(id + "." + timestamp + "."))
mac.Write(body)
expected := mac.Sum(nil)
// The header holds one signature or several separated by spaces. One "v1," entry that matches is enough; an entry of
// another version is passed over. hmac.Equal compares in constant time.
for _, entry := range strings.Split(signature, " ") {
candidate, isV1 := strings.CutPrefix(entry, "v1,")
if !isV1 {
continue
}
given, err := base64.StdEncoding.DecodeString(candidate)
if err != nil {
continue
}
if hmac.Equal(given, expected) {
return nil
}
}
return errors.New("no signature matches: the secret is another endpoint's, or the body is not the bytes as sent")
}
Call it with the three headers and the raw body, and answer 400 when it fails. In TypeScript, on a runtime with Request:
const body = new Uint8Array(await request.arrayBuffer());
try {
await verifyWebhook(process.env.SWITCHYARD_WEBHOOK_SECRET ?? "", {
id: request.headers.get("webhook-id"),
timestamp: request.headers.get("webhook-timestamp"),
signature: request.headers.get("webhook-signature"),
}, body);
} catch {
return new Response("the signature is not valid", { status: 400 });
}
A Standard Webhooks library does the same check with the same headers and the secret as it is. Switchyard's tests run these three functions and the standardwebhooks package for JavaScript against requests signed by the code that signs every delivery.
Your receiver refuses requests that are not from Switchyard. Next, check one request by hand.
Step 3 — Check one request from a terminal
Run yard webhook verify to learn why your receiver refused a request. The command runs on your machine, sends nothing over the network and needs no sign-in. It reads the secret from SWITCHYARD_WEBHOOK_SECRET or from a file named with --secret-file, never from an argument, and it never prints the secret.
Save the request's body to a file as it arrived, then pass the three headers:
yard webhook verify --id evt_812_0 --timestamp 1795000000 --signature 'v1,<base64>' --body-file body.json
Output
valid: evt_812_0 was signed with this secret 4 seconds ago
The command exits 0 when the request is valid and 1 when it is not. When it is not, the command prints one sentence, and --json prints its code:
| Code | Sentence | What to do |
|---|---|---|
secret_format | the secret must start with whsec_ | Use the secret as yard webhook add printed it. |
header_missing | {header} is missing | Pass all three headers: --id, --timestamp and --signature. |
timestamp_old | the timestamp is {n} seconds old; the limit is {tolerance} | The request was signed too long ago. An old request can be a replay. --tolerance <seconds> changes the limit. |
timestamp_ahead | the timestamp is {n} seconds ahead; check this machine's clock | Set this machine's clock. |
signature_mismatch | no signature matches: the secret is another endpoint's, or the body is not the bytes as sent | Use the secret of the endpoint the request was sent to. Pass the body's bytes as they arrived: a body that was parsed and written again does not match. |
The command exits 2 when it could not read a secret or a body, and when --tolerance is 0.
You know why a request is refused. Next, send a request on demand.
Step 4 — Send a test event
Send a test event to see your receiver accept a signed request without waiting for a task.
yard webhook test <id>
Output
delivered, answered 200 in 84 ms
<id> is the endpoint's id, as yard webhook list shows it. The command exits 0 when your receiver answered with a 2xx status within 10 seconds. It exits 1 when not, and says why:
| The command says | Meaning | What to do |
|---|---|---|
| answered {status} | your receiver answered with a status that is not 2xx | Answer 2xx within 10 seconds and do the work afterwards. |
| answered {status}, a redirect | your receiver answered with a redirect, which Switchyard does not follow | Add the final address as the endpoint. |
| no answer in 10 seconds | your receiver took too long | Answer first, then do the work. |
| could not connect | the request did not reach your receiver | Check that the host is up and accepts connections, and that its certificate is valid for its name. |
| the address resolves to a private network, so nothing was sent | the host's name resolves to an address that is not public, and Switchyard made no request | Point the host's name at a public address. |
| the endpoint's secret cannot sign | the stored secret is damaged | Remove the endpoint and add it again. |
MCP: yard_webhooks with action: "test" and id · REST: POST /v1/projects/<project>/webhooks/<id>/test · the board: "send a test event" on the endpoint's row in the project's settings.
A test event has the same headers and signature as every other request. Its body names no task:
{
"type": "event",
"id": "evt_test_9f2c41d07ab35e68",
"created_at": "2026-11-18T09:12:40.000Z",
"data": {
"type": "webhook.test",
"project": "your-project",
"seq": 812
}
}
Facts about a test event:
- Switchyard sends it to the endpoint you name, whatever events the endpoint asked for.
- Switchyard sends it one time and never again, delivered or not.
- It does not change what
yard webhook listsays about the endpoint's deliveries. - An endpoint takes at most 30 test events in one hour of the clock. The next one is refused with the status 429 and the time to send again.
- Adding an endpoint sends one test event to it. The add's answer carries its result, and that test event does not count toward the 30.
Verify
- Run
yard webhook test <id>. The command printsdeliveredand your receiver's log shows one accepted request withdata.typewebhook.test. - Change one character of the secret in your receiver, restart it, and run
yard webhook test <id>again. Your receiver answers 400 and the command printsnot delivered: answered 400. - Put the secret back and restart the receiver.
Next
- Receive webhooks: the events, the retries, and when an event is dropped.
- The yard CLI: every flag of
yard webhook verifyandyard webhook test.