package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
var secret = []byte(os.Getenv("AGENTCARD_WEBHOOK_SECRET"))
func receive(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var t, v1 string
for _, part := range strings.Split(r.Header.Get("AgentCard-Signature"), ",") {
kv := strings.SplitN(part, "=", 2)
if len(kv) == 2 {
switch kv[0] {
case "t": t = kv[1]
case "v1": v1 = kv[1]
}
}
}
if t == "" || v1 == "" {
http.Error(w, "bad signature header", 400); return
}
ts, _ := strconv.ParseInt(t, 10, 64)
if d := time.Now().Unix() - ts; d > 300 || d < -300 {
http.Error(w, "timestamp outside tolerance", 400); return
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(t + "."))
mac.Write(body)
expected := hex.EncodeToString(mac.Sum(nil))
expectedBytes, _ := hex.DecodeString(expected)
v1Bytes, _ := hex.DecodeString(v1)
if !hmac.Equal(expectedBytes, v1Bytes) {
http.Error(w, "signature mismatch", 400); return
}
// Handle the event…
w.WriteHeader(200)
}