kaiyan/twitch/webhook.go
2025-04-08 13:00:09 -04:00

56 lines
1.7 KiB
Go

package twitch
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"sync"
)
// ErrVerificationFailed is the error returned when a webhook request does not
// verify correctly.
var ErrVerificationFailed = errors.New("Twitch webhook verification failed") //lint:ignore ST1005 Twitch is a proper noun
// Receive verifies a Twitch webhook request against the given secret
// and appends the request body to b.
// The maximum allowed request length is 1 MB.
func Receive(b, secret []byte, req *http.Request) ([]byte, error) {
r := io.LimitReader(req.Body, 1<<20)
w := bytes.NewBuffer(b)
if _, err := io.Copy(w, r); err != nil {
return nil, err
}
b = w.Bytes()
h := hmac.New(sha256.New, secret)
io.WriteString(h, req.Header.Get("Twitch-Eventsub-Message-Id"))
io.WriteString(h, req.Header.Get("Twitch-Eventsub-Message-Timestamp"))
h.Write(b)
want := make([]byte, 0, len("sha256=")+sha256.Size*2)
want = append(want, "sha256="...)
sum := h.Sum(make([]byte, 0, sha256.Size))
want = hex.AppendEncode(want, sum)
got := req.Header.Get("Twitch-Eventsub-Message-Signature")
if !hmac.Equal(want, []byte(got)) {
fmt.Printf("req message id: %q\n", req.Header.Get("Twitch-Eventsub-Message-Id"))
fmt.Printf("req timestamp: %q\n", req.Header.Get("Twitch-Eventsub-Message-Timestamp"))
fmt.Printf("req body: %q\n", b)
return nil, fmt.Errorf("%w: computed %q, header has %q", ErrVerificationFailed, want, got)
}
return b, nil
}
// Secret returns a process-wide secret for webhook subscriptions.
var Secret = sync.OnceValue(func() []byte {
b := make([]byte, 32)
rand.Read(b)
return hex.AppendEncode(make([]byte, 0, 64), b)
})