webhookx

package
v0.10.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package webhookx sends and receives webhooks in the Standard Webhooks format (https://www.standardwebhooks.com): the webhook-id, webhook-timestamp and webhook-signature headers, an HMAC-SHA256 of "id.timestamp.body" and secrets written as "whsec_" followed by base64. Receivers on the other side verify it with any Standard Webhooks library.

Sending is a River job inserted in the transaction of the change it reports (Sender), so a webhook goes out exactly when the change commits and is retried with backoff. Receiving is an http.Handler (Receiver) that verifies the signature, rejects stale timestamps and handles every webhook id once, in a transaction of its own.

Index

Constants

View Source
const (
	HeaderID        = "webhook-id"
	HeaderTimestamp = "webhook-timestamp"
	HeaderSignature = "webhook-signature"
)

Headers of the Standard Webhooks format.

View Source
const AlertDeliveryFailed = "webhook_delivery_failed"

AlertDeliveryFailed is the alert kind logged when a webhook is given up on.

View Source
const DefaultTolerance = 5 * time.Minute

DefaultTolerance is how far a webhook timestamp may be from the receiver's clock.

View Source
const DeliveryAttempts = 15

DeliveryAttempts is how many times a webhook is tried. River's backoff (attempt⁴ seconds) spreads them over about two days.

Variables

View Source
var (
	ErrMissingHeaders = errors.New("webhookx: missing webhook headers")
	ErrBadTimestamp   = errors.New("webhookx: invalid webhook timestamp")
	ErrStale          = errors.New("webhookx: webhook timestamp outside the tolerance")
	ErrBadSignature   = errors.New("webhookx: no matching signature")
)

Errors of Verify.

Functions

func NewSecret

func NewSecret() string

NewSecret returns a random secret in the "whsec_<base64>" form, to hand to the other side.

func SetHeaders

func SetHeaders(h http.Header, secret Secret, id string, at time.Time, body []byte)

SetHeaders signs body with secret and sets the three webhook headers on h.

func Sign

func Sign(secret Secret, id string, at time.Time, body []byte) string

Sign returns the webhook-signature value of a message.

func Verify

func Verify(h http.Header, body []byte, secrets []Secret, now time.Time, tolerance time.Duration) (string, time.Time, error)

Verify checks the webhook headers of body against any of secrets — several while a secret is rotated — and the timestamp against now within tolerance. It returns the webhook id and timestamp.

Types

type DeliveryArgs

type DeliveryArgs struct {
	Endpoint string          `json:"endpoint"`
	ID       string          `json:"id"`
	Body     json.RawMessage `json:"body"`
}

DeliveryArgs is the River job of one webhook. It carries the endpoint by name, never its URL or secret, so the job table holds no credentials and a rotated secret applies to retries.

func (DeliveryArgs) InsertOpts

func (DeliveryArgs) InsertOpts() river.InsertOpts

InsertOpts is River's own form, so the attempts apply through riverx.Queue and a bare river.Client alike.

func (DeliveryArgs) Kind

func (DeliveryArgs) Kind() string

type Endpoint

type Endpoint struct {
	URL    string
	Secret Secret
}

Endpoint is a receiver of the project's webhooks.

type Event

type Event struct {
	ID        string
	Timestamp time.Time
	Body      []byte
	Header    http.Header
}

Event is a verified incoming webhook.

type HandleFunc

type HandleFunc func(ctx context.Context, tx pgx.Tx, e Event) error

HandleFunc processes one webhook inside the transaction that records its id: domain changes and jobs inserted with tx commit together with it, and an error rolls all of it back, so the sender's retry is processed again.

type Inserter

type Inserter interface {
	InsertTx(ctx context.Context, tx pgx.Tx, args river.JobArgs, opts *river.InsertOpts) (*rivertype.JobInsertResult, error)
}

Inserter adds a job in a transaction: *riverx.Queue and *river.Client do.

type Receiver

type Receiver struct {
	// contains filtered or unexported fields
}

Receiver is the http.Handler of one webhook source. Serve it with api.HandleHTTP.

func NewReceiver

func NewReceiver(cfg ReceiverConfig) (*Receiver, error)

NewReceiver checks the configuration. The table of processed ids is created with the first webhook, so wiring needs no database round trip.

func (*Receiver) ServeHTTP

func (r *Receiver) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP answers 204 to a processed or repeated webhook, 4xx to one that must not be retried as it is, and 500 when the handler failed, so the sender retries.

type ReceiverConfig

type ReceiverConfig struct {
	// Source names the sender; ids are unique per source.
	Source string
	// Secrets verify the signature: the current one, and the previous one while it is rotated.
	Secrets []Secret
	DB      *pgxpool.Pool
	Handle  HandleFunc

	Tolerance time.Duration // DefaultTolerance when zero
	MaxBody   int64         // 1 MiB when zero
	// Retention keeps processed ids, 24h when zero; it must exceed twice the tolerance,
	// or a replay inside the tolerance window could be processed again.
	Retention time.Duration
	Logger    *slog.Logger
	Now       func() time.Time // for tests
}

ReceiverConfig describes one incoming webhook source.

type Secret

type Secret []byte

Secret is the key both sides sign with.

func ParseSecret

func ParseSecret(s string) (Secret, error)

ParseSecret reads a secret in the "whsec_<base64>" form; the prefix is optional.

func (Secret) String

func (s Secret) String() string

String writes the secret in the "whsec_<base64>" form.

type Sender

type Sender struct {
	river.WorkerDefaults[DeliveryArgs]
	// contains filtered or unexported fields
}

Sender queues webhooks and is the River worker that delivers them: register it with riverx.AddWorker.

func NewSender

func NewSender(cfg SenderConfig) (*Sender, error)

NewSender checks the endpoints.

func (*Sender) Enqueue

func (s *Sender) Enqueue(ctx context.Context, q Inserter, tx pgx.Tx, endpoint, eventType string, data any) (string, error)

Enqueue queues a webhook of eventType with data to the endpoint inside tx: it goes out exactly when tx commits. It returns the webhook id, which every retry repeats so the receiver can drop copies.

func (*Sender) Timeout

func (s *Sender) Timeout(*river.Job[DeliveryArgs]) time.Duration

Timeout bounds one attempt.

func (*Sender) Work

func (s *Sender) Work(ctx context.Context, job *river.Job[DeliveryArgs]) error

Work delivers one webhook. A 2xx answer completes it, 410 Gone cancels it, anything else is retried; the last failed attempt logs AlertDeliveryFailed.

type SenderConfig

type SenderConfig struct {
	Endpoints map[string]Endpoint
	// Timeout of one attempt, 15s when zero.
	Timeout time.Duration
	Client  *http.Client // http.DefaultClient when nil
	Logger  *slog.Logger
	Now     func() time.Time // for tests
}

SenderConfig lists the endpoints by name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL