webhooks

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: AGPL-3.0 Imports: 33 Imported by: 0

Documentation

Overview

Package webhooks delivers normalized ReputeCast events to the endpoints a workspace registers (main spec 7.13). Every request is signed with HMAC-SHA256 using a write-only secret, retried with backoff (then kept in the dead-letter queue for 7 days), and protected against SSRF.

Index

Constants

View Source
const (
	HeaderSignature = "X-ReputeCast-Signature"
	HeaderTimestamp = "X-ReputeCast-Timestamp"
	HeaderEvent     = "X-ReputeCast-Event"
	HeaderDelivery  = "X-ReputeCast-Delivery"
)

Headers sent with every delivery.

View Source
const MaxAttempts = 8

MaxAttempts is how often a delivery is tried before it goes to the dead-letter queue.

Variables

View Source
var Backoff = []time.Duration{time.Minute, 2 * time.Minute, 4 * time.Minute, 8 * time.Minute, 30 * time.Minute, 90 * time.Minute, 225 * time.Minute}

Backoff after attempt n (1-based): 1, 2, 4, 8, 30, 90 and 225 minutes, so eight attempts span six hours.

View Source
var Events = []WebhookEventInfo{
	{Name: "contact.subscribed", Group: "Contacts"},
	{Name: "contact.unsubscribed", Group: "Contacts"},
	{Name: "contact.updated", Group: "Contacts"},
	{Name: "contact.erased", Group: "Contacts"},
	{Name: "email.sent", Group: "Email"},
	{Name: "email.delivered", Group: "Email"},
	{Name: "email.deferred", Group: "Email"},
	{Name: "email.bounced", Group: "Email"},
	{Name: "email.complained", Group: "Email"},
	{Name: "email.opened", Group: "Email"},
	{Name: "email.clicked", Group: "Email"},
	{Name: "campaign.scheduled", Group: "Campaigns"},
	{Name: "campaign.started", Group: "Campaigns"},
	{Name: "campaign.paused", Group: "Campaigns"},
	{Name: "campaign.resumed", Group: "Campaigns"},
	{Name: "campaign.completed", Group: "Campaigns"},
	{Name: "approval.requested", Group: "Approvals"},
	{Name: "approval.decided", Group: "Approvals"},
	{Name: "provider.down", Group: "Sending providers"},
	{Name: "provider.recovered", Group: "Sending providers"},
	{Name: "automation.published", Group: "Automations"},
	{Name: "message.sent", Group: "Transactional messages"},
	{Name: "message.delivered", Group: "Transactional messages"},
	{Name: "message.deferred", Group: "Transactional messages"},
	{Name: "message.bounced", Group: "Transactional messages"},
	{Name: "message.complained", Group: "Transactional messages"},
	{Name: "message.rejected", Group: "Transactional messages"},
	{Name: "message.failed", Group: "Transactional messages"},
	{Name: "message.opened", Group: "Transactional messages"},
	{Name: "message.clicked", Group: "Transactional messages"},
	{Name: "form.submitted", Group: "Forms"},

	{Name: "referral.counted", Group: "Referrals"},
	{Name: "referral.held", Group: "Referrals"},
	{Name: "referral.not_counted", Group: "Referrals"},
	{Name: "referral.milestone_reached", Group: "Referrals"},
	{Name: "referral.reward_sent", Group: "Referrals"},
	{Name: "referral.reward_failed", Group: "Referrals"},
}

Events is the catalogue of events, in display order.

Functions

func Emit

func Emit(ctx context.Context, q store.DBTX, workspaceID uuid.UUID, workspaceSlug, event string, data any) (int, error)

Emit queues an event for every endpoint of the workspace subscribed to it. Call it inside the transaction that changes the state the event reports; a periodic job picks the deliveries up within seconds. It returns the number of deliveries queued.

func NewSecret

func NewSecret() string

NewSecret returns a new signing secret ("whsec_…").

func Register

func Register(h huma.API, s *Service)

Register adds the webhooks operations.

func RegisterJobs

func RegisterJobs(reg *jobs.Registry, s *Service, log *slog.Logger)

RegisterJobs adds the delivery worker and the periodic dispatcher.

