Verifying a signature
Making sure a delivery really comes from Lidmeo, in Node, Python, PHP and Go.
Your endpoint is public: anyone can send it a request. The signature proves a delivery comes from Lidmeo and was not modified. Verify it before any processing, and answer 400 if it is wrong.
The principle
Lidmeo follows Standard Webhooks:
- the signed content is
webhook-id+.+webhook-timestamp+.+ the raw body, as received; - the key is the secret without its
whsec_prefix, base64-decoded; - the signature is
v1,followed by the HMAC-SHA256 of the content, in base64; - the
webhook-signatureheader can carry several signatures separated by a space (during a secret change): a single matching one is enough; - refuse a
webhook-timestampmore than 5 minutes away from your clock: an intercepted delivery cannot be replayed later.
The raw body
Verify the bytes received, before any JSON decoding. A body parsed then rewritten (spaces, field order) no longer gives the same signature.
With the SDKs
import { verifyWebhook, WebhookVerificationError } from "@lidmeo/sdk";
// rawBody: the body as received (string or bytes)
try {
const event = verifyWebhook(process.env.LIDMEO_WEBHOOK_SECRET!, rawBody, request.headers);
// event.type, event.data.object…
} catch (error) {
if (error instanceof WebhookVerificationError) {
// answer 400, process nothing
}
}The official standardwebhooks libraries (Node, Python, PHP, Go, Ruby, Java…) also verify Lidmeo's deliveries as they are.
Without a library
Each example below is a complete function, which returns true if the delivery is authentic.
Node.js
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyLidmeoWebhook(secret, headers, rawBody) {
const id = headers["webhook-id"];
const timestamp = headers["webhook-timestamp"];
const signatures = headers["webhook-signature"];
if (!id || !signatures || !/^\d+$/.test(timestamp ?? "")) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest();
return signatures.split(" ").some((part) => {
const [version, value] = part.split(",");
if (version !== "v1" || !value) return false;
const got = Buffer.from(value, "base64");
return got.length === expected.length && timingSafeEqual(got, expected);
});
}headers: the headers with lowercase names, like Node's req.headers. With Express, keep the raw body: express.raw({ type: "application/json" }), then req.body.toString("utf8").
Python
import base64
import hashlib
import hmac
import time
def verify_lidmeo_webhook(secret: str, headers, raw_body: bytes) -> bool:
msg_id = headers.get("webhook-id")
timestamp = headers.get("webhook-timestamp")
signatures = headers.get("webhook-signature")
if not msg_id or not timestamp or not signatures or not timestamp.isdecimal():
return False
if abs(time.time() - int(timestamp)) > 300:
return False
key = base64.b64decode(secret[len("whsec_"):] if secret.startswith("whsec_") else secret)
signed = f"{msg_id}.{timestamp}.".encode() + raw_body
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest())
for part in signatures.split(" "):
version, _, value = part.partition(",")
if version == "v1" and hmac.compare_digest(value.encode(), expected):
return True
return FalseWith Flask: verify_lidmeo_webhook(secret, request.headers, request.get_data()).
PHP
<?php
function lidmeo_verify_webhook(string $secret, array $headers, string $payload): bool
{
$headers = array_change_key_case($headers, CASE_LOWER);
$id = $headers['webhook-id'] ?? '';
$timestamp = $headers['webhook-timestamp'] ?? '';
$signatures = $headers['webhook-signature'] ?? '';
if ($id === '' || $signatures === '' || !ctype_digit($timestamp)) {
return false;
}
if (abs(time() - (int) $timestamp) > 300) {
return false;
}
$key = base64_decode(preg_replace('/^whsec_/', '', $secret));
$expected = base64_encode(hash_hmac('sha256', "$id.$timestamp.$payload", $key, true));
foreach (explode(' ', $signatures) as $part) {
[$version, $value] = array_pad(explode(',', $part, 2), 2, '');
if ($version === 'v1' && hash_equals($expected, $value)) {
return true;
}
}
return false;
}When calling: lidmeo_verify_webhook($secret, getallheaders(), file_get_contents('php://input')).
Go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"math"
"net/http"
"strconv"
"strings"
"time"
)
func verifyLidmeoWebhook(secret string, header http.Header, body []byte) bool {
id := header.Get("webhook-id")
timestamp := header.Get("webhook-timestamp")
signatures := header.Get("webhook-signature")
seconds, err := strconv.ParseInt(timestamp, 10, 64)
if id == "" || signatures == "" || err != nil {
return false
}
if math.Abs(float64(time.Now().Unix()-seconds)) > 300 {
return false
}
key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
if err != nil {
return false
}
mac := hmac.New(sha256.New, key)
mac.Write([]byte(id + "." + timestamp + "." + string(body)))
expected := mac.Sum(nil)
for _, part := range strings.Split(signatures, " ") {
version, value, ok := strings.Cut(part, ",")
if !ok || version != "v1" {
continue
}
got, err := base64.StdEncoding.DecodeString(value)
if err == nil && hmac.Equal(got, expected) {
return true
}
}
return false
}In your handler: read the body with io.ReadAll(r.Body), then verifyLidmeoWebhook(secret, r.Header, body).
A test vector
To check your code without waiting for a delivery, the Standard Webhooks test vector:
| Secret | whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw |
webhook-id | msg_p5jXN8AQM9LWM0D4loKWxJek |
webhook-timestamp | 1614265330 |
| Body | {"test": 2432232314} |
| Expected signature | v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE= |
Its timestamp is old: turn off the 5-minute check for this test. Then, Envoyer un essai (send a test) from Lidmeo sends you a test event (prospect.created), signed like a real one.