mirror of
https://github.com/therootcompany/golib.git
synced 2026-04-25 05:08:00 +00:00
Verify X-Hub-Signature-256 (and SHA-1) webhook signatures. Middleware buffers and re-exposes the body for downstream handlers. Errors honor Accept header: TSV default (text/plain for browsers), JSON, CSV, or Markdown — three fields (error, description, hint) with pseudocode hints.
31 lines
653 B
Go
31 lines
653 B
Go
package xhubsig
|
|
|
|
import (
|
|
"crypto/hmac"
|
|
"encoding/hex"
|
|
"errors"
|
|
)
|
|
|
|
var (
|
|
ErrMissingSignature = errors.New("missing signature")
|
|
ErrInvalidSignature = errors.New("invalid signature")
|
|
ErrBodyTooLarge = errors.New("body too large")
|
|
)
|
|
|
|
func Sign(h Hash, secret string, body []byte) string {
|
|
mac := hmac.New(h.New, []byte(secret))
|
|
mac.Write(body)
|
|
return h.Prefix + hex.EncodeToString(mac.Sum(nil))
|
|
}
|
|
|
|
func Verify(h Hash, secret string, body []byte, sig string) error {
|
|
if sig == "" {
|
|
return ErrMissingSignature
|
|
}
|
|
expected := Sign(h, secret, body)
|
|
if hmac.Equal([]byte(expected), []byte(sig)) {
|
|
return nil
|
|
}
|
|
return ErrInvalidSignature
|
|
}
|