> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usequotable.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify signatures

> Check the HMAC-SHA256 signature and timestamp on every webhook delivery before you trust it, with ready-to-use Node.js, Python and Go code.

Anyone who learns your endpoint URL can send it requests. The signature proves a delivery came from Quotable and wasn't changed on the way. Verify it on every request, before you parse or act on the body.

## How signing works

Every delivery carries two headers:

```http theme={"system"}
X-Quotable-Timestamp: 1790848845
X-Quotable-Signature: v1=37f5c8253d96e937ba1361d173c0b1c0b3e5b981453468ce6069585b42d861c3
```

The signature is computed like this:

1. Build the signed payload: the timestamp, a period, and the **raw request body**: `<timestamp>.<raw body>`.
2. Compute an HMAC with SHA-256, using your endpoint's **signing secret** as the key. The key is the full secret string, including its `whsec_` prefix.
3. Hex-encode the result (64 lowercase characters) and prefix it with `v1=`.

During a [secret rotation](#secret-rotation), the header carries two signatures separated by a comma, one per secret:

```http theme={"system"}
X-Quotable-Signature: v1=<signature with new secret>,v1=<signature with previous secret>
```

## Verify a delivery

**1. Read the raw body**

Use the exact bytes you received. Parsing the JSON and serializing it again changes whitespace and key order, and the signature won't match.

**2. Check the timestamp**

Reject the delivery if `X-Quotable-Timestamp` is more than **300 seconds** (5 minutes) away from your server's clock. This stops someone from replaying a captured delivery later.

**3. Compute and compare**

Compute the expected signature and compare it with **every** `v1=` value in `X-Quotable-Signature`, using a constant-time comparison. Accept the delivery if any one matches.

**4. Deduplicate**

After the signature checks out, skip the event if you've already processed its `id`. Deliveries are at-least-once.

Answer `401` or `400` when verification fails. Quotable treats that as a failed attempt and retries, which is what you want if your secret was briefly out of date.

## Code

```typescript Node.js (TypeScript) theme={"system"}
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 300;

export function verifyQuotableSignature(
  secret: string,
  rawBody: string | Buffer,
  signatureHeader: string | null | undefined,
  timestampHeader: string | null | undefined,
): boolean {
  if (!signatureHeader || !timestampHeader) return false;

  const timestamp = Number(timestampHeader);
  if (!Number.isInteger(timestamp) || timestamp <= 0) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > TOLERANCE_SECONDS) {
    return false;
  }

  const expected = createHmac("sha256", secret)
    .update(`${timestamp}.`)
    .update(rawBody)
    .digest();

  return signatureHeader
    .split(",")
    .map((part) => part.trim())
    .filter((part) => part.startsWith("v1="))
    .some((part) => {
      const offered = Buffer.from(part.slice(3), "hex");
      return offered.length === expected.length && timingSafeEqual(offered, expected);
    });
}
```

```python Python theme={"system"}
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300

def verify_quotable_signature(secret: str, raw_body: bytes,
                              signature_header: str | None,
                              timestamp_header: str | None) -> bool:
    if not signature_header or not timestamp_header:
        return False
    try:
        timestamp = int(timestamp_header)
    except ValueError:
        return False
    if timestamp <= 0 or abs(int(time.time()) - timestamp) > TOLERANCE_SECONDS:
        return False

    signed = f"{timestamp}.".encode() + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()

    offered = [
        part.strip()[3:]
        for part in signature_header.split(",")
        if part.strip().startswith("v1=")
    ]
    return any(hmac.compare_digest(sig, expected) for sig in offered)
```

```go Go theme={"system"}
package quotable

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

const toleranceSeconds = 300

func VerifySignature(secret string, rawBody []byte, signatureHeader, timestampHeader string) bool {
	if signatureHeader == "" || timestampHeader == "" {
		return false
	}
	timestamp, err := strconv.ParseInt(timestampHeader, 10, 64)
	if err != nil || timestamp <= 0 {
		return false
	}
	if math.Abs(float64(time.Now().Unix()-timestamp)) > toleranceSeconds {
		return false
	}

	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(strconv.FormatInt(timestamp, 10) + "."))
	mac.Write(rawBody)
	expected := mac.Sum(nil)

	for _, part := range strings.Split(signatureHeader, ",") {
		part = strings.TrimSpace(part)
		if !strings.HasPrefix(part, "v1=") {
			continue
		}
		offered, err := hex.DecodeString(part[3:])
		if err == nil && hmac.Equal(offered, expected) {
			return true
		}
	}
	return false
}
```

## Get the raw body in your framework

Most frameworks parse JSON for you, which throws the raw bytes away. Read the raw body first, verify, then parse.

> [tab] Next.js (App Router)
>
> ```typescript app/api/quotable-webhook/route.ts theme={"system"}
> import { verifyQuotableSignature } from "@/lib/quotable-webhook";
>
> export async function POST(request: Request) {
>   const rawBody = await request.text();
>   const ok = verifyQuotableSignature(
>     process.env.QUOTABLE_WEBHOOK_SECRET!,
>     rawBody,
>     request.headers.get("x-quotable-signature"),
>     request.headers.get("x-quotable-timestamp"),
>   );
>   if (!ok) return new Response("invalid signature", { status: 401 });
>
>   const event = JSON.parse(rawBody);
>   // Deduplicate on event.id, then hand off slow work.
>   console.log("received", event.type, event.id);
>   return new Response(null, { status: 204 });
> }
> ```
>
> Don't call `request.json()` before verifying: once the body is consumed as JSON, you can't get the original bytes back.

> [tab] Express
>
> ```javascript server.js theme={"system"}
> import express from "express";
> import { verifyQuotableSignature } from "./quotable-webhook.js";
>
> const app = express();
>
> // Raw body for this route only. Register it before any app-wide express.json().
> app.post(
>   "/hooks/quotable",
>   express.raw({ type: "application/json" }),
>   (req, res) => {
>     const ok = verifyQuotableSignature(
>       process.env.QUOTABLE_WEBHOOK_SECRET,
>       req.body, // a Buffer
>       req.get("x-quotable-signature"),
>       req.get("x-quotable-timestamp"),
>     );
>     if (!ok) return res.status(401).send("invalid signature");
>
>     const event = JSON.parse(req.body.toString("utf8"));
>     console.log("received", event.type, event.id);
>     res.sendStatus(204);
>   },
> );
>
> app.listen(3000);
> ```

> [tab] Flask
>
> ```python app.py theme={"system"}
> import json
> import os
> from flask import Flask, request
> from quotable_webhook import verify_quotable_signature
>
> app = Flask(__name__)
>
> @app.post("/hooks/quotable")
> def quotable_webhook():
>     raw_body = request.get_data()  # bytes, before any parsing
>     ok = verify_quotable_signature(
>         os.environ["QUOTABLE_WEBHOOK_SECRET"],
>         raw_body,
>         request.headers.get("X-Quotable-Signature"),
>         request.headers.get("X-Quotable-Timestamp"),
>     )
>     if not ok:
>         return "invalid signature", 401
>
>     event = json.loads(raw_body)
>     print("received", event["type"], event["id"])
>     return "", 204
> ```

> [tab] FastAPI
>
> ```python main.py theme={"system"}
> import json
> import os
> from fastapi import FastAPI, Request, Response
> from quotable_webhook import verify_quotable_signature
>
> app = FastAPI()
>
> @app.post("/hooks/quotable")
> async def quotable_webhook(request: Request):
>     raw_body = await request.body()
>     ok = verify_quotable_signature(
>         os.environ["QUOTABLE_WEBHOOK_SECRET"],
>         raw_body,
>         request.headers.get("x-quotable-signature"),
>         request.headers.get("x-quotable-timestamp"),
>     )
>     if not ok:
>         return Response("invalid signature", status_code=401)
>
>     event = json.loads(raw_body)
>     print("received", event["type"], event["id"])
>     return Response(status_code=204)
> ```

## Test your implementation

Run your verifier against this known-good input. Disable the timestamp check for this test, since the timestamp is in the past.

| Input | Value |
| - | - |
| Secret | `whsec_test` |
| `X-Quotable-Timestamp` | `1790848845` |
| Raw body | `{"id":"5d1e7a3c-2b4f-4c6e-8a0d-9f1b3c5e7a20","type":"tracking.run.finalized"}` |
| Expected `X-Quotable-Signature` | `v1=37f5c8253d96e937ba1361d173c0b1c0b3e5b981453468ce6069585b42d861c3` |

You can reproduce the signature from a shell:

```bash theme={"system"}
printf '%s' '1790848845.{"id":"5d1e7a3c-2b4f-4c6e-8a0d-9f1b3c5e7a20","type":"tracking.run.finalized"}' \
  | openssl dgst -sha256 -hmac 'whsec_test' -hex
```

## Secret rotation

When you select **Rotate secret** for an endpoint, Quotable shows a new secret once. For the next **24 hours**, every delivery carries two signatures: one with the new secret and one with the previous secret. A verifier that accepts any matching `v1=` value keeps working with either secret, so you can deploy the new one at any point in that window.

After 24 hours, only the new secret signs. Deliveries checked against the old secret then fail and are retried, so update your verifier before the window ends. See [Manage endpoints](https://docs.usequotable.com/webhooks/manage-endpoints.md#rotate-the-signing-secret).

## Security checklist

> [accordion] Use a constant-time comparison
>
> Compare signatures with `timingSafeEqual` (Node.js), `hmac.compare_digest` (Python) or `hmac.Equal` (Go). A plain `===` or `==` leaks timing information.

> [accordion] Keep the timestamp check
>
> Without it, a captured delivery can be replayed forever. Keep your server clock in sync with NTP so honest deliveries stay within 300 seconds.

> [accordion] Store the secret like a password
>
> Keep it in an environment variable or a secret manager, never in source control. It's shown only when you create the endpoint or rotate the secret.

> [accordion] Don't trust the body for authorization
>
> A valid signature proves the event came from Quotable. Before you act on ids in the payload, fetch the record from the API with your own key if the action matters.

## Next steps

> [card] [Delivery and retries](https://docs.usequotable.com/webhooks/delivery-and-retries.md)
>
> What counts as success, and when Quotable tries again.

> [card] [Slack alerts recipe](https://docs.usequotable.com/guides/slack-alerts-from-webhooks.md)
>
> A complete receiver that verifies and forwards to Slack.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.