Verify Autosana webhooks
Signing is optional on Autosana webhooks. If you set a signing secret, each delivery carries an X-Autosana-Signature-256 header holding sha256= and the hex HMAC-SHA256 of the raw body, so you can confirm it came from Autosana and wasn't changed on the way. No timestamp is signed separately, and Autosana's docs show manual verification and name no SDK.
The facts
X-Autosana-Signature-256 Not every delivery is signed: check your setup.
{raw body} The request body as sent, with no timestamp or other prefix.
Autosana webhook secret
You choose the secret yourself when you add the webhook. It's optional, and a webhook without one isn't signed. Keep it in an environment variable, not in source code.
- In the dashboard: enter it as the signing secret when you add the webhook under Settings > Integrations > Webhooks.
- Format: Autosana's docs set no format, so generate a long random value, for example with
openssl rand -hex 32. - As a key: Autosana's sample uses the secret as a plain string, so don't decode it from hex or base64, even if it looks encoded.
- Rotation: Autosana's docs don't describe rotating a secret.
Source: Autosana docs ↗
Code
// Generated with: autosana-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');
const app = express();
// Autosana: X-Autosana-Signature-256 = "sha256=" + hex(HMAC-SHA256(secret, rawBody))
function verifySignature(rawBody, signatureHeader, secret) {
if (!signatureHeader || !secret || !signatureHeader.startsWith('sha256=')) return false;
const received = signatureHeader.slice('sha256='.length);
// Check the hex shape first: Buffer.from(x, 'hex') silently truncates invalid input
if (!/^[0-9a-f]{64}$/i.test(received)) return false;
const expected = crypto.createHmac('sha256', secret).update(rawBody).digest();
return crypto.timingSafeEqual(Buffer.from(received, 'hex'), expected);
}
// express.raw with '*/*' keeps the body as a Buffer for any content type
app.post('/webhooks/autosana', express.raw({ type: '*/*' }), (req, res) => {
const signature = req.get('x-autosana-signature-256');
if (!signature) {
return res.status(400).send('Missing X-Autosana-Signature-256 header');
}
if (!Buffer.isBuffer(req.body) || !verifySignature(req.body, signature, process.env.AUTOSANA_WEBHOOK_SECRET)) {
return res.status(400).send('Invalid signature');
}
let payload;
try {
payload = JSON.parse(req.body.toString('utf8'));
} catch {
return res.status(400).send('Invalid JSON');
}
// The event name is in the body (`event`); there is no event header
switch (payload.event) {
case 'batch.completed': {
const s = payload.summary || {};
console.log(
`Batch completed for ${payload.app?.name}: ${s.passed_groups}/${s.total_groups} groups passed, ${s.failed_groups} failed`
);
for (const group of payload.run_groups || []) {
console.log(` ${group.name}: ${group.status} (${group.url})`);
}
break;
}
default:
console.log('Unhandled event:', payload.event);
}
res.json({ received: true });
});
if (require.main === module) {
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running on http://localhost:${port}`));
}
module.exports = app; // Generated with: autosana-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifySignature } from '../../../lib/verify';
export async function POST(request: NextRequest) {
// Raw body is required for signature verification
const rawBody = await request.text();
const signature = request.headers.get('x-autosana-signature-256');
if (!signature) {
return NextResponse.json({ error: 'Missing X-Autosana-Signature-256 header' }, { status: 400 });
}
if (!verifySignature(rawBody, signature, process.env.AUTOSANA_WEBHOOK_SECRET)) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
let payload: {
event?: string;
app?: { name?: string };
summary?: { total_groups?: number; passed_groups?: number; failed_groups?: number };
run_groups?: { name?: string; status?: string; url?: string }[];
};
try {
payload = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
// The event name is in the body (`event`); there is no event header
switch (payload.event) {
case 'batch.completed': {
const s = payload.summary || {};
console.log(
`Batch completed for ${payload.app?.name}: ${s.passed_groups}/${s.total_groups} groups passed, ${s.failed_groups} failed`
);
for (const group of payload.run_groups || []) {
console.log(` ${group.name}: ${group.status} (${group.url})`);
}
break;
}
default:
console.log('Unhandled event:', payload.event);
}
return NextResponse.json({ received: true });
} # Generated with: autosana-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
PREFIX = "sha256="
def verify_signature(raw_body: bytes, signature_header: str | None, secret: str | None) -> bool:
"""Autosana: X-Autosana-Signature-256 = "sha256=" + hex(HMAC-SHA256(secret, raw_body))."""
if not signature_header or not secret or not signature_header.startswith(PREFIX):
return False
received = signature_header[len(PREFIX):].lower()
computed = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
# Encode both sides to bytes so a non-ASCII header fails verification instead of raising
return hmac.compare_digest(received.encode("utf-8"), computed.encode("utf-8"))
@app.post("/webhooks/autosana")
async def autosana_webhook(request: Request):
# Raw body is required for signature verification
raw_body = await request.body()
signature = request.headers.get("x-autosana-signature-256")
if not signature:
raise HTTPException(status_code=400, detail="Missing X-Autosana-Signature-256 header")
if not verify_signature(raw_body, signature, os.getenv("AUTOSANA_WEBHOOK_SECRET")):
raise HTTPException(status_code=400, detail="Invalid signature")
try:
payload = json.loads(raw_body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
# The event name is in the body (`event`); there is no event header
event = payload.get("event") if isinstance(payload, dict) else None
if event == "batch.completed":
summary = payload.get("summary") or {}
app_name = (payload.get("app") or {}).get("name")
print(
f"Batch completed for {app_name}: {summary.get('passed_groups')}/"
f"{summary.get('total_groups')} groups passed, {summary.get('failed_groups')} failed"
)
for group in payload.get("run_groups") or []:
print(f" {group.get('name')}: {group.get('status')} ({group.get('url')})")
else:
print("Unhandled event:", event)
return {"received": True} Or install the Autosana webhooks skill:
npx skills add hookdeck/webhook-skills --skill autosana-webhooks
Common failures
The body was parsed first
Re-serialising parsed JSON can change the bytes. Compute the HMAC over the raw body before you parse it.
The webhook has no signing secret
Without a secret Autosana sends no signature header, so a receiver that requires one rejects every delivery. Set a secret on the webhook and use the same value in your receiver.
The sha256= prefix wasn't removed
The header value starts with sha256= and your computed digest doesn't. Strip the prefix before you compare them.
The secret was decoded
Autosana's sample uses the secret as a plain string. Don't decode it from hex or base64, even if you generated it as hex.
Let Event Gateway verify Autosana signatures.
Use the same signing secret on your Autosana webhook and your Hookdeck source, and Event Gateway verifies the signature on each delivery before it reaches your service, then queues it and retries failures on your schedule. A webhook with no secret sends unsigned deliveries, which fail verification there.