# Verificar a assinatura (https://docs.pongzap.com/webhooks/verificar-assinatura)

Qualquer pessoa que descubra a URL do seu endpoint pode mandar um `POST` para ela. Por isso **todo evento é assinado** no padrão aberto [Standard Webhooks](https://www.standardwebhooks.com), e o seu receptor deve recusar o que não conferir.

## Os headers [#os-headers]

| Header | O que é |
|---|---|
| `webhook-id` | O `id` do evento (`evt_…`), o mesmo em todas as tentativas |
| `webhook-timestamp` | Segundos desde 1970 (Unix) do momento deste envio |
| `webhook-signature` | `v1,` seguido da assinatura em base64. Pode vir mais de uma, separadas por espaço |

A assinatura é o HMAC-SHA256 de `{webhook-id}.{webhook-timestamp}.{corpo}`, com a chave igual aos bytes do base64 que vem depois de `whsec_` no `secret` do endpoint.

## Regras [#regras]

1. **Use o corpo cru**, byte a byte como chegou, antes de qualquer parse de JSON. Reserializar muda os bytes e a assinatura não confere.
2. **Recuse timestamps com mais de 5 minutos** de diferença do seu relógio, para que alguém não reenvie um evento antigo capturado.
3. **Compare em tempo constante** (`timingSafeEqual`, `hmac.compare_digest`, `hash_equals`).
4. Aceite se **qualquer uma** das assinaturas do header conferir.

## Com uma biblioteca [#com-uma-biblioteca]

As bibliotecas oficiais do Standard Webhooks fazem tudo isso:

<Tabs items={['Node.js', 'Python', 'PHP', 'Go']}>
<Tab value="Node.js">

```sh
npm install standardwebhooks
```

```js
import { Webhook } from 'standardwebhooks';

const wh = new Webhook(process.env.PONGZAP_WEBHOOK_SECRET); // whsec_…

app.post('/webhooks/pongzap', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = wh.verify(req.body, req.headers); // corpo cru (Buffer) e os headers
  } catch {
    return res.sendStatus(401);
  }
  // event.type, event.data…
  res.sendStatus(204);
});
```

</Tab>
<Tab value="Python">

```sh
pip install standardwebhooks
```

```python
from standardwebhooks.webhooks import Webhook

wh = Webhook(os.environ["PONGZAP_WEBHOOK_SECRET"])  # whsec_…

@app.post("/webhooks/pongzap")
def pongzap():
    try:
        event = wh.verify(request.get_data(), dict(request.headers))
    except Exception:
        return "", 401
    # event["type"], event["data"]…
    return "", 204
```

</Tab>
<Tab value="PHP">

```sh
composer require standard-webhooks/standard-webhooks
```

```php
<?php
use StandardWebhooks\Webhook;

$wh = new Webhook(getenv('PONGZAP_WEBHOOK_SECRET')); // whsec_…

try {
    // A biblioteca procura os headers em minúsculas (webhook-id…).
    $headers = array_change_key_case(getallheaders(), CASE_LOWER);
    $event = $wh->verify(file_get_contents('php://input'), $headers);
} catch (Exception $e) {
    http_response_code(401);
    exit;
}
// $event['type'], $event['data']…
http_response_code(204);
```

</Tab>
<Tab value="Go">

```sh
go get github.com/standard-webhooks/standard-webhooks/libraries
```

```go
import standardwebhooks "github.com/standard-webhooks/standard-webhooks/libraries/go"

wh, _ := standardwebhooks.NewWebhook(os.Getenv("PONGZAP_WEBHOOK_SECRET")) // whsec_…

func pongzap(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)
	if err := wh.Verify(body, r.Header); err != nil {
		w.WriteHeader(http.StatusUnauthorized)
		return
	}
	// json.Unmarshal(body, &event)…
	w.WriteHeader(http.StatusNoContent)
}
```

</Tab>
</Tabs>

## Sem biblioteca [#sem-biblioteca]

```js
import crypto from 'node:crypto';

function verify(rawBody, headers, secret) {
  const id = headers['webhook-id'];
  const ts = headers['webhook-timestamp'];
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) throw new Error('timestamp fora da janela');

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = 'v1,' + crypto.createHmac('sha256', key).update(`${id}.${ts}.`).update(rawBody).digest('base64');

  const ok = headers['webhook-signature'].split(' ').some(
    (sig) => sig.length === expected.length && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected)),
  );
  if (!ok) throw new Error('assinatura inválida');
  return JSON.parse(rawBody);
}
```

Para conferir a sua implementação, este vetor do próprio padrão precisa dar certo:

| | |
|---|---|
| `secret` | `whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw` |
| `webhook-id` | `msg_p5jXN8AQM9LWM0D4loKWxJek` |
| `webhook-timestamp` | `1614265330` |
| corpo | `{"test": 2432232314}` |
| `webhook-signature` | `v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=` |

(Ignore a janela de 5 minutos nesse teste: o timestamp é de 2021.)
