Verify Autumn webhooks

Every Autumn delivery carries a signature in the svix-signature header, because Autumn delivers through Svix. It's an HMAC-SHA256 of the message id, timestamp and raw body, keyed with the webhook's own whsec_ secret, so it shows the request came from Autumn and wasn't changed. Autumn points you to the Svix libraries to check it.

The facts

Signature header
svix-signature

Format: v1,<base64>, space-delimited when there are several

Scheme
HMAC-SHA256
Signed material
{svix-id}.{svix-timestamp}.{raw body}

The two headers and the body as sent, joined with dots. Autumn sends readers to Svix for this scheme.

Send timestamp
svix-timestamp
What to build
Use a Svix library, or recompute the HMAC over the message id, timestamp and raw body with the base64-decoded secret, then compare with each v1 entry.
Key
shared secret

Autumn webhook secret

Each webhook has its own signing secret, which starts with whsec_. It isn't your API key, and the API returns it only once, when it creates the webhook. Keep it in an environment variable, not in source code.

  • From the API: POST /v1/webhooks.create returns it as secret, and webhooks.sync returns it in secrets for each webhook it creates. Store it before you discard the response.
  • No read back: webhooks.get never returns it. Webhooks that webhooks.sync finds already exist keep their secret.
  • In the dashboard: Autumn's docs don't say where the secret appears for an endpoint added under Developer > Webhooks.
  • Format: a hand-written verifier uses the base64-decoded part after whsec_ as the key.
  • One per environment: a webhook belongs to the environment of the key that created it, so sandbox and production each need their own webhook and secret.
  • Rotating: Autumn documents no rotate call, and updating a webhook covers its URL, events, description and disabled state. To replace a secret, create a new webhook.

Source: Autumn docs ↗

Code

express/src/index.js
javascript
// Generated with: autumn-webhooks skill
// https://github.com/hookdeck/webhook-skills

import 'dotenv/config';
import crypto from 'node:crypto';
import express from 'express';
import { pathToFileURL } from 'node:url';
import { Webhook } from 'svix';

const app = express();
const PORT = process.env.PORT || 3000;

// ---------------------------------------------------------------------------
// Autumn delivers webhooks through Svix:
//   svix-id         message ID (same across retries)
//   svix-timestamp  Unix seconds when the message was sent
//   svix-signature  "v1,<base64 HMAC-SHA256>" (space-delimited list)
// Signed content: `${svix-id}.${svix-timestamp}.${rawBody}`
// Key: base64-decode of the secret after its `whsec_` prefix.
// ---------------------------------------------------------------------------

/**
 * Manual verifier (same algorithm as svix). Use it when the svix library's fixed
 * 5-minute timestamp window is a problem: Hookdeck retries and replays resend the
 * original svix-timestamp. Checks every `v1,` entry in constant time.
 *
 * @param {Buffer|string} rawBody
 * @param {object} headers - svix-id / svix-timestamp / svix-signature
 * @param {string} secret - whsec_ signing secret
 * @param {number|null} toleranceSeconds - window in seconds, or null for none
 */
