# Verify signatures

Check that a webhook really comes from Chatwise, with samples in Node.js and Python.

Anyone can send a request to your URL. The signature proves that it comes from Chatwise, that nobody changed it and that it isn't an old one sent again.

Chatwise signs the way [Standard Webhooks](https://www.standardwebhooks.com) does, so the libraries of that project can verify it too. The samples below need no library.

## How it is signed

1. The key is your signing secret without `whsec_`, decoded from base64.
2. The signed text is the `webhook-id` header, a dot, the `webhook-timestamp` header, a dot, and the raw body.
3. The signature is `v1,` and the base64 of the HMAC-SHA256 of that text.
4. `webhook-signature` holds one signature, or two with a space between them while a [secret is rotated](https://chatwise.so/docs/webhooks/secrets.md).

To verify a request:

- **Use the raw body**, byte for byte. Parsing the JSON and writing it again can change it, and then no signature matches.
- **Refuse old timestamps.** The timestamp is signed, and it is new on every attempt, so a request that is more than five minutes old isn't a retry.
- **Accept any matching signature**, and compare in constant time.
- **Limit what you read.** Until the signature is checked, the request can be from anyone. An event is at most 256 KiB.
- **Answer 400** when nothing matches.

## Verify

**Node.js** `verify.mjs`:

```js
import { createHmac, timingSafeEqual } from "node:crypto";

const FIVE_MINUTES = 5 * 60;

// rawBody is the request body exactly as received (a Buffer or a string).
// headers has lowercase names, as Node's request.headers does.
export function verifyChatwiseWebhook(rawBody, headers, secret, now = Date.now() / 1000) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) return false;

  // Refuse old requests, so a captured one can't be sent again later.
  if (!(Math.abs(now - Number(timestamp)) <= FIVE_MINUTES)) return false;

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

  // While a secret is being rotated there are two signatures. One match is enough.
  return signatures.split(" ").some((signature) => {
    const [version, value = ""] = signature.split(",");
    const received = Buffer.from(value, "base64");
    return version === "v1" && received.length === expected.length && timingSafeEqual(received, expected);
  });
}
```

**Python** `verify.py`:

```python
import base64
import hashlib
import hmac
import time

FIVE_MINUTES = 5 * 60


def verify_chatwise_webhook(raw_body, headers, secret, now=None):
    """raw_body is the request body exactly as received, as bytes.

    headers is a mapping with case-insensitive or lowercase names.
    """
    message_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not message_id or not timestamp or not signatures:
        return False

    # Refuse old requests, so a captured one can't be sent again later.
    try:
        age = abs((time.time() if now is None else now) - int(timestamp))
    except ValueError:
        return False
    if age > FIVE_MINUTES:
        return False

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

    # While a secret is being rotated there are two signatures. One match is enough.
    return any(
        hmac.compare_digest(signature.encode(), expected.encode())
        for signature in signatures.split(" ")
    )
```

## A complete server

It reads the raw body, at most the 256 KiB an event can have, verifies it, skips events it already handled, and answers before it does the work. It remembers events in memory, so it loses them when it stops: use it to try things out. Save it next to the file above.

**Node.js** `server.mjs`:

```js
import { createServer } from "node:http";
import { verifyChatwiseWebhook } from "./verify.mjs";

const secret = process.env.CHATWISE_WEBHOOK_SECRET;
const MAX_BODY_BYTES = 256 * 1024; // The largest event Chatwise sends.

// In production, keep the events in your database: save one, answer, then do the work.
const handled = new Set();

async function handle(event) {
  if (event.type === "message.received") {
    console.log(`New message in conversation ${event.data.message.conversationId}`);
  }
}

async function receive(request, response) {
  // Anyone can send a request, so don't read more than an event can be.
  if (Number(request.headers["content-length"] ?? 0) > MAX_BODY_BYTES) {
    response.writeHead(413, { Connection: "close" }).end();
    return;
  }
  const chunks = [];
  let size = 0;
  for await (const chunk of request) {
    size += chunk.length;
    if (size > MAX_BODY_BYTES) throw new Error("The body is too large");
    chunks.push(chunk);
  }
  const rawBody = Buffer.concat(chunks);

  if (!verifyChatwiseWebhook(rawBody, request.headers, secret)) {
    response.writeHead(400).end();
    return;
  }

  // The same event can arrive more than once.
  const id = request.headers["webhook-id"];
  const isNew = !handled.has(id);
  handled.add(id);

  // Answer within 10 seconds, then do the work.
  response.writeHead(204).end();
  if (isNew) await handle(JSON.parse(rawBody));
}

const server = createServer((request, response) => {
  receive(request, response).catch((error) => {
    console.error(error.message);
    response.destroy();
  });
});

server.listen(Number(process.env.PORT ?? 3000));
```

**Python** `server.py`:

```python
import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from verify import verify_chatwise_webhook

SECRET = os.environ["CHATWISE_WEBHOOK_SECRET"]
MAX_BODY_BYTES = 256 * 1024  # The largest event Chatwise sends.

# In production, keep the events in your database: save one, answer, then do the work.
handled = set()


def handle(event):
    if event["type"] == "message.received":
        print(f"New message in conversation {event['data']['message']['conversationId']}", flush=True)


class Webhooks(BaseHTTPRequestHandler):
    timeout = 10  # Seconds a sender may take.

    def do_POST(self):
        # Anyone can send a request, so don't read more than an event can be.
        length = self.headers.get("Content-Length", "")
        if not length.isdecimal() or int(length) > MAX_BODY_BYTES:
            self.answer(413)
            return
        raw_body = self.rfile.read(int(length))

        if not verify_chatwise_webhook(raw_body, self.headers, SECRET):
            self.answer(400)
            return

        # The same event can arrive more than once.
        event_id = self.headers["webhook-id"]
        is_new = event_id not in handled
        handled.add(event_id)

        # Answer within 10 seconds, then do the work.
        self.answer(204)
        if is_new:
            handle(json.loads(raw_body))

    def answer(self, status):
        self.send_response(status)
        self.end_headers()
        self.wfile.flush()


ThreadingHTTPServer(("", int(os.environ.get("PORT", "3000"))), Webhooks).serve_forever()
```

Start it with the secret you got when you created the endpoint:

**Node.js**:

```bash
CHATWISE_WEBHOOK_SECRET='whsec_…' node server.mjs
```

**Python**:

```bash
CHATWISE_WEBHOOK_SECRET='whsec_…' python3 server.py
```

## In a framework

Many frameworks parse JSON before your code runs, and some refuse a body as large as an event can be. Get both right: the raw body, and a limit of at least 256 KiB. A request your framework refuses with a 413 is a failed delivery that [isn't retried](https://chatwise.so/docs/webhooks/delivery.md#what-each-answer-does).

| Framework | The raw body | Its limit for a body |
| --- | --- | --- |
| Express | `express.raw({ type: "application/json", limit: "300kb" })` on the route | Takes at most 100 KB by default, which is too little: always set `limit` |
| Next.js route handlers | `await request.text()` | Has no limit: answer 413 yourself when `content-length` is over 300 KB |
| Flask | `request.get_data()` | Has no limit by default: set `app.config["MAX_CONTENT_LENGTH"] = 300 * 1024` |
| FastAPI | `await request.body()` | Has no limit: answer 413 yourself when `content-length` is over 300 KB |

A proxy or a host in front of your server can have a limit of its own.

With Express, next to `verify.mjs`:

`express.mjs`:

```js
import express from "express";
import { verifyChatwiseWebhook } from "./verify.mjs";

const secret = process.env.CHATWISE_WEBHOOK_SECRET;
const app = express();

// The raw body, and room for the largest event (256 KiB): Express allows 100 KB unless you say otherwise.
const rawBody = express.raw({ type: "application/json", limit: "300kb" });

app.post("/webhooks/chatwise", rawBody, (request, response) => {
  // The body is only bytes if the request said it was JSON.
  if (!Buffer.isBuffer(request.body) || !verifyChatwiseWebhook(request.body, request.headers, secret)) {
    response.sendStatus(400);
    return;
  }

  // Skip events you already handled, by webhook-id, as in the complete server above.
  response.sendStatus(204);
  const event = JSON.parse(request.body);
  console.log(`Received ${event.type}`);
});

app.listen(Number(process.env.PORT ?? 3000));
```

## If it doesn't match

- The secret is another endpoint's, or it was [rotated](https://chatwise.so/docs/webhooks/secrets.md) more than 24 hours ago.
- The body was parsed, decoded or reformatted before it was verified.
- A proxy in front of your server changes the body or removes the `webhook-` headers.
- Your server's clock is more than five minutes off.

[Send a test event](https://chatwise.so/docs/webhooks/testing.md) to try again: it is signed like every other event.
