Configuring Webhook Endpoints & Signature Verification
Automated data pipelines and external notification systems need instant alerts when short links are created, clicked, or expired. This guide registers webhook subscription endpoints and validates incoming event authenticity using HMAC-SHA256 signatures transmitted in the X-Shaf-Signature header.
Prerequisites
- Workspace permissions:
OwnerorAdminrole in your Shaf organization. - A public HTTPS endpoint capable of receiving
POSTrequests and returning a200 OKstatus within 5 seconds. - A cryptographic secret store to hold your webhook signing key (
whsec_...).
Implementation Recipe
Register a Webhook Endpoint
In the Shaf Dashboard, navigate to Settings → Webhooks and click Add Endpoint, or create one programmatically:
curl -X POST "https://shaf.app/api/v1/webhooks" \ -H "Authorization: Bearer $SHAF_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "url": "https://api.acme.com/webhooks/shaf", "events": ["link.created", "link.clicked", "link.expired", "domain.verified"], "description": "Production Link Telemetry" }'Expected response (
201 Created):{ "id": "whk_01j8k9x2m4", "url": "https://api.acme.com/webhooks/shaf", "secret": "whsec_9a7d8f2b3c4e5a6f7b8c9d0e1f2a3b4c", "events": ["link.created", "link.clicked", "link.expired", "domain.verified"], "status": "active" }Available Webhook Events
Select specific event topics to minimize delivery volume (see Webhook Events Reference for complete payload schemas):
Event Identifier Trigger Condition link.createdA new short link record is created in D1. link.updatedA link’s destination URL, slug, or parameters are modified. link.clickedA visitor resolves a short link (batched every 10 seconds). link.expiredA link reaches its expiration timestamp or max click ceiling. domain.verifiedCustom domain passes DNS CNAME validation. quota.warningWorkspace usage reaches 80% or 100% of plan thresholds. Verifying Webhook Signatures
Every HTTP delivery includes an
X-Shaf-Signatureheader formatted with a Unix timestamp and HMAC-SHA256 signature:X-Shaf-Signature: t=1732200000,v1=9a7d8f2b3c4e5a6f7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0aImplement cryptographic verification on your receiving server before processing payloads:
import crypto from 'node:crypto'; import express from 'express'; const app = express(); // Capture raw unparsed body for HMAC calculation app.post( '/webhooks/shaf', express.raw({ type: 'application/json' }), (req, res) => { const signatureHeader = req.headers['x-shaf-signature'] as string; if (!signatureHeader) { return res.status(401).send('Missing signature'); } // Extract timestamp and signature const parts = Object.fromEntries( signatureHeader.split(',').map((p) => p.split('=')) ); const timestamp = parts.t; const signature = parts.v1; // Replay attack mitigation: reject payloads older than 5 minutes const now = Math.floor(Date.now() / 1000); if (Math.abs(now - parseInt(timestamp, 10)) > 300) { return res.status(400).send('Timestamp out of tolerance'); } // Compute expected HMAC const rawBody = req.body.toString('utf8'); const signedPayload = `${timestamp}.${rawBody}`; const expectedSignature = crypto .createHmac('sha256', process.env.SHAF_WEBHOOK_SECRET!) .update(signedPayload) .digest('hex'); // Constant-time comparison const isValid = crypto.timingSafeEqual( Buffer.from(signature, 'hex'), Buffer.from(expectedSignature, 'hex') ); if (!isValid) { return res.status(403).send('Invalid signature'); } const payload = JSON.parse(rawBody); console.log(`Received verified event: ${payload.event}`); // Return 200 OK immediately res.status(200).json({ received: true }); } );import hmac import hashlib import time import os from fastapi import FastAPI, Request, HTTPException app = FastAPI() WEBHOOK_SECRET = os.environ["SHAF_WEBHOOK_SECRET"] @app.post("/webhooks/shaf") async def handle_webhook(request: Request): sig_header = request.headers.get("X-Shaf-Signature") if not sig_header: raise HTTPException(status_code=401, detail="Missing signature") parts = dict(x.split("=") for x in sig_header.split(",")) timestamp = parts.get("t") signature = parts.get("v1") # Check timestamp tolerance (5 minutes) if abs(time.time() - int(timestamp)) > 300: raise HTTPException(status_code=400, detail="Timestamp expired") raw_body = await request.body() signed_payload = f"{timestamp}.".encode("utf-8") + raw_body expected_sig = hmac.new( WEBHOOK_SECRET.encode("utf-8"), signed_payload, hashlib.sha256 ).hexdigest() if not hmac.compare_digest(signature, expected_sig): raise HTTPException(status_code=403, detail="Invalid signature") return {"received": True}Dispatch a Test Event
Trigger a mock event delivery to verify server connectivity:
curl -X POST "https://shaf.app/api/v1/webhooks/whk_01j8k9x2m4/test" \ -H "Authorization: Bearer $SHAF_API_TOKEN"
Verification
Inspect delivery telemetry in your dashboard or verify receiver logs:
-
Dispatch test payload and review response output:
curl -X POST "https://shaf.app/api/v1/webhooks/whk_01j8k9x2m4/test" \ -H "Authorization: Bearer $SHAF_API_TOKEN"Expected response (
200 OK):{ "status": "delivered", "statusCode": 200, "durationMs": 42, "responseBody": "{\"received\":true}" } -
Confirm your server logs record a successful verification with HTTP
200.
Common Gotchas
| Issue / Error | Root Cause | Solution |
|---|---|---|
Signature verification failed |
Framework parsed JSON body before computing HMAC, altering whitespace. | Verify signatures against the raw binary request buffer (express.raw or request.body()). |
Timestamp out of tolerance |
Server system clock is skewed or delivery was intercepted and replayed. | Sync server time with NTP (chrony or ntpdate). Max allowed drift is 300 seconds. |
| Automatic endpoint suspension | Endpoint returned non-2xx status codes on 10 consecutive retry attempts. | Ensure receiver responds with 200 OK immediately, delegating processing to a task queue. |
| Delivery timeout (>5000ms) | Receiver performed long synchronous work before responding. | Return 200 OK first, then execute business logic asynchronously. |