# Verify signatures

Check that a webhook really came from Mestra, with code for Node, Python and Go.

Anyone who knows your endpoint's address can send it a request. Check the signature on every request before you trust it.

## The header

Each request carries a `Mestra-Signature` header:

```
Mestra-Signature: t=1792595940,v1=07a779236830a90ea32ac9fc4a9f5c10a6cea994997bc4e3e3bc5810bb580bff
```

- `t` is the time Mestra signed the request, in Unix seconds.
- `v1` is a signature, in hex. It is the HMAC-SHA256 of the text `<t>.<raw body>`, keyed with your endpoint's secret, the whole `whsec_…` string.

Every attempt is signed afresh with a new `t`, so a retry has a different header from the first try.

## How to check

1. Split the header on `,`, then on `=`. Take `t` and every `v1`.
2. Compute the HMAC-SHA256 of `t`, a full stop, and the **raw** request body, keyed with your secret.
3. Compare it to each `v1` in constant time. Accept if any one matches.
4. Reject if `t` is more than 5 minutes from your clock, in either direction. This stops someone replaying an old request.

Use the body exactly as it arrived. If your framework parses the JSON first and you serialise it again, the bytes change and the check fails.

### Rolling a secret

While you [roll a secret](https://withmestra.com/docs/webhooks/endpoints/#roll-the-secret) and keep the old one, the header has a `v1` for each: `t=…,v1=<new>,v1=<old>`. Accepting a match on any `v1` lets you update your receiver before or after the roll, and lose nothing.

## Node

```js
const crypto = require('node:crypto');

// rawBody must be the exact bytes received, not re-serialised JSON.
function verify(rawBody, header, secret, toleranceSec = 300) {
  const parts = header.split(',').map((p) => p.split('='));
  const t = parts.find(([k]) => k === 't')?.[1];
  const sigs = parts.filter(([k]) => k === 'v1').map(([, v]) => v);
  if (!t || sigs.length === 0) return false;
  if (!/^\d+$/.test(t) || Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) return false;
  const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
  return sigs.some((s) => {
    const got = Buffer.from(s, 'hex');
    return got.length === expected.length && crypto.timingSafeEqual(got, expected);
  });
}

// In Express, keep the raw body: app.post('/hooks/mestra', express.raw({ type: 'application/json' }), (req, res) => {
//   if (!verify(req.body, req.get('Mestra-Signature') ?? '', process.env.MESTRA_WEBHOOK_SECRET)) return res.sendStatus(400);
//   res.sendStatus(200); // then do the work
// });
```

## Python

```python
import hashlib, hmac, sys, time


def verify(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    """raw_body must be the exact bytes received, not re-serialised JSON."""
    pairs = [p.split("=", 1) for p in header.split(",") if "=" in p]
    t = next((v for k, v in pairs if k == "t"), None)
    sigs = [v for k, v in pairs if k == "v1"]
    if t is None or not t.isdigit() or not sigs:
        return False
    if abs(time.time() - int(t)) > tolerance:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(s, expected) for s in sigs)
```

## Go

```go
package webhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"
)

// Verify checks a Mestra-Signature header. body must be the exact bytes received.
func Verify(body []byte, header, secret string, tolerance time.Duration) bool {
	var t string
	var sigs []string
	for _, part := range strings.Split(header, ",") {
		k, v, ok := strings.Cut(strings.TrimSpace(part), "=")
		if !ok {
			continue
		}
		switch k {
		case "t":
			t = v
		case "v1":
			sigs = append(sigs, v)
		}
	}
	sec, err := strconv.ParseInt(t, 10, 64)
	if err != nil || len(sigs) == 0 {
		return false
	}
	if d := time.Since(time.Unix(sec, 0)); d > tolerance || d < -tolerance {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(t + "."))
	mac.Write(body)
	expected := mac.Sum(nil)
	for _, s := range sigs {
		if got, err := hex.DecodeString(s); err == nil && hmac.Equal(got, expected) {
			return true
		}
	}
	return false
}
```

## Check by hand with openssl

To test your secret and a saved request, compute the signature in a shell. Save the body to `body.json` and the header to `header.txt`:

```sh
#!/bin/sh
# usage: verify.sh body.json header.txt
secret=whsec_testsecret123
t=$(sed -E 's/.*t=([0-9]+).*/\1/' "$2")
expected=$( { printf '%s.' "$t"; cat "$1"; } | openssl dgst -sha256 -hmac "$secret" | awk '{print $NF}')
if tr ',' '\n' < "$2" | grep -qx "v1=$expected"; then echo accept; else echo reject; fi
```

`accept` means one `v1` matches. This check doesn't look at `t`, so also compare it with the current time before you trust a request.

## If it doesn't match

- Use the raw body, not parsed and re-serialised JSON.
- Use the whole secret, including `whsec_`, for the endpoint that sent the request.
- Check for a trailing newline or changed encoding added by a proxy.
- Check your server's clock.
- After a roll, make sure the secret is the new one, or accept either while the old one is live.
