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

# Verifying webhook signatures

> Check that a webhook really came from Osvi before you trust it

Osvi can sign every webhook it sends you with a secret that only your account and Osvi know. Your server recomputes the signature and drops any request that doesn't match, so nobody else can send you fake call results.

Signing is **off by default**. Until you turn it on, webhooks are sent without a signature, exactly as before.

## What gets signed

With signing on, every webhook your account sends is signed:

* Post-call webhooks from your agents' **Post-Call Analysis → Integrations**.
* The per-call `webhook_url` you pass to the call API.
* Test sends from the **Test** button, and retries from **Integration Logs**.

Each signed request carries these headers:

| Header | Value |
| - | - |
| `X-Signature-Timestamp` | When the request was sent, in Unix seconds, e.g. `1780617600`. |
| `X-Signature` | Lowercase hex HMAC-SHA256 of the timestamp followed by the raw request body, using your signing secret. |
| `X-Signature-Previous` | Only for one hour after you rotate your secret: the same signature made with your previous secret. |

The signed message is the timestamp and the body joined with nothing in between:

```text theme={null}
signature = hex( HMAC-SHA256( secret, X-Signature-Timestamp + raw_body ) )
```

`raw_body` is the exact bytes Osvi sent. For `GET` and `DELETE` webhooks there is no body, so the message is just the timestamp.

## Turn on signing

1. Go to **Settings → Webhook signing**.
2. Switch on **Sign webhooks**.
3. Confirm that you understand this is a critical security setting, then enter your password again. If you sign in to Osvi with Google, sign in with Google again instead.
4. Copy the secret that appears and store it on your server, for example as `OSVI_WEBHOOK_SECRET`.

Signing starts within a minute. Admins and members can turn signing on and manage the secret; Support users can see whether it's on. Each sub-account has its own secret and its own switch.

You can reveal the secret again at any time from the same card. If you haven't confirmed it's you in the last 5 minutes, you're asked to enter your password or sign in with Google again.

> [!WARNING]
>
> Treat the secret like a password. Anyone who has it can send your server requests that look like they came from Osvi. Never put it in client-side code or a public repository.

## Verify a request

For every webhook:

1. Read the **raw request body** before parsing it as JSON. Parsing and re-serializing changes the bytes, and the signature won't match.
2. Reject the request if `X-Signature-Timestamp` is missing or more than **5 minutes** away from your server's clock. This stops someone replaying an old request.
3. Compute the HMAC-SHA256 of the timestamp followed by the raw body, with your secret, as lowercase hex.
4. Compare it with `X-Signature` using a **constant-time** comparison. If `X-Signature-Previous` is present, accept a match on either header.
5. Respond with a `401` and ignore the payload if nothing matches.

```javascript Node.js (Express) theme={null}
import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.OSVI_WEBHOOK_SECRET;
const TOLERANCE_SECONDS = 300;

function isValidOsviSignature(req) {
  const timestamp = req.get("X-Signature-Timestamp");
  if (!timestamp || !/^\d+$/.test(timestamp)) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;

  // express.raw() gives the exact bytes; GET and DELETE have no body.
  const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
  const expected = Buffer.from(
    crypto.createHmac("sha256", SECRET).update(timestamp).update(rawBody).digest("hex"),
  );

  return [req.get("X-Signature"), req.get("X-Signature-Previous")]
    .filter(Boolean)
    .some((signature) => {
      const received = Buffer.from(signature);
      return received.length === expected.length && crypto.timingSafeEqual(received, expected);
    });
}

const app = express();

app.post("/osvi/webhook", express.raw({ type: "*/*" }), (req, res) => {
  if (!isValidOsviSignature(req)) return res.sendStatus(401);

  const payload = JSON.parse(req.body.toString("utf8"));
  // ... handle the call result
  res.sendStatus(200);
});
```

