Build

Webhook signature verification

Verify every delivery with the Standard Webhooks headers: the exact signed string, HMAC-SHA256 or Ed25519 signatures, a 300-second tolerance and copy-paste verifiers for Node.js, Python and Go.

One signature format

Every Wellfriend webhook delivery, to endpoints managed in Developer API → Webhooks and to endpoints created with POST https://wellfriend.dev/api/v2/webhook-endpoints, is signed with the Standard Webhooks scheme over the message id, the timestamp and the raw body. By default the signature is HMAC-SHA256 with the endpoint's signing secret, sent as v1,<signature>. Any Standard Webhooks library can verify it, and so can the short functions on this page.

An endpoint created with signatureScheme ED25519 with POST https://wellfriend.dev/api/v2/webhook-endpoints is signed with an Ed25519 key pair instead: webhook-signature carries v1a,<base64 Ed25519 signature> over the same signed string, and you verify it with the endpoint's publicKey (standard base64 of the raw 32-byte key) returned when the endpoint is created and when its key is rotated. No shared secret is sent to you.

Read the raw request bytes before you parse anything. Parsing JSON and serializing it again changes whitespace and key order, and the signature then fails.

Both kinds of endpoint also receive one body format: a CloudEvents 1.0 event in structured mode, described on the event catalog page.

Headers

HeaderExampleMeaning
Content-Typeapplication/cloudevents+jsonThe envelope media type. Endpoints created in Developer API → Webhooks currently receive the deprecated application/json. Accept both.
webhook-idevt_2Q7mVxEvent ID. The same on every retry and replay of the event, so deduplicate on it.
webhook-timestamp1792056600Unix seconds when this attempt was signed.
webhook-signaturev1,hdMx9wz7+Y3mLTZnwkK8yg0pkSUannzmV5GhI018HPg=One or more space-separated v1,<base64 HMAC-SHA256> values, or v1a,<base64 Ed25519> values for an ED25519 endpoint. Accept the request when any of them matches.
Content-Digestsha-256=:3EtP5tgVUinVPMbWTEC4V8a4u3VXjcJo2if8JUWnFj8=:SHA-256 of the body (RFC 9530). For information only; verification does not use it.
Wellfriend-Event-Idevt_2Q7mVxSame as webhook-id.
Wellfriend-Delivery-Idwhdel_5Tq8PzThe delivery record. A replay creates a new delivery ID for the same event.
Wellfriend-Attempt3Attempt number for this delivery, starting at 1.
Wellfriend-Key-Idwhkey_...The signing secret that signed this attempt. Useful during a rotation.
Wellfriend-Signaturev1=<64 hex characters>Deprecated. Sent only to endpoints created in Developer API → Webhooks. See below.
Wellfriend-Timestamp2026-10-15T09:30:00.000ZDeprecated. Sent with Wellfriend-Signature.

The exact signed string

Concatenate the webhook-id header, a full stop, the webhook-timestamp header, a full stop and the raw body bytes. There are no spaces or newlines. HMAC-SHA256 it with the key bytes, base64-encode the 32-byte result (standard alphabet, with padding) and prefix v1, to get one signature.

The key is not the secret string itself: drop the whsec_ prefix and base64-decode the rest.

For an ED25519 endpoint, verify the 64-byte Ed25519 signature after v1a, against the same signed content with the endpoint's publicKey. The receiver snippets in Developer API → Webhooks include an Ed25519 verifier for each language.

Signed content
{webhook-id}.{webhook-timestamp}.{raw body}
Signature
v1,base64( HMAC-SHA256( key = base64decode(secret without whsec_), message = signed content ) )

Timestamp tolerance

Reject a delivery when webhook-timestamp is more than 300 seconds before or after your clock. Keep your server clock synchronized with NTP. Within the window, treat an event ID you have already accepted as a duplicate.