func SecretAD

func SecretAD(id uuid.UUID) string

SecretAD is the associated data an endpoint's secret is sealed with.

func Sign

func Sign(secret string, timestamp int64, body []byte) string

Sign returns the hex HMAC-SHA256 of "<timestamp>.<body>".

func ValidEvent

func ValidEvent(name string) bool

ValidEvent reports whether name is a known event or wildcard ("email.*", "*").

func Verify

func Verify(secret, signature string, timestamp int64, body []byte, now time.Time, tolerance time.Duration) bool

Verify checks a signature and rejects timestamps older than tolerance.

Types

type DeliverArgs

type DeliverArgs struct {
	DeliveryID uuid.UUID `json:"delivery_id"`
}

DeliverArgs makes one attempt at one delivery.

func (DeliverArgs) InsertOpts

func (DeliverArgs) InsertOpts() river.InsertOpts

InsertOpts puts deliveries on the events queue. River's own retries are off: the delivery row tracks attempts and backoff itself.

func (DeliverArgs) Kind

func (DeliverArgs) Kind() string

Kind implements river.JobArgs.

type DeliverWorker

type DeliverWorker struct {
	river.WorkerDefaults[DeliverArgs]
	S   *Service
	Log *slog.Logger
}

DeliverWorker posts a delivery and schedules the next attempt on failure.

func (*DeliverWorker) Timeout

Timeout bounds one attempt.

func (*DeliverWorker) Work

func (w *DeliverWorker) Work(ctx context.Context, job *river.Job[DeliverArgs]) error

Work implements river.Worker.

type DeliveryPathInput

type DeliveryPathInput struct {
	api.WorkspaceInput
	DeliveryID string `path:"deliveryId" format:"uuid"`
}

DeliveryPathInput is a path or query input shared by several operations.

type DispatchArgs

type DispatchArgs struct{}

DispatchArgs is the periodic sweep that queues due deliveries (emitted by other domains inside their transactions) and purges old ones.

func (DispatchArgs) InsertOpts

func (DispatchArgs) InsertOpts() river.InsertOpts

InsertOpts keeps one sweep at a time.

func (DispatchArgs) Kind

func (DispatchArgs) Kind() string

Kind implements river.JobArgs.

type DispatchWorker

type DispatchWorker struct {
	river.WorkerDefaults[DispatchArgs]
	S   *Service
	Log *slog.Logger
}

DispatchWorker queues jobs for due deliveries.

func (*DispatchWorker) Work

Work implements river.Worker.

type Envelope

type Envelope struct {
	ID        string    `json:"id"`
	Type      string    `json:"type"`
	CreatedAt time.Time `json:"created_at"`
	Workspace string    `json:"workspace"`
	Data      any       `json:"data"`
}

Envelope is the JSON body of every delivery.

type Managed

type Managed interface {
	ManagedHooks(ctx context.Context, workspaceID uuid.UUID) (map[uuid.UUID]WebhookManagedBy, error)
	ManagedHook(ctx context.Context, webhookID uuid.UUID) (*WebhookManagedBy, error)
	// Gone removes a managed endpoint that answered 410 Gone.
	Gone(ctx context.Context, webhookID uuid.UUID)
}

Managed tells which endpoints integrations manage.

type Service

type Service struct {
	Pool  *pgxpool.Pool
	Q     *store.Queries
	Audit *audit.Logger
	Box   *secrets.Box
	Jobs  *jobs.Client
	// AllowPrivate reports whether endpoints may resolve to private
	// networks (webhooks.allow_private_networks); read at each use.
	AllowPrivate func() bool
	Now          func() time.Time
	// HTTP overrides the delivery client (tests).
	HTTP *http.Client
	// Managed knows the endpoints integrations manage (internal/integrations):
	// they can't be edited by hand, other API keys don't see them, and one
	// that answers 410 Gone is removed.
	Managed Managed
}

func (*Service) Attempt

func (s *Service) Attempt(ctx context.Context, deliveryID uuid.UUID) (*time.Time, error)

Attempt makes one delivery attempt and records the result. It returns the time of the next attempt when the delivery will be retried.

func (*Service) Create

Create registers an endpoint and returns its signing secret once.