export function verifyManually(rawBody, headers, secret, toleranceSeconds = null) {
  const id = headers['svix-id'];
  const timestamp = headers['svix-timestamp'];
  const signatureHeader = headers['svix-signature'];
  if (!id || !timestamp || !signatureHeader) return false;

  const ts = Number(timestamp);
  if (!Number.isInteger(ts)) return false;
  if (toleranceSeconds !== null && Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSeconds) {
    return false;
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = Buffer.from(
    crypto.createHmac('sha256', key).update(`${id}.${timestamp}.`).update(rawBody).digest('base64')
  );

  return signatureHeader.split(' ').some((entry) => {
    const [version, sig] = entry.split(',');
    if (version !== 'v1' || !sig) return false;
    const candidate = Buffer.from(sig);
    return candidate.length === expected.length && crypto.timingSafeEqual(candidate, expected);
  });
}

/** AUTUMN_TIMESTAMP_TOLERANCE_SECONDS: unset -> svix library, "off" -> no window, N -> N seconds. */
function manualToleranceFromEnv() {
  const raw = (process.env.AUTUMN_TIMESTAMP_TOLERANCE_SECONDS || '').trim().toLowerCase();
  if (!raw) return undefined;
  if (raw === 'off') return null;
  const seconds = Number(raw);
  return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;
}

/**
 * Verify an Autumn delivery, then parse it.
 * Default: the official svix library (5-minute window, constant-time compare).
 * svix 2.x `verify()` returns nothing and throws on failure, so parse the JSON afterwards.
 *
 * @returns {object} the parsed, verified payload
 * @throws if the signature or timestamp is invalid
 */
export function verifyAutumnWebhook(rawBody, headers, secret = process.env.AUTUMN_WEBHOOK_SECRET) {
  const tolerance = manualToleranceFromEnv();
  if (tolerance === undefined) {
    new Webhook(secret).verify(rawBody, headers);
  } else if (!verifyManually(rawBody, headers, secret, tolerance)) {
    throw new Error('No matching signature found');
  }
  return JSON.parse(rawBody.toString('utf8'));
}

// In-memory dedupe for the demo. Use Redis or your database in production.
// svix-id is the same on every retry of a message to this endpoint.
const processedMessageIds = new Set();

function handleEvent(event) {
  const { type, data = {} } = event;

  switch (type) {
    case 'billing.updated': {
      const changes = data.plan_changes ?? [];
      for (const change of changes) {
        const plan = (change.subscription ?? change.purchase)?.plan_id;
        console.log(`Plan ${change.action}: ${plan} for ${data.customer_id}${data.entity_id ? `/${data.entity_id}` : ''}`);
        if (change.previous_attributes?.canceled_at === null) {
          console.log(`Cancellation set for ${data.customer_id}; deprovision when the plan expires`);
        }
      }
      if (data.tags?.includes('trial_ended')) {
        console.log(`Trial ended for ${data.customer_id}`);
      }
      break;
    }
    // A separate event with its own shape and no plan_changes.
    case 'customer.products.updated':
      console.log(`Customer products ${data.scenario}: ${data.updated_product?.id} for ${data.customer?.id}`);
      break;
    case 'balances.limit_reached':
      console.log(`Limit reached (${data.limit_type}) on ${data.feature_id} for ${data.customer_id}`);
      break;
    case 'balances.usage_alert_triggered':
      console.log(`Usage alert "${data.usage_alert?.name}" on ${data.feature_id} for ${data.customer_id}`);
      break;
    case 'billing.auto_topup_succeeded':
      console.log(`Auto top-up granted ${data.quantity_granted} ${data.feature_id} to ${data.customer_id} (balance ${data.balance_after})`);
      break;
    case 'billing.auto_topup_failed':
      console.log(`Auto top-up failed (${data.reason}) for ${data.customer_id} on ${data.feature_id}`);
      break;
    case 'invoice.finalized':
      // The invoice fields are in `data`; fall back to the body for safety.
      console.log(`Invoice finalized: ${(data.stripe_id ?? event.stripe_id)} for ${data.customer_id ?? event.customer_id}`);
      break;
    default:
      console.log(`Unhandled Autumn event type: ${type}`);
  }
}

// express.raw({ type: '*/*' }) keeps the exact bytes for any content type.
// express.json() before verification would break the signature.
app.post('/webhooks/autumn', express.raw({ type: '*/*' }), (req, res) => {
  // Fail closed: never accept unverified deliveries because a secret is missing.
  if (!process.env.AUTUMN_WEBHOOK_SECRET) {
    console.error('AUTUMN_WEBHOOK_SECRET is not set — rejecting delivery');
    return res.status(500).json({ error: 'Webhook secret not configured' });
  }

  const headers = {
    'svix-id': req.get('svix-id'),
    'svix-timestamp': req.get('svix-timestamp'),
    'svix-signature': req.get('svix-signature'),
  };
  if (!headers['svix-id'] || !headers['svix-timestamp'] || !headers['svix-signature']) {
    return res.status(400).json({ error: 'Missing Svix signature headers' });
  }
  if (!Buffer.isBuffer(req.body)) {
    return res.status(400).json({ error: 'Missing request body' });
  }

  let event;
  try {
    event = verifyAutumnWebhook(req.body, headers);
  } catch (err) {
    console.error('Autumn webhook verification failed:', err.message);
    return res.status(400).json({ error: 'Invalid signature' });
  }

  // Duplicates are normal (at-least-once delivery) — acknowledge with 200.
  if (processedMessageIds.has(headers['svix-id'])) {
    return res.status(200).json({ received: true, duplicate: true });
  }

  try {
    // Keep this fast; in production enqueue the event and process it asynchronously.
    handleEvent(event);
    processedMessageIds.add(headers['svix-id']);
  } catch (err) {
    console.error('Error handling Autumn event:', err);
    return res.status(500).json({ error: 'Internal server error' });
  }

  return res.status(200).json({ received: true });
});

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

export { app };

// Start the server only when run directly (not when imported by tests)
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  app.listen(PORT, () => {
    console.log(`Autumn webhook server listening on port ${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/autumn`);
  });
}
nextjs/app/webhooks/autumn/route.ts
typescript
// Generated with: autumn-webhooks skill
// https://github.com/hookdeck/webhook-skills

