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

# Verificar firmas

Confirma que cada solicitud provino de Violet y no fue modificada en el camino.

Cada solicitud se firma con el secreto de firma del webhook, para que puedas confirmar que provino de Violet y no fue modificada en el camino.

El `Violet-Signature` encabezado tiene este aspecto `t=1792951514,v1=5f2b…`:

* `t` es la hora de este intento, en segundos Unix. Es nuevo en cada reintento.
* `v1` es un HMAC-SHA256 hexadecimal de la cadena `<t>.<raw request body>`, generado con tu secreto. Usa el secreto completo, incluido su `whsec_` prefijo.

Para verificar una solicitud:

1. Lee los bytes del cuerpo sin procesar antes de cualquier análisis JSON.
2. Rechaza la solicitud si `t` está a más de 5 minutos de tu reloj.
3. Calcula el HMAC y compáralo con cada `v1` valor. Acepta la solicitud si alguno coincide. Como buena práctica, compara el HMAC usando la función de tiempo constante de tu lenguaje (`crypto.timingSafeEqual` en Node.js, `hmac.compare_digest` en Python) en lugar de `==`, para que los tiempos de respuesta no den pistas sobre cuán cerca está una firma falsificada.

{% tabs %}
{% tab title="Node.js" %}

```javascript
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verify(rawBody, header, secret, toleranceSeconds = 300) {
  const parts = header.split(',').map((p) => p.split('='));
  const t = Number(parts.find(([k]) => k === 't')?.[1]);
  if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
  const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest();
  return parts
    .filter(([k]) => k === 'v1')
    .some(([, sig]) => {
      const given = Buffer.from(sig, 'hex');
      return given.length === expected.length && timingSafeEqual(given, expected);
    });
}
```

{% endtab %}

{% tab title="Python" %}

```python
import hashlib, hmac, time

def verify(raw_body: bytes, header: str, secret: str, tolerance_seconds: int = 300) -> bool:
    parts = [p.split("=", 1) for p in header.split(",")]
    t = next((v for k, v in parts if k == "t"), None)
    if not t or abs(time.time() - int(t)) > tolerance_seconds:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(v, expected) for k, v in parts if k == "v1")
```

{% endtab %}
{% endtabs %}

## Rotación del secreto

El secreto se muestra una sola vez, cuando creas el webhook o rotas su secreto. Durante las 24 horas posteriores a una rotación, las solicitudes llevan dos `v1` valores: uno firmado con el nuevo secreto y otro con el antiguo. Cambia tu receptor al nuevo secreto dentro de ese periodo.

Solo la rotación más reciente mantiene la firma con el secreto antiguo. Si rotas dos veces en 24 horas, el primer secreto antiguo deja de funcionar de inmediato, así que cambia al secreto más reciente antes de rotar de nuevo.

Los encabezados personalizados no forman parte de la firma; la firma solo cubre el cuerpo.


---

# 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.violetlabs.com/es/funciones/api/webhooks-salientes/verificar-firmas.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.
