Outgoing webhooks
Verify signatures
Check that every delivery really came from Valeron before you trust it.
Anyone can send a request to your webhook URL. Valeron signs each delivery with your endpoint's secret (whsec_…) so you can tell its requests from anyone else's.
#The signature header
Every delivery has a Valeron-Signature header:
Valeron-Signature: t=1796308262,v1=5f1c0e9b8a7d6c5b4a3928170615243342516071809a0b1c2d3e4f5061728394tis a Unix time in seconds.v1is the hex HMAC-SHA256 of the string<t>.<body>, using the endpoint's signing secret as the key.<body>is the raw request body, exactly as received.
#Steps
- Read the raw body as text. Do not parse and re-serialize the JSON: that changes the bytes and the signature will not match.
- Split the header on
,and readtandv1. - Compute the HMAC-SHA256 of
t + "." + bodywith your secret and compare it withv1in constant time. - Reject the request with
400when they differ.
The timestamp lets you reject replays. Retries can arrive hours after the event, so if you check it, keep the window wide, or skip it and ignore repeats by event id instead.
#Node.js
import crypto from "node:crypto";
import express from "express";
const app = express();
function verifyValeronSignature(rawBody, header, secret) {
const parts = Object.fromEntries(
String(header ?? "").split(",").map((part) => part.trim().split("=")),
);
if (!parts.t || !parts.v1) return false;
const expected = crypto
.createHmac("sha256", secret)
.update(`${parts.t}.${rawBody}`)
.digest("hex");
const given = Buffer.from(parts.v1, "hex");
const wanted = Buffer.from(expected, "hex");
return given.length === wanted.length && crypto.timingSafeEqual(given, wanted);
}
// express.raw keeps the body exactly as it arrived.
app.post("/hooks/valeron", express.raw({ type: "application/json" }), (req, res) => {
const rawBody = req.body.toString("utf8");
if (!verifyValeronSignature(rawBody, req.get("Valeron-Signature"), process.env.VALERON_WEBHOOK_SECRET)) {
return res.status(400).send("Invalid signature");
}
const event = JSON.parse(rawBody);
queueForProcessing(event); // do the slow work after you respond
res.sendStatus(200);
});#Python
import hashlib
import hmac
import os
from flask import Flask, abort, request
app = Flask(__name__)
def verify_valeron_signature(raw_body: bytes, header: str, secret: str) -> bool:
parts = dict(part.strip().split("=", 1) for part in (header or "").split(",") if "=" in part)
if "t" not in parts or "v1" not in parts:
return False
signed = f"{parts['t']}.".encode() + raw_body
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, parts["v1"])
@app.post("/hooks/valeron")
def valeron_hook():
raw_body = request.get_data() # the exact bytes Valeron sent
if not verify_valeron_signature(raw_body, request.headers.get("Valeron-Signature"), os.environ["VALERON_WEBHOOK_SECRET"]):
abort(400)
event = request.get_json(force=True)
queue_for_processing(event) # do the slow work after you respond
return "", 200#Test it
Call POST /v1/webhook-endpoints/{endpoint_id}/test. Valeron sends a signed ping to your URL. If verification fails, check that you use the secret of that endpoint, and that your framework hands you the raw body.
If a secret leaks, call POST /v1/webhook-endpoints/{endpoint_id}/rotate-secret and update your receiver.
