# Verify signatures

Every request is signed with your webhook secret. Verify the signature before you trust the body.

## Headers

| Header | Description |
| --- | --- |
| `X-YAA-Webhook-Id` | The event ID. It stays the same when we retry an event. |
| `X-YAA-Webhook-Signature` | Base64-encoded HMAC-SHA256 signature. |
| `X-YAA-Webhook-Signature-Timestamp` | Unix time in seconds when we sent this attempt. |

## Steps

1. Read the three headers above.
2. Build the signed message by joining the ID, the timestamp and the raw request body with periods:

   ```text
   {X-YAA-Webhook-Id}.{X-YAA-Webhook-Signature-Timestamp}.{raw body}
   ```

3. Compute the HMAC-SHA256 of that message with your webhook secret as the key.
4. Base64-encode the result.
5. Compare it to `X-YAA-Webhook-Signature` with a constant-time comparison.
6. Reject the request if the timestamp is more than 5 minutes old.

> **Caution**
>
> Use the raw request body, byte for byte. If your framework parses the JSON and you serialize it again, the signature will not match.

## Examples

### Node.js

```js
const crypto = require('crypto');
const express = require('express');

const app = express();

function isValidSignature(secret, id, timestamp, rawBody, signature) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${id}.${timestamp}.${rawBody}`)
    .digest();
  const received = Buffer.from(signature, 'base64');
  return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}

// express.raw keeps the body as bytes so it can be verified.
app.post('/webhooks/accountable', express.raw({ type: 'application/json' }), (req, res) => {
  const id = req.get('X-YAA-Webhook-Id');
  const signature = req.get('X-YAA-Webhook-Signature');
  const timestamp = req.get('X-YAA-Webhook-Signature-Timestamp');
  if (!id || !signature || !timestamp) return res.status(400).send('Missing signature headers');

  const age = Math.floor(Date.now() / 1000) - Number(timestamp);
  if (Number.isNaN(age) || age > 300) return res.status(400).send('Stale timestamp');

  const rawBody = req.body.toString('utf8');
  if (!isValidSignature(process.env.YAA_WEBHOOK_SECRET, id, timestamp, rawBody, signature)) {
    return res.status(401).send('Invalid signature');
  }

  const event = JSON.parse(rawBody);
  // Queue the event for processing, then respond.
  res.sendStatus(200);
});
```

### Python

```python
import base64
import hashlib
import hmac
import os
import time

from flask import Flask, request

app = Flask(__name__)

def is_valid_signature(secret: str, event_id: str, timestamp: str, raw_body: bytes, signature: str) -> bool:
    message = f"{event_id}.{timestamp}.".encode() + raw_body
    expected = hmac.new(secret.encode(), message, hashlib.sha256).digest()
    try:
        received = base64.b64decode(signature)
    except ValueError:
        return False
    return hmac.compare_digest(received, expected)

@app.post("/webhooks/accountable")
def accountable_webhook():
    event_id = request.headers.get("X-YAA-Webhook-Id")
    signature = request.headers.get("X-YAA-Webhook-Signature")
    timestamp = request.headers.get("X-YAA-Webhook-Signature-Timestamp")
    if not event_id or not signature or not timestamp:
        return "Missing signature headers", 400

    if not timestamp.isdigit() or time.time() - int(timestamp) > 300:
        return "Stale timestamp", 400

    raw_body = request.get_data()  # bytes, before any JSON parsing
    if not is_valid_signature(os.environ["YAA_WEBHOOK_SECRET"], event_id, timestamp, raw_body, signature):
        return "Invalid signature", 401

    event = request.get_json()
    # Queue the event for processing, then respond.
    return "", 200
```

### C#

```csharp
using System.Security.Cryptography;
using System.Text;

var app = WebApplication.Create(args);

app.MapPost("/webhooks/accountable", async (HttpRequest request) =>
{
    string? id = request.Headers["X-YAA-Webhook-Id"];
    string? signature = request.Headers["X-YAA-Webhook-Signature"];
    string? timestamp = request.Headers["X-YAA-Webhook-Signature-Timestamp"];
    if (id is null || signature is null || timestamp is null)
        return Results.BadRequest("Missing signature headers");

    if (!long.TryParse(timestamp, out var sentAt) ||
        DateTimeOffset.UtcNow.ToUnixTimeSeconds() - sentAt > 300)
        return Results.BadRequest("Stale timestamp");

    // Read the body as text before any JSON parsing.
    using var reader = new StreamReader(request.Body, Encoding.UTF8);
    var rawBody = await reader.ReadToEndAsync();

    var secret = Environment.GetEnvironmentVariable("YAA_WEBHOOK_SECRET")!;
    var expected = HMACSHA256.HashData(
        Encoding.UTF8.GetBytes(secret),
        Encoding.UTF8.GetBytes($"{id}.{timestamp}.{rawBody}"));

    byte[] received;
    try { received = Convert.FromBase64String(signature); }
    catch (FormatException) { return Results.Unauthorized(); }

    if (!CryptographicOperations.FixedTimeEquals(received, expected))
        return Results.Unauthorized();

    // Queue the event for processing, then respond.
    return Results.Ok();
});

app.Run();
```

## Test your code

Check your code against these fixed values. They are also in [`/test-vectors/webhook-signature.json`](https://developers.youareaccountable.com/test-vectors/webhook-signature.json).

| Input | Value |
| --- | --- |
| Secret | `0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef` |
| `X-YAA-Webhook-Id` | `breathalyzer_665f1c2ab7e4d90012a3f4c1_1767225600000_k3x9q2a` |
| `X-YAA-Webhook-Signature-Timestamp` | `1767225600` |

The raw body, with no spaces or line breaks:

```text
{"event_type":"breathalyzer.result.deleted","data":{"test_id":"665f1c2ab7e4d90012a3f4c3"}}
```

Your code should compute this signature:

```text
AlssRB6xfuj0mWw9X2XTPipmFP7/P+hAhhykmdI6Bdc=
```

The timestamp is January 1, 2026. Skip the 5 minute check when you test with these values.

## Secrets

- Store the secret in a secret manager or an environment variable. Keep it out of source control.
- Each webhook has its own secret.
- To replace a secret, use **Rotate Secret** in the dashboard. The old secret stops working right away.
