Receive webhooks
Your endpoint must do four things on every delivery: verify the signature over the raw body, reject old timestamps, skip events it already processed, and answer 2xx within 10 seconds. The examples below do exactly that.
The signature is sha256= followed by the hex HMAC-SHA256 of the timestamp, a dot and the body:
X-Goldmaster-Signature = "sha256=" + hex(HMAC_SHA256(secret, X-Goldmaster-Timestamp + "." + rawBody))import crypto from 'node:crypto';import express from 'express';
const app = express();const secret = process.env.DUTY_WEBHOOK_SECRET;const seen = new Set(); // use your database in production
app.post('/hooks/duty', express.raw({ type: 'application/json' }), (req, res) => { const timestamp = req.get('X-Goldmaster-Timestamp') ?? ''; const signature = req.get('X-Goldmaster-Signature') ?? ''; const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(`${timestamp}.`).update(req.body).digest('hex');
const valid = signature.length === expected.length && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)); const fresh = Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300; if (!valid || !fresh) return res.sendStatus(401);
const key = req.get('Idempotency-Key'); if (seen.has(key)) return res.sendStatus(200); seen.add(key);
const event = JSON.parse(req.body.toString('utf8')); queue.push(event); // process after answering res.sendStatus(200);});import hashlibimport hmacimport osimport time
from flask import Flask, abort, request
app = Flask(__name__)SECRET = os.environ["DUTY_WEBHOOK_SECRET"].encode()seen: set[str] = set() # use your database in production
@app.post("/hooks/duty")def duty_webhook(): timestamp = request.headers.get("X-Goldmaster-Timestamp", "") signature = request.headers.get("X-Goldmaster-Signature", "") body = request.get_data() # raw bytes expected = "sha256=" + hmac.new(SECRET, f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, expected) or abs(time.time() - int(timestamp or 0)) > 300: abort(401)
key = request.headers["Idempotency-Key"] if key in seen: return "", 200 seen.add(key)
queue.put(request.get_json()) # process after answering return "", 200package main
import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "io" "math" "net/http" "os" "strconv" "time")
var secret = []byte(os.Getenv("DUTY_WEBHOOK_SECRET"))
func dutyWebhook(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { http.Error(w, "bad body", http.StatusBadRequest) return } timestamp := r.Header.Get("X-Goldmaster-Timestamp") mac := hmac.New(sha256.New, secret) mac.Write([]byte(timestamp + ".")) mac.Write(body) expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
sent, _ := strconv.ParseInt(timestamp, 10, 64) fresh := math.Abs(float64(time.Now().Unix()-sent)) <= 300 if !hmac.Equal([]byte(r.Header.Get("X-Goldmaster-Signature")), []byte(expected)) || !fresh { http.Error(w, "invalid signature", http.StatusUnauthorized) return } if alreadyProcessed(r.Header.Get("Idempotency-Key")) { w.WriteHeader(http.StatusOK) return } enqueue(body) // process after answering w.WriteHeader(http.StatusOK)}<?php$secret = getenv('DUTY_WEBHOOK_SECRET');$body = file_get_contents('php://input'); // raw bytes$timestamp = $_SERVER['HTTP_X_GOLDMASTER_TIMESTAMP'] ?? '';$signature = $_SERVER['HTTP_X_GOLDMASTER_SIGNATURE'] ?? '';$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $body, $secret);
if (!hash_equals($expected, $signature) || abs(time() - (int) $timestamp) > 300) { http_response_code(401); exit;}
$key = $_SERVER['HTTP_IDEMPOTENCY_KEY'];if (!already_processed($key)) { enqueue(json_decode($body, true)); // process after answering}http_response_code(200);using System.Security.Cryptography;using System.Text;
app.MapPost("/hooks/duty", async (HttpRequest request) =>{ var secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("DUTY_WEBHOOK_SECRET")!); using var buffer = new MemoryStream(); await request.Body.CopyToAsync(buffer); var body = buffer.ToArray(); // raw bytes
var timestamp = request.Headers["X-Goldmaster-Timestamp"].ToString(); var signed = Encoding.UTF8.GetBytes(timestamp + ".").Concat(body).ToArray(); var expected = "sha256=" + Convert.ToHexString(HMACSHA256.HashData(secret, signed)).ToLowerInvariant(); var provided = request.Headers["X-Goldmaster-Signature"].ToString();
var fresh = long.TryParse(timestamp, out var sent) && Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - sent) <= 300; if (!fresh || !CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(provided), Encoding.UTF8.GetBytes(expected))) return Results.Unauthorized();
var key = request.Headers["Idempotency-Key"].ToString(); if (!await AlreadyProcessed(key)) Enqueue(body); // process after answering return Results.Ok();});import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;import java.security.MessageDigest;import java.util.HexFormat;
public final class DutySignature { private static final byte[] SECRET = System.getenv("DUTY_WEBHOOK_SECRET").getBytes(StandardCharsets.UTF_8);
/** True when the delivery is authentic and less than five minutes old. */ public static boolean verify(String timestamp, String signature, byte[] rawBody) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(SECRET, "HmacSHA256")); mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8)); String expected = "sha256=" + HexFormat.of().formatHex(mac.doFinal(rawBody));
long age = Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(timestamp)); return age <= 300 && MessageDigest.isEqual( expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8)); }}require "openssl"require "rack/utils"require "sinatra"
SECRET = ENV.fetch("DUTY_WEBHOOK_SECRET")
post "/hooks/duty" do body = request.body.read # raw bytes timestamp = request.env["HTTP_X_GOLDMASTER_TIMESTAMP"].to_s signature = request.env["HTTP_X_GOLDMASTER_SIGNATURE"].to_s expected = "sha256=" + OpenSSL::HMAC.hexdigest("SHA256", SECRET, "#{timestamp}.#{body}")
halt 401 unless Rack::Utils.secure_compare(expected, signature) && (Time.now.to_i - timestamp.to_i).abs <= 300
key = request.env["HTTP_IDEMPOTENCY_KEY"] enqueue(JSON.parse(body)) unless already_processed?(key) # process after answering status 200endTest it
Section titled “Test it”- Expose your endpoint over HTTPS with a public address (in development, a tunnel such as
cloudflaredorngrok). - Create a webhook pointing to it and keep the
secret. - Open a request or comment on one in the portal. Within a few seconds the delivery reaches you.
- Check what happened with List deliveries: status, attempts, the response code you returned and the last error.