http interaction verification

This commit is contained in:
basil 2025-06-02 13:43:24 -04:00
parent 1cf3d96f8f
commit f19b4ede12
Signed by: basil
SSH key fingerprint: SHA256:y04xIFL/yqNaG9ae9Vl95vELtHfApGAIoOGLeVLP/fE

View file

@ -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
}