Skip to Content
CerebrumDocs
GuidesAPI referenceTrust & security

Verify webhook signatures

Cerebrum sends webhooks through Svix. Real and simulated notifications use Svix signing; there is no unsigned fallback delivery when Svix is disabled. Verify every request before parsing or acting on it.

Get the correct secret and headers

Create or select the endpoint in the Svix application portal and copy that endpoint's signing secret. It is not your Cerebrum API key, and svixAppId in the payload is not a secret. Keep the secret out of source control.

Each request carries:

  • svix-id — the message ID, retained when the same message is resent; use it for durable duplicate detection.
  • svix-timestamp — the delivery-attempt timestamp.
  • svix-signature — one or more signatures to verify.

Use the exact raw request body. Parsing JSON and stringifying it before verification can change the signed bytes. The official Svix libraries verify these headers and their timestamp tolerance; they also accept the equivalent webhook-id, webhook-timestamp, and webhook-signature names.

With CRA delegation, postbacks and parent-owned destinations use the parent CRA application's endpoint secrets. Explicit child destinations can receive a separate child-application delivery. payload.organizationId retains the event's child-organization context, but it does not replace the receiving endpoint's secret.

Runnable local durable inbox and worker

This example uses Node.js 24, Express, the official svix package, and Node's built-in SQLite driver. It implements all of the following:

  • raw-body Svix verification;
  • a unique svix_id constraint in a persistent SQLite inbox;
  • acknowledgement only after the inbox insert succeeds;
  • successful duplicate handling without repeated processing;
  • a separate worker that retrieves the exact order, invite, or monitoring report;
  • recovery of rows left processing by a terminated local worker;
  • local retry limits and quarantine for unsupported or unknown events.

Install the two external packages:

npm install express svix

Save the following complete example as receiver.mjs:

import express from "express";
import { Webhook } from "svix";
import { DatabaseSync } from "node:sqlite";

const apiKey = process.env.CEREBRUM_API_KEY;
const secret = process.env.CEREBRUM_WEBHOOK_SECRET;
const baseUrl = (process.env.CEREBRUM_BASE_URL || "https://api.cerebrum.com").replace(/\/$/, "");
const port = Number(process.env.PORT || 3000);

if (!apiKey || !secret) {
  throw new Error("Set CEREBRUM_API_KEY and CEREBRUM_WEBHOOK_SECRET");
}

const db = new DatabaseSync(process.env.WEBHOOK_DB_PATH || "./cerebrum-inbox.sqlite");
db.exec(`
  CREATE TABLE IF NOT EXISTS inbox (
    id INTEGER PRIMARY KEY,
    svix_id TEXT NOT NULL UNIQUE,
    payload TEXT NOT NULL,
    resource_json TEXT,
    status TEXT NOT NULL DEFAULT 'pending',
    attempts INTEGER NOT NULL DEFAULT 0,
    last_error TEXT,
    received_at TEXT NOT NULL,
    processed_at TEXT
  )
`);
db.exec("UPDATE inbox SET status = 'pending' WHERE status = 'processing'");

const webhook = new Webhook(secret);
const app = express();
const insert = db.prepare(`
  INSERT INTO inbox (svix_id, payload, received_at)
  VALUES (?, ?, ?)
  ON CONFLICT(svix_id) DO NOTHING
  RETURNING id
`);

app.post(
  "/webhooks/cerebrum",
  express.raw({ type: "application/json" }),
  (req, res) => {
    if (!Buffer.isBuffer(req.body)) {
      res.status(400).end();
      return;
    }

    const svixId = req.header("svix-id") || "";
    const rawBody = req.body.toString("utf8");
    let payload;

    try {
      webhook.verify(rawBody, {
        "svix-id": svixId,
        "svix-timestamp": req.header("svix-timestamp") || "",
        "svix-signature": req.header("svix-signature") || "",
      });
      payload = JSON.parse(rawBody);
    } catch {
      res.status(400).end();
      return;
    }

    try {
      const row = insert.get(svixId, JSON.stringify(payload), new Date().toISOString());
      if (!row) {
        res.status(200).json({ status: "duplicate" });
        return;
      }
      res.status(204).end();
    } catch {
      res.status(500).end();
    }
  }
);

