diff --git a/interaction.go b/interaction.go index 06481c4..1991410 100644 --- a/interaction.go +++ b/interaction.go @@ -2,9 +2,12 @@ package discord import ( "bytes" + "crypto/ed25519" + "encoding/hex" "encoding/json" "errors" "fmt" + "io" "net/http" ) @@ -131,3 +134,29 @@ type InteractionResponse[T any] struct { Type InteractionResponseType `json:"type"` Data T `json:"data,omitempty"` } + +func VerifyHTTPInteraction(publicKey ed25519.PublicKey, r *http.Request) (*Interaction[any], []byte, error) { + sigHeader := r.Header.Get("X-Signature-Ed25519") + signature, err := hex.DecodeString(sigHeader) + if err != nil { + return nil, nil, err + } + + timestamp := []byte(r.Header.Get("X-Signature-Timestamp")) + + bs, err := io.ReadAll(r.Body) + if err != nil { + return nil, nil, err + } + + ok := ed25519.Verify(publicKey, append(timestamp, bs...), signature) + + if !ok { + return nil, nil, errors.New("unable to verify ed25519 signature") + } + + req := Interaction[any]{} + + err = json.Unmarshal(bs, &req) + return &req, bs, err +}