func (*Service) Delete

func (s *Service) Delete(ctx context.Context, ws *store.Workspace, id uuid.UUID) error

Delete removes an endpoint and its delivery log.

func (*Service) Deliveries

func (s *Service) Deliveries(ctx context.Context, ws *store.Workspace, webhookID *uuid.UUID, state string, limit int) (WebhookDeliveryList, error)

Deliveries returns the latest deliveries, newest first.

func (*Service) Delivery

func (s *Service) Delivery(ctx context.Context, ws *store.Workspace, id uuid.UUID) (WebhookDeliveryDetail, error)

Delivery returns one delivery with its payload.

func (*Service) List

func (s *Service) List(ctx context.Context, ws *store.Workspace) (WebhookList, error)

List returns the workspace's endpoints with 24-hour delivery stats.

func (*Service) Retry

func (s *Service) Retry(ctx context.Context, ws *store.Workspace, deliveryID, webhookID *uuid.UUID) (WebhookRetryResult, error)

Retry queues failed deliveries for an immediate attempt: one delivery, every failed one of an endpoint, or every failed one of the workspace. Dead-lettered deliveries start a fresh round of attempts (replay).

func (*Service) RotateSecret

func (s *Service) RotateSecret(ctx context.Context, ws *store.Workspace, id uuid.UUID) (WebhookSecretResult, error)

RotateSecret replaces the signing secret. Deliveries sign with the new one at once.

func (*Service) SetEnabled

func (s *Service) SetEnabled(ctx context.Context, ws *store.Workspace, id uuid.UUID, enabled bool) error

SetEnabled pauses or resumes an endpoint. Events keep queuing while it is paused and are delivered in order when it resumes.

func (*Service) Test

Test sends a webhook.test event right away and returns the result.

func (*Service) Update

func (s *Service) Update(ctx context.Context, ws *store.Workspace, id uuid.UUID, in WebhookInput) (WebhookView, error)

Update changes an endpoint's URL, name or events.

type WebhookCreated

type WebhookCreated struct {
	Webhook WebhookView `json:"webhook"`
	Secret  string      `json:"secret" doc:"The signing secret. Shown only in this response."`
}

WebhookCreated carries the signing secret, shown once.

type WebhookDeliveryDetail

type WebhookDeliveryDetail struct {
	Delivery WebhookDeliveryView `json:"delivery"`
	Payload  json.RawMessage     `json:"payload"`
	Response string              `json:"response" doc:"First kilobyte of the endpoint's last response"`
}

WebhookDeliveryDetail adds the payload and the endpoint's response.

type WebhookDeliveryList

type WebhookDeliveryList struct {
	Items []WebhookDeliveryView `json:"items"`
	// Queued counts deliveries waiting per endpoint id.
	Queued map[string]int64 `json:"queued"`
}

WebhookDeliveryList is the delivery log.

type WebhookDeliveryView

type WebhookDeliveryView struct {
	ID        string `json:"id"`
	WebhookID string `json:"webhookId"`
	Endpoint  string `json:"endpoint" doc:"Host and path, e.g. api.acme.io/hooks/reputecast"`
	Event     string `json:"event"`
	// Subtype qualifies the event ("hard" for email.bounced).
	Subtype       string     `json:"subtype,omitempty"`
	State         string     `json:"state" enum:"pending,delivering,delivered,retrying,dead,held"`
	StatusCode    *int32     `json:"statusCode,omitempty"`
	StatusText    string     `json:"statusText,omitempty" doc:"Bad Gateway"`
	DurationMs    *int32     `json:"durationMs,omitempty"`
	Error         string     `json:"error,omitempty"`
	Attempts      int32      `json:"attempts"`
	MaxAttempts   int32      `json:"maxAttempts"`
	CreatedAt     time.Time  `json:"createdAt"`
	LastAttemptAt *time.Time `json:"lastAttemptAt,omitempty"`
	NextAttemptAt *time.Time `json:"nextAttemptAt,omitempty"`
	// BackoffMinutes is the wait before the next attempt.
	BackoffMinutes *int `json:"backoffMinutes,omitempty"`
}

WebhookDeliveryView is one row of the delivery log.

