Appearance
Webhooks and signatures
Webhooks go both ways. A hook's webhook step sends signed JSON to your system; a webhook source receives your system's deliveries and starts hooks. MCP clients that subscribe to events get signed deliveries too. This page has the exact schemes, and code that verifies them.
Webhooks to your system
A hook's webhook step sends to an https URL:
json
{"id": "send", "type": "webhook", "params": {
"url": "https://crm.example.com/frege",
"method": "POST",
"headers": {"X-Source": "frege"},
"body": {"order": "{{event.response.id}}"}}}method is POST when left out (or GET, PUT, PATCH, DELETE). The host must be a name or a public address, with no user info. Without a body, the whole event is sent:
json
{"event": "client.credential_expired", "event_id": "0b6c…",
"data": {"client": {"id": 42, "name": "Ann", "phone": "998"}, "reason": "refresh_rejected", "upstream": {"status": 401, "step": "refresh"}}}Don't put secrets in headers: anyone who can see the environment can read them. A step may not set Host, Content-Length, Content-Type, Transfer-Encoding or any X-Frege-* header.
Headers
| Header | Value |
|---|---|
Content-Type | application/json |
User-Agent | Frege-Hooks/1 |
X-Frege-Event | The event's name. |
X-Frege-Delivery | The run's id. |
X-Frege-Delivery-Step | <run id>:<step id>. |
X-Frege-Timestamp | Unix seconds when this attempt was sent. |
X-Frege-Signature | sha256=<hex HMAC-SHA256(secret, "<X-Frege-Timestamp>.<body>")> |
Webhook-Id | <run id>:<step id>: the same on every attempt, different for each webhook step of a run. |
Webhook-Timestamp | The same as X-Frege-Timestamp. |
Webhook-Signature | v1,<base64 HMAC-SHA256(secret, "<Webhook-Id>.<Webhook-Timestamp>.<body>")> |
Every delivery carries both signatures: the hex one, and a Standard Webhooks one. Verify either.
The key is the secret's own text, whsec_ included, as bytes. It is not base64-decoded, which is not what Standard Webhooks libraries do by default: use a library's raw-key form (NewWebhookRaw in Go), or the functions below.
The secret
Each hook has its own signing secret, whsec_ and 43 more characters. A manager reads it, and replaces it, at:
bash
curl "https://api.frege.io/v1/projects/$PROJECT/hooks/$HOOK/secret" \
-H "Authorization: Bearer $TOKEN" -H "X-Frege-Stage: live"
# {"data": {"signing_secret": "whsec_..."}}
curl -X POST "https://api.frege.io/v1/projects/$PROJECT/hooks/$HOOK/secret" \
-H "Authorization: Bearer $TOKEN" -H "X-Frege-Stage: live"A replaced secret stops signing at once: there is no overlap.
Retries
- An answer below
300is a success. A3xxis a failure, and redirects are not followed. - No answer, a timeout,
408,429and any5xxare retried, by the hook'smax_attempts(3 by default): 30 seconds later, then doubling. Any other answer fails the step without a retry. - Frege waits 10 seconds and reads at most 64 KB of your answer.
- An attempt is signed afresh: a new timestamp, the same
Webhook-Id. UseWebhook-Idto drop a delivery you have already taken.
MCP event deliveries
An event subscription sends Webhook-Id (msg_…), Webhook-Timestamp and Webhook-Signature, the same Standard Webhooks scheme, with two differences:
- The key is decoded, as Standard Webhooks says: the base64 bytes after
whsec_of the secret you subscribed with. - While a secret rotates,
Webhook-Signatureholds two signatures separated by a space. Accept a delivery when any of them matches.
Verifying a signature
Verify against the raw body, byte for byte, before parsing it. Refusing a timestamp far from now (say, five minutes) stops a replayed delivery; Frege signs every attempt with the time it was sent.
js
import crypto from 'node:crypto';
// X-Frege-Signature: "sha256=" + hex HMAC-SHA256(secret, "<timestamp>.<body>").
export function verifyFregeSignature(secret, timestamp, body, header) {
const want = 'sha256=' + crypto.createHmac('sha256', secret).update(`${timestamp}.`).update(body).digest('hex');
return safeEqual(want, header ?? '');
}
// Webhook-Signature: space-separated "v1,<base64>" over "<id>.<timestamp>.<body>".
export function verifyStandardSignature(key, id, timestamp, body, header) {
const want = crypto.createHmac('sha256', key).update(`${id}.${timestamp}.`).update(body).digest('base64');
return (header ?? '').split(' ').some((s) => s.startsWith('v1,') && safeEqual(s.slice(3), want));
}
function safeEqual(a, b) {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && crypto.timingSafeEqual(x, y);
}
// A hook's key is its secret as written; an event subscription's is the decoded base64 after "whsec_".
export const hookKey = (secret) => Buffer.from(secret);
export const eventKey = (secret) => Buffer.from(secret.slice('whsec_'.length), 'base64');python
import base64
import hashlib
import hmac
def verify_frege_signature(secret: str, timestamp: str, body: bytes, header: str) -> bool:
"""X-Frege-Signature: "sha256=" + hex HMAC-SHA256(secret, "<timestamp>.<body>")."""
mac = hmac.new(secret.encode(), timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
return hmac.compare_digest("sha256=" + mac, header or "")
def verify_standard_signature(key: bytes, msg_id: str, timestamp: str, body: bytes, header: str) -> bool:
"""Webhook-Signature: space-separated "v1,<base64>" over "<id>.<timestamp>.<body>"."""
mac = hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256).digest()
want = base64.b64encode(mac).decode()
return any(s.startswith("v1,") and hmac.compare_digest(s[3:], want) for s in (header or "").split(" "))
def hook_key(secret: str) -> bytes:
"""A hook's key is its secret as written."""
return secret.encode()
def event_key(secret: str) -> bytes:
"""An event subscription's key is the decoded base64 after "whsec_"."""
b64 = secret.removeprefix("whsec_")
return base64.b64decode(b64 + "=" * (-len(b64) % 4))go
package webhooks
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"strings"
)
// VerifyFregeSignature checks X-Frege-Signature: "sha256=" + hex HMAC-SHA256(secret, "<timestamp>.<body>").
func VerifyFregeSignature(secret, timestamp string, body []byte, header string) bool {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(timestamp + "."))
mac.Write(body)
want := "sha256=" + hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(want), []byte(header))
}
// VerifyStandardSignature checks Webhook-Signature: space-separated "v1,<base64>" over "<id>.<timestamp>.<body>".
func VerifyStandardSignature(key []byte, id, timestamp string, body []byte, header string) bool {
mac := hmac.New(sha256.New, key)
mac.Write([]byte(id + "." + timestamp + "."))
mac.Write(body)
want := base64.StdEncoding.EncodeToString(mac.Sum(nil))
for _, s := range strings.Fields(header) {
if sig, ok := strings.CutPrefix(s, "v1,"); ok && hmac.Equal([]byte(sig), []byte(want)) {
return true
}
}
return false
}
// HookKey is a hook's secret as written; EventKey the decoded base64 after "whsec_" of a subscription's.
func HookKey(secret string) []byte { return []byte(secret) }
func EventKey(secret string) ([]byte, error) {
return base64.RawStdEncoding.DecodeString(strings.TrimRight(strings.TrimPrefix(secret, "whsec_"), "="))
}bash
# The hex signature of a saved delivery (body.json, its exact bytes) and its X-Frege-Timestamp:
{ printf '%s.' "$TIMESTAMP"; cat body.json; } | openssl dgst -sha256 -hmac "$SECRET" | awk '{print "sha256=" $NF}'
# The Standard Webhooks signature, keyed with a hook's secret as written:
{ printf '%s.%s.' "$WEBHOOK_ID" "$TIMESTAMP"; cat body.json; } | openssl dgst -sha256 -hmac "$SECRET" -binary | base64In an HTTP handler, read the body untouched. With Express:
js
import express from 'express';
import { hookKey, verifyStandardSignature } from './webhooks.js';
const app = express();
app.post('/frege', express.raw({ type: 'application/json' }), (req, res) => {
const ok = verifyStandardSignature(hookKey(process.env.FREGE_HOOK_SECRET), req.get('webhook-id'),
req.get('webhook-timestamp'), req.body, req.get('webhook-signature'));
if (!ok) return res.sendStatus(401);
const delivery = JSON.parse(req.body);
// Drop a Webhook-Id you have already handled, then act on delivery.event and delivery.data.
res.sendStatus(204);
});Webhooks from your system
Your backend can tell Frege when something happens (an order filled, a payment received), and a hook acts on it at once: messages the customer in Telegram, runs an agent, calls a tool.
1. Make a source
bash
curl -X POST "https://api.frege.io/v1/projects/$PROJECT/hooks/sources" \
-H "Authorization: Bearer $TOKEN" -H "X-Frege-Stage: live" \
-H "Content-Type: application/json" \
-d '{"name": "Orders", "verification": {"mode": "hmac", "header": "X-Signature", "prefix": "sha256="}, "delivery_id_header": "X-Delivery-Id"}'The answer has the source's receive_url (https://api.frege.io/v1/webhooks/in/src_…) and its secret, shown this once. Send your own secret (16 to 512 characters) to use one you already have; without it Frege makes one (whin_…). POST .../hooks/sources/{sourceID}/secret replaces it at once.
2. Sign each delivery
verification says how your system proves a delivery is its own:
mode | Fields | Your system sends |
|---|---|---|
hmac | header, prefix, encoding, timestamp_header, tolerance_seconds | HMAC-SHA256 of the raw body, keyed with the secret's bytes, in header after prefix. encoding is hex (the default) or base64. With timestamp_header (Unix seconds), the signed content is <timestamp>.<body>, and a timestamp more than tolerance_seconds from now (300 by default, at most 3600) is refused. |
secret_header | header, prefix | The secret itself in header, after prefix (such as "Bearer "). |
Common senders fit as they are: GitHub (X-Hub-Signature-256, prefix sha256=, hex), Shopify (X-Shopify-Hmac-Sha256, base64). SHA-1 is not offered.
bash
BODY='{"order": {"id": "A-1001", "status": "filled"}, "client": {"phone": "+998901234567"}}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}')
curl -X POST "$RECEIVE_URL" \
-H "Content-Type: application/json" \
-H "X-Signature: sha256=$SIG" \
-H "X-Delivery-Id: order-A-1001-filled" \
--data-binary "$BODY"| Answer | When |
|---|---|
202 | Taken; the hooks run from a queue. Also for a delivery id the source already took, which is not taken again. |
404 | No such source, a disabled one, or a signature that does not verify: all the same, on purpose. |
413 | The body is over 64 KB. |
429 | Over 20 deliveries a second (bursts of 100) to the source. |
delivery_id_header names the header with your own delivery id. A delivery with an id the source already took is not taken again, so your retries never message anyone twice. Without it there is no deduplication.
3. Add a hook
A hook with "trigger": "webhook" and "source": "<source id>" runs on each verified delivery. Its conditions and texts read the JSON body as event.body.… and the headers as event.headers.… (lowercased; signatures, tokens, keys and cookies are dropped).
Name who the delivery is about with customer: a path under event.body or event.headers, and the identity it is.
json
{"name": "Order filled", "trigger": "webhook", "source": "<source id>",
"customer": {"from": "event.body.client.phone", "identity": "phone"},
"filter": [{"field": "body.order.status", "op": "equals", "value": "filled"}],
"steps": [{"id": "tell", "type": "notify", "params": {"channel": "telegram", "to": "customer", "topic": "orders",
"text": "Your order {{event.body.order.id}} is filled."}}]}The customer whose identity matches exactly gets the hook's steps. When none or several match, the steps are skipped and the run says why.
GET .../hooks/sources/{sourceID}/deliveries lists the source's deliveries for 30 days: whether each verified, which customers it matched and how its runs went. POST .../deliveries/{deliveryID}/replay gives one to the hooks again.