> For the complete documentation index, see [llms.txt](https://black-sheep-finance.gitbook.io/black-sheep-finance-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://black-sheep-finance.gitbook.io/black-sheep-finance-docs/webhooks/signatures.md).

# Signature verification

Every webhook is signed with **HMAC-SHA256** using your endpoint's signing secret. Verify before trusting the payload.

## Headers

| Header                   | Value                                      |
| ------------------------ | ------------------------------------------ |
| `X-BlackSheep-Signature` | `sha256=<hex digest>`                      |
| `X-BlackSheep-Event`     | event name, e.g. `approval.pending`        |
| `X-BlackSheep-Delivery`  | unique delivery UUID (for log correlation) |

## Algorithm

```
hex( HMAC_SHA256( secret, raw_request_body ) )
```

The body is the **raw bytes** of the JSON payload — verify before `JSON.parse`. Don't re-serialize.

## Node.js

```ts
import { createHmac, timingSafeEqual } from "crypto";

export function verifyBlackSheep(rawBody: string, header: string, secret: string) {
  const provided = header.replace(/^sha256=/, "");
  const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
  const a = Buffer.from(provided, "hex");
  const b = Buffer.from(expected, "hex");
  return a.length === b.length && timingSafeEqual(a, b);
}
```

## Cloudflare Workers / edge runtimes

```ts
export async function verifyBlackSheep(rawBody: string, header: string, secret: string) {
  const key = await crypto.subtle.importKey(
    "raw", new TextEncoder().encode(secret),
    { name: "HMAC", hash: "SHA-256" }, false, ["sign"],
  );
  const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(rawBody));
  const expected = [...new Uint8Array(sig)].map(b => b.toString(16).padStart(2, "0")).join("");
  const provided = header.replace(/^sha256=/, "");
  // constant-time compare
  if (provided.length !== expected.length) return false;
  let diff = 0;
  for (let i = 0; i < expected.length; i++) diff |= provided.charCodeAt(i) ^ expected.charCodeAt(i);
  return diff === 0;
}
```

## Express example

```ts
import express from "express";
import { verifyBlackSheep } from "./verify";

const app = express();

app.post(
  "/hooks/blacksheep",
  express.raw({ type: "application/json" }), // preserve raw body
  (req, res) => {
    const sig = req.header("X-BlackSheep-Signature") ?? "";
    if (!verifyBlackSheep(req.body.toString("utf8"), sig, process.env.BS_WEBHOOK_SECRET!)) {
      return res.status(401).send("invalid signature");
    }
    const payload = JSON.parse(req.body.toString("utf8"));
    handleEvent(payload);
    res.status(200).send("ok");
  },
);
```

## What to reject

* Missing signature header → 401.
* Mismatched signature → 401.
* Timestamp older than 5 minutes (replay protection) → 401.
* Duplicate `event_id` you've already processed → 200 + skip (at-least-once delivery).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://black-sheep-finance.gitbook.io/black-sheep-finance-docs/webhooks/signatures.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