Signing secret format

  • New secrets are whsec_ followed by the standard base64 encoding of 32 random bytes, as Standard Webhooks expects.
  • Endpoints created in Developer API → Webhooks before 15 October 2026 were issued the same 32 bytes in the unpadded base64url alphabet (- and _ instead of + and /). The verifiers on this page and the Wellfriend SDKs accept both. A third-party Standard Webhooks library may need the secret converted first: replace - with +, _ with / and add = padding. Rotating the secret also gives you the standard form.
  • The secret is shown once, when the endpoint is created or the secret is rotated. Store it in a secret manager.

Copy-paste verifiers

These functions use only the standard library, and each one returns true for the test vector below.

Node.js
import { createHmac, timingSafeEqual } from "node:crypto";

// rawBody: the exact request bytes (Buffer). headers: Node's lower-cased headers.
// secrets: current signing secret, plus the previous one during a rotation.
export function verifyWellfriendWebhook(rawBody, headers, secrets, nowSeconds = Math.floor(Date.now() / 1000)) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"] ?? "";
  if (!id || !/^\d+$/.test(timestamp)) return false;
  if (Math.abs(nowSeconds - Number(timestamp)) > 300) return false;
  for (const secret of secrets) {
    const key = Buffer.from(secret.replace(/^whsec_/, "").replace(/-/g, "+").replace(/_/g, "/"), "base64");
    const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(rawBody).digest();
    for (const entry of (headers["webhook-signature"] ?? "").split(" ")) {
      const [version, value] = entry.split(",");
      if (version !== "v1" || !value) continue;
      const supplied = Buffer.from(value, "base64");
      if (supplied.length === expected.length && timingSafeEqual(supplied, expected)) return true;
    }
  }
  return false;
}
Python
import base64
import hashlib
import hmac
import time


def verify_wellfriend_webhook(raw_body: bytes, headers, secrets, now=None) -> bool:
    """raw_body: exact request bytes. headers: a case-insensitive mapping (Flask, Django, Starlette)."""
    message_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp", "")
    if not message_id or not timestamp.isdigit():
        return False
    if abs(int(now if now is not None else time.time()) - int(timestamp)) > 300:
        return False
    signed = f"{message_id}.{timestamp}.".encode() + raw_body
    for secret in secrets:
        encoded = secret.removeprefix("whsec_").rstrip("=").replace("-", "+").replace("_", "/")
        key = base64.b64decode(encoded + "=" * (-len(encoded) % 4))
        expected = hmac.new(key, signed, hashlib.sha256).digest()
        for entry in headers.get("webhook-signature", "").split():
            version, _, value = entry.partition(",")
            if version == "v1" and hmac.compare_digest(base64.b64decode(value), expected):
                return True
    return False
Go
package webhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// VerifyWellfriendWebhook checks body (the exact request bytes) against the
// current signing secret and, during a rotation, the previous one.
func VerifyWellfriendWebhook(body []byte, header http.Header, secrets []string, now time.Time) bool {
	id, timestamp := header.Get("webhook-id"), header.Get("webhook-timestamp")
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if id == "" || err != nil || now.Unix()-seconds > 300 || seconds-now.Unix() > 300 {
		return false
	}
	for _, secret := range secrets {
		encoded := strings.NewReplacer("-", "+", "_", "/").Replace(strings.TrimRight(strings.TrimPrefix(secret, "whsec_"), "="))
		key, err := base64.RawStdEncoding.DecodeString(encoded)
		if err != nil {
			continue
		}
		mac := hmac.New(sha256.New, key)
		mac.Write([]byte(id + "." + timestamp + "."))
		mac.Write(body)
		expected := mac.Sum(nil)
		for _, entry := range strings.Fields(header.Get("webhook-signature")) {
			version, value, ok := strings.Cut(entry, ",")
			supplied, err := base64.StdEncoding.DecodeString(value)
			if ok && version == "v1" && err == nil && hmac.Equal(supplied, expected) {
				return true
			}
		}
	}
	return false
}

With the Wellfriend SDKs

