interactions.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package discordgo
  2. import (
  3. "bytes"
  4. "crypto/ed25519"
  5. "encoding/hex"
  6. "io"
  7. "io/ioutil"
  8. "net/http"
  9. )
  10. // VerifyInteraction implements message verification of the discord interactions api
  11. // signing algorithm, as documented here:
  12. // https://discord.com/developers/docs/interactions/slash-commands#security-and-authorization
  13. func VerifyInteraction(r *http.Request, key ed25519.PublicKey) bool {
  14. var msg bytes.Buffer
  15. signature := r.Header.Get("X-Signature-Ed25519")
  16. if signature == "" {
  17. return false
  18. }
  19. sig, err := hex.DecodeString(signature)
  20. if err != nil {
  21. return false
  22. }
  23. if len(sig) != ed25519.SignatureSize {
  24. return false
  25. }
  26. timestamp := r.Header.Get("X-Signature-Timestamp")
  27. if timestamp == "" {
  28. return false
  29. }
  30. msg.WriteString(timestamp)
  31. defer r.Body.Close()
  32. var body bytes.Buffer
  33. // at the end of the function, copy the original body back into the request
  34. defer func() {
  35. r.Body = ioutil.NopCloser(&body)
  36. }()
  37. // copy body into buffers
  38. _, err = io.Copy(&msg, io.TeeReader(r.Body, &body))
  39. if err != nil {
  40. return false
  41. }
  42. return ed25519.Verify(key, msg.Bytes(), sig)
  43. }