> For the complete documentation index, see [llms.txt](https://docs.tokenbot.com/home/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tokenbot.com/home/api-docs/webhooks/security.md).

# Security

## Signature Verification

Every webhook delivery is signed so you can verify it came from TokenBot. Each request includes these headers:

| Header                   | Description                                 |
| ------------------------ | ------------------------------------------- |
| `X-TokenBot-Signature`   | `sha256=<hex_digest>` HMAC of the payload   |
| `X-TokenBot-Timestamp`   | Unix seconds when the signature was created |
| `X-TokenBot-Event`       | The event type (e.g. `trade.executed`)      |
| `X-TokenBot-Delivery-Id` | Unique delivery ID (use for idempotency)    |

### How It Works

1. TokenBot builds the string `${timestamp}.${raw_body}`.
2. It computes `HMAC-SHA256(secret, that_string)` and sends it as `X-TokenBot-Signature: sha256=<hex>`, with the timestamp in `X-TokenBot-Timestamp`.
3. You recompute the same HMAC and compare in constant time.
4. Reject deliveries whose timestamp is older than your tolerance (TokenBot uses a 5-minute replay window).

### Node.js Example

```javascript
const crypto = require('crypto');

function verifyWebhook(rawBody, signature, timestamp, secret, toleranceSeconds = 300) {
  // Reject stale deliveries
  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - Number(timestamp)) > toleranceSeconds) return false;

  const expected = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(`${timestamp}.${rawBody}`, 'utf8')
    .digest('hex');

  return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}

// Express middleware (note: raw body is required)
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  const ok = verifyWebhook(
    req.body,
    req.headers['x-tokenbot-signature'],
    req.headers['x-tokenbot-timestamp'],
    process.env.WEBHOOK_SECRET
  );
  if (!ok) return res.status(401).send('Invalid signature');

  const event = JSON.parse(req.body);
  // Process event...
  res.status(200).send('OK');
});
```

### Python Example

```python
import hmac, hashlib, time

def verify_webhook(raw_body: bytes, signature: str, timestamp: str, secret: str, tolerance=300) -> bool:
    if abs(int(time.time()) - int(timestamp)) > tolerance:
        return False
    signed = f"{timestamp}.".encode() + raw_body
    expected = 'sha256=' + hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature, expected)
```

## Secrets

Webhook signing secrets are prefixed `whsec_` and are shown **only once**, when the webhook is created. Rotate a secret with `POST /v1/webhooks/:id/rotate-secret` (the previous secret keeps working for a short grace window).

## Best Practices

* Always verify signatures **and** the timestamp before processing events.
* Use `crypto.timingSafeEqual` (Node.js) or `hmac.compare_digest` (Python) to prevent timing attacks.
* Deduplicate using `X-TokenBot-Delivery-Id` (or the payload's `event_id`).
* Respond with `2xx` quickly; process events asynchronously.


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.tokenbot.com/home/api-docs/webhooks/security.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
