Verify Fireberry webhooks

Fireberry doesn't sign webhook requests, so there's no signature to check. Add a secret header to the Webhook action and compare its whole value on your endpoint in constant time. That shows the sender knows the secret, but it doesn't cover the body or stop a replayed request.

The facts

Signature header
None (unsigned)
What to build
Compare the header you added with your stored value, byte for byte
Key
shared secret

Fireberry webhook secret

There's no Fireberry-issued secret. You choose the header and its value in the Webhook action's Header section. Keep it in an environment variable, not in source code.

  • Generate a long random value yourself, for example with openssl rand -hex 32.
  • Set on each Webhook action with + Add Header, so every automation can have its own.
  • The whole value is what's sent, so include any prefix such as Bearer in what you compare.
  • Fireberry documents no secret field type, rotation flow or test and live values. To rotate, edit the action.

Source: Fireberry docs ↗

Code

express/src/index.js
javascript
// Generated with: fireberry-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');

const app = express();

// The automation's author picks the HTTP method, so accept all five Fireberry offers.
const METHODS = new Set(['POST', 'PUT', 'PATCH', 'GET', 'DELETE']);

/**
 * Constant-time string comparison. Lengths are checked first because timingSafeEqual
 * throws on unequal lengths; both sides are compared as equal-length Buffers.
 */
function safeEqual(a, b) {
  const ba = Buffer.from(String(a), 'utf8');
  const bb = Buffer.from(String(b), 'utf8');
  return ba.length === bb.length && crypto.timingSafeEqual(ba, bb);
}

/**
 * Fireberry does not sign requests. The webhook automation action sends whatever
 * Header key/value pairs you configured, so the header name is user-chosen. Compare
 * the WHOLE value (do not strip a "Bearer " prefix). A static shared credential
 * authenticates the sender, not the body, and offers no replay protection.
 */
function verifyFireberryRequest(
  headers,
  secret = process.env.FIREBERRY_WEBHOOK_SECRET,
  headerName = process.env.FIREBERRY_WEBHOOK_HEADER || 'Authorization'
) {
  if (!secret) return false; // never accept when unconfigured
  const received = headers[headerName.toLowerCase()]; // Node lowercases header names
  return Boolean(received) && safeEqual(received, secret);
}

// Fireberry adds no event field: the body is free text written by the automation's author.
// This handler assumes an illustrative JSON body such as
//   {"event": "account.created", "record": {"accountname": "Acme"}}
function handleEvent(payload) {
  const { event, record } = payload;

  switch (event) {
    case 'account.created':
      console.log(`Account created: ${record && record.accountname}`);
      // Your code: sync the new account to your system
      break;

    case 'record.updated':
      console.log(`Record updated: ${record && record.id}`);
      // Your code: apply the changed fields
      break;

    default:
      console.log(`Unhandled event: ${event}`);
  }
}

// Read the body raw (any content type) so the request is authenticated before parsing.
app.all('/webhooks/fireberry', express.raw({ type: '*/*' }), (req, res) => {
  if (!METHODS.has(req.method)) {
    res.set('Allow', [...METHODS].join(', '));
    return res.status(405).json({ error: 'Method not allowed' });
  }

  if (!verifyFireberryRequest(req.headers)) {
    return res.status(401).json({ error: 'Invalid or missing webhook secret header' });
  }

  // GET (and sometimes DELETE) requests have no body: acknowledge them.
  const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
  if (raw.trim() === '') {
    console.log(`${req.method} webhook with empty body`);
    return res.status(200).json({ received: true });
  }

  let payload;
  try {
    payload = JSON.parse(raw);
  } catch {
    return res.status(400).json({ error: 'Invalid JSON body' });
  }

  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
    return res.status(400).json({ error: 'Expected a JSON object' });
  }

  try {
    handleEvent(payload);
  } catch (err) {
    console.error('Error handling Fireberry webhook:', err);
    return res.status(500).json({ error: 'Handler error' });
  }

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

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

module.exports = app;
module.exports.verifyFireberryRequest = verifyFireberryRequest;

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: http://localhost:${PORT}/webhooks/fireberry`);
  });
}
nextjs/app/webhooks/fireberry/route.ts
typescript
// Generated with: fireberry-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyFireberryRequest } from '../../../lib/verify-fireberry';

// Fireberry adds no event field: the body is free text written by the automation's author.
// This handler assumes an illustrative JSON body such as
//   {"event": "account.created", "record": {"accountname": "Acme"}}
interface FireberryPayload {
  event?: string;
  record?: { id?: string; accountname?: string; [key: string]: unknown };
  [key: string]: unknown;
}

