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

# Security

> Learn how to secure your webhook implementation

To ensure that webhook requests are genuinely from Superleap and haven't been tampered with, we include a signature in each webhook request. (Provided a secret key is set up against the url)

## Signature Verification

We include a signature in the `x-superleap-signature` header of each webhook request. You should verify this signature before processing the webhook payload.

### Verification Algorithm

```
key                = webhook_secret
message            = webhook_body // raw webhook request body
received_signature = webhook_signature
expected_signature = hmac('sha256', message, key)
if expected_signature != received_signature
    throw SecurityError
end
```

> **Important**: You must stringify the request body with zero whitespace before generating the HMAC signature to ensure a correct match.
> You can validate your signature verification implementation with the following test code:

<CodeGroup>
  ```javascript security.js theme={null}
  const crypto = require('crypto');
  secret_key = "abcd";
  const sampleJson = { "test": "test" };
  const key = Buffer.from(secret_key, 'utf-8');
  const body = JSON.stringify(sampleJson, null, 0);
  console.log(body);
  const hmac = crypto.createHmac('sha256', key);
  hmac.update(body);
  const generatedSignature = hmac.digest('hex');
  console.log(generatedSignature);
  ```
</CodeGroup>

In the above code snippet, replace `sampleJson` with the request body and `secret_key` with your secret key for testing. The output of this code will be:

1. The stringified JSON with no whitespace
2. The expected signature that should match the one in the `x-superleap-signature` header

## Best Practices

1. **Always verify signatures**: Never skip the signature verification step in production.
2. **Use environment variables**: Store your webhook secret as an environment variable, not in your code.
3. **Implement idempotency**: Process webhooks idempotently to prevent duplicate actions if the same webhook is received multiple times. (Use x-superleap-event-id for the same)
4. **Respond quickly**: Your webhook endpoint should acknowledge receipt of the webhook quickly (2xx status code) and perform any time-consuming work asynchronously.
5. **Monitor for failures**: Implement monitoring to alert you of repeated webhook failures.
6. **Proper JSON handling**: Always stringify JSON with no whitespace (using `null, 0` in JavaScript) when calculating signatures to ensure consistency.
