Verify Aimfox webhooks

Aimfox doesn't sign webhooks, so there's no signature to compute. You set a header name and value on the webhook, and your endpoint compares the whole value in constant time. A match shows the sender knows the value, but nothing covers the body, and a captured request can be replayed.

The facts

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

Aimfox webhook secret

There's no Aimfox-issued secret. You choose the header and its value when you add the webhook, or set them through the API. Keep it in an environment variable, not in source code.

  • Generate a long random value yourself, for example with openssl rand -hex 32.
  • The Add Webhook dialog has separate Header name and Header value fields. It sits behind a toggle, and the header is optional.
  • Set per webhook, so each endpoint can have its own value.
  • In the API, PATCH /api/v3/webhooks/:webhook_id takes a headers object such as {"Authorization": "Bearer 123"}. The create example doesn't include one.
  • For Basic Auth, the value is a whole Basic <base64> string you generate yourself.
  • Include any Bearer or Basic prefix in the value you compare.
  • Aimfox documents no rotation flow and no separate test and live values.

Source: Aimfox docs ↗

Code

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

const app = express();

/**
 * Constant-time string comparison. Hashing both sides first gives equal-length
 * buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
 */
function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(String(a)).digest();
  const hb = crypto.createHash('sha256').update(String(b)).digest();
  return crypto.timingSafeEqual(ha, hb);
}

/**
 * Aimfox does not sign payloads. The only authentication is the "Authentication Header"
 * you add to the webhook: a user-chosen header name (AIMFOX_WEBHOOK_HEADER, default
 * Authorization) whose whole value (AIMFOX_WEBHOOK_SECRET, including any "Bearer " or
 * "Basic " prefix) is compared as-is. This authenticates the sender, not the body, and
 * gives no replay protection.
 */
function verifyAimfoxRequest(headers, secret = process.env.AIMFOX_WEBHOOK_SECRET) {
  if (!secret) return false; // never accept when unconfigured
  const name = (process.env.AIMFOX_WEBHOOK_HEADER || 'Authorization').toLowerCase();
  const received = headers[name]; // Node lowercases incoming header names
  return Boolean(received) && safeEqual(received, secret);
}