function handleEvent(payload: FireberryPayload): void {
  const { event, record } = payload;

  switch (event) {
    case 'account.created':
      console.log(`Account created: ${record?.accountname}`);
      // Your code: sync the new account to your system
      break;

    case 'record.updated':
      console.log(`Record updated: ${record?.id}`);
      // Your code: apply the changed fields
      break;

    default:
      console.log(`Unhandled event: ${event}`);
  }
}

// The automation's author picks the HTTP method, so the same handler serves all five.
async function handle(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyFireberryRequest(request.headers)) {
    return NextResponse.json({ error: 'Invalid or missing webhook secret header' }, { status: 401 });
  }

  // Read as text so any content type is accepted; GET requests have no body.
  const raw = await request.text();
  if (raw.trim() === '') {
    console.log(`${request.method} webhook with empty body`);
    return NextResponse.json({ received: true });
  }

  let payload: unknown;
  try {
    payload = JSON.parse(raw);
  } catch {
    return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
  }

  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
    return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
  }

  try {
    handleEvent(payload as FireberryPayload);
  } catch (err) {
    console.error('Error handling Fireberry webhook:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  return NextResponse.json({ received: true });
}

export const POST = handle;
export const PUT = handle;
export const PATCH = handle;
export const GET = handle;
export const DELETE = handle;
fastapi/main.py
python
# Generated with: fireberry-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()

# The automation's author picks the HTTP method, so accept all five Fireberry offers.
METHODS = ["POST", "PUT", "PATCH", "GET", "DELETE"]


def safe_equal(a: str, b: str) -> bool:
    """Constant-time comparison on bytes (compare_digest raises on non-ASCII str)."""
    return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))


def verify_fireberry_request(headers, secret=None, header_name=None) -> bool:
    """Fireberry does not sign requests. The webhook automation action sends whatever
    Header key/value pairs you configured, so the header name is user-chosen. Compare
    the WHOLE value (do not strip a "Bearer " prefix). A static shared credential
    authenticates the sender, not the body, and offers no replay protection.
    """
    secret = secret if secret is not None else os.environ.get("FIREBERRY_WEBHOOK_SECRET")
    header_name = header_name or os.environ.get("FIREBERRY_WEBHOOK_HEADER") or "Authorization"
    if not secret:
        return False  # never accept when unconfigured
    received = headers.get(header_name)  # Starlette headers are case-insensitive
    return bool(received) and safe_equal(received, secret)


async def require_fireberry_secret(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is read."""
    if not verify_fireberry_request(request.headers):
        raise HTTPException(status_code=401, detail="Invalid or missing webhook secret header")


# Fireberry adds no event field: the body is free text written by the automation's author.
# This handler assumes an illustrative JSON body such as
#   {"event": "account.created", "record": {"accountname": "Acme"}}
def handle_event(payload: dict) -> None:
    event = payload.get("event")
    record = payload.get("record") or {}

    if event == "account.created":
        print(f"Account created: {record.get('accountname')}")
        # Your code: sync the new account to your system

    elif event == "record.updated":
        print(f"Record updated: {record.get('id')}")
        # Your code: apply the changed fields

    else:
        print(f"Unhandled event: {event}")


@app.api_route(
    "/webhooks/fireberry",
    methods=METHODS,
    dependencies=[Depends(require_fireberry_secret)],
)
async def fireberry_webhook(request: Request):
    # Read the raw body so any content type is accepted; GET requests have no body.
    raw_body = await request.body()
    if not raw_body.strip():
        print(f"{request.method} webhook with empty body")
        return {"received": True}

    try:
        payload = json.loads(raw_body)
    except (json.JSONDecodeError, UnicodeDecodeError):
        raise HTTPException(status_code=400, detail="Invalid JSON body")

    if not isinstance(payload, dict):
        raise HTTPException(status_code=400, detail="Expected a JSON object")

    try:
        handle_event(payload)
    except Exception as err:  # noqa: BLE001
        print(f"Error handling Fireberry webhook: {err}")
        raise HTTPException(status_code=500, detail="Handler 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=8000)

From hookdeck/webhook-skills ↗

Or install the Fireberry webhooks skill:

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

Common failures

The compared value is missing a prefix

Fireberry sends the header value as you entered it. If you entered Bearer abc123, compare the whole string, prefix included.

The header is on a different automation

Headers belong to each Webhook action, so a new automation pointing at the same endpoint needs the header added too.

The value uses a field reference

The Header section accepts field references, so a value built from one changes with the record and won't match a single stored secret.

The route doesn't allow the method

The action can use POST, GET, PUT, DELETE or PATCH. A POST-only route rejects the others before your header check runs.

From Hookdeck's Fireberry guide

Let Event Gateway check your Fireberry key.

Set the header name and value on a Fireberry source and Event Gateway checks them on each request. A request with the wrong key still gets a 200, but it's recorded as failed verification and creates no event.

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