# Verificare le firme dei webhook

> Formspree Docs · Funzionalità avanzate · 28 febbraio 2026

Ecco come verificare le firme dei webhook di Formspree nel codice del tuo ricevitore.

Il dettaglio chiave è che Formspree **non** firma solo il body grezzo. Firma sia il timestamp che il body grezzo, in questo formato:

```
{timestamp}.{raw_body}
```

La firma viene inviata nell'header `Formspree-Signature` usando questo formato:

```
t=<unix>,v1=<hex>
```

## Requisiti chiave

- Usa il **body grezzo della richiesta** esattamente come ricevuto.
- Analizza l'header `Formspree-Signature` per estrarre `t` e `v1`.
- Calcola `HMAC_SHA256(secret, f"{t}.{raw_body}")` e confrontalo con `v1`.
- Facoltativo: rifiuta le richieste più vecchie di una finestra di tolleranza (protezione dai replay).

## Esempi di codice

Ecco alcuni frammenti di codice per aiutarti a iniziare.

### Python (Flask)

```python
import hmac
import hashlib
import time
from flask import Flask, request, abort

app = Flask(__name__)

SIGNING_SECRET = "your_signing_secret"  # Set this to the secret shown in Formspree

def verify_formspree_signature(secret, signature_header, raw_body, tolerance=300):
    if not signature_header:
        return False

    try:
        # Header format: "t=<unix>,v1=<hex>"
        parts = dict(item.split("=", 1) for item in signature_header.split(","))
        timestamp = int(parts.get("t", "0"))
        received_sig = parts.get("v1")
    except Exception:
        return False

    if not received_sig:
        return False

    # Optional: reject old requests to prevent replay attacks
    if abs(int(time.time()) - timestamp) > tolerance:
        return False

    # Formspree signs: "{timestamp}.{raw_body}"
    signed_payload = f"{timestamp}.{raw_body}"

    # Compute HMAC-SHA256 with the shared secret
    expected_sig = hmac.new(
        key=secret.encode("utf-8"),
        msg=signed_payload.encode("utf-8"),
        digestmod=hashlib.sha256,
    ).hexdigest()

    # Constant-time compare to avoid timing attacks
    return hmac.compare_digest(expected_sig, received_sig)

@app.post("/webhook")
def webhook():
    # Important: read the raw request body as sent
    raw_body = request.get_data(as_text=True)
    signature = request.headers.get("Formspree-Signature", "")

    if not verify_formspree_signature(SIGNING_SECRET, signature, raw_body):
        abort(401)

    return ("ok", 200)
```

### JavaScript (Node.js + Express)

```javascript
const crypto = require("crypto");
const express = require("express");
const app = express();

const SIGNING_SECRET = "your_signing_secret"; // Set this to the secret shown in Formspree

// Capture the raw body before JSON parsing changes it
app.use(express.json({
  verify: (req, res, buf) => {
    req.rawBody = buf.toString("utf8");
  }
}));

function verifyFormspreeSignature(secret, signatureHeader, rawBody, tolerance = 300) {
  if (!signatureHeader) return false;

  // Header format: "t=<unix>,v1=<hex>"
  const parts = Object.fromEntries(
    signatureHeader.split(",").map(s => s.split("=", 2))
  );
  const timestamp = parseInt(parts.t || "0", 10);
  const receivedSig = parts.v1;

  if (!receivedSig) return false;

  // Optional: reject old requests to prevent replay attacks
  const now = Math.floor(Date.now() / 1000);
  if (Math.abs(now - timestamp) > tolerance) return false;

  // Formspree signs: "{timestamp}.{raw_body}"
  const signedPayload = `${timestamp}.${rawBody}`;

  // Compute HMAC-SHA256 with the shared secret
  const expectedSig = crypto
    .createHmac("sha256", secret)
    .update(signedPayload, "utf8")
    .digest("hex");

  // Constant-time compare to avoid timing attacks
  return crypto.timingSafeEqual(
    Buffer.from(expectedSig, "utf8"),
    Buffer.from(receivedSig, "utf8")
  );
}

app.post("/webhook", (req, res) => {
  const signature = req.header("Formspree-Signature") || "";

  if (!verifyFormspreeSignature(SIGNING_SECRET, signature, req.rawBody)) {
    return res.status(401).send("invalid signature");
  }

  res.status(200).send("ok");
});

app.listen(3000);
```

## Risoluzione dei problemi e questioni comuni

Ecco alcuni errori comuni a cui prestare attenzione:

- **Ri-serializzare il JSON prima di firmare**: verifica rispetto ai byte del body grezzo della richiesta esattamente come ricevuti, poiché l'analisi e la ri-conversione in stringa del JSON cambieranno la sequenza di byte e renderanno invalido l'HMAC.
- **Firmare solo il body (manca il prefisso `t.`)**: come accennato sopra, Formspree firma insieme il timestamp e il payload, quindi devi calcolare l'HMAC su `t.<raw_body>` (incluso il delimitatore `t.`) anziché sul solo body.
- **Confrontare con l'intera stringa dell'header invece che con il valore `v1`**: estrai il valore della firma `v1` dall'header della firma e confronta solo quel digest esadecimale, non l'intero contenuto dell'header separato da virgole.
- **Usare un secret diverso dal `signing_secret` configurato per il webhook**: assicurati che il secret che usi per l'HMAC sia esattamente il signing secret del webhook preso dalle impostazioni del webhook di Formspree, non la tua API key o un altro secret del progetto.
