# Verify the signature

- Section: Webhooks (TTF API reference)
- Source: https://ttf.bot/developers/docs/#webhook-signatures
- The whole reference as one text: https://ttf.bot/developers/docs/llms-full.txt

Anyone can POST to your server. The signature proves the body came from TTF and was not changed.

## How it works

1. Take the `X-TTF-Timestamp` header and the **raw** body bytes (exactly as received, not re-encoded JSON).
2. Compute HMAC-SHA256 with your endpoint secret (the whole `whsec_...` text) as the key, over `timestamp + "." + body`. Write it as lower-case hex.
3. Compare it, in constant time, with each `v1=` value of `X-TTF-Signature`. One match = valid.
4. Refuse a timestamp more than 300 seconds (5 minutes) from your clock: that stops replays of an old delivery.

## Python

```python
import hashlib
import hmac
import re
import time

_HEX64 = re.compile(r'[0-9a-f]{64}')


def verify_ttf_signature(secret, headers, body, tolerance=300, now=None):
    """secret: your 'whsec_...' text; headers: the request headers; body: the RAW body (bytes).
    Returns True or False, never raises."""
    h = {str(k).lower(): str(v) for k, v in headers.items()}
    try:
        ts = int(h['x-ttf-timestamp'])
    except (KeyError, ValueError):
        return False
    if abs((time.time() if now is None else now) - ts) > tolerance:
        return False
    expected = hmac.new(secret.encode('utf-8'), f'{ts}.'.encode('ascii') + body, hashlib.sha256).hexdigest()
    for part in h.get('x-ttf-signature', '').split(','):
        scheme, _, value = part.strip().partition('=')
        if scheme == 'v1' and _HEX64.fullmatch(value) and hmac.compare_digest(value, expected):
            return True
    return False
```

## Node.js

Read the raw body (for Express: `express.raw({type: 'application/json'})`), never the parsed JSON.

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

// secret: your 'whsec_...' text; headers: lower-case header names; rawBody: a Buffer of the RAW body
function verifyTtfSignature(secret, headers, rawBody, toleranceSec = 300, nowSec = Date.now() / 1000) {
  const ts = Number(headers['x-ttf-timestamp']);
  if (!Number.isInteger(ts) || Math.abs(nowSec - ts) > toleranceSec) return false;
  const expected = crypto.createHmac('sha256', secret).update(`${ts}.`).update(rawBody).digest('hex');
  return String(headers['x-ttf-signature'] || '').split(',').some((part) => {
    const [scheme, value] = part.trim().split('=');
    return scheme === 'v1' && /^[0-9a-f]{64}$/.test(value || '') &&
      crypto.timingSafeEqual(Buffer.from(value, 'ascii'), Buffer.from(expected, 'ascii'));
  });
}

module.exports = { verifyTtfSignature };
```

## Test it with these values

Your function must return **true** for this request (we test our own examples against the same values):

| Field | Value |
| --- | --- |
| Secret | `whsec_dGVzdC12ZWN0b3Itc2VjcmV0LWZvci10dGYtZG9jcy0` |
| X-TTF-Timestamp | `1795001500` |
| Body (raw bytes, UTF-8) | `{"id":"01JDR4W4D5E6F7G8H9J0K1L2M3","type":"ping","created_ms":1795001500000,"reason":"test","event":{"v":1,"id":"01JDR4W4N5M6B7V8C9X0Z1A2S3","type":"ping","ts":1795001500000,"data":{"text":"Test delivery from TTF"}}}` |
| X-TTF-Signature | `v1=33997caf7b21de24aa31c7754caaef491dd8c36664897a9ac5b60ed5cac1b36b` |
| Your clock (now) | `1795001530` |

And **false** when one byte of the body changes, the secret is different, or the timestamp is older than 5 minutes.