const claim = db.prepare(`
  UPDATE inbox
  SET status = 'processing', attempts = attempts + 1
  WHERE id = (
    SELECT id FROM inbox WHERE status = 'pending' ORDER BY id LIMIT 1
  )
  RETURNING id, payload, attempts
`);
const complete = db.prepare(`
  UPDATE inbox
  SET status = ?, resource_json = ?, processed_at = ?, last_error = NULL
  WHERE id = ?
`);
const fail = db.prepare(`
  UPDATE inbox SET status = ?, last_error = ? WHERE id = ?
`);
const knownEvents = new Set([
  "ORDER_STATUS_CHANGE",
  "ORDER_SCORE_CHANGE",
  "ORDER_CUSTOM_SCORE_CHANGE",
  "ORDER_DISPUTE_RESOLVED",
  "ORDER_ERROR",
  "VOUCHER_REDEEMED",
  "VOUCHER_ACCEPTED",
  "VOUCHER_STARTED",
  "VOUCHER_CANCELED",
  "VOUCHER_EXPIRED",
  "VOUCHER_OPTED_OUT",
  "BEAM_INPUT_CREATED",
  "MONITORING_REPORT_GENERATED",
]);

async function retrieve(payload) {
  const routes = {
    order: "/v1/orders/",
    invite: "/v1/vid/invites/",
    report: "/v1/monitoring/reports/",
  };
  const route = routes[payload.idType];

  if (!knownEvents.has(payload.event) || !route) {
    return { status: "quarantined", resource: null };
  }

  const response = await fetch(`${baseUrl}${route}${encodeURIComponent(payload.id)}`, {
    headers: { apikey: apiKey },
    signal: AbortSignal.timeout(10000),
  });
  if (!response.ok) {
    throw new Error(`Resource retrieval returned HTTP ${response.status}`);
  }

  return { status: "complete", resource: await response.json() };
}

let working = false;

async function work() {
  if (working) return;
  working = true;

  try {
    const row = claim.get();
    if (!row) return;

    try {
      const payload = JSON.parse(row.payload);
      const outcome = await retrieve(payload);
      complete.run(
        outcome.status,
        outcome.resource === null ? null : JSON.stringify(outcome.resource),
        new Date().toISOString(),
        row.id
      );
    } catch (error) {
      fail.run(row.attempts >= 5 ? "failed" : "pending", String(error), row.id);
    }
  } finally {
    working = false;
  }
}

const timer = setInterval(() => {
  void work().catch((error) => console.error("Worker error", error));
}, 2000);

const server = app.listen(port, () => {
  console.log(`Webhook receiver listening on port ${port}`);
});

function shutdown() {
  clearInterval(timer);
  server.close(() => {
    db.close();
    process.exit(0);
  });
}

process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown);

Do not register express.json() for this route. The route-specific express.raw() middleware must see the request before any JSON parser.

Configure the environment and run it:

export CEREBRUM_BASE_URL="https://api.cerebrum.com"
export CEREBRUM_API_KEY="REPLACE_WITH_YOUR_API_KEY"
export CEREBRUM_WEBHOOK_SECRET="whsec_REPLACE_WITH_ENDPOINT_SECRET"
node receiver.mjs

Use the base URL for a supported environment in which your key works; no public sandbox is assumed. Expose /webhooks/cerebrum through your supported HTTPS development tunnel and configure that exact endpoint in Svix. Then follow Test webhook delivery.

The HTTP insert is one atomic SQLite write. ON CONFLICT DO NOTHING RETURNING returns no row for an already stored svix-id, so only the first delivery is acknowledged as new. The worker claims rows with a second atomic update, uses a busy flag to prevent overlapping local iterations, and applies a 10-second application timeout to resource retrieval. On restart, rows interrupted in processing become pending again. Run one local worker against the example database file; use a managed database and queue with lease recovery when deploying multiple workers.

Failed resource retrieval stays pending for up to five local worker attempts and then becomes failed. This is an example application policy, not a Cerebrum delivery guarantee. Unknown events and unsupported Beam inputs become quarantined rather than triggering an invented action. A deliberately fake simulation order ID cannot be retrieved; use receiver-only acceptance for that test or supply an existing accessible order UUID.

For production, preserve the same ordering: verify, durably accept, acknowledge, then retrieve and process. See Response requirements and Delivery and retry policy.

On this page