import { NextResponse } from 'next/server';
import { handleEvent, verifyAutumnWebhook, type AutumnEvent } from '../../../lib/autumn';

// In-memory dedupe for the demo. Use Redis or your database in production.
// svix-id is the same on every retry of a message to this endpoint.
const processedMessageIds = new Set<string>();

export async function POST(request: Request) {
  // Fail closed: never accept unverified deliveries because a secret is missing.
  const secret = process.env.AUTUMN_WEBHOOK_SECRET;
  if (!secret) {
    console.error('AUTUMN_WEBHOOK_SECRET is not set — rejecting delivery');
    return NextResponse.json({ error: 'Webhook secret not configured' }, { status: 500 });
  }

  const svixId = request.headers.get('svix-id');
  const svixTimestamp = request.headers.get('svix-timestamp');
  const svixSignature = request.headers.get('svix-signature');
  if (!svixId || !svixTimestamp || !svixSignature) {
    return NextResponse.json({ error: 'Missing Svix signature headers' }, { status: 400 });
  }

  // Raw body: the signature covers the exact bytes, so never verify request.json().
  // request.text() works for any content type.
  const rawBody = await request.text();

  let event: AutumnEvent;
  try {
    event = verifyAutumnWebhook(
      rawBody,
      { 'svix-id': svixId, 'svix-timestamp': svixTimestamp, 'svix-signature': svixSignature },
      secret
    );
  } catch (err) {
    console.error('Autumn webhook verification failed:', (err as Error).message);
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  // Duplicates are normal (at-least-once delivery) — acknowledge with 200.
  if (processedMessageIds.has(svixId)) {
    return NextResponse.json({ received: true, duplicate: true });
  }

  try {
    // Keep this fast; in production enqueue the event and process it asynchronously.
    handleEvent(event);
    processedMessageIds.add(svixId);
  } catch (err) {
    console.error('Error handling Autumn event:', err);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: autumn-webhooks skill
# https://github.com/hookdeck/webhook-skills
"""Autumn webhook receiver for FastAPI.

Autumn delivers webhooks through Svix:
  svix-id         message ID (same across retries)
  svix-timestamp  Unix seconds when the message was sent
  svix-signature  "v1,<base64 HMAC-SHA256>" (space-delimited list)
Signed content: f"{svix-id}.{svix-timestamp}.{raw_body}"
Key: base64-decode of the secret after its `whsec_` prefix.
"""

import base64
import hashlib
import hmac
import json
import logging
import os
import time
from typing import Any, Dict, Optional

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
from svix.webhooks import Webhook, WebhookVerificationError

load_dotenv()

logger = logging.getLogger("autumn-webhooks")
logging.basicConfig(level=logging.INFO)

app = FastAPI(title="Autumn Webhook Handler")

# In-memory dedupe for the demo. Use Redis or your database in production.
# svix-id is the same on every retry of a message to this endpoint.
processed_message_ids: set = set()


def verify_manually(
    raw_body: bytes, headers: Dict[str, str], secret: str, tolerance: Optional[int] = None
) -> bool:
    """Manual verifier (same algorithm as svix).

    Use it when the svix library's fixed 5-minute timestamp window is a problem:
    Hookdeck retries and replays resend the original svix-timestamp. Checks every
    `v1,` entry in constant time. `tolerance` is a window in seconds, or None for none.
    """
    msg_id = headers.get("svix-id")
    timestamp = headers.get("svix-timestamp")
    signature_header = headers.get("svix-signature")
    if not (msg_id and timestamp and signature_header):
        return False
    try:
        ts = int(timestamp)
    except ValueError:
        return False
    if tolerance is not None and abs(int(time.time()) - ts) > tolerance:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest())

    ok = False
    for entry in signature_header.split(" "):
        version, _, sig = entry.partition(",")
        if version == "v1" and hmac.compare_digest(sig.encode(), expected):
            ok = True
    return ok


def manual_tolerance_from_env():
    """AUTUMN_TIMESTAMP_TOLERANCE_SECONDS: unset -> (False, None) use svix; "off" -> (True, None); N -> (True, N)."""
    raw = os.environ.get("AUTUMN_TIMESTAMP_TOLERANCE_SECONDS", "").strip().lower()
    if not raw:
        return False, None
    if raw == "off":
        return True, None
    try:
        seconds = int(raw)
    except ValueError:
        return False, None
    return (True, seconds) if seconds >= 0 else (False, None)


def verify_autumn_webhook(raw_body: bytes, headers: Dict[str, str], secret: str) -> Dict[str, Any]:
    """Verify an Autumn delivery, then parse it.

    Default: the official svix library (5-minute window, constant-time compare).
    svix 2.x `verify()` returns None (it raises on failure), so the JSON is parsed here afterwards.
    """
    use_manual, tolerance = manual_tolerance_from_env()
    if use_manual:
        if not verify_manually(raw_body, headers, secret, tolerance):
            raise ValueError("No matching signature found")
    else:
        Webhook(secret).verify(raw_body, headers)
    return json.loads(raw_body)


async def verified_autumn_delivery(request: Request) -> Dict[str, Any]:
    """FastAPI dependency: returns {"id": svix-id, "event": payload} or raises."""
    # Fail closed: never accept unverified deliveries because a secret is missing.
    secret = os.environ.get("AUTUMN_WEBHOOK_SECRET")
    if not secret:
        logger.error("AUTUMN_WEBHOOK_SECRET is not set — rejecting delivery")
        raise HTTPException(status_code=500, detail="Webhook secret not configured")

    headers = {
        "svix-id": request.headers.get("svix-id"),
        "svix-timestamp": request.headers.get("svix-timestamp"),
        "svix-signature": request.headers.get("svix-signature"),
    }
    if not all(headers.values()):
        raise HTTPException(status_code=400, detail="Missing Svix signature headers")

    # Raw body: the signature covers the exact bytes, so never verify request.json().
    raw_body = await request.body()
    try:
        event = verify_autumn_webhook(raw_body, headers, secret)
    except (WebhookVerificationError, ValueError) as err:
        logger.warning("Autumn webhook verification failed: %s", err)
        raise HTTPException(status_code=400, detail="Invalid signature")
    return {"id": headers["svix-id"], "event": event}


def handle_event(event: Dict[str, Any]) -> None:
    event_type = event.get("type")
    data = event.get("data") or {}

    if event_type == "billing.updated":
        for change in data.get("plan_changes") or []:
            plan = (change.get("subscription") or change.get("purchase") or {}).get("plan_id")
            entity = f"/{data['entity_id']}" if data.get("entity_id") else ""
            logger.info("Plan %s: %s for %s%s", change.get("action"), plan, data.get("customer_id"), entity)
            previous = change.get("previous_attributes") or {}
            if "canceled_at" in previous and previous["canceled_at"] is None:
                logger.info("Cancellation set for %s; deprovision when the plan expires", data.get("customer_id"))
        if "trial_ended" in (data.get("tags") or []):
            logger.info("Trial ended for %s", data.get("customer_id"))
    # A separate event with its own shape and no plan_changes.
    elif event_type == "customer.products.updated":
        logger.info(
            "Customer products %s: %s for %s",
            data.get("scenario"),
            (data.get("updated_product") or {}).get("id"),
            (data.get("customer") or {}).get("id"),
        )
    elif event_type == "balances.limit_reached":
        logger.info(
            "Limit reached (%s) on %s for %s", data.get("limit_type"), data.get("feature_id"), data.get("customer_id")
        )
    elif event_type == "balances.usage_alert_triggered":
        logger.info(
            'Usage alert "%s" on %s for %s',
            (data.get("usage_alert") or {}).get("name"), data.get("feature_id"), data.get("customer_id"),
        )
    elif event_type == "billing.auto_topup_succeeded":
        logger.info(
            "Auto top-up granted %s %s to %s (balance %s)",
            data.get("quantity_granted"), data.get("feature_id"), data.get("customer_id"), data.get("balance_after"),
        )
    elif event_type == "billing.auto_topup_failed":
        logger.info(
            "Auto top-up failed (%s) for %s on %s", data.get("reason"), data.get("customer_id"), data.get("feature_id")
        )
    elif event_type == "invoice.finalized":
        # The invoice fields are in `data`; fall back to the body for safety.
        logger.info(
            "Invoice finalized: %s for %s",
            data.get("stripe_id") or event.get("stripe_id"), data.get("customer_id") or event.get("customer_id"),
        )
    else:
        logger.info("Unhandled Autumn event type: %s", event_type)


@app.post("/webhooks/autumn")
async def autumn_webhook(delivery: Dict[str, Any] = Depends(verified_autumn_delivery)):
    message_id = delivery["id"]

    # Duplicates are normal (at-least-once delivery) — acknowledge with 200.
    if message_id in processed_message_ids:
        return {"received": True, "duplicate": True}

    try:
        # Keep this fast; in production enqueue the event and process it asynchronously.
        handle_event(delivery["event"])
        processed_message_ids.add(message_id)
    except Exception:
        logger.exception("Error handling Autumn event")
        raise HTTPException(status_code=500, detail="Internal server error")

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8000)))

From hookdeck/webhook-skills ↗

Or install the Autumn webhooks skill:

npx skills add hookdeck/webhook-skills --skill autumn-webhooks

Common failures

Body parsed before verification

Parsing the JSON and serialising it again changes the bytes, which breaks the signature. Verify against the raw request body.

Secret from the wrong environment

A webhook belongs to the environment of the key that created it, so a sandbox webhook's secret won't verify a production delivery. Your API key won't work either.

Secret not decoded

In a hand-written verifier, the HMAC key is the base64-decoded part of the secret after whsec_, not the string as shown.

Delivery replayed late

The Svix libraries reject a timestamp more than five minutes from the current time, and a message replayed through a relay keeps its original timestamp. Hand-written verifiers can widen or drop that check.

From Hookdeck's Autumn guide

Let Event Gateway verify Autumn signatures.

Event Gateway verifies the signature on each Autumn delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Autumn. Facts are compiled from public sources and linked inline.