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

# Authentication

> Verify that each v2 webhook came from StockInsights, with the Standard Webhooks signature.

## Why verify

Your endpoint is a public URL, so anyone can send a `POST` to it. StockInsights
signs every v2 request with a secret that only you and StockInsights know. When
the signature is correct, the request came from StockInsights and its body was
not changed on the way.

> [!WARNING]
>
> Verify the signature before you use the payload.

v2 uses the [Standard Webhooks](https://www.standardwebhooks.com/) signature
scheme. Thus you can use a Standard Webhooks library, or write the check
yourself in a few lines.

## Request headers

| Header | Description |
| - | - |
| `webhook-id` | The event id, for example `evt_06afd889-e0df-7dde-8000-84708b20988a`. It is the same as `id` in the body. Every retry of an event has the same id. |
| `webhook-timestamp` | When the request was signed, in UNIX seconds. |
| `webhook-signature` | The signature: `v1,` and a base64 HMAC-SHA256. |
| `X-StockInsights-Event` | The event type, for example `quarterly-result.created`. |
| `X-StockInsights-Delivery` | The id of one event going to one destination. Every retry has the same id. Useful in logs and support requests. |
| `Content-Type` | `application/json` |
| `User-Agent` | `stockinsights-webhooks/1.0` |

## The signing secret

The v2 signing secret has the form `whsec_` followed by base64, for example
`whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw`. The part after `whsec_` is the key,
base64-encoded.

> [!NOTE]
>
> The v2 secret is the same key as your v1 secret, in another format. The v1
> secret is hex. To get the v2 secret from it, decode the hex to bytes, encode
> the bytes as base64, and put `whsec_` in front.

When you rotate the secret, the previous secret stops working at once. Deploy
the new secret to your endpoint just before or just after you rotate.

## How the signature is made

1. StockInsights joins the event id, the timestamp and the raw request body with
   dots: `{webhook-id}.{webhook-timestamp}.{body}`.
2. It computes an HMAC-SHA256 of that text. The key is the base64-decoded part
   of the secret after `whsec_`.
3. It encodes the HMAC as base64 and sends it as `v1,<signature>` in the
   `webhook-signature` header.

The `webhook-signature` header can hold more than one signature, separated by
spaces, for example during a key rotation. The request is valid when one of them
matches.

> [!WARNING]
>
> Compute the HMAC over the raw request body, exactly as you received it. Do not
> parse the JSON and serialize it again: the bytes change, and the signature does
> not match.

## Verify with a library

The Standard Webhooks libraries do all the steps, including the timestamp check.
They take the secret with its `whsec_` prefix.

```javascript Node.js theme={null}
// npm install standardwebhooks
import { Webhook } from "standardwebhooks";

const wh = new Webhook(process.env.STOCKINSIGHTS_WEBHOOK_SECRET); // "whsec_..."

app.post("/webhooks/stockinsights", express.raw({ type: "application/json" }), (req, res) => {
  let event;
  try {
    event = wh.verify(req.body.toString("utf8"), req.headers);
  } catch (err) {
    return res.status(400).send("invalid signature");
  }
  res.sendStatus(200);
  handleEvent(event); // process after you answer
});
```

```python Python theme={null}
# pip install standardwebhooks
from standardwebhooks.webhooks import Webhook, WebhookVerificationError

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


@app.post("/webhooks/stockinsights")
def stockinsights_webhook(request):
    try:
        event = wh.verify(request.body, dict(request.headers))
    except WebhookVerificationError:
        return Response(status=400)
    queue_event(event)  # process after you answer
    return Response(status=200)
```

## Verify without a library

```javascript Node.js theme={null}
const crypto = require("crypto");

function verifyWebhook(rawBody, headers, secret, toleranceSeconds = 300) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) return false;

  // Refuse an old request, so a captured request cannot be sent again later.
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;

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

  return signatures.split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    if (version !== "v1" || !signature) return false;
    const a = Buffer.from(signature);
    const b = Buffer.from(expected);
    return a.length === b.length && crypto.timingSafeEqual(a, b);
  });
}
```

```python Python theme={null}
import base64
import hashlib
import hmac
import time


def verify_webhook(raw_body: bytes, headers: dict, secret: str, tolerance_seconds: int = 300) -> bool:
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not (msg_id and timestamp and signatures):
        return False

    # Refuse an old request, so a captured request cannot be sent again later.
    if abs(time.time() - int(timestamp)) > tolerance_seconds:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()

    for entry in signatures.split(" "):
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return True
    return False
```

## After the check

* Answer with a `2xx` status as soon as the signature is correct. Do slow work
  after you answer. See [Delivery & retries](https://docs.stockinsights.ai/webhooks/delivery-and-retries.md).
* De-duplicate on `webhook-id`. The same event can arrive more than once.
* Refuse a request with an old `webhook-timestamp`. The libraries refuse a
  timestamp that is more than 5 minutes from your clock.


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