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

# Verify signatures

> Validate the Routa-Signature header to make sure each webhook came from Routa and was not changed.

Anyone who knows your endpoint URL can send a request to it. The signature proves that the event came from Routa and that the body was not modified. **Always verify it before you process the event.**

## The header

```http theme={null}
Routa-Signature: t=1757000000,v1=9f86d0818...
```

| Part | Description |
| - | - |
| `t` | Unix timestamp, in seconds, of the moment Routa signed the delivery. |
| `v1` | Signature in hexadecimal. There can be more than one `v1=` during a secret rotation (see below). |

The signature is computed like this:

```text theme={null}
v1 = HMAC-SHA256(secret, "{t}.{raw_body}")   // hex result
```

## How to verify

**1. Read the raw body**

Use the bytes **exactly as they arrived**. If you parse and serialize the JSON again, the bytes change and the signature does not match.

**2. Check the timestamp**

Reject the delivery if `t` is more than **5 minutes** away from the current time. This protects against a captured request being replayed.

**3. Compute the HMAC**

Compute the HMAC-SHA256 of `"{t}.{raw_body}"` with the endpoint `secret`.

**4. Compare in constant time**

Compare with **each** `v1` value of the header using a constant-time comparison. One match is enough.

## With the SDK

`constructEvent` does all of this, makes no network calls and returns the typed event.

```ts theme={null}
import { Routa, RoutaSignatureVerificationError } from '@routa-chat/sdk'

const routa = new Routa({ apiKey: process.env['ROUTA_API_KEY']! })
const signingSecret = process.env['ROUTA_WEBHOOK_SECRET']!

// Works with any framework that hands you a Fetch API `Request`.
export async function handleWebhook(request: Request): Promise<Response> {
  const rawBody = await request.text()

  try {
    const event = await routa.webhooks.constructEvent(
      rawBody,
      request.headers.get('routa-signature'),
      signingSecret
    )

    switch (event.type) {
      case 'message.delivered':
        console.log('delivered', event.data)
        break
      case 'message.failed':
        console.log('failed', event.data)
        break
    }

    return new Response(null, { status: 200 })
  } catch (error) {
    if (error instanceof RoutaSignatureVerificationError) {
      return new Response('Invalid signature', { status: 400 })
    }
    throw error
  }
}
```

See more in [Webhooks in the SDK](https://docs.routa.chat/en/sdk/webhooks.md).

## Without the SDK

```ts Node.js theme={null}
import { createHmac, timingSafeEqual } from 'node:crypto'

const TOLERANCE_SECONDS = 5 * 60

export function verifyRoutaSignature(
  rawBody: string,
  header: string | null,
  secrets: string[]
): boolean {
  if (!header) return false

  let timestamp = NaN
  const signatures: string[] = []
  for (const part of header.split(',')) {
    const [key, value] = part.trim().split('=')
    if (key === 't') timestamp = Number.parseInt(value ?? '', 10)
    if (key === 'v1' && value) signatures.push(value)
  }
  if (Number.isNaN(timestamp) || signatures.length === 0) return false

  const age = Math.abs(Date.now() / 1000 - timestamp)
  if (age > TOLERANCE_SECONDS) return false

  return secrets.some((secret) => {
    const expected = createHmac('sha256', secret)
      .update(`${timestamp}.${rawBody}`)
      .digest()
    return signatures.some((signature) => {
      const received = Buffer.from(signature, 'hex')
      return received.length === expected.length && timingSafeEqual(received, expected)
    })
  })
}
```

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

TOLERANCE_SECONDS = 5 * 60


def verify_routa_signature(raw_body: bytes, header: str | None, secrets: list[str]) -> bool:
    if not header:
        return False

    timestamp = None
    signatures = []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t" and value.isdigit():
            timestamp = int(value)
        elif key == "v1" and value:
            signatures.append(value)
    if timestamp is None or not signatures:
        return False

    if abs(time.time() - timestamp) > TOLERANCE_SECONDS:
        return False

    signed = f"{timestamp}.".encode() + raw_body
    for secret in secrets:
        expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
        if any(hmac.compare_digest(expected, signature) for signature in signatures):
            return True
    return False
```

> [!WARNING]
>
> Never compare signatures with `==`. A comparison that stops at the first different byte lets someone find the correct signature by timing your responses.

## Secret rotation

To change the secret without losing events, call `POST /v1/webhook_endpoints/{id}/rotate_secret`. The response carries the new `secret`.

* For **24 hours**, both secrets (the new one and the previous one) sign deliveries, and the header carries two `v1=` values.
* During that time, validate with both secrets. The SDK accepts a list: `constructEvent(rawBody, header, [newSecret, previousSecret])`.
* After the window, the old secret stops being valid.

```bash theme={null}
curl -X POST https://api.routa.chat/v1/webhook_endpoints/whe_01J8.../rotate_secret \
  -H "Authorization: Bearer $ROUTA_API_KEY"
```

## Common problems

> [accordion] The signature never matches
>
> It is almost always the body: a middleware already parsed the JSON and you are using its serialization. Configure your framework to expose the raw body on the webhook route (`express.raw({ type: 'application/json' })`, for example).

> [accordion] It works in tests but fails in production
>
> Check that you use the secret of the right endpoint. Each one has its own. Also check that the server clock is synchronized, since the tolerance is 5 minutes.

> [accordion] It fails right after rotating the secret
>
> Validate with both the new secret and the previous one until the 24-hour window ends.


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