```python Python (Flask) theme={null}
import hashlib
import hmac
import os
import time

from flask import Flask, abort, request

SECRET = os.environ["OSVI_WEBHOOK_SECRET"].encode()
TOLERANCE_SECONDS = 300

app = Flask(__name__)


def is_valid_osvi_signature(req) -> bool:
    timestamp = req.headers.get("X-Signature-Timestamp", "")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    raw_body = req.get_data()  # exact bytes, before any JSON parsing
    expected = hmac.new(SECRET, timestamp.encode() + raw_body, hashlib.sha256).hexdigest()

    candidates = [req.headers.get("X-Signature"), req.headers.get("X-Signature-Previous")]
    return any(
        signature and hmac.compare_digest(signature.encode(), expected.encode())
        for signature in candidates
    )


@app.post("/osvi/webhook")
def osvi_webhook():
    if not is_valid_osvi_signature(request):
        abort(401)

    payload = request.get_json()
    # ... handle the call result
    return "", 200
```

```ruby Ruby (Rails) theme={null}
class OsviWebhooksController < ActionController::API
  TOLERANCE_SECONDS = 300

  def create
    return head :unauthorized unless valid_osvi_signature?

    payload = JSON.parse(request.raw_post)
    # ... handle the call result
    head :ok
  end

  private

  def valid_osvi_signature?
    timestamp = request.headers["X-Signature-Timestamp"].to_s
    return false unless timestamp.match?(/\A\d+\z/)
    return false if (Time.now.to_i - timestamp.to_i).abs > TOLERANCE_SECONDS

    raw_body = request.raw_post.to_s # exact bytes, before any JSON parsing
    expected = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("OSVI_WEBHOOK_SECRET"), timestamp + raw_body)

    [request.headers["X-Signature"], request.headers["X-Signature-Previous"]]
      .compact
      .any? { |signature| ActiveSupport::SecurityUtils.secure_compare(signature, expected) }
  end
end
```

```go Go (net/http) theme={null}
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"net/http"
	"os"
	"strconv"
	"time"
)

const toleranceSeconds = 300

var secret = []byte(os.Getenv("OSVI_WEBHOOK_SECRET"))

func validOsviSignature(r *http.Request, rawBody []byte) bool {
	timestamp := r.Header.Get("X-Signature-Timestamp")
	ts, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		return false
	}
	if age := time.Now().Unix() - ts; age > toleranceSeconds || age < -toleranceSeconds {
		return false
	}

	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(timestamp))
	mac.Write(rawBody)
	expected := []byte(hex.EncodeToString(mac.Sum(nil)))

	for _, signature := range []string{r.Header.Get("X-Signature"), r.Header.Get("X-Signature-Previous")} {
		if signature != "" && hmac.Equal([]byte(signature), expected) {
			return true
		}
	}
	return false
}

func osviWebhook(w http.ResponseWriter, r *http.Request) {
	rawBody, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) // exact bytes
	if err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	if !validOsviSignature(r, rawBody) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}

	var payload map[string]any
	if len(rawBody) > 0 {
		_ = json.Unmarshal(rawBody, &payload)
	}
	// ... handle the call result
	w.WriteHeader(http.StatusOK)
}
```

### Check your code

Run your verification against these values. It should produce the signature shown.

| Input | Value |
| - | - |
| Secret | `sk_webhook_test_secret` |
| `X-Signature-Timestamp` | `1780617600` |
| Raw body | `{"call_log_id":"abc","call_status":"picked"}` |
| Expected `X-Signature` | `25bee09a8de1be1092e6b5505175c5c75063667fb7d56748e73a5593deb70e4e` |

The timestamp in this example is fixed, so skip the 5-minute check while you test.

## Rotate the secret

Rotate the secret if it may have leaked, or as routine hygiene.

1. In **Settings → Webhook signing**, click **Rotate secret** and confirm it's you (password or Google).
2. Within a minute, Osvi starts signing with the new secret. For the next **hour**, each webhook also carries `X-Signature-Previous`, signed with your old secret, so your server keeps accepting requests while you deploy the new one.
3. Wait at least a minute after rotating, then update your server with the new secret.
4. If the old secret leaked, click **Expire it now** to stop accepting it immediately instead of waiting out the hour.

If your server checks both `X-Signature` and `X-Signature-Previous`, as the examples above do, a rotation never rejects a genuine request.

## Turn off signing

Switch off **Sign webhooks** in **Settings → Webhook signing**. Within a minute, webhooks are sent without a signature. If your server requires a signature, it will start rejecting them, so update it first.

Your secret is kept. Turning signing back on uses the same secret, so you don't need to change anything on your server.


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