function handleEvent(payload) {
  const { event_type: type, id } = payload;

  switch (type) {
    case 'account_logged_in':
      console.log(`Account logged in (${id})`);
      // Your code: mark the account active (payload.event.account)
      break;

    case 'account_logged_out':
      console.log(`Account logged out (${id})`);
      // Your code: alert someone to re-authenticate (payload.event.account)
      break;

    case 'new_connection':
      console.log(`New connection (${id})`);
      // Your code: create a CRM contact
      break;

    case 'view':
      console.log(`Profile viewed (${id})`);
      break;

    case 'connect':
      console.log(`Connection request sent (${id})`);
      break;

    case 'accepted':
      console.log(`Connection request accepted (${id})`);
      // Your code: start a follow-up sequence
      break;

    case 'inmail':
      console.log(`InMail sent (${id})`);
      break;

    case 'message':
      console.log(`Message sent (${id})`);
      break;

    case 'new_reply':
      console.log(`New reply (${id})`);
      // Your code: notify sales
      break;

    case 'reply':
      console.log(`First campaign reply (${id})`);
      break;

    case 'inmail_reply':
      console.log(`InMail reply (${id})`);
      break;

    case 'lead_label_added':
      console.log(`Lead label added (${id})`);
      // Your code: sync the label to your CRM
      break;

    case 'campaign_created':
      console.log(`Campaign created (${id})`);
      break;

    case 'campaign_started':
      console.log(`Campaign started (${id})`);
      break;

    case 'campaign_ended':
      console.log(`Campaign ended (${id})`);
      break;

    case 'inbox_event':
      console.log(`Inbox event (${id})`);
      break;

    case 'campaign_reply':
      console.log(`Campaign reply (${id})`);
      break;

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

// Read the body raw (any content type) so the request is authenticated before parsing.
app.post('/webhooks/aimfox', express.raw({ type: '*/*' }), (req, res) => {
  if (!verifyAimfoxRequest(req.headers)) {
    return res.status(401).json({ error: 'Invalid or missing Aimfox authentication header' });
  }

  let payload;
  try {
    const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
    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 Aimfox event:', 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.verifyAimfoxRequest = verifyAimfoxRequest;

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: POST http://localhost:${PORT}/webhooks/aimfox`);
  });
}
nextjs/app/webhooks/aimfox/route.ts
typescript
// Generated with: aimfox-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyAimfoxRequest } from '../../../lib/verify-aimfox';

interface AimfoxPayload {
  id?: string;
  event_type?: string;
  workspace?: Record<string, unknown>;
  event?: Record<string, unknown>;
  [key: string]: unknown;
}

function handleEvent(payload: AimfoxPayload): void {
  const { event_type: type, id } = payload;

  switch (type) {
    case 'account_logged_in':
      console.log(`Account logged in (${id})`);
      // Your code: mark the account active (payload.event.account)
      break;

    case 'account_logged_out':
      console.log(`Account logged out (${id})`);
      // Your code: alert someone to re-authenticate (payload.event.account)
      break;

    case 'new_connection':
      console.log(`New connection (${id})`);
      // Your code: create a CRM contact
      break;

    case 'view':
      console.log(`Profile viewed (${id})`);
      break;

    case 'connect':
      console.log(`Connection request sent (${id})`);
      break;

    case 'accepted':
      console.log(`Connection request accepted (${id})`);
      // Your code: start a follow-up sequence
      break;

    case 'inmail':
      console.log(`InMail sent (${id})`);
      break;

    case 'message':
      console.log(`Message sent (${id})`);
      break;

    case 'new_reply':
      console.log(`New reply (${id})`);
      // Your code: notify sales
      break;

    case 'reply':
      console.log(`First campaign reply (${id})`);
      break;

    case 'inmail_reply':
      console.log(`InMail reply (${id})`);
      break;

    case 'lead_label_added':
      console.log(`Lead label added (${id})`);
      // Your code: sync the label to your CRM
      break;

    case 'campaign_created':
      console.log(`Campaign created (${id})`);
      break;

    case 'campaign_started':
      console.log(`Campaign started (${id})`);
      break;

    case 'campaign_ended':
      console.log(`Campaign ended (${id})`);
      break;

    case 'inbox_event':
      console.log(`Inbox event (${id})`);
      break;

    case 'campaign_reply':
      console.log(`Campaign reply (${id})`);
      break;

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

export async function POST(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyAimfoxRequest(request.headers)) {
    return NextResponse.json(
      { error: 'Invalid or missing Aimfox authentication header' },
      { status: 401 }
    );
  }

  let payload: unknown;
  try {
    // Read as text so any content type is accepted.
    payload = JSON.parse(await request.text());
  } 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 AimfoxPayload);
  } catch (err) {
    console.error('Error handling Aimfox event:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: aimfox-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os

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

load_dotenv()

app = FastAPI()


def safe_equal(a: str, b: str) -> bool:
    """Constant-time comparison: compare_digest on bytes (equal-length SHA-256 digests).
    Passing str would raise TypeError on non-ASCII input."""
    return hmac.compare_digest(
        hashlib.sha256(a.encode("utf-8")).digest(),
        hashlib.sha256(b.encode("utf-8")).digest(),
    )


def verify_aimfox_request(headers, secret=None) -> bool:
    """Aimfox does not sign payloads. The only authentication is the "Authentication Header"
    you add to the webhook: a user-chosen header name (AIMFOX_WEBHOOK_HEADER, default
    Authorization) whose whole value (AIMFOX_WEBHOOK_SECRET, including any "Bearer " or
    "Basic " prefix) is compared as-is. This authenticates the sender, not the body, and
    gives no replay protection.
    """
    secret = secret if secret is not None else os.environ.get("AIMFOX_WEBHOOK_SECRET")
    if not secret:
        return False  # never accept when unconfigured
    name = os.environ.get("AIMFOX_WEBHOOK_HEADER") or "Authorization"
    received = headers.get(name.lower())  # incoming header names are lowercased
    return bool(received) and safe_equal(received, secret)


async def require_aimfox_header(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is parsed."""
    if not verify_aimfox_request(request.headers):
        raise HTTPException(status_code=401, detail="Invalid or missing Aimfox authentication header")


def handle_event(payload: dict) -> None:
    event_type = payload.get("event_type")
    event_id = payload.get("id")

    if event_type == "account_logged_in":
        print(f"Account logged in ({event_id})")
        # Your code: mark the account active (payload["event"]["account"])

    elif event_type == "account_logged_out":
        print(f"Account logged out ({event_id})")
        # Your code: alert someone to re-authenticate (payload["event"]["account"])

    elif event_type == "new_connection":
        print(f"New connection ({event_id})")
        # Your code: create a CRM contact

    elif event_type == "view":
        print(f"Profile viewed ({event_id})")

    elif event_type == "connect":
        print(f"Connection request sent ({event_id})")

    elif event_type == "accepted":
        print(f"Connection request accepted ({event_id})")
        # Your code: start a follow-up sequence

    elif event_type == "inmail":
        print(f"InMail sent ({event_id})")

    elif event_type == "message":
        print(f"Message sent ({event_id})")

    elif event_type == "new_reply":
        print(f"New reply ({event_id})")
        # Your code: notify sales

    elif event_type == "reply":
        print(f"First campaign reply ({event_id})")

    elif event_type == "inmail_reply":
        print(f"InMail reply ({event_id})")

    elif event_type == "lead_label_added":
        print(f"Lead label added ({event_id})")
        # Your code: sync the label to your CRM

    elif event_type == "campaign_created":
        print(f"Campaign created ({event_id})")

    elif event_type == "campaign_started":
        print(f"Campaign started ({event_id})")

    elif event_type == "campaign_ended":
        print(f"Campaign ended ({event_id})")

    elif event_type == "inbox_event":
        print(f"Inbox event ({event_id})")

    elif event_type == "campaign_reply":
        print(f"Campaign reply ({event_id})")

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


@app.post("/webhooks/aimfox", dependencies=[Depends(require_aimfox_header)])
async def aimfox_webhook(request: Request):
    # Read the raw body so any content type is accepted.
    raw_body = await request.body()

    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 Aimfox event: {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 Aimfox webhooks skill:

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

Common failures

The compared value is missing a prefix

The whole header value has to match. If you entered Bearer abc123, or a Basic value, compare the whole string, prefix included.

The code checks a different header

You choose the header's name. If you named it X-Aimfox-Secret, a check that reads Authorization rejects every delivery.

The webhook has no header set

Aimfox's API example creates a webhook without headers, and the list example shows headers: null. Add it with PATCH /api/v3/webhooks/:webhook_id or in Workspace settings.

A proxy removes the header

A load balancer or proxy in front of your app may strip or rename a custom header, or consume Authorization, before your code sees it.

From Hookdeck's Aimfox guide

Let Event Gateway check Aimfox's authentication header.

Event Gateway checks the header you set on each Aimfox delivery before it reaches your service, then queues it and retries failures on your schedule.

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