Verify Ampersand webhooks
Every Ampersand webhook message carries a signature in the svix-signature header, because Ampersand delivers through Svix. It's an HMAC-SHA256 of the message id, timestamp and raw body, keyed with the destination's own signing secret, so it shows the message came from Ampersand and wasn't changed. Ampersand points you to the Svix libraries to check it.
Ampersand's event list covers notifications only. Read and subscribe results reach the same URL with an action field and no event type: see choosing events.
The facts
svix-signature Format: v1,<base64>, space-delimited when there are several
{svix-id}.{svix-timestamp}.{raw body} The two headers and the body as sent, joined with dots. Ampersand sends readers to Svix for this scheme.
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. Ampersand webhook secret
Each destination has its own webhook signing secret, shown in the Ampersand dashboard. It isn't your API key. Keep it in an environment variable, not in source code.
- In the dashboard: open Destinations, click the destination, then click "Click here to view the secret".
- From the API: get the destination with
includeSecrets=true, which returns it assecrets.webhookSigningKey. - Format: the dashboard shows a value starting
whsec_. A hand-written verifier uses the base64-decoded part after that prefix as the key. - One per destination: with several destinations, you need the secret for each one.
- Dev and prod: Ampersand recommends separate projects and destinations are added per project, so each environment has its own secret.
- Rotating: click "Click here to view the secret", then "Rotate secret". Ampersand doesn't say whether the old secret keeps working for a while.
Source: Ampersand docs ↗
Code
// Generated with: ampersand-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { pathToFileURL } from 'node:url';
import dotenv from 'dotenv';
import express from 'express';
import { Webhook } from 'svix';
dotenv.config({ quiet: true });
export const app = express();
const PORT = process.env.PORT || 3000;
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Ampersand sends two kinds of webhook bodies to a webhook destination:
// - notifications: { notificationType, data }
// - read / subscribe results: { action, groupRef, objectName, result, resultInfo, ... }
function handleNotification(type, data = {}) {
switch (type) {
case 'installation.created':
case 'installation.updated':
case 'installation.deleted':
console.log(`Installation event ${type}:`, { installationId: data.installationId, groupRef: data.groupRef });
break;
case 'connection.created':
case 'connection.refreshed':
case 'connection.updated':
case 'connection.deleted':
console.log(`Connection event ${type}:`, { connectionId: data.connectionId, provider: data.provider });
break;
case 'connection.error':
console.error('Connection error:', { connectionId: data.connectionId, errors: data.errors });
break;
case 'read.backfill.done':
case 'read.triggered.done':
console.log(`Read finished (${type}):`, { installationId: data.installationId, objectName: data.objectName });
break;
case 'read.backfill.error':
case 'read.triggered.error':
case 'read.schedule.paused':
console.error(`Read problem (${type}):`, { installationId: data.installationId, objectName: data.objectName });
break;
case 'write.async.done':
console.log('Async write done:', { installationId: data.installationId, objectName: data.objectName });
break;
case 'subscribe.create.success':
case 'subscribe.update.success':
case 'subscribe.delete.success':
case 'subscribe.create.error':
case 'subscribe.update.error':
case 'subscribe.delete.error':
console.log(`Subscribe event ${type}:`, { installationId: data.installationId, objectName: data.objectName });
break;
case 'destination.webhook.disabled':
console.error('Webhook destination disabled:', { destinationId: data.destinationId, url: data.url });
break;
case 'destination.delivery.error':
console.error('Delivery failed:', { destinationId: data.destinationId, error: data.error });
break;
default:
console.log('Unhandled notification type:', type);
}
}
function handleResult(message) {
const { action, groupRef, objectName, resultInfo } = message;
console.log(`Received ${action} result:`, { groupRef, objectName, numRecords: resultInfo?.numRecords });
if (resultInfo?.type === 'url') {
// A record over 300KB is not inlined: GET resultInfo.downloadUrl within 15 minutes.
console.log('Result is too large to inline, download it from resultInfo.downloadUrl');
} else {
for (const record of message.result ?? []) {
// record.fields / record.mappedFields / record.raw (subscribe: record.subscribeEventType)
console.log('Record:', record.fields?.id ?? record.raw?.id);
}
}
}
// IMPORTANT: express.raw({ type: '*/*' }) keeps the exact bytes for any content type,
// which is what the signature covers. Parse the body only after verification.
// The limit allows Ampersand's 300 KB messages; Express defaults to 100 KB.
app.post('/webhooks/ampersand', express.raw({ type: '*/*', limit: '350kb' }), (req, res) => {
const secret = process.env.AMPERSAND_WEBHOOK_SECRET;
if (!secret || !secret.startsWith('whsec_')) {
console.error('Invalid webhook secret configuration');
return res.status(500).json({ error: 'Server configuration error' });
}
const id = req.headers['svix-id'];
const timestamp = req.headers['svix-timestamp'];
const signature = req.headers['svix-signature'];
if (!id || !timestamp || !signature || !Buffer.isBuffer(req.body)) {
return res.status(400).json({ error: 'Missing required webhook headers' });
}
try {
// The svix library decodes the secret, enforces a fixed 5-minute timestamp window and
// checks every v1 signature in constant time. As of svix 2.x it returns undefined.
new Webhook(secret).verify(req.body, {
'svix-id': id,
'svix-timestamp': timestamp,
'svix-signature': signature,
});
} catch (err) {
console.error('Webhook verification failed:', err.message || err);
const detail = /timestamp/i.test(err.message || '') ? 'Timestamp too old' : 'Invalid signature';
return res.status(400).json({ error: detail });
}
let message;
try {
message = JSON.parse(req.body.toString('utf8'));
} catch {
return res.status(400).json({ error: 'Invalid JSON' });
}
if (message === null || typeof message !== 'object' || Array.isArray(message)) {
return res.status(400).json({ error: 'Invalid JSON' });
}
// Dispatch on notificationType when present, otherwise treat it as a read/subscribe result.
if (typeof message.notificationType === 'string') {
handleNotification(message.notificationType, message.data);
return res.status(200).json({ success: true, type: message.notificationType });
}
handleResult(message);
return res.status(200).json({ success: true, type: message.action ?? 'read' });
});
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
app.listen(PORT, () => {
console.log(`Ampersand webhook server running on port ${PORT}`);
console.log(`Webhook endpoint: http://localhost:${PORT}/webhooks/ampersand`);
});
} // Generated with: ampersand-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextResponse } from 'next/server';
import { handleNotification, handleResult, verifyAmpersandWebhook } from '../../../lib/ampersand';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
// Read the RAW body (any content type) and verify before parsing.
const rawBody = await request.text();
const result = verifyAmpersandWebhook(rawBody, request.headers, process.env.AMPERSAND_WEBHOOK_SECRET);
if (!result.valid) {
console.error('Webhook verification failed:', result.error);
return NextResponse.json({ error: result.error }, { status: result.status ?? 400 });
}
let message: Record<string, any>;
try {
message = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
if (message === null || typeof message !== 'object' || Array.isArray(message)) {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
// Dispatch on notificationType when present, otherwise treat it as a read/subscribe result.
if (typeof message.notificationType === 'string') {
handleNotification(message.notificationType, message.data);
return NextResponse.json({ success: true, type: message.notificationType }, { status: 200 });
}
handleResult(message);
return NextResponse.json({ success: true, type: message.action ?? 'read' }, { status: 200 });
} # Generated with: ampersand-webhooks skill
# https://github.com/hookdeck/webhook-skills
import json
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import JSONResponse
from svix.webhooks import Webhook, WebhookVerificationError
load_dotenv()
app = FastAPI(title="Ampersand Webhook Handler")
@app.get("/health")
async def health_check():
"""Health check endpoint."""
return {"status": "ok"}
def handle_notification(notification_type: str, data: dict) -> None:
"""Notifications: {"notificationType": "...", "data": {...}}."""
if notification_type in ("installation.created", "installation.updated", "installation.deleted"):
print(f"Installation event {notification_type}: {data.get('installationId')} ({data.get('groupRef')})")
elif notification_type in (
"connection.created", "connection.refreshed", "connection.updated", "connection.deleted"
):
print(f"Connection event {notification_type}: {data.get('connectionId')} ({data.get('provider')})")
elif notification_type == "connection.error":
print(f"Connection error: {data.get('connectionId')} {data.get('errors')}")
elif notification_type in ("read.backfill.done", "read.triggered.done"):
print(f"Read finished ({notification_type}): {data.get('installationId')} {data.get('objectName')}")
elif notification_type in ("read.backfill.error", "read.triggered.error", "read.schedule.paused"):
print(f"Read problem ({notification_type}): {data.get('installationId')} {data.get('objectName')}")
elif notification_type == "write.async.done":
print(f"Async write done: {data.get('installationId')} {data.get('objectName')}")
elif notification_type in (
"subscribe.create.success", "subscribe.update.success", "subscribe.delete.success",
"subscribe.create.error", "subscribe.update.error", "subscribe.delete.error",
):
print(f"Subscribe event {notification_type}: {data.get('installationId')} {data.get('objectName')}")
elif notification_type == "destination.webhook.disabled":
print(f"Webhook destination disabled: {data.get('destinationId')} {data.get('url')}")
elif notification_type == "destination.delivery.error":
print(f"Delivery failed: {data.get('destinationId')} {data.get('error')}")
else:
print(f"Unhandled notification type: {notification_type}")
def handle_result(message: dict) -> None:
"""Read / subscribe results: {"action": "...", "groupRef": ..., "result": [...], "resultInfo": {...}}."""
result_info = message.get("resultInfo") or {}
print(
f"Received {message.get('action')} result: {message.get('groupRef')} "
f"{message.get('objectName')} ({result_info.get('numRecords')} records)"
)
if result_info.get("type") == "url":
# A record over 300KB is not inlined: GET resultInfo.downloadUrl within 15 minutes.
print("Result is too large to inline, download it from resultInfo.downloadUrl")
return
for record in message.get("result") or []:
# record["fields"] / record["mappedFields"] / record["raw"] (subscribe: record["subscribeEventType"])
print(f"Record: {(record.get('fields') or {}).get('id') or (record.get('raw') or {}).get('id')}")
@app.post("/webhooks/ampersand")
async def ampersand_webhook(
request: Request,
svix_id: str = Header(None),
svix_timestamp: str = Header(None),
svix_signature: str = Header(None),
):
"""Receive and verify an Ampersand webhook (delivered via Svix)."""
secret = os.environ.get("AMPERSAND_WEBHOOK_SECRET")
if not secret or not secret.startswith("whsec_"):
print("Invalid webhook secret configuration")
raise HTTPException(status_code=500, detail="Server configuration error")
if not all([svix_id, svix_timestamp, svix_signature]):
raise HTTPException(status_code=400, detail="Missing required webhook headers")
# Verify against the RAW body (any content type) — never a re-serialized payload.
body = await request.body()
try:
# Decodes the secret, enforces a fixed 5-minute timestamp window and checks every
# v1 entry in constant time. As of svix 2.x it returns None.
Webhook(secret).verify(
body,
{
"svix-id": svix_id,
"svix-timestamp": svix_timestamp,
"svix-signature": svix_signature,
},
)
except (WebhookVerificationError, ValueError) as err: # ValueError: e.g. non-ASCII header values
detail = "Timestamp too old" if "timestamp" in str(err).lower() else "Invalid signature"
print(f"Webhook verification failed: {err}")
raise HTTPException(status_code=400, detail=detail)
# Verified — only now is it safe to parse.
try:
message = json.loads(body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
if not isinstance(message, dict):
raise HTTPException(status_code=400, detail="Invalid JSON")
# Dispatch on notificationType when present, otherwise treat it as a read/subscribe result.
notification_type = message.get("notificationType")
if isinstance(notification_type, str):
data = message.get("data")
handle_notification(notification_type, data if isinstance(data, dict) else {})
return JSONResponse(content={"success": True, "type": notification_type}, status_code=200)
handle_result(message)
return JSONResponse(content={"success": True, "type": message.get("action") or "read"}, status_code=200)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the Ampersand webhooks skill:
npx skills add hookdeck/webhook-skills --skill ampersand-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.
Wrong destination's secret
Each destination has its own webhook signing secret, and dev and prod projects have separate destinations. 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.
Let Event Gateway verify Ampersand signatures.
Event Gateway verifies the signature on each Ampersand delivery before it reaches your service, then queues it and retries failures on your schedule.