Each SDK checks the Standard Webhooks headers over the raw body with a five-minute tolerance and returns the typed event; a bad signature raises WebhookVerificationError. Pass a list of secrets while you rotate one.

TypeScript
import { verifyWebhook } from "wellfriend-document-sdk";

const secret = process.env.WELLFRIEND_WEBHOOK_SECRET;
if (!secret) throw new Error("Set WELLFRIEND_WEBHOOK_SECRET.");
const event = verifyWebhook(rawBody, request.headers, [secret]);
Python
from wellfriend import verify_webhook

event = verify_webhook(raw_body, request.headers, [secret])
Go
event, err := wellfriend.VerifyWebhook(body, r.Header, []string{secret})
Rust
let event = wellfriend::verify_webhook(&body, &headers, &[secret])?;

Test vector

Check your verifier with this delivery. With your clock set to the timestamp, it must return true; change one byte of the body and it must return false.

InputValue
Secretwhsec_+//+fT4/AAECAwT7/wUGBwgJ+gsMDQ4P+//+EBESExQV
webhook-idevt_2Q7mVx
webhook-timestamp1792056600
Body{"data":{"documentId":"doc_8kq2W1","versionId":"ver_3Jx9Lm","versionNumber":2},"datacontenttype":"application/json","id":"evt_2Q7mVx","source":"wellfriend://workspaces/ws_7Hq2Lm4Xc9","specversion":"1.0","subject":"doc_8kq2W1","time":"2026-10-15T09:30:00.000Z","type":"com.wellfriend.document.version.created.v2","wellfriend":{"occurred_at":"2026-10-15T09:30:00.000Z","resource_revision":2,"sequence":"41"}}
webhook-signaturev1,hdMx9wz7+Y3mLTZnwkK8yg0pkSUannzmV5GhI018HPg=

Rotation

Rotate a secret with Rotate secret in Developer API → Webhooks or with POST https://wellfriend.dev/api/v2/webhook-endpoints/{endpointId}/rotate-secret. The new secret is shown once. Wellfriend signs with it straight away and keeps the previous secret valid for 24 hours; on the API, set overlapSeconds (300 to 604800) to choose another window.

During the overlap, webhook-signature carries one signature per valid secret, newest first, so a receiver that knows either secret still verifies. Wellfriend-Key-Id names the newest secret. Remove the old secret from your receiver once the window has passed.

Deprecated: the Wellfriend-Signature v1= format

Endpoints created in Developer API → Webhooks also receive the older Wellfriend-Signature and Wellfriend-Timestamp headers. This format is deprecated: move your receiver to the Standard Webhooks headers. Wellfriend will announce a date before it stops sending them. Endpoints created with POST https://wellfriend.dev/api/v2/webhook-endpoints never receive them.

The old format is HMAC-SHA256, keyed by the UTF-8 bytes of the whole secret string (including whsec_), over seven lines joined with newline characters: the HTTP method, the request path with its query, Content-Digest, Wellfriend-Timestamp, Wellfriend-Event-Id, Wellfriend-Delivery-Id and Wellfriend-Attempt. The header value is v1= followed by the lowercase hex digest. The SDK verifiers still accept it.

Deprecated: Content-Type application/json

Endpoints created in Developer API → Webhooks currently receive Content-Type application/json. Endpoints created through the v2 API always receive application/cloudevents+json. The body is the same envelope either way.

application/json on these deliveries is deprecated. Wellfriend will announce a date before every delivery switches to application/cloudevents+json. Accept both media types now.

The signature covers the body only, so the media type never changes verification.

After verification

  • Parse the JSON envelope.
  • Check that the event type is one you subscribed to.
  • Record the event ID under a unique constraint, so a repeated delivery is recognised.
  • Store or queue the work, then return a 2xx response. Run slow work after you answer.

Failure response

Return a non-2xx response for an invalid signature, an expired timestamp or a failed write on your side; Wellfriend retries it. Log the reason with the event and delivery IDs, never the signing secret or sensitive payload fields.