# Verify signatures

Every webhook GlobalyMint sends is signed with your endpoint's secret. Check the signature before you trust the body.

## What we send

| Header | Value |
| --- | --- |
| `x-mint-signature` | `t=1763424000,v1=5f2a…`: a Unix timestamp and an HMAC-SHA256 signature in hex |
| `x-mint-timestamp` | The same timestamp, in Unix seconds |

The signature is the HMAC-SHA256 of the string `{t}.{raw body}`, keyed with your endpoint's `whsec_` secret. The body is the exact bytes we sent.

## Verify with the SDK

The handler checks the signature and the timestamp, then calls your function. It answers 400 for a bad signature or a timestamp more than 5 minutes from now, 500 if your function throws (so we send the event again), and 200 otherwise.

```ts title="app/api/mint/webhooks/route.ts"
import { Mint } from '@globaly-inc/mint-sdk'

const mint = new Mint({ secretKey: process.env.MINT_SECRET_KEY! })

export const POST = mint.webhooks.handler({
  secret: process.env.MINT_WEBHOOK_SECRET!, // whsec_…
  on: {
    'invoice.paid': async (event) => {
      // event.id is stable: use it to skip duplicates.
      await grantAccess(event.data.customer_external_id)
    },
  },
})
```

> **Use the raw body.**
>
>
> Parsing the JSON first and serialising it again changes the bytes, and the signature will not match. Read the body as text, verify, then parse.
>

If your framework parses JSON before your code runs, read the body as a string for this route and verify it yourself:

```ts title="fastify.ts"
app.register(async (r) => {
  r.addContentTypeParser('application/json', { parseAs: 'string' }, (_req, body, done) => done(null, body))

  r.post('/webhooks/mint', async (req, reply) => {
    const event = await mint.webhooks
      .verify(req.body as string, req.headers['x-mint-signature'] as string | undefined, process.env.MINT_WEBHOOK_SECRET!)
      .catch(() => null)
    if (!event) return reply.status(400).send({ error: 'invalid signature' })
    await mint.webhooks.process(event)
    return { received: true }
  })
})
```

`verifyWebhook(rawBody, header, secret, { toleranceSec })` is also exported on its own and needs no client.

## Verify by hand

In any language:

1. Read `t` and every `v1` value from `x-mint-signature`.
2. Reject the request if `t` is more than 300 seconds from the current time.
3. Compute the HMAC-SHA256 of `t`, a full stop and the raw body, with your secret as the key, and write it as lowercase hex.
4. Compare it with each `v1` value using a constant-time comparison. Accept the request if any one matches.

**Node**

```js title="verify.mjs"
import { createHmac, timingSafeEqual } from 'node:crypto'

export function verifyMintSignature(rawBody, header, secret, toleranceSec = 300) {
  const parts = String(header ?? '').split(',').map((p) => p.trim().split('='))
  const t = Number(parts.find(([k]) => k === 't')?.[1])
  const signatures = parts.filter(([k]) => k === 'v1').map(([, v]) => v)
  if (!Number.isInteger(t) || signatures.length === 0) return false
  if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSec) return false

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

**Python**

```python title="verify.py"
import hashlib
import hmac
import time

def verify_mint_signature(raw_body: bytes, header: str, secret: str, tolerance_sec: int = 300) -> bool:
    parts = [p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p]
    timestamps = [v for k, v in parts if k == "t"]
    signatures = [v for k, v in parts if k == "v1"]
    if not timestamps or not timestamps[0].isdigit() or not signatures:
        return False
    t = int(timestamps[0])
    if abs(int(time.time()) - t) > tolerance_sec:
        return False

    signed = str(t).encode() + b"." + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, s) for s in signatures)
```

**Go**

```go title="verify.go"
package mint

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

func VerifyMintSignature(rawBody []byte, header, secret string, tolerance time.Duration) bool {
	var ts string
	var signatures []string
	for _, part := range strings.Split(header, ",") {
		k, v, ok := strings.Cut(strings.TrimSpace(part), "=")
		if !ok {
			continue
		}
		switch k {
		case "t":
			ts = v
		case "v1":
			signatures = append(signatures, v)
		}
	}
	t, err := strconv.ParseInt(ts, 10, 64)
	if err != nil || len(signatures) == 0 {
		return false
	}
	if math.Abs(float64(time.Now().Unix()-t)) > tolerance.Seconds() {
		return false
	}

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(ts + "."))
	mac.Write(rawBody)
	expected := []byte(hex.EncodeToString(mac.Sum(nil)))
	for _, s := range signatures {
		if hmac.Equal(expected, []byte(s)) {
			return true
		}
	}
	return false
}
```

## Rotating a secret

Rotate a secret in the dashboard under Developers › Webhooks, or with `POST /api/v1/webhook-endpoints/{id}/rotate-secret`. The new secret is shown once.

For 24 hours after a rotation we sign every delivery with both secrets. The header carries two `v1` values, the new secret's first, and a delivery is valid if either matches. The SDK accepts any matching `v1`, and so do the samples above, so you can switch to the new secret at any point in those 24 hours without a failed delivery.

Once the new secret is deployed, you can end the overlap early from the dashboard or with `POST /api/v1/webhook-endpoints/{id}/end-secret-overlap`. After that only the new secret signs.

## Handle duplicates

A valid signature proves who sent the event, not that you have not seen it. Store `event.id` and skip repeats. See [Receive events](/docs/webhooks#handle-duplicates-and-order).

## Troubleshooting

| What you see | Likely cause |
| --- | --- |
| `invalid_signature` | The body was parsed and re-serialised before verifying, or the secret belongs to another endpoint or mode. |
| `timestamp_out_of_tolerance` | Your server's clock is wrong, or the request was held in a queue for more than 5 minutes before you verified it. |
| `malformed_header` | The `x-mint-signature` header is missing. Check that a proxy is not removing it. |
| `malformed_payload` | The signature matched but the body is not an event. This should not happen; tell us. |

These are the `code` values on the SDK's `WebhookVerificationError`.
