> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cimento.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Verifying signatures

> Check that a webhook request came from Cimento and wasn't changed on the way, using your endpoint's signing secret.

Anyone who learns your endpoint's URL can send it a request. Cimento signs every request with your endpoint's signing secret, so you can tell its requests from anyone else's. Verify the signature before you trust a request.

Cimento publishes SDKs for Go and TypeScript that verify a request and hand you the event. Cimento also follows the [Standard Webhooks](https://www.standardwebhooks.com) specification, so in any other language you can verify with one of its open-source libraries instead of writing the check yourself.

| Your receiver is written in | Use |
| - | - |
| Go | [The Cimento SDK](#verify-with-a-cimento-sdk) |
| TypeScript or JavaScript | [The Cimento SDK](#verify-with-a-cimento-sdk) |
| Another language | [A Standard Webhooks library](#verify-with-a-standard-webhooks-library), or [your own check](#verify-it-yourself) |

## Verify with a Cimento SDK

Install the SDK. Neither has any dependencies.

```bash Go theme={null}
go get github.com/cimento-ai/cimento-sdk/go/webhooks
```

```bash TypeScript theme={null}
npm install @cimento/webhooks
```

Then give it your endpoint's signing secret, the `whsec_...` value Cimento shows once when you create the endpoint.

```go Go theme={null}
wh, err := webhooks.NewWebhook(os.Getenv("CIMENTO_WEBHOOK_SECRET"))
if err != nil {
	log.Fatal(err)
}

handle := func(ctx context.Context, event *webhooks.Event) error {
	switch data := event.Data.(type) {
	case *webhooks.TrainingAssignmentCompletedPayload:
		log.Printf("%s finished training, recorded by the %s", data.User.ID, data.CompletedBy)
	case *webhooks.PhishingSimulationPayload:
		// Five event types share this payload.
		if event.Type == webhooks.EventTypePhishingSimulationClicked {
			log.Printf("%s clicked a simulation", data.User.ID)
		}
	default:
		// A type added to Cimento since this version, or one this
		// receiver has no use for. Answering 2xx is right for both.
	}
	return nil
}

http.Handle("/webhooks/cimento", webhooks.Handler(wh, handle,
	webhooks.OnReject(func(r *http.Request, err error) {
		log.Printf("refused a webhook from %s: %v", r.RemoteAddr, err)
	}),
))
```

```typescript TypeScript theme={null}
import { createServer } from "node:http";

import { Webhook, WebhookVerificationError } from "@cimento/webhooks";

const webhook = new Webhook(process.env.CIMENTO_WEBHOOK_SECRET!);

export const server = createServer(async (request, response) => {
  // The signature is over the body as it was sent, so collect the bytes
  // and verify them before anything parses them.
  const chunks: Buffer[] = [];
  for await (const chunk of request) {
    chunks.push(chunk as Buffer);
  }
  try {
    const event = await webhook.verify(Buffer.concat(chunks), request.headers);
    console.log(event.id, event.type, event.occurredAt);
    response.writeHead(204).end();
  } catch (error) {
    if (!(error instanceof WebhookVerificationError)) {
      throw error;
    }
    const unauthorized = ["invalid_signature", "timestamp_too_old"];
    response.writeHead(unauthorized.includes(error.code) ? 401 : 400).end();
  }
});
```

The SDK does the whole check for you:

* it verifies the signature over the body exactly as it arrived;
* it rejects a request whose `webhook-timestamp` is more than five minutes from your server's time;
* it accepts a request signed with either secret while you [rotate](#rotate-the-secret);
* it returns the event with `data` typed for the event's `type`. See [Reading events with an SDK](https://docs.cimento.ai/webhooks/receiving-events.md#reading-events-with-an-sdk).

In Go, `Handler` also answers Cimento: `204` when your function returns nil, `500` when it returns an error, and `401` or `400` for a request that doesn't verify. The TypeScript example does the same by hand for a plain Node server.

If your TypeScript server speaks the Fetch API, as Cloudflare Workers, Deno, Bun, Hono and Next.js route handlers do, `fetchHandler` answers for you in the same way:

```typescript TypeScript theme={null}
import { fetchHandler, Webhook } from "@cimento/webhooks";

const webhook = new Webhook(process.env.CIMENTO_WEBHOOK_SECRET!);

export const receive = fetchHandler(
  webhook,
  async (event) => {
    if (!event.known) {
      // A type added to Cimento since this version. Answering 2xx is right.
      return;
    }
    switch (event.type) {
      case "training.assignment.completed":
        console.log(
          `${event.data.user.id} finished training, recorded by the ${event.data.completedBy}`,
        );
        break;
      case "phishing.simulation.clicked":
        console.log(`${event.data.user.id} clicked a simulation`);
        break;
    }
  },
  {
    onReject: (request, error) =>
      console.warn(`refused a webhook: ${error.code}`),
  },
);
```

Each SDK's reference has the rest: the errors a failed check gives, and how to sign a request of your own to test your receiver.

> [card] [Go](https://pkg.go.dev/github.com/cimento-ai/cimento-sdk/go/webhooks)
>
> `github.com/cimento-ai/cimento-sdk/go/webhooks` on pkg.go.dev. Needs Go 1.26 or newer.

> [card] [TypeScript](https://www.npmjs.com/package/@cimento/webhooks)
>
> `@cimento/webhooks` on npm. Needs Node 22 or newer, or any runtime with Web Crypto.

## What is signed

Each request has three headers:

| Header | Value |
| - | - |
| `webhook-id` | The event's id. |
| `webhook-timestamp` | When this attempt was made, in seconds since the Unix epoch. |
| `webhook-signature` | One or more signatures, separated by spaces. Each is `v1,` followed by a base64 value. |

The signature is an HMAC-SHA256 of the id, the timestamp and the request body, joined by full stops:

```text Signed content theme={null}
{webhook-id}.{webhook-timestamp}.{body}
```

The key is your signing secret with the `whsec_` prefix removed and the rest decoded from base64.

## Verify with a Standard Webhooks library

For a language Cimento has no SDK for, Standard Webhooks has [libraries](https://github.com/standard-webhooks/standard-webhooks) for Python, Java, Ruby, PHP, C#, Rust and others. Each takes your secret, the raw body and the headers, and throws or returns an error when the request doesn't verify.

```python Python theme={null}
import os

from flask import Flask, request
from standardwebhooks.webhooks import Webhook, WebhookVerificationError

app = Flask(__name__)
webhook = Webhook(os.environ["CIMENTO_WEBHOOK_SECRET"])


@app.post("/webhooks/cimento")
def receive():
    try:
        # request.get_data() is the exact bytes Cimento sent.
        event = webhook.verify(request.get_data(), dict(request.headers))
    except WebhookVerificationError:
        return "invalid signature", 400

    # Store the event, answer, then do the work.
    return "", 204
```

The libraries also reject a request whose `webhook-timestamp` is more than five minutes from the current time. They give you the body as parsed JSON, not as a typed event.

## Verify it yourself

If you'd rather not add a library, the check is short:

**1. Read the raw body**

Use the request body exactly as it arrived, before any JSON parsing. See [Use the raw body](#use-the-raw-body).

**2. Check the timestamp**

Reject the request if `webhook-timestamp` is more than five minutes from your server's time. This stops someone replaying an old request.

**3. Compute the signature**

Join `webhook-id`, `webhook-timestamp` and the body with full stops, and compute its HMAC-SHA256 with your decoded secret. Base64-encode the result.

**4. Compare**

Split `webhook-signature` on spaces, and take the part after `v1,` from each. The request is genuine if any of them equals your value. Use a constant-time comparison.

```javascript Node.js theme={null}
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

export function verify(secret, headers, rawBody) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) return false;

  const age = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key)
    .update(`${id}.${timestamp}.`)
    .update(rawBody)
    .digest();

  return signatures.split(" ").some((signature) => {
    const [version, value] = signature.split(",");
    if (version !== "v1" || !value) return false;
    const given = Buffer.from(value, "base64");
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}
```

```python Python theme={null}
import base64
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 5 * 60


def verify(secret: str, headers: dict, raw_body: bytes) -> bool:
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        return False

    try:
        age = abs(time.time() - int(timestamp))
    except ValueError:
        return False
    if age > TOLERANCE_SECONDS:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = hmac.new(key, signed, hashlib.sha256).digest()

    for signature in signatures.split(" "):
        version, _, value = signature.partition(",")
        if version != "v1" or not value:
            continue
        try:
            given = base64.b64decode(value)
        except ValueError:
            continue
        if hmac.compare_digest(given, expected):
            return True
    return False
```

### Check your code

These values are the Standard Webhooks specification's own example. Your code should produce this signature from them:

| | Value |
| - | - |
| Secret | `whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw` |
| `webhook-id` | `msg_p5jXN8AQM9LWM0D4loKWxJek` |
| `webhook-timestamp` | `1614265330` |
| Body | `{"test": 2432232314}` |
| Signed content | `msg_p5jXN8AQM9LWM0D4loKWxJek.1614265330.{"test": 2432232314}` |
| `webhook-signature` | `v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=` |

The timestamp is from 2021, so skip the timestamp check while you test with these values. The body has one space after the colon; the signature changes if you remove it.

## Use the raw body

The signature covers the exact bytes Cimento sent. If your framework parses the JSON and you turn it back into text, the result can differ from what was signed and the check fails, even though the data is the same. Two things in Cimento's bodies make this likely:

* the body is compact, with no spaces or line breaks;
* the characters `<`, `>` and `&` inside text are written as `\u003c`, `\u003e` and `\u0026`.

So read the body as bytes, verify, and only then parse it.

## Rotate the secret

Rotate the secret if it may have leaked, or on whatever schedule your policy sets.

**1. Rotate**

On the endpoint's row, open the **⋯** menu, choose **Rotate secret** and confirm. Cimento shows **Your new signing secret** once. Copy it.

**2. Update your receiver**

Replace the old secret with the new one in your receiver.

For 24 hours after a rotation, Cimento signs each request with both secrets, so `webhook-signature` holds two signatures: the new secret's first, then the old one's. A receiver that accepts a request when any signature matches keeps working throughout, whichever secret it holds. The SDKs, the libraries and the code above do this.

With a Cimento SDK you can also give the receiver both secrets while your deployment moves from the old one to the new one:

```go Go theme={null}
wh, err := webhooks.NewWebhook(newSecret, webhooks.WithAdditionalSecrets(oldSecret))
```

```typescript TypeScript theme={null}
const webhook = new Webhook(newSecret, { additionalSecrets: [oldSecret] });
```

After 24 hours, only the new secret is used.

> [!WARNING]
>
> If you rotate again within those 24 hours, the oldest secret stops working at once. Cimento keeps one previous secret, not two.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.