type WebhookEventInfo

type WebhookEventInfo struct {
	Name        string `json:"name" example:"email.bounced"`
	Group       string `json:"group" example:"Email"`
	Description string `json:"description"`
	// DescriptionText is the description's message, for the events other
	// packages add from their own catalogs.
	DescriptionText i18n.Text `json:"-"`
}

WebhookEventInfo describes an event endpoints can subscribe to.

type WebhookInput

type WebhookInput struct {
	Name        string   `json:"name" maxLength:"80"`
	Description string   `json:"description,omitempty" maxLength:"120"`
	URL         string   `json:"url" maxLength:"500"`
	Events      []string `json:"events" minItems:"1" maxItems:"40"`
}

WebhookInput creates or updates an endpoint.

type WebhookList

type WebhookList struct {
	Items  []WebhookView      `json:"items"`
	Events []WebhookEventInfo `json:"events"`
	// Headers name the signature headers for the "Verify a signature" card.
	SignatureHeader string `json:"signatureHeader"`
	TimestampHeader string `json:"timestampHeader"`
	MaxAttempts     int    `json:"maxAttempts"`
}

WebhookList is the outgoing webhooks card.

type WebhookManagedBy

type WebhookManagedBy struct {
	IntegrationID string `json:"integrationId"`
	Kind          string `json:"kind" example:"n8n"`
	Name          string `json:"name" example:"n8n"`
	// Workflow is the workflow that created it ("Unsubscribes → Acme Cloud CRM").
	Workflow string `json:"workflow,omitempty"`
	// Endpoint is its URL masked, as the integration's page shows it: a
	// workflow tool's webhook address often carries a token.
	Endpoint string `json:"endpoint,omitempty" example:"https://n8n.acme.io/webhook/7c1e…/reputecast"`
}

WebhookManagedBy names the integration that manages an endpoint.

type WebhookPathInput

type WebhookPathInput struct {
	api.WorkspaceInput
	WebhookID string `path:"webhookId" format:"uuid"`
}

WebhookPathInput is a path or query input shared by several operations.

type WebhookRetryInput

type WebhookRetryInput struct {
	WebhookID string `json:"webhookId,omitempty" doc:"Only this endpoint; empty retries every endpoint"`
}

WebhookRetryInput limits "Retry all failed" to one endpoint.

type WebhookRetryResult

type WebhookRetryResult struct {
	Queued int `json:"queued"`
}

WebhookRetryResult counts the deliveries queued again.

type WebhookSecretResult

type WebhookSecretResult struct {
	Secret string `json:"secret"`
}

WebhookSecretResult carries a new signing secret, shown once.

type WebhookTestResult

type WebhookTestResult struct {
	Delivery WebhookDeliveryView `json:"delivery"`
}

WebhookTestResult is the outcome of a test delivery.

type WebhookView

type WebhookView struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Description string   `json:"description"`
	URL         string   `json:"url"`
	Events      []string `json:"events"`
	Enabled     bool     `json:"enabled"`
	// Status is new (no delivery yet), healthy, failing or paused.
	Status          string     `json:"status" enum:"new,healthy,failing,paused"`
	LastStatus      *int32     `json:"lastStatus,omitempty"`
	LastDeliveryAt  *time.Time `json:"lastDeliveryAt,omitempty"`
	FailingSince    *time.Time `json:"failingSince,omitempty"`
	SecretRotatedAt *time.Time `json:"secretRotatedAt,omitempty" doc:"Set when the secret was replaced after creation"`
	CreatedAt       time.Time  `json:"createdAt"`
	Total24h        int64      `json:"total24h" doc:"Deliveries attempted in the last 24 hours"`
	Success24h      *float64   `json:"success24h,omitempty" doc:"Percent delivered in the last 24 hours"`
	Queued          int64      `json:"queued" doc:"Deliveries waiting for an attempt or a retry"`
	// ManagedBy is set for endpoints an integration created: their URL,
	// events and secret change only in the integration.
	ManagedBy *WebhookManagedBy `json:"managedBy,omitempty"`
}

WebhookView is an endpoint as listed. The secret is never returned.

Jump to

Keyboard shortcuts

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