Verifying Signature
Each webhook request carries a signature which can be used to verify its authenticity. Use the secret key that you get while creating webhook endpoint to verify the signature.
How the signature is built
Each request carries these headers:
| Header | Example |
|---|---|
x-daestro-event | job.completed |
x-daestro-delivery | 018f0000-0000-7000-8000-0000000000aa |
x-daestro-timestamp | 1762000000 |
x-daestro-signature | v1=da8780890fadf76384a77d573ef778874... |
x-daestro-idempotency-key | job.completed:018f...0001:018f...0003 |
The value after v1= is a lowercase hex HMAC-SHA256. The key is the UTF-8 bytes of the secret. The message is:
{x-daestro-timestamp}.{raw request body}v1 names this scheme. A future scheme would use a different prefix.
Steps
- Read the raw request body as bytes. Do this before any JSON parsing. A body that was parsed and serialized again will not match.
- Read
x-daestro-timestamp. It must be a whole number of Unix seconds. Reject it if it is more than 5 minutes from your clock. - Read
x-daestro-signature. It must start withv1=. - Compute
HMAC-SHA256(secret, timestamp + "." + raw_body). - Compare it to the received digest with a constant-time comparison.
- Only then parse the JSON.
Responding
- Return a
2xxas soon as the payload is verified and recorded. Do slow work after you respond. Requests time out after 10 seconds. - Return
401when the signature is wrong. Most4xxcodes are not retried. The exceptions are408,425, and429. - Do not return
410unless you want the endpoint turned off.410 Gonedeactivates the endpoint. - Timeouts, network errors, and
5xxresponses are retried for about three days. Each retry gets a new timestamp and signature, so the 5 minute window still applies. - One event can reach you more than once. Use
x-daestro-deliveryorx-daestro-idempotency-keyto skip duplicates.
Test vector
Every verify function below takes the current time as an argument. Pass now = 1762000000 with these values and it should return true:
| Input | Value |
|---|---|
| secret | Xk7pQ2mR9vL4tW8nB3cF6hJ1sD5gZ0aE2uY8oPqKxVbM3nTr |
| timestamp | 1762000000 |
| body | {"event":"job.completed","api_version":"2026.11","data":{"job_id":"018f0000-0000-7000-8000-000000000001","state":"completed"}} |
| signature | v1=46757a40b295293926a4db9930983e6e83f0eab4695135b63d7cf8f099365eee |
The examples read the secret from the DAESTRO_WEBHOOK_SECRET environment variable and listen on POST /webhooks/daestro.
Node.js (Express)
npm install express// server.mjs
import crypto from "node:crypto";
import express from "express";
const secret = process.env.DAESTRO_WEBHOOK_SECRET;
if (!secret) throw new Error("DAESTRO_WEBHOOK_SECRET is not set");
export function verify(body, timestamp, signature, now = Date.now() / 1000) {
const age = Math.abs(now - Number(timestamp));
if (!Number.isFinite(age) || age > 300) return false;
const received = /^v1=([0-9a-f]{64})$/.exec(signature ?? "")?.[1];
if (!received) return false;
const expected = crypto
.createHmac("sha256", secret)
.update(`${timestamp}.`)
.update(body)
.digest("hex");
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received));
}
const app = express();
app.post("/webhooks/daestro", express.raw({ type: "*/*" }), (req, res) => {
if (!verify(req.body, req.get("x-daestro-timestamp"), req.get("x-daestro-signature"))) {
return res.sendStatus(401);
}
const payload = JSON.parse(req.body);
console.log(`received ${payload.event}`, payload.data);
res.sendStatus(204);
});
app.listen(8080);Run it with node server.mjs. express.raw keeps the body as a Buffer. Do not put express.json() in front of this route.
Python (Flask)
pip install flask# app.py
import hashlib
import hmac
import os
import time
from flask import Flask, request
TOLERANCE_SECONDS = 300
def verify(raw_body: bytes, timestamp: str | None, signature: str | None,
secret: str, now: int | None = None) -> bool:
if timestamp is None or signature is None:
return False
if not (timestamp.isascii() and timestamp.isdigit()):
return False
now = int(time.time()) if now is None else now
if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
return False
if not signature.startswith("v1="):
return False
received = signature[3:].encode()
expected = hmac.new(
secret.encode(),
timestamp.encode() + b"." + raw_body,
hashlib.sha256,
).hexdigest().encode()
return hmac.compare_digest(expected, received)
SECRET = os.environ["DAESTRO_WEBHOOK_SECRET"]
app = Flask(__name__)
@app.post("/webhooks/daestro")
def daestro_webhook():
raw_body = request.get_data()
ok = verify(
raw_body,
request.headers.get("x-daestro-timestamp"),
request.headers.get("x-daestro-signature"),
SECRET,
)
if not ok:
return "", 401
payload = request.get_json(force=True)
print(f"received {payload['event']}", payload["data"])
return "", 204
if __name__ == "__main__":
app.run(port=8080)Call request.get_data() before anything else reads the body.
Go (standard library)
// main.go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const tolerance = 5 * time.Minute
func verify(body []byte, timestamp, signature, secret string, now time.Time) bool {
if timestamp == "" || strings.Trim(timestamp, "0123456789") != "" {
return false
}
ts, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
return false
}
sent := time.Unix(ts, 0)
if now.Sub(sent) > tolerance || sent.Sub(now) > tolerance {
return false
}
hexDigest, ok := strings.CutPrefix(signature, "v1=")
if !ok {
return false
}
received, err := hex.DecodeString(hexDigest)
if err != nil {
return false
}
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(timestamp))
mac.Write([]byte("."))
mac.Write(body)
return hmac.Equal(mac.Sum(nil), received)
}
type event struct {
Event string `json:"event"`
Data json.RawMessage `json:"data"`
}
func main() {
secret := os.Getenv("DAESTRO_WEBHOOK_SECRET")
if secret == "" {
log.Fatal("DAESTRO_WEBHOOK_SECRET is not set")
}
http.HandleFunc("POST /webhooks/daestro", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "cannot read body", http.StatusBadRequest)
return
}
ok := verify(
body,
r.Header.Get("X-Daestro-Timestamp"),
r.Header.Get("X-Daestro-Signature"),
secret,
time.Now(),
)
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
var payload event
if err := json.Unmarshal(body, &payload); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
return
}
log.Printf("received %s: %s", payload.Event, payload.Data)
w.WriteHeader(http.StatusNoContent)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}Needs Go 1.22 or newer for the POST /path route pattern.
Rust (axum)
# Cargo.toml
[dependencies]
axum = "0.8"
hex = "0.4"
hmac = "0.12"
serde_json = "1"
sha2 = "0.10"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }// src/main.rs
use axum::{
Router,
body::Bytes,
extract::State,
http::{HeaderMap, StatusCode},
routing::post,
};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
type HmacSha256 = Hmac<Sha256>;
const TOLERANCE_SECS: i64 = 300;
fn verify(body: &[u8], timestamp: &str, signature: &str, secret: &str, now: i64) -> bool {
if timestamp.is_empty() || !timestamp.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
let Ok(ts) = timestamp.parse::<i64>() else {
return false;
};
if (now - ts).abs() > TOLERANCE_SECS {
return false;
}
let Some(hex_digest) = signature.strip_prefix("v1=") else {
return false;
};
let Ok(received) = hex::decode(hex_digest) else {
return false;
};
let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC accepts any key length");
mac.update(timestamp.as_bytes());
mac.update(b".");
mac.update(body);
mac.verify_slice(&received).is_ok()
}
async fn webhook(State(secret): State<Arc<String>>, headers: HeaderMap, body: Bytes) -> StatusCode {
let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
let (Some(timestamp), Some(signature)) =
(header("x-daestro-timestamp"), header("x-daestro-signature"))
else {
return StatusCode::UNAUTHORIZED;
};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("clock is after 1970")
.as_secs() as i64;
if !verify(&body, timestamp, signature, &secret, now) {
return StatusCode::UNAUTHORIZED;
}
let Ok(payload) = serde_json::from_slice::<serde_json::Value>(&body) else {
return StatusCode::BAD_REQUEST;
};
println!("received {}: {}", payload["event"], payload["data"]);
StatusCode::NO_CONTENT
}
#[tokio::main]
async fn main() {
let secret = std::env::var("DAESTRO_WEBHOOK_SECRET").expect("DAESTRO_WEBHOOK_SECRET is not set");
let app = Router::new()
.route("/webhooks/daestro", post(webhook))
.with_state(Arc::new(secret));
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
axum::serve(listener, app).await.unwrap();
}verify_slice compares in constant time.
Ruby (Sinatra)
gem install sinatra rackup puma# app.rb
require "json"
require "openssl"
require "rack/utils"
require "sinatra"
TOLERANCE_SECONDS = 300
SECRET = ENV.fetch("DAESTRO_WEBHOOK_SECRET")
def verify(raw_body, timestamp, signature, secret, now: Time.now.to_i)
return false if timestamp.nil? || signature.nil?
return false unless timestamp.match?(/\A\d{1,18}\z/)
return false if (now - timestamp.to_i).abs > TOLERANCE_SECONDS
return false unless signature.start_with?("v1=")
received = signature.delete_prefix("v1=")
message = "#{timestamp}.".b + raw_body.b
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, message)
Rack::Utils.secure_compare(expected, received)
end
set :port, 8080
post "/webhooks/daestro" do
request.body.rewind
raw_body = request.body.read
ok = verify(
raw_body,
request.env["HTTP_X_DAESTRO_TIMESTAMP"],
request.env["HTTP_X_DAESTRO_SIGNATURE"],
SECRET
)
halt 401 unless ok
payload = JSON.parse(raw_body)
puts "received #{payload['event']}: #{payload['data']}"
status 204
endRun it with ruby app.rb.
PHP
<?php
// webhook.php
const TOLERANCE_SECONDS = 300;
function verify(string $rawBody, ?string $timestamp, ?string $signature, string $secret, ?int $now = null): bool
{
if ($timestamp === null || $signature === null) {
return false;
}
if (!preg_match('/\A\d{1,18}\z/', $timestamp)) {
return false;
}
$now ??= time();
if (abs($now - (int) $timestamp) > TOLERANCE_SECONDS) {
return false;
}
if (!str_starts_with($signature, 'v1=')) {
return false;
}
$received = substr($signature, 3);
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
return hash_equals($expected, $received);
}
$secret = getenv('DAESTRO_WEBHOOK_SECRET');
if ($secret === false || $secret === '') {
http_response_code(500);
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit;
}
$rawBody = file_get_contents('php://input');
$ok = verify(
$rawBody,
$_SERVER['HTTP_X_DAESTRO_TIMESTAMP'] ?? null,
$_SERVER['HTTP_X_DAESTRO_SIGNATURE'] ?? null,
$secret
);
if (!$ok) {
http_response_code(401);
exit;
}
$payload = json_decode($rawBody, true, flags: JSON_THROW_ON_ERROR);
error_log("received {$payload['event']}");
http_response_code(204);Needs PHP 8.0 or newer. Try it with php -S 0.0.0.0:8080 webhook.php.
Java (JDK only)
// DaestroWebhook.java
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.HexFormat;
public class DaestroWebhook {
private static final long TOLERANCE_SECONDS = 300;
static boolean verify(byte[] rawBody, String timestamp, String signature, String secret, long nowSeconds) {
if (timestamp == null || signature == null) {
return false;
}
if (!timestamp.matches("\\d{1,18}")) {
return false;
}
if (Math.abs(nowSeconds - Long.parseLong(timestamp)) > TOLERANCE_SECONDS) {
return false;
}
if (!signature.startsWith("v1=")) {
return false;
}
byte[] received;
try {
received = HexFormat.of().parseHex(signature.substring(3));
} catch (IllegalArgumentException e) {
return false;
}
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
byte[] expected = mac.doFinal(rawBody);
return MessageDigest.isEqual(expected, received);
} catch (GeneralSecurityException e) {
throw new IllegalStateException(e);
}
}
public static void main(String[] args) throws IOException {
String secret = System.getenv("DAESTRO_WEBHOOK_SECRET");
if (secret == null || secret.isEmpty()) {
throw new IllegalStateException("DAESTRO_WEBHOOK_SECRET is not set");
}
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/webhooks/daestro", exchange -> handle(exchange, secret));
server.start();
}
private static void handle(HttpExchange exchange, String secret) throws IOException {
try {
if (!"POST".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(405, -1);
return;
}
byte[] body;
try (InputStream in = exchange.getRequestBody()) {
body = in.readAllBytes();
}
boolean ok = verify(
body,
exchange.getRequestHeaders().getFirst("X-Daestro-Timestamp"),
exchange.getRequestHeaders().getFirst("X-Daestro-Signature"),
secret,
Instant.now().getEpochSecond()
);
if (!ok) {
exchange.sendResponseHeaders(401, -1);
return;
}
String event = exchange.getRequestHeaders().getFirst("X-Daestro-Event");
String json = new String(body, StandardCharsets.UTF_8);
System.out.println("received " + event + ": " + json);
exchange.sendResponseHeaders(204, -1);
} finally {
exchange.close();
}
}
}Needs Java 17 or newer for HexFormat. Run it with java DaestroWebhook.java. Parse json with your JSON library, for example Jackson.
C# (ASP.NET Core minimal API)
dotnet new web -n DaestroWebhook// Program.cs
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
var secret = Environment.GetEnvironmentVariable("DAESTRO_WEBHOOK_SECRET");
if (string.IsNullOrEmpty(secret))
{
throw new InvalidOperationException("DAESTRO_WEBHOOK_SECRET is not set");
}
var app = WebApplication.CreateBuilder(args).Build();
app.MapPost("/webhooks/daestro", async (HttpRequest request) =>
{
using var buffer = new MemoryStream();
await request.Body.CopyToAsync(buffer);
var body = buffer.ToArray();
var ok = DaestroSignature.Verify(
body,
request.Headers["x-daestro-timestamp"].ToString(),
request.Headers["x-daestro-signature"].ToString(),
secret,
DateTimeOffset.UtcNow.ToUnixTimeSeconds());
if (!ok)
{
return Results.Unauthorized();
}
using var payload = JsonDocument.Parse(body);
var eventName = payload.RootElement.GetProperty("event").GetString();
Console.WriteLine($"received {eventName}");
return Results.NoContent();
});
app.Run("http://0.0.0.0:8080");
static class DaestroSignature
{
private const long ToleranceSeconds = 300;
public static bool Verify(byte[] body, string timestamp, string signature, string secret, long nowSeconds)
{
if (timestamp.Length is 0 or > 18 || !timestamp.All(char.IsAsciiDigit))
{
return false;
}
if (Math.Abs(nowSeconds - long.Parse(timestamp)) > ToleranceSeconds)
{
return false;
}
if (!signature.StartsWith("v1=", StringComparison.Ordinal))
{
return false;
}
byte[] received;
try
{
received = Convert.FromHexString(signature.AsSpan(3));
}
catch (FormatException)
{
return false;
}
var prefix = Encoding.UTF8.GetBytes(timestamp + ".");
var message = new byte[prefix.Length + body.Length];
prefix.CopyTo(message, 0);
body.CopyTo(message, prefix.Length);
var expected = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), message);
return CryptographicOperations.FixedTimeEquals(expected, received);
}
}Needs .NET 7 or newer for char.IsAsciiDigit.