Skip to content

Configuring Webhook Endpoints & Signature Verification

Subscribe to link, click, and security events and verify HMAC-SHA256 signatures with X-Shaf-Signature.

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: Owner or Admin role in your Shaf organization.
  • A public HTTPS endpoint capable of receiving POST requests and returning a 200 OK status within 5 seconds.
  • A cryptographic secret store to hold your webhook signing key (whsec_...).

Implementation Recipe

  1. 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"
    }
  2. Available Webhook Events

    Select specific event topics to minimize delivery volume (see Webhook Events Reference for complete payload schemas):

    Event Identifier Trigger Condition
    link.created A new short link record is created in D1.
    link.updated A link’s destination URL, slug, or parameters are modified.
    link.clicked A visitor resolves a short link (batched every 10 seconds).
    link.expired A link reaches its expiration timestamp or max click ceiling.
    domain.verified Custom domain passes DNS CNAME validation.
    quota.warning Workspace usage reaches 80% or 100% of plan thresholds.
  3. Verifying Webhook Signatures

    Every HTTP delivery includes an X-Shaf-Signature header formatted with a Unix timestamp and HMAC-SHA256 signature:

    X-Shaf-Signature: t=1732200000,v1=9a7d8f2b3c4e5a6f7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0a

    Implement 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}
  4. 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:

  1. 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}"
    }
  2. 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.

Type to search…

↑↓ navigate↵ selectEsc close